상속: NewTOAPIA.GL.GLModel
        /// <summary>
        /// Converts board to neurel net training example.  Returns example corresopnding to normalized board (current player's checker color is blue, last player is green)
        /// </summary>
        /// <param name="lastPlayerToGo">Current Player which corresponds to last checker placed on board.</param>
        public static Example ToNormalizedExample(Board board, Checker lastPlayerToGo)
        {
            Debug.Assert(lastPlayerToGo != Checker.Empty);
            List<double> boardState = board.Cells.Cast<Checker>().Select(c=>Transform.ToNormalizedValue(c, lastPlayerToGo)).ToList();
            List<int> features = new List<int>();

            // 42 Input Units - Board State Only
            // return new Example(boardState);

            foreach (Checker checker in new List<Checker> { lastPlayerToGo, Board.Toggle(lastPlayerToGo) })
            {
                features.AddRange(board.LineOfX(checker));
                features.AddRange(board.LineOfX(checker, potential: true));
                features.AddRange(board.NumbersInColumns(checker));
                features.AddRange(board.NumbersInRows(checker));
                features.Add(board.NumberOnBoard(checker));
            }
            boardState.AddRange(features.Select(e => (double)e));

            // 40 Input Units - Features Only
            //return new Example(features.Select(e => (double)e).ToList());

            // 82 Input Units - Board State and Features
            return new Example(boardState);
        }
예제 #2
0
        public static void UpdateCheckersList()
        {
            try
            {
                using (StreamReader sr = new StreamReader(LocalPath.AbsoluteCheckersDirectory + "stdCheckers.inf"))
                {
                    Checker temp;
                    int id = 1;
                    while (!sr.EndOfStream)
                    {
                        temp = new Checker()
                            {
                                CheckerID = id.ToString(),
                                FileName = sr.ReadLine(),
                                Description = sr.ReadLine()
                            };
                        temp.Available = File.Exists(LocalPath.AbsoluteCheckersDirectory + temp.FileName);

                        checkers.Add(temp);
                        id++;
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error("Error occurred on updating checker list:", ex);
            }
        }
예제 #3
0
 public static CheckResults Check(string sqlToCheck, params string[] arguments)
 {
     var allArguments = arguments.ToList();
     allArguments.Add("/i:" + sqlToCheck);
     Checker c = new Checker(new Arguments(allArguments.ToArray()));
     return c.Run();
 }
예제 #4
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="refUser">User data</param>
 public MinimizeCondition(UserData refUser)
     : base(refUser)
 {
     m_nIndex = 0;
     m_refChecker = new Checker(refUser, PropertiesPluginKinect.Instance.MinimizeCherckerTolerance);
     m_GestureBegin = false;
 }
예제 #5
0
        public void _002_Can_Make_Move()
        {
            var game = new Game
            {
                Board = new Board(),
                Player1 = new FakePlayer(true),
                Player2 = new FakePlayer(false),
                CheckersSet = new List<Checker>
                {
                    new Checker(true, false,  new Coordinate(2, 1)),
                    new Checker(true, false,  new Coordinate(3, 4)),
                    new Checker(false, false, new Coordinate(1, 2)),
                    new Checker(false, false, new Coordinate(2, 5)),
                    new Checker(false, false, new Coordinate(4, 5)),
                }
            };
            game.CurrentPlayer = game.Player1;

            game.Move = new Move();

            var moveStartCoordinate = game.ConvertIntoCoordinates(game.CurrentPlayer.EnterCoordinates());
            game.Move.AddCoordinate(moveStartCoordinate);

            var moveEndCoordinate = game.ConvertIntoCoordinates("c5");
            game.Move.AddCoordinate(moveEndCoordinate);

            game.MoveChecker();

            var actual = game.GetChecker(moveEndCoordinate);
            var expected = new Checker(true, false, new Coordinate(3, 2));

            Assert.AreEqual(expected, actual);
        }
예제 #6
0
 protected Bot(Checker myColor, double? lambda = null, LambdaType? lambdaType = null)
 {
     Debug.Assert(myColor != Checker.Empty);
     MyColor = myColor;
     Lambda = lambda ?? 0.05;
     LambdaType = lambdaType ?? LambdaType.ProbabilityDistribution;
 }
예제 #7
0
파일: FrmCheck.cs 프로젝트: hy1314200/HyDM
        private void Check()
        {
            if (m_Task == null)
                return;

            Checker checker = new Checker();
            checker.CheckingRuleChanged += new DealingRuleChangedHandler(checker_PretreatingRuleChanged);
            checker.PretreatingRuleChanged += new DealingRuleChangedHandler(checker_PretreatingRuleChanged);
            checker.VerifyedComplete += new VerifyedCompleteHandler(checker_VerifyedComplete);
            checker.VerifyingRuleChanged += new DealingRuleChangedHandler(checker_PretreatingRuleChanged);
            checker.PretreatComplete += new CheckEventHandler(checker_PretreatComplete);

            checker.BaseWorkspace = m_Task.BaseWorkspace;
            checker.QueryConnection = m_Task.QueryConnection;
            checker.QueryWorkspace = m_Task.QueryWorkspace;
            checker.ResultPath = m_Task.GetResultDBPath();
            TemplateRules templateRules = new TemplateRules(m_Task.SchemaID);
            checker.RuleInfos = templateRules.CurrentSchemaRules; //Helper.RuleInfoHelper.GetRuleInfos(m_Task.SchemaID);
            checker.SchemaID = m_Task.SchemaID;
            checker.TopoDBPath = m_Task.GetTaskFolder();
            checker.TopoTolerance = m_Task.TopoTolerance;

            Common.Utility.Log.TaskLogManager.SetLogFile("f:\\CheckLog.log");
            checker.Messager = LogDeal;
            if (checker.Check())
            {
                MessageBox.Show("成功");
            }
            else
            {
                MessageBox.Show("失败");
            }
        }
예제 #8
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="refUser">User Data</param>
 public PostureHomeCondition(UserData refUser)
     : base(refUser)
 {
     m_nIndex = 0;
     m_frameInitCounter = 0;
     m_refChecker = new Checker(refUser, PropertiesPluginKinect.Instance.PostureCheckerTolerance);
     m_GestureBegin = false;
 }
예제 #9
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="refUser">User data</param>
 /// <param name="hand"> hand treated</param>
 public WaveLeftCondition(UserData refUser, JointType hand)
     : base(refUser)
 {
     m_nIndex = 0;
     m_nTryCondition = 0;
     m_refChecker = new Checker(refUser, PropertiesPluginKinect.Instance.WaveCheckerTolerance);
     m_refHand = hand;
     m_GestureBegin = false;
 }
 public static double ToNormalizedValue(Checker checker, Checker lastPlayerToGo)
 {
     if (checker == Checker.Empty)
         return ToValue(checker);
     else if (checker == lastPlayerToGo)
         return ToValue(Checker.Green);
     else
         return ToValue(Checker.Blue);  // The player that is about to go will be blue.
 }
예제 #11
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="refUser">User data</param>
 /// <param name="leftOrRightHand">Hand treated</param>
 public SwipeCondition(UserData refUser, JointType leftOrRightHand)
     : base(refUser)
 {
     m_nIndex = 0;
     m_refHand = leftOrRightHand;
     m_refChecker = new Checker(refUser, PropertiesPluginKinect.Instance.SwipeCheckerTolerance);
     m_handVelocity = new List<double>();
     m_GestureBegin = false;
 }
 public static double ToValue(Checker checker)
 {
     switch (checker)
     {
         case Checker.Blue: return -1.0;
         case Checker.Green: return 1.0;
         case Checker.Empty: return 0.0;
         default: throw new Exception();
     }
 }
예제 #13
0
        public void _003_CheckerProperties()
        {
            var game = new Game();
            game.CreateCheckers(false);

            var actualChecker = game.CheckersSet[0];
            var expectedChecker = new Checker(false, false, new Coordinate(0, 1));

            Assert.AreEqual(expectedChecker, actualChecker);
        }
예제 #14
0
        public KnnBot(Checker myColor)
            : base(myColor)
        {
            learner = new KNearestNeighbor(5, 1000);

            // this learner needs to have at least one example
            // to start with
            Example e = MakeExample(new Board(), Checker.Blue);
            e.Labels.Add(0.5);
            LearnOneExample(e);
        }
예제 #15
0
        public void _002_CheckerCanBeMovedToSpecifiedCoordinates()
        {
            var checker = new Checker(true, false, new Coordinate(0, 1));

            checker.Coordinate.Change(new Coordinate(3,0));

            var actual = checker;
            var expected = new Checker(true, false, new Coordinate(3, 0));

            Assert.AreEqual(expected, actual);
        }
예제 #16
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="refUser">User data</param>
 /// <param name="hand">Hand treated</param>
 public WaveRightCondition(UserData refUser, JointType hand)
     : base(refUser)
 {
     m_nIndex = 0;
     m_refChecker = new Checker(refUser, PropertiesPluginKinect.Instance.WaveCheckerTolerance);
     m_nTryCondition = 0;
     m_handVelocity = new List<double>();
     m_refDirection = EnumKinectDirectionGesture.KINECT_DIRECTION_NONE;
     m_refHand = hand;
     m_GestureBegin = false;
 }
예제 #17
0
 private void checkSudokuButton_Click(object sender, RoutedEventArgs e)
 {
     string sudoku = sudokuTextBox.Text;
     if (sudoku == "test")
     {
         sudoku = exampleSudoku;
     }
     checker = new Checker(sudoku);
     outputTextBlock.Text = checker.FormatSudoku();
     Solver solver = new Solver(sudoku);
     outputTextBlock.Text = String.Join(",", solver.GetEmptyPlacesPerSquare());
 }
        public PingdomManager()
        {
            m_Credentials = AppConfigParser.Create<Credentials>();
            m_WebServices = WebServices.Connect( m_Credentials.AuthToken,m_Credentials.URL);
            HttpChecker = new Checker<HTTPCheck>(m_WebServices);

            PingChecker = new Checker<PingCheck>(m_WebServices);
            PortChecker = new Checker<PortCheck>(m_WebServices);



        }
예제 #19
0
        public void _001_Player_Can_Select_Checker()
        {
            var game = new Game();
            var validInput = new FakePlayer(true).EnterCoordinates();

            var expectedChecker = new Checker(false, false, new Coordinate(2, 1));

            game.CreateCheckers(false);

            var moveStartCoordinate = game.ConvertIntoCoordinates(validInput);
            var actualChecker = game.GetChecker(moveStartCoordinate);

            Assert.AreEqual(actualChecker, expectedChecker);
        }
예제 #20
0
파일: Program.cs 프로젝트: edyoung/Prequel
        static int Main(string[] args)
        {
            Arguments arguments;
            try
            {
                arguments = new Arguments(args);

                var checker = new Checker(arguments);

                var results = checker.Run();

                if (arguments.DisplayLogo)
                {
                    Console.WriteLine("Prequel version {0}", GetProgramVersion());
                }

                if (results.Errors.Count > 0)
                {
                    Console.WriteLine("SQL Parse Errors:");
                    foreach (var error in results.Errors)
                    {
                        Console.WriteLine(results.FormatError(error));
                    }
                }

                if (results.Warnings.Count > 0)
                {
                    Console.WriteLine("Warnings:");
                    foreach (var warning in results.Warnings)
                    {
                        Console.WriteLine(results.FormatWarning(warning));
                    }
                }
                return (int)results.ExitCode;
            }
            catch (ProgramTerminatingException ex)
            {
                Console.Error.WriteLine("Prequel version {0}", GetProgramVersion());
                Console.Error.WriteLine(ex.Message);
                Console.Error.WriteLine(Arguments.UsageDescription);
                return (int)ex.ExitCode;
            }
        }
        public void BatchAddCheckers(Checker start, List<int> columnHistory, bool updateBoard = true, bool delay = true, Board completedBoard = null)
        {
            Storyboard story = new Storyboard();
            Checker checker = start;
            int i = 0;
            foreach (int column in columnHistory)
            {
                Image image = new Image();
                image.Stretch = Stretch.Uniform;
                image.Source = (checker == Checker.Blue ? new BitmapImage(new Uri("/Icons/orbz_water.ico", UriKind.Relative)) : new BitmapImage(new Uri("/Icons/orbz_spirit.ico", UriKind.Relative)));
                image.SetValue(Grid.ColumnProperty, column);
                int? minRow = gridBoard.Children.OfType<Image>().Where(e => (int)e.GetValue(Grid.ColumnProperty) == column).Select(e => (int?)e.GetValue(Grid.RowProperty)).Min();
                if (minRow.HasValue && minRow == 0)
                    throw new Exception("Cannot add checker to full column");
                int row = (int)(minRow.HasValue ? minRow - 1 : 5);
                image.SetValue(Grid.ZIndexProperty, -1);
                image.SetValue(Grid.RowProperty, row);
                image.Opacity = 0;
                image.Height = gridBoard.RowDefinitions[0].ActualHeight;
                gridBoard.Children.Add(image);
                if (updateBoard)
                    CurrentBoard.AddChecker(checker, column);

                ThicknessAnimation animation = new ThicknessAnimation(new Thickness(0, -gridBoard.ActualHeight * 2 * Settings.Default.DropHeightRatio, 0, 0), new Thickness(0, 0, 0, 0), TimeSpan.FromMilliseconds(Settings.Default.DropSpeed));
                animation.EasingFunction = new BounceEase() { Bounces = 3, Bounciness = 5, EasingMode = System.Windows.Media.Animation.EasingMode.EaseOut };
                animation.BeginTime = TimeSpan.FromMilliseconds(i * Settings.Default.MoveDelay);
                Storyboard.SetTarget(animation, image);
                Storyboard.SetTargetProperty(animation, new PropertyPath(Image.MarginProperty));
                story.Children.Add(animation);

                DoubleAnimation fade = (completedBoard != null && !completedBoard.WinningSequence.Any(t => t.Item1 == row && t.Item2 == column) ? Fade(image, 1, Settings.Default.FadeTo, i * Settings.Default.MoveDelay, Settings.Default.FadeSpeed) : Fade(image, 0, 1, i * Settings.Default.MoveDelay, 0));
                story.Children.Add(fade);
                story.Completed += new EventHandler(story_Completed);

                checker = Board.Toggle(checker);
                ++i;
            }
            story.Begin();
        }
예제 #22
0
        private void ShowInfo(HttpContext context)
        {
            var writer = context.Response.Output;
            var checker = new Checker(new CheckParams(this.patcherInfo.configuration));

            {
                writer.WriteLine("<h1>Patches to install</h1>");
                int totalPatches = 0;

                writer.WriteLine("<ol>");
                foreach(var patchId in checker.GetPatchesToInstall()) {
                    writer.WriteLine("<li>{0}: \"{1}\"</li>", patchId.version, patchId.name);
                    totalPatches++;
                }
                writer.WriteLine("</ol>");

                writer.WriteLine("<p>Total patches: {0}</p>", totalPatches);
                if(totalPatches > 0) {
                    WriteForm(writer, ACTION_INSTALLALL, "Install all patches");
                }
            }

            {
                writer.WriteLine("<h1>Installed patches</h1>");
                int totalPatches = 0;

                writer.WriteLine("<ol>");
                foreach(var patchId in checker.GetInstalledPatches()) {
                    writer.WriteLine("<li>{0}: \"{1}\"</li>", patchId.version, patchId.name);
                    totalPatches++;
                }
                writer.WriteLine("</ol>");

                writer.WriteLine("<p>Total patches: {0}</p>", totalPatches);
                if(totalPatches > 0) {
                    WriteForm(writer, ACTION_ROLLBACKLATEST, "Uninstall latest patch");
                }
            }
        }
예제 #23
0
        public override ExecutionResult Execute(ExecutionContext executionContext)
        {
            var result = new ExecutionResult();

            // Create a temp file with the submission code
            string submissionFilePath;

            try
            {
                submissionFilePath = this.CreateSubmissionFile(executionContext.Code);
            }
            catch (ArgumentException exception)
            {
                result.IsCompiledSuccessfully = false;
                result.CompilerComment        = exception.Message;

                return(result);
            }

            // Create a sandbox executor source file in the working directory
            var sandboxExecutorSourceFilePath = $"{this.workingDirectory}\\{SandboxExecutorClassName}";

            File.WriteAllText(sandboxExecutorSourceFilePath, this.SandboxExecutorCode);

            // Compile all source files - sandbox executor and submission file
            var compilerPath   = this.getCompilerPathFunc(executionContext.CompilerType);
            var compilerResult = this.CompileSourceFiles(
                executionContext.CompilerType,
                compilerPath,
                executionContext.AdditionalCompilerArguments,
                new[] { submissionFilePath, sandboxExecutorSourceFilePath });

            // Assign compiled result info to the execution result
            result.IsCompiledSuccessfully = compilerResult.IsCompiledSuccessfully;
            result.CompilerComment        = compilerResult.CompilerComment;
            if (!result.IsCompiledSuccessfully)
            {
                return(result);
            }

            // Prepare execution process arguments and time measurement info
            var classPathArgument = $"-classpath \"{this.workingDirectory}\"";

            var submissionFilePathLastIndexOfSlash = submissionFilePath.LastIndexOf('\\');
            var classToExecute = submissionFilePath.Substring(submissionFilePathLastIndexOfSlash + 1);

            var timeMeasurementFilePath = $"{this.workingDirectory}\\{TimeMeasurementFileName}";

            // Create an executor and a checker
            var executor = new StandardProcessExecutor();
            var checker  = Checker.CreateChecker(executionContext.CheckerAssemblyName, executionContext.CheckerTypeName, executionContext.CheckerParameter);

            // Process the submission and check each test
            foreach (var test in executionContext.Tests)
            {
                var processExecutionResult = executor.Execute(
                    this.javaExecutablePath,
                    test.Input,
                    executionContext.TimeLimit,
                    executionContext.MemoryLimit,
                    new[] { classPathArgument, SandboxExecutorClassName, classToExecute, $"\"{timeMeasurementFilePath}\"" });

                UpdateExecutionTime(timeMeasurementFilePath, processExecutionResult, executionContext.TimeLimit);

                var testResult = this.ExecuteAndCheckTest(test, processExecutionResult, checker, processExecutionResult.ReceivedOutput);
                result.TestResults.Add(testResult);
            }

            return(result);
        }
예제 #24
0
	public BigBen(Checker checker) : base(checker)
	{
	}
예제 #25
0
        public void Update_Method()
        {
            ListBox method_ListBox = ControlExtensions.FindControl <ListBox>(this, "method_ListBox");

            if (method_ListBox.SelectedItem == null)
            {
                ResourceManager.mainWindowVM.Tips = "需要选定要更新的Method!";
                return;
            }

            ComboBox returnType_ComboBox = ControlExtensions.FindControl <ComboBox>(this, "returnType_ComboBox");

            if (returnType_ComboBox.SelectedItem == null)
            {
                ResourceManager.mainWindowVM.Tips = "需要选定自定Method的返回类型!";
                return;
            }

            TextBox methodName_TextBox = ControlExtensions.FindControl <TextBox>(this, "methodName_TextBox");

            if (methodName_TextBox.Text == null || methodName_TextBox.Text.Length == 0)
            {
                ResourceManager.mainWindowVM.Tips = "需要给出自定Method的方法名!";
                return;
            }

            if (((Method)method_ListBox.SelectedItem).Name != methodName_TextBox.Text && Checker.UserType_Contain_PropName(VM.UserType, methodName_TextBox.Text))
            {
                ResourceManager.mainWindowVM.Tips = "标识符重复!";
                return;
            }

            ObservableCollection <Attribute> parameters = ((UserType_EW_VM)DataContext).Params;

            Method method = new Method(
                (Type)returnType_ComboBox.SelectedItem,
                methodName_TextBox.Text,
                parameters,
                Crypto.None
                );

            string achieve = ((Method)method_ListBox.SelectedItem).Achieve;

            method.Achieve = achieve;

            VM.UserType.Methods[method_ListBox.SelectedIndex] = method;
            ResourceManager.mainWindowVM.Tips = "更新了自定Method:" + method;

            // 更新完成后,要将临时参数列表拿掉,这样再向临时参数列表中添加/更新内容也不会影响刚刚添加的Method
            // ((UserType_EW_VM)DataContext).Params = new ObservableCollection<Attribute>();

            // 【11月10日bugfix】更新完成后,将这个临时参数表复制一份保留
            ObservableCollection <Attribute> tmp = new ObservableCollection <Attribute>();

            foreach (Attribute attribute in ((UserType_EW_VM)DataContext).Params)
            {
                tmp.Add(new Attribute(attribute));
            }
            ((UserType_EW_VM)DataContext).Params = tmp;
        }
예제 #26
0
        public async Task DeleteSecretAsync(string path, string mountPoint = null)
        {
            Checker.NotNull(path, "path");

            await _polymath.MakeVaultApiRequest(mountPoint ?? _polymath.VaultClientSettings.SecretsEngineMountPoints.KeyValueV2, "/data/" + path.Trim('/'), HttpMethod.Delete).ConfigureAwait(_polymath.VaultClientSettings.ContinueAsyncTasksOnCapturedContext);
        }
예제 #27
0
 /// <summary>
 /// 设置商品状态
 /// </summary>
 /// <param name="status"></param>
 internal void SetStatus(ProductStatus status)
 {
     this.Status = Checker.NotNull(status, nameof(status));
 }
예제 #28
0
 /// <summary>
 /// 设置sku
 /// </summary>
 /// <param name="sku"></param>
 internal void SetSku(string sku)
 {
     this.Sku = Checker.NotNullOrEmpty(sku.Trim(), nameof(sku));
 }
 /// <exception cref="ArgumentNullException">key is null</exception>
 public string SerializePublicKey(PublicKey key)
 {
     Checker.CheckNull(key);
     return(SerializeKey(key.E, key.N));
 }
예제 #30
0
 public void InvalidFileNameRaisesError()
 {
     var c = new Checker(new Arguments("??"));
     Action act = () => c.Run();
     act.ShouldThrow<ProgramTerminatingException>();
 }
예제 #31
0
 public bool IsTurnRight(string figure, string from, string to)
 {
     return(Checker.CheckStep(figure, from, to));
 }
예제 #32
0
 public ActionResult GetCommentsForPost(int id, int?page)
 {
     return(this.PartialView(this.commentService.GetLatestCommentsForAPost(id, GlobalConstants.PageSize,
                                                                           Checker.GetValidPageNumber(page)).Project().To <CommentViewModel>().ToList()));
 }
예제 #33
0
 public OrderDeliveryInfomation(string name, string phone, string address)
 {
     this.Name    = Checker.NotNullOrEmpty(name, nameof(name));
     this.Phone   = Checker.NotNullOrEmpty(phone, nameof(phone));
     this.Address = Checker.NotNullOrEmpty(address, nameof(address));
 }
예제 #34
0
 public OrderItemProduct(long id, string name, decimal price)
 {
     this.Id    = Checker.GTZero(id, nameof(id));
     this.Name  = Checker.NotNullOrEmpty(name, nameof(name));
     this.Price = Checker.GTZero(price, nameof(price));
 }
예제 #35
0
 static void Main()
 {
     Checker.Start();
 }
예제 #36
0
        public void MakingNewChecker()
        {
            Checker checker = new Checker();

            Assert.IsNotNull(checker.GameObj);
        }
 /// <exception cref="ArgumentNullException">serializer is null</exception>
 public KeySerializer(IBigNumberSerializer serializer)
 {
     Checker.CheckNull(serializer);
     this.serializer = serializer;
 }
예제 #38
0
 public void ParseInvalidFile()
 {
     using (var t = new TempFile("select >>>"))
     {
         Checker c = new Checker(new Arguments(t.FileName));
         var results = c.Run();
         results.Errors.Should().NotBeEmpty();
         results.ExitCode.Should().Be(ExitReason.GeneralFailure);
     }
 }
 /// <exception cref="ArgumentNullException">key is null</exception>
 public string SerializePrivateKey(PrivateKey key)
 {
     Checker.CheckNull(key);
     return(SerializeKey(key.D, key.N));
 }
        public static int Start(string processPath, string targetWindowsUser, string args = "",
                                bool runAsAdmin = false)
        {
            Checker.Begin().CheckFileExists(processPath)
            .NotNullOrEmpty(targetWindowsUser, nameof(targetWindowsUser));

            var targetSession = GetSessionId(targetWindowsUser);

            if (targetSession.ConnectionState != WTS_CONNECTSTATE_CLASS.WTSActive)
            {
                throw new Win32ErrorCodeException($"TargetWindowsUser:{targetWindowsUser} not active",
                                                  Win32ErrorCode.UserNotActive);
            }

            if (!Win32Api.WTSQueryUserToken(targetSession.SessionId, out var hToken))
            {
                throw new Win32ErrorCodeException($"TargetWindowsUser:{targetWindowsUser} get token failed",
                                                  Win32ErrorCode.GetUserTokenFailed);
            }

            var environmentPtr = IntPtr.Zero;

            if (!Win32Api.CreateEnvironmentBlock(ref environmentPtr, hToken, false))
            {
                throw new Win32ErrorCodeException("CreateEnvironmentBlock('" + hToken + "')");
            }

            var dwCreationFlags = StandardDef.NormalPriorityClass | StandardDef.CreateUnicodeEnvironment |
                                  StandardDef.ExtendedStartupInfoPresent;

            if (args != null && !args.StartsWith(" "))
            {
                args = $" {args}";
            }

            var startupInfo = new StartupInfoEx();
            var token       = runAsAdmin ? GetProcessElevation(hToken) : hToken;

            startupInfo.StartupInfo.cb = Marshal.SizeOf(startupInfo);
            var childProcStarted = Win32Api.CreateProcessAsUser(
                token,
                processPath,
                args,
                IntPtr.Zero,
                IntPtr.Zero,
                false,
                dwCreationFlags,
                environmentPtr,
                Path.GetDirectoryName(processPath),
                ref startupInfo,
                out var tProcessInfo
                );

            if (!childProcStarted)
            {
                throw new Win32ErrorCodeException($"TargetWindowsUser:{targetWindowsUser} start failed",
                                                  Win32ErrorCode.Win32ErrorProcessStartFailed);
            }

            var processId = tProcessInfo.dwProcessId;

            try
            {
                if (tProcessInfo.hThread != IntPtr.Zero)
                {
                    Win32Api.CloseHandle(tProcessInfo.hThread);
                }
                if (tProcessInfo.hProcess != IntPtr.Zero)
                {
                    Win32Api.CloseHandle(tProcessInfo.hProcess);
                }
                if (token != IntPtr.Zero)
                {
                    Win32Api.CloseHandle(token);
                }
                if (startupInfo.lpAttributeList != IntPtr.Zero)
                {
                    //不再需要参数的时候,要释放内存
                    Win32Api.DeleteProcThreadAttributeList(startupInfo.lpAttributeList);
                    Marshal.FreeHGlobal(startupInfo.lpAttributeList);
                }
            }
            catch (Exception ex)
            {
                throw new Win32ErrorCodeException(ex.Message, Win32ErrorCode.Win32ErrorProcessDisposeFailed);
            }

            return(processId);
        }
예제 #41
0
 /// <summary>
 /// 设置Name
 /// </summary>
 /// <param name="name"></param>
 internal void SetName(string name)
 {
     this.Name = Checker.NotNullOrEmpty(name.Trim(), nameof(name));
 }
예제 #42
0
 private static void CheckTableAndColumnName(DataTable table, string columnName)
 {
     Checker.Begin().NotNull(table, nameof(table)).NotNullOrEmpty(columnName, nameof(columnName));
 }
예제 #43
0
 /// <summary>
 /// 修改unit
 /// </summary>
 /// <param name="newSku"></param>
 public void SetUnit(string unit)
 {
     this.Unit = Checker.NotNullOrEmpty(unit.Trim(), nameof(unit));
 }
예제 #44
0
        public void MakingNewChecker2()
        {
            Checker checker = new Checker();

            Assert.AreEqual(checker.PlayerColor, "");
        }
예제 #45
0
        public async Task <Secret <SecretData <T> > > ReadSecretAsync <T>(string path, int?version = null, string mountPoint = null, string wrapTimeToLive = null)
        {
            Checker.NotNull(path, "path");

            return(await _polymath.MakeVaultApiRequest <Secret <SecretData <T> > >(mountPoint ?? _polymath.VaultClientSettings.SecretsEngineMountPoints.KeyValueV2, "/data/" + path.Trim('/') + (version != null ? ("?version=" + version) : ""), HttpMethod.Get, wrapTimeToLive : wrapTimeToLive).ConfigureAwait(_polymath.VaultClientSettings.ContinueAsyncTasksOnCapturedContext));
        }
예제 #46
0
        public void _001_CanCreateChecker()
        {
            var checker = new Checker(true, false, new Coordinate(0, 1));

            Assert.IsNotNull(checker);
        }
예제 #47
0
	public BigBen(Checker checker, Guid gId) : base(checker, gId)
	{
	}
예제 #48
0
 /// <summary>
 /// Places the specified checker in this point instantly.
 /// </summary>
 public void PlaceInstantly(Checker checker)
 {
     checker.Point = this;
     checker.GetComponent <Mover>().MoveToInstantly(new Node(GetNextPosition(), CheckerRotation));
     m_Checkers.Push(checker);
 }
예제 #49
0
        public void MakingNewChecker3()
        {
            Checker checker = new Checker();

            Assert.AreEqual(checker.IsKing, false);
        }
        public override ExecutionResult Execute(ExecutionContext executionContext)
        {
            var result = new ExecutionResult();

            // Copy the sandbox executor source code to a file in the working directory
            File.WriteAllText(this.SandboxExecutorSourceFilePath, this.SandboxExecutorCode);

            // Create a temp file with the submission code
            string submissionFilePath;

            try
            {
                submissionFilePath = this.CreateSubmissionFile(executionContext);
            }
            catch (ArgumentException exception)
            {
                result.IsCompiledSuccessfully = false;
                result.CompilerComment        = exception.Message;

                return(result);
            }

            var compilerResult = this.DoCompile(executionContext, submissionFilePath);

            // Assign compiled result info to the execution result
            result.IsCompiledSuccessfully = compilerResult.IsCompiledSuccessfully;
            result.CompilerComment        = compilerResult.CompilerComment;
            if (!result.IsCompiledSuccessfully)
            {
                return(result);
            }

            // Prepare execution process arguments and time measurement info
            var classPathArgument = $"-classpath \"{this.WorkingDirectory}\"";

            var classToExecuteFilePath = compilerResult.OutputFile;
            var classToExecute         = classToExecuteFilePath
                                         .Substring(
                this.WorkingDirectory.Length + 1,
                classToExecuteFilePath.Length - this.WorkingDirectory.Length - JavaCompiledFileExtension.Length - 1)
                                         .Replace('\\', '.');

            var timeMeasurementFilePath = $"{this.WorkingDirectory}\\{TimeMeasurementFileName}";

            // Create an executor and a checker
            var executor = new StandardProcessExecutor();
            var checker  = Checker.CreateChecker(executionContext.CheckerAssemblyName, executionContext.CheckerTypeName, executionContext.CheckerParameter);

            // Process the submission and check each test
            foreach (var test in executionContext.Tests)
            {
                var processExecutionResult = executor.Execute(
                    this.javaExecutablePath,
                    test.Input,
                    executionContext.TimeLimit * 2, // Java virtual machine takes more time to start up
                    executionContext.MemoryLimit,
                    new[] { classPathArgument, SandboxExecutorClassName, classToExecute, $"\"{timeMeasurementFilePath}\"" });

                UpdateExecutionTime(timeMeasurementFilePath, processExecutionResult, executionContext.TimeLimit);

                var testResult = this.ExecuteAndCheckTest(test, processExecutionResult, checker, processExecutionResult.ReceivedOutput);
                result.TestResults.Add(testResult);
            }

            return(result);
        }
예제 #51
0
        public void MakingNewChecker4()
        {
            Checker checker = new Checker();

            Assert.AreEqual(checker.Selected, false);
        }
        public SolrFieldAttribute(string name)
        {
            Checker.IsNullOrWhiteSpace(name);

            this.Name = name;
        }
예제 #53
0
파일: Node.cs 프로젝트: xzxzxc/checkers
 public Node(Cell cell, Checker killed, MoveDirection previousMoveDirection)
 {
     Cell   = cell;
     Killed = killed;
     PreviousMoveDirection = previousMoveDirection;
 }
예제 #54
0
 /// <summary>
 /// Создаем контроллер и выбираем пользователя
 /// </summary>
 public UserController(User user)
 {
     Checker.CheckProperty(user);
     User = user;
 }
예제 #55
0
 public void ErrorFormattingLooksOK()
 {
     using (var t = new TempFile("\nselect >>>"))
     {
         Checker c = new Checker(new Arguments(t.FileName));
         var results = c.Run();
         var error = results.Errors[0];
         string errorMessage = results.FormatError(error);
         errorMessage.Should()
             .ContainEquivalentOf(t.FileName, "message should contain the filename")
             .And.Contain("(2)", "message should contain the line number")
             .And.Contain("ERROR", "message should contain ERROR for build tools which look for that")
             .And.Contain(error.Number.ToString(), "message should contain SQL's error code")
             .And.Contain("Incorrect syntax near select", "message should contain SQL's error message");
     }
 }
예제 #56
0
파일: FrmCheck.cs 프로젝트: zj8487/HyDM
 void checker_PretreatComplete(Checker sender)
 {
     this.Invoke(new SetTextHandler(SetOperateText), new object[] { "预处理完成" });
 }
예제 #57
0
 public void ParseFile()
 {
     using (var t = new TempFile("select * from foo"))
     {
         Checker c = new Checker(new Arguments(t.FileName));
         var results = c.Run();
         results.ExitCode.Should().Be(ExitReason.Success);
     }
 }
예제 #58
0
 internal WarehousePosition(string code, string description)
 {
     this.Code        = Checker.NotNullOrEmpty(code, nameof(code));
     this.Description = description != null?description.Trim() : string.Empty;
 }
예제 #59
0
 public void ParseMissingFile()
 {
     var c = new Checker(new Arguments("missing.xyz"));
     Action act = () => c.Run();
     act.ShouldThrow<ProgramTerminatingException>().WithMessage("*missing.xyz*").And.ExitCode.Equals(ExitReason.IOError);
 }
예제 #60
0
        public UnitOfWork(TContext context)
        {
            Checker.NotNullArgument(context, nameof(context));

            _context = context;
        }