Пример #1
0
        internal PythonInterpreter Clone()
        {
            var res = new PythonInterpreter();

            res.Id = Id;
            return(res);
        }
        internal async Task <IServiceManager> CreateServicesAsync(string root, InterpreterConfiguration configuration = null)
        {
            configuration = configuration ?? PythonVersions.LatestAvailable;
            configuration.AssertInstalled();
            Trace.TraceInformation("Cache Path: " + configuration.ModuleCachePath);
            configuration.ModuleCachePath = TestData.GetAstAnalysisCachePath(configuration.Version, true);
            configuration.SearchPaths     = new[] { GetAnalysisTestDataFilesPath() };
            configuration.TypeshedPath    = TestData.GetDefaultTypeshedPath();

            var sm = CreateServiceManager();

            sm.AddService(new DiagnosticsService());

            TestLogger.Log(TraceEventType.Information, "Create TestDependencyResolver");
            var dependencyResolver = new TestDependencyResolver();

            sm.AddService(dependencyResolver);

            TestLogger.Log(TraceEventType.Information, "Create PythonAnalyzer");
            var analyzer = new PythonAnalyzer(sm);

            sm.AddService(analyzer);

            TestLogger.Log(TraceEventType.Information, "Create PythonInterpreter");
            var interpreter = await PythonInterpreter.CreateAsync(configuration, root, sm);

            sm.AddService(interpreter);

            TestLogger.Log(TraceEventType.Information, "Create RunningDocumentTable");
            var documentTable = new RunningDocumentTable(root, sm);

            sm.AddService(documentTable);

            return(sm);
        }
 public ScenariosComponent(SandboxGame game, PenumbraComponent penumbra, PenumbraControllerComponent penumbraController, PythonInterpreter interpreter)
     : base(game)
 {
     _penumbra = penumbra;
     _penumbraController = penumbraController;
     _interpreter = interpreter;
 }
Пример #4
0
        public HelloPythonGame()
        {
            Window.Title = "Hello Python in MonoGame :)";
            _graphics    = new GraphicsDeviceManager(this)
            {
                PreferredBackBufferWidth  = 1280,
                PreferredBackBufferHeight = 720
            };

            // Create a sample cube component.
            var cube = new CubeComponent(this);

            Components.Add(cube);

            // Create a console component.
            _console = new ConsoleComponent(this);
            Components.Add(_console);

            // Create an interpreter - this will execute the commands typed into console.
            // In this case we are creating a python interpreter which allows python code to be executed.
            var interpreter = new PythonInterpreter();

            // Register the cube and the console itself as objects we can manipulate in-game.
            interpreter.AddVariable("cube", cube);
            interpreter.AddVariable("console", _console);
            // Finally, tell the console to use this interpreter.
            _console.Interpreter = interpreter;

            // Add component for on-screen helper instructions.
            Components.Add(new InstructionsComponent(this));
        }
Пример #5
0
        private void sbOk()
        {
            string strValidation;

            try
            {
                Script = txtCommand.Text;
                if (Script.Trim() != "")
                {
                    strValidation = PythonInterpreter.ValidatePython(Script);
                    if (strValidation.Trim() == "")
                    {
                        this.Close();
                    }
                    else
                    {
                        BMessage.Instance.fnMessage(strValidation, Properties.Resources.ResourceManager.GetString("AppName").ToString(), MessageBoxButton.OK, BMessage.enm_MessageImages.Critical);;
                    }
                }
                else
                {
                    this.Close();
                }
            }
            catch (Exception ex)
            {
                throw new Exception(Properties.Resources.ResourceManager.GetString("msgError").ToString(), ex);
            }
        }
Пример #6
0
        private static List <VariablesResult> CollectVariables(List <FilePatternVariables> variables, string file)
        {
            List <VariablesResult> result = new List <VariablesResult>();
            MatchCollection        objMatchs;
            List <string>          auxValues;

            try
            {
                foreach (FilePatternVariables filePatternVariablese in variables)
                {
                    result.Add(new VariablesResult()
                    {
                        Name = filePatternVariablese.Name, Values = new List <VariablesResultItem>()
                    });
                    objMatchs = Regex.Matches(file, filePatternVariablese.SearchPatern, regexOptions);
                    foreach (Match match in objMatchs)
                    {
                        if (match.Success &&
                            (filePatternVariablese.ExclusionPatern == null ||
                             filePatternVariablese.ExclusionPatern.Equals("") ||
                             Regex.Matches(match.Value, @filePatternVariablese.ExclusionPatern).Count == 0) &&
                            !string.IsNullOrEmpty(match.Value))
                        {
                            auxValues = new List <string>();
                            if (filePatternVariablese.Script != null &&
                                !filePatternVariablese.Script.Equals("") &&
                                PythonInterpreter.ValidatePython(pythonScript) == "")
                            {
                                auxValues.AddRange(PythonInterpreter.ProcessString(pythonScript, filePatternVariablese.Script, match.Value));
                            }
                            else
                            {
                                auxValues.Add(match.Value);
                            }
                            result.Last().Values.AddRange(auxValues.Select(value => new VariablesResultItem()
                            {
                                Value = value
                            }));
                        }
                    }

                    if (filePatternVariablese.Variables != null &&
                        filePatternVariablese.Variables.Count > 0)
                    {
                        result.Last().Values.ForEach(value =>
                        {
                            value.Variables = new List <VariablesResult>();
                            value.Variables.AddRange(CollectVariables(filePatternVariablese.Variables, value.Value));
                        });
                    }
                }
                return(result);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
Пример #7
0
 internal static bool IsSame(PythonInterpreter self, PythonInterpreter other)
 {
     if (self == null)
     {
         return(other == null);
     }
     else if (other != null)
     {
         return(self.Id == other.Id);
     }
     return(false);
 }
        public async Task TestPython(UploadViewModel model)
        {
            await Task.Delay(500);

            pythonInterpreter = new PythonInterpreter();
            var user = await FileHub.WaitForUserID(model.identifier.ToString());

            foreach (var item in model.documents)
            {
                TestFile(user, item);
            }
        }
Пример #9
0
        internal StandaloneTarget Clone()
        {
            var res = new StandaloneTarget();

            if (PythonInterpreter != null)
            {
                res.PythonInterpreter = PythonInterpreter.Clone();
            }

            res.InterpreterPath  = InterpreterPath;
            res.WorkingDirectory = WorkingDirectory;
            res.Script           = Script;
            res.Arguments        = Arguments;
            return(res);
        }
Пример #10
0
 internal static bool IsSame(StandaloneTarget self, StandaloneTarget other)
 {
     if (self == null)
     {
         return(other == null);
     }
     else if (other != null)
     {
         return(PythonInterpreter.IsSame(self.PythonInterpreter, other.PythonInterpreter) &&
                self.InterpreterPath == other.InterpreterPath &&
                self.WorkingDirectory == other.WorkingDirectory &&
                self.Script == other.Script &&
                self.Arguments == other.Arguments);
     }
     return(false);
 }
Пример #11
0
        /// <summary>
        /// Initialize all classes and set renderstates
        /// </summary>
        protected override void Initialize()
        {
            base.Initialize();

#if DEBUG
            // Initialize the python console
            console = new PythonInterpreter(this, consoleFont);
            console.AddGlobal("game", this);
#endif

            windowHandle = this.Window.Handle;

            IsFixedTimeStep   = true;
            TargetElapsedTime = new TimeSpan(10000000L / 30L);

            //graphics.ApplyChanges();
            LogicThread.Start();
        }
Пример #12
0
        public GMGame()
        {
            graphics = new GraphicsDeviceManager(this);
            graphics.PreferredBackBufferWidth  = 1366;
            graphics.PreferredBackBufferHeight = 768;


            console = new ConsoleComponent(this);
            console.TimeToToggleOpenClose = 0.05f;
            Components.Add(console);

            interpreter         = new PythonInterpreter();
            console.Interpreter = interpreter;

            interpreter.AddVariable("gm", this);

            Content.RootDirectory = "Content";
            world = new MainWorld(this);
        }
        protected async Task <IServiceManager> CreateServicesAsync(string root, InterpreterConfiguration configuration, IServiceManager sm = null)
        {
            configuration = configuration ?? PythonVersions.LatestAvailable;
            configuration.AssertInstalled();
            Trace.TraceInformation("Cache Path: " + configuration.DatabasePath);
            configuration.DatabasePath = TestData.GetAstAnalysisCachePath(configuration.Version, true);
            configuration.SearchPaths  = new[] { GetAnalysisTestDataFilesPath() };
            configuration.TypeshedPath = TestData.GetDefaultTypeshedPath();

            sm = sm ?? CreateServiceManager();

            var clientApp = Substitute.For <IClientApplication>();

            sm.AddService(clientApp);

            var idle = Substitute.For <IIdleTimeService>();

            sm.AddService(idle);

            var ds = GetDiagnosticsService(Services);

            if (ds != null)
            {
                sm.AddService(ds);
            }

            TestLogger.Log(TraceEventType.Information, "Create PythonAnalyzer");
            var analyzer = new PythonAnalyzer(sm);

            sm.AddService(analyzer);

            TestLogger.Log(TraceEventType.Information, "Create PythonInterpreter");
            var interpreter = await PythonInterpreter.CreateAsync(configuration, root, sm);

            sm.AddService(interpreter);

            TestLogger.Log(TraceEventType.Information, "Create RunningDocumentTable");
            var documentTable = new RunningDocumentTable(sm);

            sm.AddService(documentTable);

            return(sm);
        }
        public void ProcessStringTest()
        {
            string strCommand;
            string strreturn;

            try
            {
                strCommand = "def main(n):\r\n";
                strCommand = strCommand + "\treturn n.replace('<%TEST%>', '<%REPLACED%>')";
                strreturn  = PythonInterpreter.ProcessString(strCommand, "Command test = <%TEST%>");

                if (strreturn != "Command test = <%REPLACED%>")
                {
                    Assert.Fail("Wrong return: " + strreturn);
                }
            }
            catch (Exception ex)
            {
                Assert.Fail(ex.Message);
            }
        }
Пример #15
0
        protected async Task <IServiceManager> CreateServicesAsync(string root, InterpreterConfiguration configuration, string stubCacheFolderPath = null, IServiceManager sm = null, string[] searchPaths = null)
        {
            configuration = configuration ?? PythonVersions.LatestAvailable;
            configuration.AssertInstalled();
            Trace.TraceInformation("Cache Path: " + stubCacheFolderPath);

            searchPaths = searchPaths ?? new[] { GetAnalysisTestDataFilesPath() };
            var typeshedPath = TestData.GetDefaultTypeshedPath();

            sm = sm ?? CreateServiceManager();

            sm.AddService(Substitute.For <IClientApplication>())
            .AddService(Substitute.For <IIdleTimeService>());

            var ds = GetDiagnosticsService(Services);

            if (ds != null)
            {
                sm.AddService(ds);
            }

            TestLogger.Log(TraceEventType.Information, "Create PythonAnalyzer");

            CacheService.Register(sm, stubCacheFolderPath);
            var analyzer = new PythonAnalyzer(sm);

            sm.AddService(analyzer);

            TestLogger.Log(TraceEventType.Information, "Create PythonInterpreter");
            var interpreter = await PythonInterpreter.CreateAsync(configuration, root, sm, typeshedPath, searchPaths.ToImmutableArray());

            sm.AddService(interpreter);

            TestLogger.Log(TraceEventType.Information, "Create RunningDocumentTable");
            sm.AddService(new RunningDocumentTable(sm));

            return(sm);
        }
Пример #16
0
 /// <summary>
 /// When the controller is loaded generate a new python interpreter.
 /// </summary>
 public SetController()
 {
     Interpreter = new PythonInterpreter();
 }
Пример #17
0
 public virtual void Setup()
 {
     Input       = new FakeConsoleInput();
     Interpreter = new PythonInterpreter();
 }
Пример #18
0
        public Main()
        {
            self = this;

            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";

            // Set Width and Height og game screen
            graphics.PreferredBackBufferWidth  = Settings.Default.ScreenWidth;
            graphics.PreferredBackBufferHeight = Settings.Default.ScreenHeight;

            // Set windows start posion to center screen
            Window.Position = new Point((GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Width / 2) - (graphics.PreferredBackBufferWidth / 2), (GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Height / 2) - (graphics.PreferredBackBufferHeight / 2));

            // For detect FPS in FramerateCounter.cs
            graphics.SynchronizeWithVerticalRetrace = false;
            IsFixedTimeStep = false;

            // Restore fullscreen setting
            if (Settings.Default.FullScreen)
            {
                graphics.ToggleFullScreen();
            }
            graphics.ApplyChanges();

            // Initial ScreenTransition
            ScreenTransitions.FadeOUT();

            // Initial QuakeConsole
            console = new ConsoleComponent(this);
            Components.Add(console);

            // Add interpreter for QuakeConsole
            pythonInterpreter   = new PythonInterpreter();
            manualInterpreter   = new ManualInterpreter();
            console.Interpreter = manualInterpreter;

            // Add variable for PythonInterpreter
            pythonInterpreter.AddVariable("console", console);
            pythonInterpreter.AddVariable("manual", manualInterpreter);

            // Add command for ManualInterpreter
            manualInterpreter.RegisterCommand("fullscreen", args => {
                if (args.Length == 0)
                {
                    return;
                }
                else if (graphics.IsFullScreen && args[0].Equals("off"))
                {
                    graphics.ToggleFullScreen();
                }
                else if (!graphics.IsFullScreen && args[0].Equals("on"))
                {
                    graphics.ToggleFullScreen();
                }
            });
            manualInterpreter.RegisterCommand("fps", args => {
                if (args.Length == 0)
                {
                    return;
                }
                else if (args[0].Equals("on"))
                {
                    Settings.Default.ShowFPS = true;
                    Settings.Default.Save();
                }
                else if (args[0].Equals("off"))
                {
                    Settings.Default.ShowFPS = false;
                    Settings.Default.Save();
                }
            });
            manualInterpreter.RegisterCommand("Level", args => {
                if (args.Length < 2)
                {
                    return;
                }
                else if (args[0].Equals("="))
                {
                    Settings.Default.LevelSelected = int.Parse(args[1]);
                    Settings.Default.Save();
                }
            });
            manualInterpreter.RegisterCommand("console.Interpreter", args => {
                if (args.Length < 2)
                {
                    return;
                }
                else if (args[0].Equals("=") & args[1].Equals("python"))
                {
                    console.Interpreter = pythonInterpreter;
                }
            });
            manualInterpreter.RegisterCommand("exit", args => { Exit(); });
            manualInterpreter.RegisterCommand("ResetLevel", args => { ScreenManager.LoadScreen(new GamePlayScreen()); });

            BGM = Content.Load <Song>("Audios/POL-mad-run-short");
            MediaPlayer.IsRepeating = true;
            MediaPlayer.Volume      = Settings.Default.BGMVolume;
            MediaPlayer.Play(BGM);

            AudioManager.AddAudioEffect("click", Content.Load <SoundEffect>("Audios/NFF-select").CreateInstance());
            AudioManager.AddAudioEffect("shoot", Content.Load <SoundEffect>("Audios/NFF-rasp").CreateInstance());
            AudioManager.AddAudioEffect("die", Content.Load <SoundEffect>("Audios/NFF-lose").CreateInstance());
            AudioManager.AddAudioEffect("switch", Content.Load <SoundEffect>("Audios/NFF-click-switch").CreateInstance());
        }
Пример #19
0
        public async Task <InitializeResult> InitializeAsync(InitializeParams @params, CancellationToken cancellationToken)
        {
            _disposableBag.ThrowIfDisposed();
            _clientCaps = @params.capabilities;
            _log        = _services.GetService <ILogger>();

            _services.AddService(new DiagnosticsService(_services));

            var cacheFolderPath = @params.initializationOptions.cacheFolderPath;
            var fs = _services.GetService <IFileSystem>();

            if (cacheFolderPath != null && !fs.DirectoryExists(cacheFolderPath))
            {
                _log?.Log(TraceEventType.Warning, Resources.Error_InvalidCachePath);
                cacheFolderPath = null;
            }

            var analyzer = new PythonAnalyzer(_services, cacheFolderPath);

            _services.AddService(analyzer);

            analyzer.AnalysisComplete += OnAnalysisComplete;
            _disposableBag.Add(() => analyzer.AnalysisComplete -= OnAnalysisComplete);

            _services.AddService(new RunningDocumentTable(_services));
            _rdt = _services.GetService <IRunningDocumentTable>();

            _rootDir = @params.rootUri != null? @params.rootUri.ToAbsolutePath() : @params.rootPath;

            if (_rootDir != null)
            {
                _rootDir = PathUtils.NormalizePathAndTrim(_rootDir);
            }

            Version.TryParse(@params.initializationOptions.interpreter.properties?.Version, out var version);

            var configuration = new InterpreterConfiguration(null, null,
                                                             interpreterPath: @params.initializationOptions.interpreter.properties?.InterpreterPath,
                                                             version: version
                                                             )
            {
                // Split on ';' to support older VS Code extension versions which send paths as a single entry separated by ';'. TODO: Eventually remove.
                // Note that the actual classification of these paths as user/library is done later in MainModuleResolution.ReloadAsync.
                SearchPaths = @params.initializationOptions.searchPaths
                              .Select(p => p.Split(';', StringSplitOptions.RemoveEmptyEntries)).SelectMany()
                              .ToList(),
                TypeshedPath = @params.initializationOptions.typeStubSearchPaths.FirstOrDefault()
            };

            _interpreter = await PythonInterpreter.CreateAsync(configuration, _rootDir, _services, cancellationToken);

            _services.AddService(_interpreter);

            var fileSystem = _services.GetService <IFileSystem>();

            _indexManager = new IndexManager(fileSystem, _interpreter.LanguageVersion, _rootDir,
                                             @params.initializationOptions.includeFiles,
                                             @params.initializationOptions.excludeFiles,
                                             _services.GetService <IIdleTimeService>());
            _indexManager.IndexWorkspace().DoNotWait();
            _services.AddService(_indexManager);
            _disposableBag.Add(_indexManager);

            DisplayStartupInfo();

            _completionSource = new CompletionSource(
                ChooseDocumentationSource(_clientCaps?.textDocument?.completion?.completionItem?.documentationFormat),
                Settings.completion
                );

            _hoverSource = new HoverSource(
                ChooseDocumentationSource(_clientCaps?.textDocument?.hover?.contentFormat)
                );

            var sigInfo = _clientCaps?.textDocument?.signatureHelp?.signatureInformation;

            _signatureSource = new SignatureSource(
                ChooseDocumentationSource(sigInfo?.documentationFormat),
                sigInfo?.parameterInformation?.labelOffsetSupport == true
                );

            return(GetInitializeResult());
        }
Пример #20
0
        private void DrawGridScript()
        {
            if (CorrectedSubjects != null)
            {
                if (Program.Test.Code != null)
                {
                    // Create columns
                    if (Program.Test.Code.OutputVariables != null)
                    {
                        for (int i = 0; i < Program.Test.Code.OutputVariables.Count; i++)
                        {
                            dataGrid.Columns.Add(Program.Test.Code.OutputVariables[i].Name, Program.Test.Code.OutputVariables[i].Name);
                        }
                    }

                    var interp = new PythonInterpreter();
                    try
                    {
                        interp.Initialize(Program.Test.Code);
                        Fraction total = new Fraction();
                        // Create rows
                        for (int i = 0; i < CorrectedSubjects.Count; i++)
                        {
                            dataGrid.Rows.Add(1);
                            int  row          = dataGrid.RowCount - 1;
                            bool errorAnalyse = false;

                            // Not enough pages (or too many):
                            if (CorrectedSubjects[i].CorrectedPages.Count != Program.Test.Pages.Count)
                            {
                                errorAnalyse = true;
                            }
                            else
                            {
                                // Some error on page level?
                                for (int j = 0; j < CorrectedSubjects[i].CorrectedPages.Count; j++)
                                {
                                    if (!CorrectedSubjects[i].CorrectedPages[j].Status.Analyzed || CorrectedSubjects[i].CorrectedPages[j].Status.BarCodeError ||
                                        CorrectedSubjects[i].CorrectedPages[j].Status.CalibrationError || CorrectedSubjects[i].CorrectedPages[j].Status.ContainsDoubts ||
                                        CorrectedSubjects[i].CorrectedPages[j].Status.PageNumberOrHashError)
                                    {   // Error "too many checked" is allowed
                                        errorAnalyse = true;
                                        break;
                                    }
                                }
                            }

                            if (errorAnalyse)
                            {
                                dataGrid.Rows[row].DefaultCellStyle.BackColor = Color.Red;
                            }

                            dataGrid.Rows[row].Cells[0].Value = CorrectedSubjects[i].Id;
                            dataGrid.Rows[row].Cells[1].Value = CorrectedSubjects[i].PageCount();
                            if (!errorAnalyse)
                            {
                                var outputVars = interp.Score(CorrectedSubjects[i]);
                                currentNumberOfOutputVars = outputVars.Count;
                                for (int j = 0; j < outputVars.Count; j++)
                                {
                                    if (outputVars[j].Value != null)
                                    {
                                        dataGrid.Rows[i].Cells[outputVars[j].Name].Value = Math.Round(outputVars[j].Value.ToDecimal(), Program.UserSettings.numberOfDecimalsInResults);
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Error in script:\r\n" + interp.engine.GetService <ExceptionOperations>().FormatException(ex), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
        }
Пример #21
0
        public async Task <InitializeResult> InitializeAsync(InitializeParams @params, CancellationToken cancellationToken)
        {
            _disposableBag.ThrowIfDisposed();
            _clientCaps = @params.capabilities;
            _log        = _services.GetService <ILogger>();

            _services.AddService(new DiagnosticsService(_services));

            var analyzer = new PythonAnalyzer(_services);

            _services.AddService(analyzer);

            _services.AddService(new RunningDocumentTable(_services));
            _rdt = _services.GetService <IRunningDocumentTable>();

            // TODO: multi-root workspaces.
            var rootDir = @params.rootUri != null? @params.rootUri.ToAbsolutePath() : PathUtils.NormalizePath(@params.rootPath);

            Version.TryParse(@params.initializationOptions.interpreter.properties?.Version, out var version);

            var configuration = new InterpreterConfiguration(null, null,
                                                             interpreterPath: @params.initializationOptions.interpreter.properties?.InterpreterPath,
                                                             moduleCachePath: @params.initializationOptions.interpreter.properties?.DatabasePath,
                                                             version: version
                                                             )
            {
                // TODO: Remove this split once the extension is updated and no longer passes the interpreter search paths directly.
                // This is generally harmless to keep around.
                SearchPaths  = @params.initializationOptions.searchPaths.Select(p => p.Split(';', StringSplitOptions.RemoveEmptyEntries)).SelectMany().ToList(),
                TypeshedPath = @params.initializationOptions.typeStubSearchPaths.FirstOrDefault()
            };

            _interpreter = await PythonInterpreter.CreateAsync(configuration, rootDir, _services, cancellationToken);

            _services.AddService(_interpreter);

            var fileSystem = _services.GetService <IFileSystem>();

            _indexManager = new IndexManager(fileSystem, _interpreter.LanguageVersion, rootDir,
                                             @params.initializationOptions.includeFiles,
                                             @params.initializationOptions.excludeFiles,
                                             _services.GetService <IIdleTimeService>());
            _indexManager.IndexWorkspace().DoNotWait();
            _services.AddService(_indexManager);
            _disposableBag.Add(_indexManager);

            DisplayStartupInfo();

            _completionSource = new CompletionSource(
                ChooseDocumentationSource(_clientCaps?.textDocument?.completion?.completionItem?.documentationFormat),
                Settings.completion
                );

            _hoverSource = new HoverSource(
                ChooseDocumentationSource(_clientCaps?.textDocument?.hover?.contentFormat)
                );

            _signatureSource = new SignatureSource(
                ChooseDocumentationSource(_clientCaps?.textDocument?.signatureHelp?.signatureInformation?.documentationFormat)
                );

            return(GetInitializeResult());
        }
Пример #22
0
        public async Task InitializedAsync(InitializedParams @params, CancellationToken cancellationToken = default, IReadOnlyList <string> userConfiguredPaths = null)
        {
            var initializationOptions = _initParams?.initializationOptions;

            _services.AddService(new DiagnosticsService(_services));

            _analyzer = new PythonAnalyzer(_services);
            _services.AddService(_analyzer);

            _analyzer.AnalysisComplete += OnAnalysisComplete;
            _disposableBag.Add(() => _analyzer.AnalysisComplete -= OnAnalysisComplete);

            _services.AddService(new RunningDocumentTable(_services));
            _rdt = _services.GetService <IRunningDocumentTable>();

            var     interpeterPath = initializationOptions?.interpreter.properties?.InterpreterPath;
            Version version        = null;

            if (!string.IsNullOrWhiteSpace(interpeterPath))
            {
                Version.TryParse(initializationOptions?.interpreter.properties?.Version, out version);
            }
            else
            {
                var fs      = _services.GetService <IFileSystem>();
                var exePath = PathUtils.LookPath(fs, "python");
                if (exePath != null && TryGetPythonVersion(exePath, out version))
                {
                    _log?.Log(TraceEventType.Information, Resources.UsingPythonFromPATH);
                    interpeterPath = exePath;
                }
                else
                {
                    interpeterPath = null;
                }
            }

            var configuration = new InterpreterConfiguration(
                interpreterPath: interpeterPath,
                version: version
                );
            //_services.AddService(new ModuleDatabase(_services));

            var typeshedPath = initializationOptions?.typeStubSearchPaths.FirstOrDefault();

            userConfiguredPaths = userConfiguredPaths ?? initializationOptions?.searchPaths;
            _interpreter        = await PythonInterpreter.CreateAsync(configuration, Root, _services, typeshedPath, userConfiguredPaths.ToImmutableArray(), cancellationToken);

            _log?.Log(TraceEventType.Information,
                      string.IsNullOrEmpty(_interpreter.Configuration.InterpreterPath)
                ? Resources.InitializingForGenericInterpreter
                : Resources.InitializingForPythonInterpreter.FormatInvariant(_interpreter.Configuration.InterpreterPath));

            var fileSystem = _services.GetService <IFileSystem>();

            _indexManager = new IndexManager(fileSystem, _interpreter.LanguageVersion, Root,
                                             initializationOptions?.includeFiles,
                                             initializationOptions?.excludeFiles,
                                             _services.GetService <IIdleTimeService>());

            _indexManager.IndexWorkspace().DoNotWait();
            _analyzer.AnalysisComplete += IndexLibraries;
            _disposableBag.Add(() => _analyzer.AnalysisComplete -= IndexLibraries);
            _services.AddService(_indexManager);
            _disposableBag.Add(_indexManager);

            var textDocCaps = _initParams?.capabilities?.textDocument;

            _completionSource = new CompletionSource(
                ChooseDocumentationSource(textDocCaps?.completion?.completionItem?.documentationFormat),
                Settings.completion, Services
                );

            _hoverSource = new HoverSource(
                ChooseDocumentationSource(textDocCaps?.hover?.contentFormat)
                );

            var sigInfo = textDocCaps?.signatureHelp?.signatureInformation;

            _signatureSource = new SignatureSource(
                ChooseDocumentationSource(sigInfo?.documentationFormat),
                sigInfo?.parameterInformation?.labelOffsetSupport == true
                );

            _initialized = true;
        }
Пример #23
0
        public async Task <InitializeResult> InitializeAsync(InitializeParams @params, CancellationToken cancellationToken)
        {
            _disposableBag.ThrowIfDisposed();
            _clientCaps = @params.capabilities;
            _log        = _services.GetService <ILogger>();

            _services.AddService(new DiagnosticsService(_services));

            var analyzer = new PythonAnalyzer(_services);

            _services.AddService(analyzer);

            _services.AddService(new RunningDocumentTable(_services));
            _rdt = _services.GetService <IRunningDocumentTable>();

            _rootDir = @params.rootUri != null? @params.rootUri.ToAbsolutePath() : @params.rootPath;

            if (_rootDir != null)
            {
                _rootDir = PathUtils.NormalizePath(_rootDir);
                _rootDir = PathUtils.TrimEndSeparator(_rootDir);
            }

            Version.TryParse(@params.initializationOptions.interpreter.properties?.Version, out var version);

            var configuration = new InterpreterConfiguration(null, null,
                                                             interpreterPath: @params.initializationOptions.interpreter.properties?.InterpreterPath,
                                                             moduleCachePath: @params.initializationOptions.interpreter.properties?.DatabasePath,
                                                             version: version
                                                             )
            {
                // 1) Split on ';' to support older VS Code extension versions which send paths as a single entry separated by ';'. TODO: Eventually remove.
                // 2) Normalize paths.
                // 3) If a path isn't rooted, then root it relative to the workspace root. If _rootDir is null, then accept the path as-is.
                // 4) Trim off any ending separator for a consistent style.
                // 5) Filter out any entries which are the same as the workspace root; they are redundant. Also ignore "/" to work around the extension (for now).
                // 6) Remove duplicates.
                SearchPaths = @params.initializationOptions.searchPaths
                              .Select(p => p.Split(';', StringSplitOptions.RemoveEmptyEntries)).SelectMany()
                              .Select(PathUtils.NormalizePath)
                              .Select(p => _rootDir == null || Path.IsPathRooted(p) ? p : Path.GetFullPath(p, _rootDir))
                              .Select(PathUtils.TrimEndSeparator)
                              .Where(p => !string.IsNullOrWhiteSpace(p) && p != "/" && !p.PathEquals(_rootDir))
                              .Distinct(PathEqualityComparer.Instance)
                              .ToList(),
                TypeshedPath = @params.initializationOptions.typeStubSearchPaths.FirstOrDefault()
            };

            _interpreter = await PythonInterpreter.CreateAsync(configuration, _rootDir, _services, cancellationToken);

            _services.AddService(_interpreter);

            var fileSystem = _services.GetService <IFileSystem>();

            _indexManager = new IndexManager(fileSystem, _interpreter.LanguageVersion, _rootDir,
                                             @params.initializationOptions.includeFiles,
                                             @params.initializationOptions.excludeFiles,
                                             _services.GetService <IIdleTimeService>());
            _indexManager.IndexWorkspace().DoNotWait();
            _services.AddService(_indexManager);
            _disposableBag.Add(_indexManager);

            DisplayStartupInfo();

            _completionSource = new CompletionSource(
                ChooseDocumentationSource(_clientCaps?.textDocument?.completion?.completionItem?.documentationFormat),
                Settings.completion
                );

            _hoverSource = new HoverSource(
                ChooseDocumentationSource(_clientCaps?.textDocument?.hover?.contentFormat)
                );

            _signatureSource = new SignatureSource(
                ChooseDocumentationSource(_clientCaps?.textDocument?.signatureHelp?.signatureInformation?.documentationFormat)
                );

            return(GetInitializeResult());
        }
Пример #24
0
    // Use this for initialization
    public void Awake()
    {
        numberofASVs = Random.Range(50, 50);         //Defines the number of ASVs to be spawned between the range of 3 and 10
        //Debug.Log(numberofASVs); //Print this value

        for (int i = 0; i < numberofASVs; i++) //Do the code below for every ASV which has been spawned
        {
            //float angle = i * Mathf.PI*2f / numberofASVs;
            //Debug.Log((180*angle)/Mathf.PI);

            Vector3 position = new Vector3(Random.Range(minxpos, maxxpos), Random.Range(0.5f, 0.5f), Random.Range(minzpos, maxzpos)); //Randomly generate the position with the bounds defined above
            Debug.Log(position);                                                                                                      //Print this value
            GameObject ASV       = Instantiate(prefabASV, position, Quaternion.identity) as GameObject;                               //Generate the ASV prefab as a new game object at the location generated above
            int        j         = i + 1;
            string     ASVnumber = j.ToString();
            ASV.name = ASV.name.Replace("(Clone)", " " + ASVnumber); // Convert ASV name to specific number for ASV

            Names.Add(j);

            if (position.x > 0)
            {
                if (position.z > 0)
                {
                    AngleFromObject = 180 * (Mathf.PI / 2 - Mathf.Atan(Mathf.Abs(position.z) / Mathf.Abs(position.x))) / Mathf.PI;
                }
                else
                {
                    AngleFromObject = 180 * (Mathf.PI - Mathf.Atan(Mathf.Abs(position.x) / Mathf.Abs(position.z))) / Mathf.PI;
                }
            }
            if (position.x < 0)
            {
                if (position.z < 0)
                {
                    AngleFromObject = 180 * ((3 * Mathf.PI) / 2 - Mathf.Atan(Mathf.Abs(position.z) / Mathf.Abs(position.x))) / Mathf.PI;
                }
                else
                {
                    AngleFromObject = 180 * (2 * Mathf.PI - Mathf.Atan(Mathf.Abs(position.x) / Mathf.Abs(position.z))) / Mathf.PI;
                }
            }
            Angles.Add(AngleFromObject);
        }
        IList ASV_Order = PythonInterpreter.PatchParameter(Names, Angles) as IList;

        for (int i = 0; i < numberofASVs; i++)
        {
            ASVNum  = System.Convert.ToInt32(ASV_Order[i]);
            ASVNum += 1;
            temp    = "ASV " + ASVNum.ToString();
            if (Counter == 0)
            {
                TargetAngle = 0;
                Counter    += 1;
            }

            else
            {
                TargetAngle = 360 / (numberofASVs / Counter);
                Counter    += 1;
            }

            ASVn = GameObject.Find(temp);
            var script = ASVn.GetComponent <ASVController>();
            script.TargetAngle = TargetAngle;
            script.ASVName     = temp;
            script.MinDist     = ObjSize;

            Debug.Log(ASVNum + ", " + TargetAngle);
        }
    }
        public static string ToPDF(this Worksets set)
        {
            var time = DateTime.Now.ToString("dd-hh-mm hh-MM-ss");
            var path = AppContext.BaseDirectory + "/prints/";

            if (!File.Exists(path + set.WorksetName + "-" + time + ".pdf"))
            {
                Directory.CreateDirectory(path);
                File.Create(path + set.WorksetName + "-" + time + ".pdf").Close();
            }
            writer   = new PdfWriter(path + set.WorksetName + "-" + time + ".pdf");
            pdf      = new PdfDocument(writer);
            document = new Document(pdf, Page);


            Paragraph p = new Paragraph().Add(new Text(set.WorksetName + "\n\n").SetBold().SetUnderline().SetFontSize(22f)).SetTextAlignment(TextAlignment.CENTER);

            document.Add(p);

            Table tbl = new Table(1);

            tbl.SetWidth(UnitValue.CreatePercentValue(100));

            var interpreter = new PythonInterpreter();
            var work        = DatabaseConnector.GetWhere <Work>($"WorksetID={set.WorksetID}");

            for (int i = 0; i < work.Length; i++)
            {
                var   question = interpreter.GenerateQuestion(AppContext.BaseDirectory + @"wwwroot\lib\Python\" + DatabaseConnector.Get <QuestionTypes>().SingleOrDefault(x => x.TypeID == work[i].QuestionType).Class, work[i].Seed);
                Table qTbl     = new Table(1);
                qTbl.SetKeepTogether(true);
                qTbl.SetWidth(UnitValue.CreatePercentValue(100));

                var qCell = new Cell().Add(new Paragraph("Question " + i + ":").SetBold()).SetTextAlignment(TextAlignment.CENTER).SetBorderLeft(Border.NO_BORDER).SetBorderRight(Border.NO_BORDER).SetBorderTop(Border.NO_BORDER);
                var AskQ  = new Cell().Add(new Paragraph(question.GetQuestion() as string)).SetTextAlignment(TextAlignment.LEFT).SetVerticalAlignment(VerticalAlignment.TOP).SetBorder(Border.NO_BORDER);
                var ans   = question.Answer("");
                qTbl.AddCell(qCell).AddCell(AskQ);
                if (ans.Contains(","))
                {
                    var answerTitles = question.Boxes().Split(',');
                    var workcell     = new Cell().Add(new Paragraph("   ").SetTextAlignment(TextAlignment.RIGHT).SetVerticalAlignment(VerticalAlignment.BOTTOM)).SetVerticalAlignment(VerticalAlignment.BOTTOM).SetHeight(60f).SetBorder(Border.NO_BORDER);
                    qTbl.AddCell(workcell);
                    for (int q = 0; q < answerTitles.Length; q++)
                    {
                        try
                        {
                            var AnsCell = new Cell().Add(new Paragraph(answerTitles[q] + ": ___________________.").SetTextAlignment(TextAlignment.RIGHT).SetVerticalAlignment(VerticalAlignment.BOTTOM)).SetVerticalAlignment(VerticalAlignment.BOTTOM).SetHeight(70f).SetBorder(Border.NO_BORDER);
                            qTbl.AddCell(AnsCell);
                        }
                        catch (IndexOutOfRangeException)
                        {
                            var AnsCell = new Cell().Add(new Paragraph("Answer" + q + ": ___________________.").SetTextAlignment(TextAlignment.RIGHT).SetVerticalAlignment(VerticalAlignment.BOTTOM)).SetVerticalAlignment(VerticalAlignment.BOTTOM).SetHeight(70f).SetBorder(Border.NO_BORDER);
                            qTbl.AddCell(AnsCell);
                        }
                    }
                }
                else
                {
                    var AnsCell = new Cell().Add(new Paragraph("Answer: ___________________.").SetTextAlignment(TextAlignment.RIGHT).SetVerticalAlignment(VerticalAlignment.BOTTOM)).SetVerticalAlignment(VerticalAlignment.BOTTOM).SetHeight(70f).SetBorder(Border.NO_BORDER);
                    qTbl.AddCell(AnsCell);
                }

                var cell = new Cell();
                cell.Add(qTbl);
                tbl.AddCell(cell);
            }


            document.Add(tbl);

            document.Close();
            return(path + set.WorksetName + "-" + time + ".pdf");
        }
Пример #26
0
 /// <summary>
 /// Create a PythonInterpreterView with values from a PythonInterpreter.
 /// </summary>
 public PythonInterpreterView(PythonInterpreter interpreter)
 {
     _name = null;
     _id   = interpreter.Id;
     _path = null;
 }
Пример #27
0
        public String fnExecuteText(Card p_card)
        {
            String           strReturn;
            DataSet          objReturn;
            DataSet          objAuxReturn;
            String           strCommand;
            List <Parameter> objAuxParameter;
            List <string>    strStatements;
            int    intTableIndex;
            string strTableName;

            try
            {
                strReturn    = "";
                objAuxReturn = null;

                strCommand = p_card.Command;
                if (strCommand.Trim() != "")
                {
                    //Execute pre python script
                    if (p_card.PrePythonScript.Trim() != "")
                    {
                        strCommand = PythonInterpreter.ProcessString(p_card.PrePythonScript, strCommand);
                    }

                    //Execute python script by parameter
                    objAuxParameter = PythonInterpreter.ProcessParameters(p_card.Parameters);

                    foreach (Parameter parameter in objAuxParameter)
                    {
                        strCommand = strCommand.Replace(parameter.Tag, parameter.Value);
                    }

                    //Separete statements
                    strStatements = strCommand.Split(new string[] { "<!STATEMENT!>" }, StringSplitOptions.None).ToList();

                    objReturn     = new DataSet();
                    intTableIndex = 0;
                    foreach (string statement in strStatements)
                    {
                        strCommand   = statement;
                        strTableName = SpinerBaseBO.Instance.fnGetTableName(strCommand);
                        strCommand   = SpinerBaseBO.Instance.fnRemoveSpecialTags(strCommand);
                        strCommand   = fnRecursiveReplace(strCommand, objReturn);
                        objAuxReturn = objDataBase.fnExecute(strCommand);
                        foreach (DataTable table in objAuxReturn.Tables)
                        {
                            if (strTableName.Trim() != "")
                            {
                                table.TableName = strTableName;
                            }
                            else
                            {
                                table.TableName = "table_" + intTableIndex.ToString();
                            }
                            objReturn.Tables.Add(table.Copy());
                            intTableIndex++;
                        }
                    }

                    foreach (DataTable table in objReturn.Tables)
                    {
                        if (objReturn.Tables.Count > 1)
                        {
                            strReturn = strReturn + table.TableName + ":" + (char)13 + (char)10;
                        }
                        foreach (DataRow row in table.Rows)
                        {
                            foreach (DataColumn column in table.Columns)
                            {
                                strReturn = strReturn + row[column.ColumnName].ToString() + (char)9;
                            }
                            strReturn = strReturn + (char)13 + (char)10;
                        }
                    }

                    //Execute pos python script
                    if (p_card.PosPythonScript.Trim() != "")
                    {
                        strReturn = PythonInterpreter.ProcessString(p_card.PosPythonScript, strReturn);
                    }
                }
                else
                {
                    throw new Exception("Empty command");
                }
            }
            catch (DataBaseException exbd)
            {
                if (exbd.Code != DataBaseException.enmDataBaseExeptionCode.NotExists && !exbd.Message.Trim().ToUpper().Contains("NOT EXISTS"))
                {
                    throw new Exception(exbd.Message, exbd);
                }
                else
                {
                    strReturn = "";
                }
            }
            catch (Exception)
            {
                throw;
            }

            return(strReturn);
        }
Пример #28
0
        public async Task InitializedAsync(InitializedParams @params, CancellationToken cancellationToken = default, IReadOnlyList <string> userConfiguredPaths = null)
        {
            var initializationOptions = _initParams?.initializationOptions;

            _services.AddService(new DiagnosticsService(_services));

            var cacheFolderPath = initializationOptions?.cacheFolderPath;
            var fs = _services.GetService <IFileSystem>();

            if (cacheFolderPath != null && !fs.DirectoryExists(cacheFolderPath))
            {
                _log?.Log(TraceEventType.Warning, Resources.Error_InvalidCachePath);
                cacheFolderPath = null;
            }

            var analyzer = new PythonAnalyzer(_services, cacheFolderPath);

            _services.AddService(analyzer);

            analyzer.AnalysisComplete += OnAnalysisComplete;
            _disposableBag.Add(() => analyzer.AnalysisComplete -= OnAnalysisComplete);

            _services.AddService(new RunningDocumentTable(_services));
            _rdt = _services.GetService <IRunningDocumentTable>();

            Version.TryParse(initializationOptions?.interpreter.properties?.Version, out var version);

            var configuration = new InterpreterConfiguration(null, null,
                                                             interpreterPath: initializationOptions?.interpreter.properties?.InterpreterPath,
                                                             version: version
                                                             );

            var typeshedPath = initializationOptions?.typeStubSearchPaths.FirstOrDefault();

            userConfiguredPaths = userConfiguredPaths ?? initializationOptions?.searchPaths;
            _interpreter        = await PythonInterpreter.CreateAsync(configuration, Root, _services, typeshedPath, userConfiguredPaths.ToImmutableArray(), cancellationToken);

            _services.AddService(_interpreter);

            _log?.Log(TraceEventType.Information,
                      string.IsNullOrEmpty(_interpreter.Configuration.InterpreterPath)
                ? Resources.InitializingForGenericInterpreter
                : Resources.InitializingForPythonInterpreter.FormatInvariant(_interpreter.Configuration.InterpreterPath));

            var fileSystem = _services.GetService <IFileSystem>();

            _indexManager = new IndexManager(fileSystem, _interpreter.LanguageVersion, Root,
                                             initializationOptions?.includeFiles,
                                             initializationOptions?.excludeFiles,
                                             _services.GetService <IIdleTimeService>());
            _indexManager.IndexWorkspace().DoNotWait();
            _services.AddService(_indexManager);
            _disposableBag.Add(_indexManager);

            var textDocCaps = _initParams?.capabilities?.textDocument;

            _completionSource = new CompletionSource(
                ChooseDocumentationSource(textDocCaps?.completion?.completionItem?.documentationFormat),
                Settings.completion
                );

            _hoverSource = new HoverSource(
                ChooseDocumentationSource(textDocCaps?.hover?.contentFormat)
                );

            var sigInfo = textDocCaps?.signatureHelp?.signatureInformation;

            _signatureSource = new SignatureSource(
                ChooseDocumentationSource(sigInfo?.documentationFormat),
                sigInfo?.parameterInformation?.labelOffsetSupport == true
                );
        }