Exemplo n.º 1
0
        public IEnumerator StandalonePublish()
        {
            // Restart the server, making sure there is no Shotgun client
            PythonRunner.StopServer(false);

            // Make sure the Shotgun client has stopped
            double initTime = EditorApplication.timeSinceStartup;

            while (Bootstrap.IsClientAlive())
            {
                if (EditorApplication.timeSinceStartup - initTime > shutdownTimeout)
                {
                    Assert.That(false, Is.True);
                }
                System.Threading.Thread.Sleep(100);
            }
            // Bootstrap Shotgun with our test client
            Bootstrap.SpawnClient(clientPath);

            // Give some time for the client to connect
            yield return(PythonRunner.WaitForConnection(Constants.clientName, connectionTimeout));

            // Wait until the client is fully bootstrapped
            initTime = EditorApplication.timeSinceStartup;
            while (!PythonRunner.CallServiceOnClient(Constants.clientName, "bootstrapped"))
            {
                if (EditorApplication.timeSinceStartup - initTime > bootstrapTimeout)
                {
                    break;
                }
                yield return(null);
            }

            // Fake a recording by copying a video file in the right location
            string videoFilePath   = Path.GetFullPath($"{testsPath}/standalone_publish.mp4");
            var    destinationPath = Path.Combine(System.IO.Path.GetTempPath(), Application.productName);

            destinationPath += ".mp4";

            System.IO.File.Copy(videoFilePath, destinationPath, true);

            Service.Call("standalone_publish");

            // Wait until the client has finished publishing
            initTime = EditorApplication.timeSinceStartup;
            while (!PythonRunner.CallServiceOnClient(Constants.clientName, "published"))
            {
                if (EditorApplication.timeSinceStartup - initTime > publishTimeout)
                {
                    break;
                }
                yield return(null);
            }

            // Upon success, the Python script creates a game object named
            // after the product name
            GameObject go = GameObject.Find(Application.productName);

            Assert.IsNotNull(go);
        }
Exemplo n.º 2
0
 public static void InitializeWorker()
 {
     // The client here spawned could also be launched from the command line.
     PythonRunner.SpawnClient(CLIENT_PATH,
                              wantLogging: true);
     EditorCoroutineUtility.StartCoroutineOwnerless(WaitForWorkerAndInitialize());
 }
Exemplo n.º 3
0
        public void TestIsPythonLibraryLoaded()
        {
            PythonRunner.EnsureInitialized();
            var result = PythonRunner.IsPythonLibraryLoaded();

            Assert.That(result, Is.True);
        }
Exemplo n.º 4
0
        public void TestScriptAssembliesInSysPath()
        {
            PythonRunner.EnsureInitialized();

            using (Py.GIL())
            {
                dynamic sysmod  = Py.Import("sys");
                dynamic syspath = sysmod.path;
                bool    found   = false;
                foreach (string path in syspath)
                {
                    if (path == Path.GetFullPath("Library/ScriptAssemblies").Replace("\\", "/"))
                    {
                        found = true;
                        break;
                    }
                }
                Assert.True(found);

                // Next, try to load PythonRunner from python
                dynamic clrmod = Py.Import("clr");
                clrmod.AddReference("Unity.Scripting.Python.Editor");
                dynamic pythonRunnerMod = Py.Import("UnityEditor.Scripting.Python");
                string  version         = pythonRunnerMod.PythonRunner.PythonVersion;
                Assert.That(version, Is.EqualTo(PythonRunner.PythonVersion));
            }
        }
Exemplo n.º 5
0
        private void BkWorkerOnDoWork(object sender, DoWorkEventArgs doWorkEventArgs)
        {
            string firstFileData  = PythonRunner.RunWithArgument(sourcePath);
            string secondFileData = PythonRunner.RunWithArgument(targetPath);

            doWorkEventArgs.Result = new Tuple <string, string>(firstFileData, secondFileData);
        }
Exemplo n.º 6
0
// ReSharper disable AssignNullToNotNullAttribute
        public MainViewModel()
        {
            // Initialize some defaults.
            _startDate        = MinStartDate;
            _endDate          = MaxEndDate;
            _numClusters      = DefaultClusters;
            _needsTreeRefresh = true;
            _needsChartRedraw = true;

            PythonRunner = new PythonRunner(ConfigurationManager.AppSettings["pythonPath"], 20000);
            DbPath       = Path.GetFullPath(ConfigurationManager.AppSettings["dbFile"]);

            string chartScript = Path.Combine(
                Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
                ConfigurationManager.AppSettings["scripts"],
                "chart.py");

            string kMeansScript = Path.Combine(
                Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
                ConfigurationManager.AppSettings["scripts"],
                "kmeans.py");

            // Initialize 'child' VMs.
            StockListVm = new StockListViewModel(this);
            TreeViewVm  = new TreeViewViewModel(this, kMeansScript);
            ChartVm     = new ChartViewModel(this, chartScript);

            // 'Invalidate' chart and tree when stock selection changes.
            StockListVm.Stocks.ToList().ForEach(si => si.SelectionChanged += (sender, args) =>
            {
                NeedsChartRedraw = true;
                NeedsTreeRefresh = true;
                OnPropertyChanged(nameof(StockListVm.CollectionView));
            });
        }
Exemplo n.º 7
0
 static void PrintHelloWorldFromPython()
 {
     PythonRunner.RunString(@"
             import UnityEngine;
             UnityEngine.Debug.Log('hello console')
             ");
 }
Exemplo n.º 8
0
        public async Task <Result> HandleAsync(AddDocumentToSourceStoreCommand command,
                                               CancellationToken cancellationToken)
        {
            Console.WriteLine($"[AddDocumentToSourceStoreCommandHandler] received command {command}");

            await UpdateFileStatus(command, OperationStatus.NotInitialized);

            var result = PythonRunner.Run(
                _scriptsConfiguration.UploadSource,
                $"{command.UserId} {command.FileId} Repository  {command.File.FileName} {command.File.Content}"
                );

            Console.WriteLine(result);
            if (result.TrimEnd().Split("\n").Last() == "-1")
            {
                Console.WriteLine($"[AddDocumentToSourceStoreCommandHandler] Upload failed for file {command.FileId}");
                await UpdateFileStatus(command, OperationStatus.Failed);

                return(Result.Fail($"Upload failed for file {command.FileId}"));
            }
            Console.WriteLine($"[AddDocumentToSourceStoreCommandHandler] upload successful");
            await UpdateFileStatus(command, OperationStatus.Complete);

            return(Guid.NewGuid().ToSuccessfulResult());
        }
Exemplo n.º 9
0
        public void SuicideProbability()
        {
            //this test is correct with default suicide_result if he still has only 2 posts

            Client cl = new User("durov");
            string id = cl.Link;

            // calling script to process data and make prediction
            PythonRunner.RunScript(AppSettings.PythonScriptPath, AppSettings.PythonPath);
            Thread.Sleep(10000);
            //get prediction
            double res = cl.SuicideProbability(DateTime.MinValue, DateTime.MaxValue, id);

            //disabling script
            IPEndPoint ipe    = new IPEndPoint(AppSettings.LocalIP, AppSettings.ClientPort);
            Socket     socket = new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

            socket.Connect(ipe);
            Byte[] bytesSent = Encoding.UTF32.GetBytes("~exit~::");
            socket.Send(bytesSent, bytesSent.Length, 0);

            //+ Check correctness with your eyes
            Console.WriteLine(res);
            Assert.IsTrue(res < 0.999 && res >= 0.00);
        }
Exemplo n.º 10
0
        public void TestUndoRedirectStdout()
        {
            // open python console
            PythonConsoleWindow.ShowWindow();

            var prevContents = PythonConsoleWindow.s_window.m_outputContents;

            PythonConsoleWindow.s_window.m_outputContents = "";

            var msg       = "hello world";
            var pythonCmd = string.Format("print ('{0}')", msg);

            PythonRunner.RunString(pythonCmd);
            var output = PythonConsoleWindow.s_window.m_outputContents;

            Assert.That(output, Is.EqualTo(msg + "\n"));

            PythonRunner.UndoRedirectStdout();


            PythonConsoleWindow.s_window.m_outputContents = "";

            // stdout should no longer be redirected
            PythonRunner.RunString(pythonCmd);
            output = PythonConsoleWindow.s_window.m_outputContents;

            Assert.That(output, Is.Null.Or.Empty);

            PythonConsoleWindow.s_window.m_outputContents = prevContents;
            PythonConsoleWindow.s_window.Close();

            // redo stdout redirection
            PythonRunner.RedirectStdout();
        }
Exemplo n.º 11
0
        public Controller(string dbPath, string _pyPath, string _pyScriptsPath)
        {
            _persistance = new Persistance();
            this.dbPath  = dbPath;

            this.pythonPath        = _pyPath;
            this.pythonScriptsPath = _pyScriptsPath;

            this.pyRunnes = new PythonRunner(this.pythonPath);

            /*
             * //string dbpath = @"C:\Users\Enrico\Desktop\ordiniMI2018.sqlite";
             * string sdb = ConfigurationManager.AppSettings["dbServer"];
             *
             * switch (sdb)
             * {
             *  case "SQLiteConn":
             *      connectionString = ConfigurationManager.ConnectionStrings["SQLiteConn"].ConnectionString;
             *      connectionString = connectionString.Replace("DBFILE", dbPath);
             *      _persistance.SetFactory(ConfigurationManager.ConnectionStrings["SQLiteConn"].ProviderName);
             *      break;
             *  case "LocalDbConn":
             *      connectionString = ConfigurationManager.ConnectionStrings["LocalSqlServConn"].ConnectionString;
             *      _persistance.SetFactory(ConfigurationManager.ConnectionStrings["LocalSqlServConn"].ProviderName);
             *      break;
             *  case "RemoteSqlServConn":
             *      connectionString = ConfigurationManager.ConnectionStrings["RemoteSQLConn"].ConnectionString;
             *      _persistance.SetFactory(ConfigurationManager.ConnectionStrings["RemoteSQLConn"].ProviderName);
             *      break;
             *
             * }
             * _persistance.connectionString = connectionString;
             */
        }
 public override void OnInspectorGUI()
 {
     if (GUILayout.Button("Launch Python Script", GUILayout.Height(35)))
     {
         string path = Application.dataPath + "/Plugins/LeapMotion/Core/Scripts/Python_Scripts/test.py";
         PythonRunner.RunFile(path);
     }
 }
Exemplo n.º 13
0
 static void OnHierarchyChanged()
 {
     // This is the simplest way to call Python code.
     PythonRunner.RunString(@"
             import PySideExample
             PySideExample.update_camera_list()
             ");
 }
Exemplo n.º 14
0
 public Controller()
 {
     this.dbPath           = ConfigurationManager.AppSettings["dbordiniFile"];
     this.pythonPath       = ConfigurationManager.AppSettings["pythonPath"];
     this.pythonScriptPath = ConfigurationManager.AppSettings["pyScripts"];
     this.pyRunner         = new PythonRunner(this.pythonPath, 20000);
     P = new Persistence(dbPath);
 }
Exemplo n.º 15
0
 protected void Application_Start()
 {
     AreaRegistration.RegisterAllAreas();
     FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
     RouteConfig.RegisterRoutes(RouteTable.Routes);
     BundleConfig.RegisterBundles(BundleTable.Bundles);
     PythonRunner.RunScript(AppSettings.PythonScriptPath, AppSettings.PythonPath);
 }
Exemplo n.º 16
0
 public Controller(string _pyPath, string _pyScriptsPath)
 {
     this.pythonPath        = _pyPath;
     this.pythonScriptsPath = _pyScriptsPath;
     P        = new Persistence();
     GAP      = new GAPclass();
     pyRunner = new PythonRunner(pythonPath, 20000);
 }
 public void Setup()
 {
     PythonRunner.EnsureInitialized();
     using (Py.GIL())
     {
         dynamic module = PythonEngine.ImportModule("unity_python.common.spawn_process");
         spawn = module.spawn_process_in_environment;
     }
 }
    void CamCapture()
    {
        // ScreenCapture.CaptureScreenshot(Application.dataPath + "/Screenshots/" + fileCount + ".png");
        // fileCount++;

        string path = Application.dataPath + "/Plugins/LeapMotion/Core/Scripts/Python_Scripts/test.py";

        PythonRunner.RunFile(path);
    }
 public UserEntryController(IUserEntryRepo userEntry, UserManager <User> userManager, IUserSettingsRepo userSettingsRepo,
                            PythonRunner pythonRunner, IConfiguration configuration, IImageEntryRepo imageEntryRepo, IUserRepo userRepo)
 {
     _userEntryRepo    = userEntry;
     _userManager      = userManager;
     _userSettingsRepo = userSettingsRepo;
     _pythonRunner     = pythonRunner;
     _configuration    = configuration;
     _imageEntryRepo   = imageEntryRepo;
     _userRepo         = userRepo;
 }
        /// <summary>
        /// Calls a service on the Shotgun client.
        /// </summary>
        /// <param name="serviceName">The name of the service</param>
        /// <param name="args">Arguments to pass to the service</param>
        public static void Call(string serviceName, params object[] args)
        {
            // Do our best to get a valid client
            if (!Client.EnsureConnection())
            {
                return;
            }

            // Then call the service
            _ = PythonRunner.CallAsyncServiceOnClient(Constants.clientName, serviceName, args);
        }
Exemplo n.º 21
0
        public MainViewModel()
        {
            GoCommand               = new MyCommand(p => Go(), CanGo);
            StopCommand             = new MyCommand(p => Stop(), CanStop);
            IncreaseFontSizeCommand = new MyCommand(p => IncreaseFontSize(), CanIncreaseFontSize);
            DecreaseFontSizeCommand = new MyCommand(p => DecreaseFontSize(), CanDecreaseFontSize);

            runner         = new PythonRunner();
            runner.Output += Runner_OutputReceived;
            runner.Error  += Runner_ErrorReceived;
            runner.ExecutionStateChanged += Runner_ExecutionStateChanged;
            ProgramInteraction.Input     += ProgramInteraction_Input;
        }
Exemplo n.º 22
0
        // Helper for TestProjectAssemblyReferencesAdded.
        // Tries to import System and run a command with PythonRunner.RunString().
        // Called once before and after domain reload.
        private void TestImportSystemHelper()
        {
            var importSystem = "import System;System.IO.File.Exists('test.txt')";

            PythonRunner.RunString(importSystem);

            // System has an extra m, so this should throw an exception
            var importSystemInvalid = "import Systemm;System.IO.File.Exists('test.txt')";

            Assert.Throws <PythonException>(() =>
            {
                PythonRunner.RunString(importSystemInvalid);
            });
        }
Exemplo n.º 23
0
 public AdminService(FantasyCriticService fantasyCriticService, IFantasyCriticRepo fantasyCriticRepo, IMasterGameRepo masterGameRepo,
                     InterLeagueService interLeagueService, IOpenCriticService openCriticService, IClock clock, ILogger <OpenCriticService> logger, IRDSManager rdsManager,
                     RoyaleService royaleService, PythonRunner pythonRunner)
 {
     _fantasyCriticService = fantasyCriticService;
     _fantasyCriticRepo    = fantasyCriticRepo;
     _masterGameRepo       = masterGameRepo;
     _interLeagueService   = interLeagueService;
     _openCriticService    = openCriticService;
     _clock         = clock;
     _logger        = logger;
     _rdsManager    = rdsManager;
     _royaleService = royaleService;
     _pythonRunner  = pythonRunner;
 }
Exemplo n.º 24
0
        public async Task <KeyValuePair <bool, List <Mark> > > GetSecondMiddlePrediction(string groupCourseId)
        {
            var result = await Task.Run <bool>(() => PythonRunner.Run(OperationNames.PredictForSecondMiddle, groupCourseId));

            if (!result)
            {
                return(new KeyValuePair <bool, List <Mark> >(false, null));
            }

            var secondMiddle = (await lessonRepository.GetByGroupCourse(groupCourseId)).FirstOrDefault(l => l.LessonType == LessonType.SecondMiddle);

            var predictedMiddleMarks = await markRepository.GetPredictedMarksByLesson(secondMiddle.Id, (int)secondMiddle.LessonType);

            return(new KeyValuePair <bool, List <Mark> >(true, predictedMiddleMarks));
        }
Exemplo n.º 25
0
        private double getAnalysisResult(AnalyzeDocumentCommand command)
        {
            var scriptResult = PythonRunner.Run(
                _scriptsConfiguration.PerformAnalysis,
                command.FileId.ToString()
                );

            Console.WriteLine(scriptResult);
            var last = scriptResult.TrimEnd().Split("\n").Last();

            if (double.TryParse(last, out var result))
            {
                return(result);
            }
            throw new NotSupportedException(scriptResult);
        }
Exemplo n.º 26
0
 void DisplayResultSameThread(PythonRunner runner, PythonRunResult result)
 {
     if (result.hasError)
     {
         StdoutDisp.Text = "\n" + result.errorString;
     }
     else
     {
         string tableStr = "";
         foreach (KeyValuePair <string, object> de in result.returnedValues)
         {
             tableStr += de.Key + "=" + de.Value + "(" + de.Value.GetType() + ")\n";
         }
         StdoutDisp.Text = runner.stdout + "\n" + tableStr;
     }
 }
Exemplo n.º 27
0
 void DisplayResult(PythonRunner runner, PythonRunResult result)
 {
     if (result.hasError)
     {
         Application.Current.Dispatcher.Invoke(new Action(() => { StdoutDisp.Text = "\n" + result.errorString; }));
     }
     else
     {
         string tableStr = "";
         foreach (KeyValuePair <string, object> de in result.returnedValues)
         {
             tableStr += de.Key + "=" + de.Value + "(" + de.Value.GetType() + ")\n";
         }
         Application.Current.Dispatcher.Invoke(new Action(() => { StdoutDisp.Text = runner.stdout + "\n" + tableStr; }));
     }
 }
Exemplo n.º 28
0
        public async Task <JudgeResult> RunSubmissionAsync()
        {
            LanguageTypes.Base.Runner runner;
            switch (Submission.Program.Language)
            {
            case Language.C:
                runner = new CRunner(Contest, Problem, Submission, Box, Provider);
                break;

            case Language.Cpp:
                runner = new CppRunner(Contest, Problem, Submission, Box, Provider);
                break;

            case Language.Java:
                runner = new JavaRunner(Contest, Problem, Submission, Box, Provider);
                break;

            case Language.Python:
                runner = new PythonRunner(Contest, Problem, Submission, Box, Provider);
                break;

            case Language.Golang:
                runner = new GolangRunner(Contest, Problem, Submission, Box, Provider);
                break;

            case Language.Rust:
                runner = new RustRunner(Contest, Problem, Submission, Box, Provider);
                break;

            case Language.CSharp:
                runner = new CSharpRunner(Contest, Problem, Submission, Box, Provider);
                break;

            case Language.Haskell:
                runner = new HaskellRunner(Contest, Problem, Submission, Box, Provider);
                break;

            case Language.LabArchive:
                return(Problem.Type switch
                {
                    ProblemType.Ordinary => JudgeResult.UnknownLanguageFailure,
                    ProblemType.TestKitLab => await
                    new TestKitRunner(Contest, Problem, Submission, Box, Provider).RunSubmissionAsync(),
                    _ => throw new ArgumentOutOfRangeException()
                });
Exemplo n.º 29
0
        public void TestCanInstallPythonCheck()
        {
            // In order to have this function return true, python would need to not be installed
            // or loaded. However, this would require restarting Unity which is out of scope for this test.
            // Instead test all the cases where the function should return false.

            // With 0 versionStatus correct package is already installed, nothing to do
            Assert.That(PythonRunner.CanInstallPythonCheck(versionStatus: 0, localPackage: false), Is.False);
            Assert.That(PythonRunner.CanInstallPythonCheck(versionStatus: 0, localPackage: true), Is.False);

            // With versionStatus < 0, needsDowngrade, but don't do so immediately
            Assert.That(PythonRunner.CanInstallPythonCheck(versionStatus: -1, localPackage: false), Is.False);
            Assert.That(PythonRunner.CanInstallPythonCheck(versionStatus: -1, localPackage: true), Is.False);

            // With versionStatus > 0, needs upgrade but don't do so immediately
            Assert.That(PythonRunner.CanInstallPythonCheck(versionStatus: 1, localPackage: false), Is.False);
            Assert.That(PythonRunner.CanInstallPythonCheck(versionStatus: 1, localPackage: true), Is.False);
        }
Exemplo n.º 30
0
        static void CreateOrReinitialize()
        {
            // You can manually add the sample directory to your sys.path in
            // the Python Settings under site-packages. Or you can do it
            // programmatically like so.
            string dir = __DIR__();

            PythonRunner.EnsureInitialized();
            using (Py.GIL())
            {
                dynamic sys = PythonEngine.ImportModule("sys");
                if ((int)sys.path.count(dir) == 0)
                {
                    sys.path.append(dir);
                }
            }

            // Now that we've set up the path correctly, we can import the
            // Python side of this example as a module:
            PythonRunner.RunString(@"
                    import PySideExample

                    PySideExample.create_or_reinitialize()
                    ");

            // We can't register events in Python directly, so register them
            // here in C#:
            EditorApplication.hierarchyChanged += OnHierarchyChanged;
            EditorApplication.update           += OnUpdate;

            //
            // A domain reload happens when you change C# code or when you
            // launch into play mode (unless you selected the option not to
            // reload then).
            //
            // When it happens, your C# state is entirely reinitialized. The
            // Python state, however, remains as it was.
            //
            // To store information about what happened in the previous domain,
            // Unity provides the SessionState. Alternately we could have
            // stored the data in a variable in Python.
            //
            SessionState.SetBool(kStateName, true);
        }