public void SingleSolution() { CurrentState state = new CurrentState(); IDecision[] decisions = new IDecision[] { new MoveToFridge(state), new KillFridgeGuardian(state), new OpenFridgeDecision(state), new GetBananaFromFridge(state) }; Planner planner = new Planner(StateOffset.Heuristic); for (int i = 0; i < decisions.Length; i++) { planner.AddDecision(decisions[i]); } StateOffset goal = new StateOffset(); goal.Set("HasBanana", true); Queue<IDecision> plan = planner.CreatePlan(goal); Assert.Greater(plan.Count, 0); Assert.AreSame(decisions[0], plan.Dequeue()); // MoveToFridge Assert.AreSame(decisions[1], plan.Dequeue()); // KillFridgeGuardian Assert.AreSame(decisions[1], plan.Dequeue()); // KillFridgeGUardian Assert.AreSame(decisions[1], plan.Dequeue()); // KillFridgeGuardian Assert.AreSame(decisions[2], plan.Dequeue()); // OpenFridge Assert.AreSame(decisions[3], plan.Dequeue()); // GetBananaFromFridge }
private CurrentState(Method method, CurrentState oldState) { this.Assembly = oldState.Assembly; this.assemblySuppressed = oldState.assemblySuppressed; this.Type = oldState.Type; this.typeSuppressed = oldState.typeSuppressed; this.Method = method; this.methodSuppressed = null; }
public CurrentState(TypeNode type, CurrentState oldState) { this.Type = type; this.Method = null; this.typeSuppressed = null; this.methodSuppressed = null; this.Assembly = oldState.Assembly; this.assemblySuppressed = oldState.assemblySuppressed; }
public Koopa(Vector2 initialPosition, CurrentState type) : base(new Vector2(initialPosition.X, initialPosition.Y)) { Texture2D koopaTexture = Textures.GetTexture(Textures.Texture.koopa); walking = new Animation(koopaTexture, new Rectangle(0, 0 + (24 * World.WorldType), 16, 24), 2, timeBetweenAnimation, 0); hopping = new Animation(koopaTexture, new Rectangle(48, 0 + (24 * World.WorldType), 16, 24), 2, timeBetweenAnimation, 0); velocity.X = -walkingSpeed; state = type; }
public virtual void Initialize(GameObject _newCamPoint, GameObject _triggerObj) { isGoingHome = false; currentCamPoint = _newCamPoint; ResetDayTimers (); direction = RandomDirection (); StartCoroutine (ExitBuilding (_triggerObj.GetComponent<Collider>(), true)); currentState = CurrentState.CS_Sleeping; }
public Spikey(Vector2 initialPosition, CurrentState type) : base(initialPosition) { walking = new Animation(Textures.GetTexture(Textures.Texture.spikey), new Rectangle(0, 0, 16, 16), 2, timeBetweenAnimation, 0); thrown = new Animation(Textures.GetTexture(Textures.Texture.spikey), new Rectangle(32, 0, 16, 16), 2, timeBetweenAnimation, 0); state = type; if (state == CurrentState.walking) velocity.X = walkingSpeed; else velocity.Y = thrownSpeed; }
void DebugManager_OnProcessStateChanged(object sender, DebuggerEventArgs e) { var oldState = currentState; currentState = new CurrentState(); var dbg = (DnDebugger)sender; switch (DebugManager.Instance.ProcessState) { case DebuggerProcessState.Starting: savedEvalState = null; break; case DebuggerProcessState.Continuing: if (dbg.IsEvaluating && savedEvalState == null) savedEvalState = oldState; break; case DebuggerProcessState.Running: if (!dbg.IsEvaluating) ClearStackFrameLines(); break; case DebuggerProcessState.Stopped: if (dbg.IsEvaluating) break; // Don't update the selected thread if we just evaluated something if (UpdateState(savedEvalState)) { currentState.Thread = DebugManager.Instance.Debugger.Current.Thread; SelectedFrameNumber = 0; } else currentState = savedEvalState; savedEvalState = null; foreach (var textView in MainWindow.Instance.AllVisibleTextViews) UpdateStackFrameLines(textView, false); break; case DebuggerProcessState.Terminated: savedEvalState = null; ClearStackFrameLines(); break; default: throw new InvalidOperationException(); } if (StackFramesUpdated != null) StackFramesUpdated(this, new StackFramesUpdatedEventArgs(dbg)); }
public void serialPingServers(BackgroundWorker worker, DoWorkEventArgs e, int[] speeds ) { while (!worker.CancellationPending) { Ping pingSender = new Ping(); PingOptions options = new PingOptions(); options.DontFragment = true; string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; // сделать размер буфера изменяемым в настройках CurrentState state = new CurrentState(); byte[] buffer = Encoding.ASCII.GetBytes(data); // сделать изменяемым в настройках int timeout = speeds[2]; // сделать изменяемым в настройках double count = serverList.Count; double i = 0; int progress; foreach (serverControl server in serverList) { System.Threading.Thread.Sleep(speeds[0]); if (worker.CancellationPending) { break; } i++; progress = (int)Math.Round((i / count) * 100); string host = server.objectAddress; // сделать изменяемым в настройках PingReply reply = pingSender.Send(host, timeout, buffer, options); if (reply.Status == IPStatus.Success) { state.address = server.objectAddress; state.isOnline = true; worker.ReportProgress(progress, state); } else { state.address = server.objectAddress; state.isOnline = false; worker.ReportProgress(progress, state); } } if (!workState) System.Threading.Thread.Sleep(1000); System.Threading.Thread.Sleep(speeds[1]); } e.Cancel = true; }
public override void Update(GameTime gameTime) { walking.Update(gameTime); thrown.Update(gameTime); if (velocity.X < 0) effects = SpriteEffects.None; else effects = SpriteEffects.FlipHorizontally; if (state == CurrentState.thrown && isOnSolidTile) { state = CurrentState.walking; velocity.X = walkingSpeed; } base.Update(gameTime); }
private Planner BasicPlanner() { CurrentState state = new CurrentState(); IDecision[] decisions = new IDecision[] { new MoveToFridge(state), new KillFridgeGuardian(state), new OpenFridgeDecision(state), new GetBananaFromFridge(state) }; Planner planner = new Planner(StateOffset.Heuristic); for (int i = 0; i < decisions.Length; i++) { planner.AddDecision(decisions[i]); } return planner; }
public void CountWords( System.ComponentModel.BackgroundWorker worker, System.ComponentModel.DoWorkEventArgs e) { CurrentState state = new CurrentState(); string line = ""; int elapsedTime = 20; DateTime lastReportDateTime = DateTime.Now; if (CompareString == null || CompareString == string.Empty) { throw new Exception("CompareString not specified."); } try { using (System.IO.StreamReader stream = new System.IO.StreamReader(SourceFile)) { while (!stream.EndOfStream) { if (worker.CancellationPending) { e.Cancel = true; break; } else { line = stream.ReadLine(); WordCount += CountInString(line, CompareString); LinesCounted += 1; int compare = DateTime.Compare( DateTime.Now, lastReportDateTime.AddMilliseconds(elapsedTime)); if (compare > 0) { state.LinesCounted = LinesCounted; state.WordsMatched = WordCount; worker.ReportProgress(0, state); lastReportDateTime = DateTime.Now; } } } state.LinesCounted = LinesCounted; state.WordsMatched = WordCount; worker.ReportProgress(0, state); } } catch (Exception exc) { throw exc; } }
public void parallelPingServers(System.ComponentModel.BackgroundWorker worker, System.ComponentModel.DoWorkEventArgs e, int[] speeds, ARSMonitor.serverControl server ) { Ping pingSender = new Ping(); PingOptions options = new PingOptions(); options.DontFragment = true; string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; // сделать размер буфера изменяемым в настройках CurrentState state = new CurrentState(); byte[] buffer = Encoding.ASCII.GetBytes(data); // сделать изменяемым в настройках int timeout = 120; // сделать изменяемым в настройках double count = serverList.Count; double i = 0; int progress; i++; progress = (int)Math.Round((i / count) * 100); //elements.Find(el => el.Child == server); string host = server.objectAddress; // сделать изменяемым в настройках while (!worker.CancellationPending) { PingReply reply = pingSender.Send(host, timeout, buffer, options); if (reply.Status == IPStatus.Success) { state.address = server.objectAddress; state.isOnline = true; /*while (worker.IsBusy) System.Threading.Thread.Sleep(100);*/ worker.ReportProgress(progress, state); } else { state.address = server.objectAddress; state.isOnline = false; worker.ReportProgress(progress, state); } if (!workState) System.Threading.Thread.Sleep(1000); System.Threading.Thread.Sleep(speeds[1]); } e.Cancel = true; }
//wait(reset), BigBottom, Alarm, LittleBottom, Postpone(10 bigbottom), WelcomeBack private void BigBottom() { currentState = CurrentState.BigBottom; soundPlayer.Stop(); //BigBottom状态,计时50分钟,大按钮消失,leave按钮enable,postpone和finish button unabled,GotitButton显示got it StartButton.Visibility = Visibility.Hidden; TimeBlock.Visibility = Visibility.Visible; GotitButton.Visibility = Visibility.Visible; PostponeButton.Visibility = Visibility.Visible; LeaveButton.Visibility = Visibility.Visible; GotitButton.IsEnabled = false; PostponeButton.IsEnabled = false; LeaveButton.IsEnabled = true; TipBlock.Text = "Your Bottom is getting bigger!"; TipBlock.Visibility = Visibility.Visible; timeTicks = 0; TimeBlock.Text = "0:0"; timer.Start(); }
public void GoalNodeNeighborIterator() { CurrentState state = new CurrentState(); List<IDecision> decisions = new List<IDecision>() { new MoveToFridge(state), new KillFridgeGuardian(state), new OpenFridgeDecision(state), new GetBananaFromFridge(state) }; StateOffset goal = new StateOffset(); //goal.SetStateValue("HasBanana", true, false); GoalNode end = new GoalNode(goal, decisions); int i = decisions.Count - 1; foreach (GoalNode neighbor in end.GetNeighbors()) { Console.WriteLine(end.GetEdge(neighbor)); //Assert.AreSame(decisions[i--], end.GetEdge(neighbor)); } }
void Awake() { //iniate audio source and cache variables if(GetComponent<AudioSource>() == null) { c_Audio = gameObject.AddComponent<AudioSource>(); } else { c_Audio = GetComponent<AudioSource>(); } brain = GetComponent<AIStateManager>(); previousState = brain.currentState; previousPanic = brain.panic; //set the pitch correctly c_Audio.pitch = basePitch; c_Audio.pitch = c_Audio.pitch + Random.Range( -randomPitch, randomPitch); }
public ICommand GetCommand() { //Check which state we are in switch (currentState) { //If we are at the initial welcome for the new character, just change the state and move on case CurrentState.InitialWelcome: currentState = CurrentState.EnteringPasswordFirst; break; //We need to get the first out of two password entries and make sure it's legal. case CurrentState.EnteringPasswordFirst: { GetPassword(PasswordPhase.FirstPassword); break; } case CurrentState.EnteringPasswordSecond: { GetPassword(PasswordPhase.SecondPassword); break; } } return new NoOpCommand(); }
public override void Execute() { watch = new Stopwatch(); Console.WriteLine("Beginning execution for Bi-directional"); Console.WriteLine("Initial State: "); CurrentState.Format(); watch.Start(); FrontOpenSet.Enqueue(CurrentState); BackOpenSet.Enqueue(new State(GlobalVar.GOAL)); while (FrontOpenSet.Count > 0 || BackOpenSet.Count > 0) { //pop from queue for each direction var front = FrontOpenSet.Dequeue(); var back = BackOpenSet.Dequeue(); if (FrontClosedSet.ContainsKey(front.Key) == false) { FrontClosedSet.Add(front.Key, front); } if (BackClosedSet.ContainsKey(back.Key) == false) { BackClosedSet.Add(back.Key, back); } //check if either is at it's respective goal positions, just in case they don't ever intersect if (front.IsEqualToGoal()) { watch.Stop(); Console.WriteLine("Found goal through front open set, no intersection"); SolutionFound(front); break; } if (back.IsEqualToGoal(CurrentState.StateArray)) { watch.Stop(); Console.WriteLine("Found goal through back open set, no intersection"); SolutionFound(back); break; } var fChildren = front.BuildChildren(); var bChildren = back.BuildChildren(); foreach (var child in fChildren) { if (FrontClosedSet.ContainsKey(child.Key)) { continue; } FrontOpenSet.Enqueue(child); if (!frontparents.ContainsKey(child.Key)) { frontparents.Add(child.Key, front); } } foreach (var child in bChildren) { if (BackClosedSet.ContainsKey(child.Key)) { continue; } BackOpenSet.Enqueue(child); if (!backparents.ContainsKey(child.Key)) { backparents.Add(child.Key, back); } } //chech if either is in the closed set of each direction if (BackClosedSet.ContainsKey(front.Key)) { Console.WriteLine("Found Solution"); SolutionFound(front); //found solution break; } if (FrontClosedSet.ContainsKey(back.Key)) { Console.WriteLine("Found Solution"); SolutionFound(back); //found solution break; } if (BackOpenSet.Count == 0 && FrontOpenSet.Count == 0) { throw new Exception("no solution"); } } watch.Stop(); Console.WriteLine("Elapsed time: {0} ms", watch.Elapsed.Milliseconds); }
protected virtual void WaitForGreenLight() { currentState = CurrentState.CS_WaitingToCross; if(currentCrossWalk.currentCWState == CrossWalk.CrosswalkState.CWS_Green && currentState == CurrentState.CS_WaitingToCross) { isCrossing = true; StartCoroutine(CrossStreet(currentCrossWalk.gameObject)); CancelInvoke("WaitForGreenLight"); } }
public void OnTileRightClicked(object sender, object args) { CurrentState.OnTileRightClicked(); }
private void OnEndTurnButtonPressed(object sender, object args) { CurrentState.OnEndTurnButtonPressed(); }
public void OnAbilityButtonPressed(object sender, object args) { CurrentAbility = ((Events.OnAbilityButtonPressed)args).Ability; CurrentState.OnAbilityButtonPressed(); }
private void btnStop_Click(object sender, EventArgs e) { _currentState = CurrentState.Paused; }
public override void VisitClass(Class Class) { if (Class == null) return; var savedState = this.currentState; this.currentState = savedState.Derive(Class); try { this.CheckClass(Class); CheckForWrapperImplementationsForInheritedInterfaceImplementations(Class); } finally { this.currentState = savedState; } base.VisitClass(Class); }
private void Robot_OnWallOnLeft() { LogCall(); CurrentState.OnWallOnLeft(); }
private void Robot_OnLineAppears() { LogCall(); CurrentState.OnLineAppears(); }
public void ProcessReservationResponsePacket(MultiplayerSessionReservation reservation) { Reservation = reservation; CurrentState.NegotiateReservation(this); }
private void Robot_OnNoWallOnRight() { LogCall(); CurrentState.OnNoWallOnRight(); }
public void RequestSessionReservation(PlayerSettings playerSettings, AuthenticationContext authenticationContext) { PlayerSettings = playerSettings; AuthenticationContext = authenticationContext; CurrentState.NegotiateReservation(this); }
public void Connect(string ipAddress, int port) { IpAddress = ipAddress; ServerPort = port; CurrentState.NegotiateReservation(this); }
public void JoinSession() { CurrentState.JoinSession(this); }
private void LoadFile() { initButtonsForProcess(); _currentState = CurrentState.InProcces; int readBytes = DEFAULT_BUFFER_SIZE; try { while (_file.Peek() >= 0 && readBytes >= DEFAULT_BUFFER_SIZE) { readBytes = _file.Read(_buff, 0, DEFAULT_BUFFER_SIZE); if (readBytes < DEFAULT_BUFFER_SIZE) _strBuff.Append(_buff, 0, readBytes); else _strBuff.Append(_buff); Application.DoEvents(); if (!isInProcces()) break; _loaded += readBytes; _loadedValue = Convert.ToInt32(_loaded/_step); _loadedValue = (_loadedValue > progressBar.Maximum) ? progressBar.Maximum : _loadedValue; progressBar.Value = _loadedValue; txtLoaded.Text = (_loaded/1000).ToString("f3"); Refresh(); } } catch (IOException ex) { setCancelled(); Messenger.ShowError(MsgsBase.Res.File_IO_error_ex, ex); } catch (OutOfMemoryException ex) { setCancelled(); Messenger.ShowError(MsgsBase.Res.Error_Out_of_memory_ex, ex); } catch (Exception ex) { setCancelled(); Messenger.ShowError(MsgsBase.Res.Undefined_error_ex, ex); } finally { if (_file != null) _file.Close(); } initButtonsForPause(); if (_currentState == CurrentState.Canceled) { this.DialogResult = DialogResult.Cancel; _strBuff = new StringBuilder(0); Close(); return; } else if (_currentState == CurrentState.Accepted || isInProcces()) { this.DialogResult = DialogResult.OK; Close(); return; } }
private void Robot_OnBeaconClose(int id) { Log(new RobotEventLogEntry($"Robot_OnBeaconClose({id})")); CurrentState.OnBeaconClose(id); }
private void OpenFileForm_Closing(object sender, CancelEventArgs e) { _currentState = CurrentState.Canceled; e.Cancel = false; }
public void Action() { CurrentState.Action(); }
public override void VisitAssembly(AssemblyNode assembly) { this.currentState = new CurrentState(assembly); if (ContractNodes.IsAlreadyRewritten(assembly)) { this.HandleError(new Error(1029, "Cannot extract contracts from rewritten assembly '" + assembly.Name + "'.", assembly.SourceContext)); return; } base.VisitAssembly(assembly); }
public void InsertQuarter() { CurrentState.InsertQuarter(); }
public static List <KeyValuePair <int, string> > getModesList(CurrentState cs) { log.Info("getModesList Called"); if (cs.firmware == MainV2.Firmwares.PX4) { /* * union px4_custom_mode { * struct { * uint16_t reserved; * uint8_t main_mode; * uint8_t sub_mode; * }; * uint32_t data; * float data_float; * }; */ var temp = new List <KeyValuePair <int, string> >() { new KeyValuePair <int, string>((int)PX4_CUSTOM_MAIN_MODE.PX4_CUSTOM_MAIN_MODE_MANUAL << 16, "Manual"), new KeyValuePair <int, string>((int)PX4_CUSTOM_MAIN_MODE.PX4_CUSTOM_MAIN_MODE_ACRO << 16, "Acro"), new KeyValuePair <int, string>((int)PX4_CUSTOM_MAIN_MODE.PX4_CUSTOM_MAIN_MODE_STABILIZED << 16, "Stabalized"), new KeyValuePair <int, string>((int)PX4_CUSTOM_MAIN_MODE.PX4_CUSTOM_MAIN_MODE_RATTITUDE << 16, "Rattitude"), new KeyValuePair <int, string>((int)PX4_CUSTOM_MAIN_MODE.PX4_CUSTOM_MAIN_MODE_ALTCTL << 16, "Altitude Control"), new KeyValuePair <int, string>((int)PX4_CUSTOM_MAIN_MODE.PX4_CUSTOM_MAIN_MODE_POSCTL << 16, "Position Control"), new KeyValuePair <int, string>((int)PX4_CUSTOM_MAIN_MODE.PX4_CUSTOM_MAIN_MODE_OFFBOARD << 16, "Offboard Control"), new KeyValuePair <int, string>( ((int)PX4_CUSTOM_MAIN_MODE.PX4_CUSTOM_MAIN_MODE_AUTO << 16) + (int)PX4_CUSTOM_SUB_MODE_AUTO.PX4_CUSTOM_SUB_MODE_AUTO_READY << 24, "Auto: Ready"), new KeyValuePair <int, string>( ((int)PX4_CUSTOM_MAIN_MODE.PX4_CUSTOM_MAIN_MODE_AUTO << 16) + (int)PX4_CUSTOM_SUB_MODE_AUTO.PX4_CUSTOM_SUB_MODE_AUTO_TAKEOFF << 24, "Auto: Takeoff"), new KeyValuePair <int, string>( ((int)PX4_CUSTOM_MAIN_MODE.PX4_CUSTOM_MAIN_MODE_AUTO << 16) + (int)PX4_CUSTOM_SUB_MODE_AUTO.PX4_CUSTOM_SUB_MODE_AUTO_LOITER << 24, "Loiter"), new KeyValuePair <int, string>( ((int)PX4_CUSTOM_MAIN_MODE.PX4_CUSTOM_MAIN_MODE_AUTO << 16) + (int)PX4_CUSTOM_SUB_MODE_AUTO.PX4_CUSTOM_SUB_MODE_AUTO_MISSION << 24, "Auto"), new KeyValuePair <int, string>( ((int)PX4_CUSTOM_MAIN_MODE.PX4_CUSTOM_MAIN_MODE_AUTO << 16) + (int)PX4_CUSTOM_SUB_MODE_AUTO.PX4_CUSTOM_SUB_MODE_AUTO_RTL << 24, "RTL"), new KeyValuePair <int, string>( ((int)PX4_CUSTOM_MAIN_MODE.PX4_CUSTOM_MAIN_MODE_AUTO << 16) + (int)PX4_CUSTOM_SUB_MODE_AUTO.PX4_CUSTOM_SUB_MODE_AUTO_LAND << 24, "Auto: Landing") }; return(temp); } else if (cs.firmware == MainV2.Firmwares.ArduPlane) { var flightModes = Utilities.ParameterMetaDataRepository.GetParameterOptionsInt("FLTMODE1", cs.firmware.ToString()); flightModes.Add(new KeyValuePair <int, string>(16, "INITIALISING")); flightModes.Add(new KeyValuePair <int, string>(17, "QStabilize")); flightModes.Add(new KeyValuePair <int, string>(18, "QHover")); flightModes.Add(new KeyValuePair <int, string>(19, "QLoiter")); flightModes.Add(new KeyValuePair <int, string>(20, "QLand")); flightModes.Add(new KeyValuePair <int, string>(21, "QRTL")); return(flightModes); } else if (cs.firmware == MainV2.Firmwares.Ateryx) { var flightModes = Utilities.ParameterMetaDataRepository.GetParameterOptionsInt("FLTMODE1", cs.firmware.ToString()); //same as apm return(flightModes); } else if (cs.firmware == MainV2.Firmwares.ArduCopter2) { var flightModes = Utilities.ParameterMetaDataRepository.GetParameterOptionsInt("FLTMODE1", cs.firmware.ToString()); return(flightModes); } else if (cs.firmware == MainV2.Firmwares.ArduRover) { var flightModes = Utilities.ParameterMetaDataRepository.GetParameterOptionsInt("MODE1", cs.firmware.ToString()); return(flightModes); } else if (cs.firmware == MainV2.Firmwares.ArduTracker) { var temp = new List <KeyValuePair <int, string> >(); temp.Add(new KeyValuePair <int, string>(0, "MANUAL")); temp.Add(new KeyValuePair <int, string>(1, "STOP")); temp.Add(new KeyValuePair <int, string>(2, "SCAN")); temp.Add(new KeyValuePair <int, string>(3, "SERVO_TEST")); temp.Add(new KeyValuePair <int, string>(10, "AUTO")); temp.Add(new KeyValuePair <int, string>(16, "INITIALISING")); return(temp); } return(null); }
public void EjectQuarter() { CurrentState.EjectQuarter(); }
public void OnEscapeButtonPressed(object sender, object args) { CurrentAbility = null; CurrentState.OnEscapeButtonPressed(); }
public void TurnCrank() { CurrentState.TurnCrank(); CurrentState.Dispense(); }
protected virtual IEnumerator Talking() { yield return new WaitForSeconds (talkingTime); currentState = CurrentState.CS_Walking; yield return null; }
//check on the type of the current state public bool IsInState(State <entity_type> s) { bool answ = (s.GetType() == CurrentState.GetType()); return(answ); }
private IEnumerator CrossStreet(GameObject _crossingTrigger) { yield return new WaitForSeconds (UnityEngine.Random.Range(0.35f, 0.55f)); currentState = CurrentState.CS_Crossing; GameObject newCamPoint = _crossingTrigger.GetComponent<CornerTrigger> ().GetCitizenCamerapoint (currentCamPoint); currentCamPoint = newCamPoint; transform.eulerAngles = new Vector3 (transform.eulerAngles.x, newCamPoint.transform.eulerAngles.y, newCamPoint.transform.eulerAngles.z); //Vector3 targetVec = transform.forward * _crossingTrigger.GetComponent<CornerTrigger> ().distanceToCross; while(isCrossing) { transform.position += (_crossingTrigger.transform.forward * moveSpeed * Time.deltaTime); yield return null; } direction = RandomDirection (); currentState = CurrentState.CS_Walking; yield return null; }
public override void VisitMethod(Method method) { if (method == null) return; // closures used from methods are visited from the method from which they are referenced if (HelperMethods.IsCompilerGenerated(method)) return; var savedState = this.currentState; try { this.currentState = savedState.Derive(method); if (this.contractNodes.IsObjectInvariantMethod(method)) { return; } // Check Abbreviators if (ContractNodes.IsAbbreviatorMethod(method)) { if (method.IsVirtual) { this.HandleError( new Error(1064, "Contract abbreviator method '" + method.FullName + "' cannot be virtual or implement an interface method.'", HelperMethods.SourceContextOfMethod(method))); } if (!HelperMethods.IsVoidType(method.ReturnType)) { this.HandleError( new Error(1060, "Contract abbreviator method '" + method.FullName + "' must have void return type.'", HelperMethods.SourceContextOfMethod(method))); } if (method.Contract != null) { #if false if (IsNonTrivial(method.Contract.ContractInitializer)) { this.HandleError(new Error(1061, "Contract abbreviator validator method '" + method.FullName + "' may not use closures.'", HelperMethods.SourceContextOfMethod(method))); } #endif if (method.Contract.HasLegacyValidations) { this.HandleError( new Error(1062, "Contract abbreviator '" + method.FullName + "' cannot contain if-then-throw contracts or validator calls. Only regular contracts and abbreviator calls are allowed.", HelperMethods.SourceContextOfMethod(method))); } if (method.Contract.EnsuresCount + method.Contract.RequiresCount == 0) { this.HandleError( new Warning(1063, "No contracts recognized in contract abbreviator '" + method.FullName + "'.", HelperMethods.SourceContextOfMethod(method))); } } else { // no contracts this.HandleError( new Warning(1063, "No contracts recognized in contract abbreviator '" + method.FullName + "'.", HelperMethods.SourceContextOfMethod(method))); } // abbreviator code must be completely visible to all callers as it is effectively inlined there. this.visibilityChecker.CheckRequires(method.Contract); this.visibilityChecker.CheckAbbreviatorEnsures(method.Contract); return; // no further checks as we check the rest in use-site methods. } // Check Contracts contents and visibility this.CheckMethodContract(method.Contract); // Check purity this.purityChecker.Check(method); // Check Method Body this.methodBodyChecker.Check(method); SourceContext sourceContext = HelperMethods.SourceContextOfMethod(method); Method firstRootMethod = null; var methodDeclaringType = method.DeclaringType; Contract.Assume(methodDeclaringType != null); TypeNode classForWhichThisIsContractMethod = HelperMethods.IsContractTypeForSomeOtherType(methodDeclaringType, this.contractNodes); foreach (var rootMethod in RootMethodsForRequires(method)) { Contract.Assume(rootMethod != null); if (classForWhichThisIsContractMethod != null) { if (method.Contract == null) continue; if (rootMethod.DeclaringType != classForWhichThisIsContractMethod) { this.HandleError( new Warning(1076, string.Format( "Contract class {2} cannot define contract for method {0} as its original definition is not in type {1}. Define the contract on type {3} instead.", rootMethod.FullName, classForWhichThisIsContractMethod, methodDeclaringType.FullName, rootMethod.DeclaringType), sourceContext)); continue; } if (!rootMethod.IsAbstract) { this.HandleError( new Error(1077, string.Format( "Contract class {1} cannot define contract for non-abstract method {0}. Define the contract on {0} instead.", rootMethod.FullName, methodDeclaringType.FullName), sourceContext)); continue; } // contract class methods can only override/implement the methods of their original type continue; } if (!allowPreconditionsInOverrides) { // Overrides cannot add preconditions unless this is "the" contract method for an abstract method if (method.Contract != null && method.Contract.Requires != null) { foreach (RequiresPlain req in method.Contract.Requires) { if (req == null) continue; if (!this.explicitUserValidations || !req.IsFromValidation) { SourceContext sc = req.SourceContext; if (rootMethod.DeclaringType is Interface) { this.HandleError( new Warning(1033, string.Format( "Method '{0}' implements interface method '{1}', thus cannot add Requires.", method.FullName, rootMethod.FullName), sc)); } else { this.HandleError( new Warning(1032, string.Format("Method '{0}' overrides '{1}', thus cannot add Requires.", method.FullName, rootMethod.FullName), sc)); } return; // only one error per method } } } // Multiple root methods with contracts // check that none of them have contracts if (firstRootMethod == null) { firstRootMethod = rootMethod; } else { bool someContracts = HasPlainRequires(GetMethodWithContractFor(rootMethod)) || HasPlainRequires(GetMethodWithContractFor(firstRootMethod)); if (someContracts) { // found 2 that are in conflict and at least one of them has contracts this.HandleError(new Warning(1035, String.Format( "Method '{0}' cannot implement/override two methods '{1}' and '{2}', where one has Requires.", method.FullName, firstRootMethod.FullName, rootMethod.FullName), sourceContext)); return; // only one error per method } } } // if (classForWhichThisIsContractMethod != null) continue; // skip rest of checks in this iteration // Check that validations are present if necessary if (this.explicitUserValidations && !HasValidations(method.Contract)) { var rootMethodContract = GetMethodWithContractFor(rootMethod).Contract; if (rootMethodContract != null) { for (int i = 0; i < rootMethodContract.RequiresCount; i++) { var req = (RequiresPlain) rootMethodContract.Requires[i]; if (req == null) continue; if (!req.IsWithException) continue; var operation = (rootMethod.DeclaringType is Interface) ? "implements" : "overrides"; if (req.SourceConditionText != null && req.ExceptionType.Name != null) { this.HandleError(new Warning(1055, String.Format( "Method '{0}' should contain custom argument validation for 'Requires<{3}>({2})' as it {4} '{1}' which suggests it does. If you don't want to use custom argument validation in this assembly, change the assembly mode to 'Standard Contract Requires'.", method.FullName, rootMethod.FullName, req.SourceConditionText, req.ExceptionType.Name.Name, operation), sourceContext)); } else { this.HandleError(new Warning(1055, String.Format( "Method '{0}' should contain custom argument validation as it {2} '{1}' which suggests it does. If you don't want to use custom argument validation in this assembly, change the assembly mode to 'Standard Contract Requires'.", method.FullName, rootMethod.FullName, operation), sourceContext)); return; // avoid dups } } } } } // Check that OOB types have no legacy requires (can't inherit them anyway, so should be Requires<E>) if (classForWhichThisIsContractMethod != null) { if (HasValidations(method.Contract)) { this.HandleError(new Error(1078, string.Format( "Method '{0}' annotating type '{1}' should use Requires<E> instead of custom validation.", method.FullName, classForWhichThisIsContractMethod.FullName), sourceContext)); } // skip rest of checks return; } // Explicit parameter validations should not use Requires<E> if (this.explicitUserValidations && method.Contract != null) { for (int i = 0; i < method.Contract.RequiresCount; i++) { var req = (RequiresPlain) method.Contract.Requires[i]; if (req == null) continue; if (req.IsFromValidation) continue; if (!req.IsWithException) continue; // found Requires<E> this.HandleError(new Error(1058, String.Format( "Method '{0}' should not have Requires<E> contract when assembly mode is set to 'Custom Parameter Validation'. Either change it to a legacy if-then-throw validation or change the assembly mode to 'Standard Contract Requires'.", method.FullName), req.SourceContext)); return; // avoid duplicate errors. } } // non-user validation assembly if (!this.explicitUserValidations && HasValidations(method.Contract)) { if (firstRootMethod != null) { this.HandleError(new Warning(1056, String.Format( "Method '{0}' has custom parameter validation but assembly mode is not set to support this. It will be ignored (but base method contract may be inherited).", method.FullName), sourceContext)); } else { this.HandleError(new Warning(1057, String.Format( "Method '{0}' has custom parameter validation but assembly mode is not set to support this. It will be treated as Requires<E>.", method.FullName), sourceContext)); } } // Check Validators if (ContractNodes.IsValidatorMethod(method)) { if (method.IsVirtual) { this.HandleError(new Error(1059, "Contract argument validator method '" + method.FullName + "' cannot be virtual or implement an interface method.'", HelperMethods.SourceContextOfMethod(method))); } if (!HelperMethods.IsVoidType(method.ReturnType)) { this.HandleError(new Error(1050, "Contract argument validator method '" + method.FullName + "' must have void return type.'", HelperMethods.SourceContextOfMethod(method))); } if (method.Contract != null) { #if false if (IsNonTrivial(method.Contract.ContractInitializer)) { this.HandleError(new Error(1051, "Contract argument validator method '" + method.FullName + "' may not use closures.'", HelperMethods.SourceContextOfMethod(method))); } #endif if (!method.Contract.HasLegacyValidations) { this.HandleError(new Warning(1053, "No validation code recognized in contract argument validator '" + method.FullName + "'.", HelperMethods.SourceContextOfMethod(method))); } if (HasNonValidationContract(method.Contract)) { this.HandleError(new Error(1054, "Contract argument validator '" + method.FullName + "' cannot contain ordinary contracts. Only if-then-throw or validator calls are allowed.", HelperMethods.SourceContextOfMethod(method))); } } else { // no validations this.HandleError(new Warning(1053, "No validation code recognized in contract argument validator '" + method.FullName + "'.", HelperMethods.SourceContextOfMethod(method))); } } } finally { this.currentState = savedState; } }
public virtual bool StartTalking() { if(currentState == CurrentState.CS_Walking) { currentState = CurrentState.CS_Talking; StartCoroutine(Talking ()); return true; } return false; }
public override void Update() { // only needs to update current state CurrentState.Update(); }
/// <summary> /// Returns whether a specific key is currently released up. /// </summary> /// <param name="key">Key to check</param> /// <returns>True on released up</returns> public Boolean IsKeyUp(Keys key) { return(CurrentState.IsKeyUp(key)); }
public override bool IsMovingDown() { return(CurrentState.IsKeyDown(Keys.A)); }
private void setCancelled() { _currentState = CurrentState.Canceled; }
public void Update() { GlobalState?.Execute(_owner); CurrentState?.Execute(_owner); }
private void btnOk_Click(object sender, EventArgs e) { _currentState = CurrentState.Accepted; }
////============================================================================= //// Private Method //// ////============================================================================= /// <summary> /// 再描画する /// </summary> private void Refresh() { CurrentState.Draw(this); }
public static void MapLogs(string[] logs) { foreach (var logfile in logs) { if (File.Exists(logfile + ".jpg")) continue; double minx = 99999; double maxx = -99999; double miny = 99999; double maxy = -99999; List<PointLatLngAlt> locs = new List<PointLatLngAlt>(); try { if (logfile.ToLower().EndsWith(".tlog")) { MAVLinkInterface mine = new MAVLinkInterface(); using (mine.logplaybackfile = new BinaryReader(File.Open(logfile, FileMode.Open, FileAccess.Read, FileShare.Read))) { mine.logreadmode = true; CurrentState cs = new CurrentState(); while (mine.logplaybackfile.BaseStream.Position < mine.logplaybackfile.BaseStream.Length) { byte[] packet = mine.readPacket(); if (packet.Length < 5) continue; try { if (MainV2.speechEngine != null) MainV2.speechEngine.SpeakAsyncCancelAll(); } catch { } if (packet[5] == (byte)MAVLink.MAVLINK_MSG_ID.GLOBAL_POSITION_INT) { var loc = packet.ByteArrayToStructure<MAVLink.mavlink_global_position_int_t>(6); if (loc.lat == 0 || loc.lon == 0) continue; locs.Add(new PointLatLngAlt(loc.lat / 10000000.0f, loc.lon / 10000000.0f)); minx = Math.Min(minx, loc.lon / 10000000.0f); maxx = Math.Max(maxx, loc.lon / 10000000.0f); miny = Math.Min(miny, loc.lat / 10000000.0f); maxy = Math.Max(maxy, loc.lat / 10000000.0f); } } } } else if (logfile.ToLower().EndsWith(".bin") || logfile.ToLower().EndsWith(".log")) { bool bin = logfile.ToLower().EndsWith(".bin"); using (var st = File.OpenRead(logfile)) { using (StreamReader sr = new StreamReader(st)) { while (sr.BaseStream.Position < sr.BaseStream.Length) { string line = ""; if (bin) { line = BinaryLog.ReadMessage(sr.BaseStream); } else { line = sr.ReadLine(); } if (line.StartsWith("FMT")) { DFLog.FMTLine(line); } else if (line.StartsWith("GPS")) { var item = DFLog.GetDFItemFromLine(line, 0); var lat = double.Parse(item.items[DFLog.FindMessageOffset(item.msgtype, "Lat")]); var lon = double.Parse(item.items[DFLog.FindMessageOffset(item.msgtype, "Lng")]); if (lat == 0 || lon == 0) continue; locs.Add(new PointLatLngAlt(lat, lon)); minx = Math.Min(minx, lon); maxx = Math.Max(maxx, lon); miny = Math.Min(miny, lat); maxy = Math.Max(maxy, lat); } } } } } if (locs.Count > 10) { // add a bit of buffer var area = RectLatLng.FromLTRB(minx - 0.001, maxy + 0.001, maxx + 0.001, miny - 0.001); var map = GetMap(area); var grap = Graphics.FromImage(map); PointF lastpoint = new PointF(); foreach (var loc in locs) { PointF newpoint = GetPixel(area, loc, map.Size); if (!lastpoint.IsEmpty) grap.DrawLine(Pens.Red, lastpoint, newpoint); lastpoint = newpoint; } map.Save(logfile + ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg); map.Dispose(); map = null; } else { var map = new Bitmap(100, 100); var grap = Graphics.FromImage(map); grap.DrawString("No gps data", SystemFonts.DefaultFont, Brushes.Red, 0, 0, StringFormat.GenericDefault); map.Save(logfile + ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg); map.Dispose(); map = null; } } catch { continue; } } }
public override int GetHashCode() { return(17 + 31 * CurrentState.GetHashCode() + 31 * Token.GetHashCode()); }
public override void VisitTypeNode(TypeNode typeNode) { if (typeNode == null) return; var savedState = this.currentState; this.currentState = savedState.Derive(typeNode); try { GatherInvariantMethods(typeNode.Members); this.CheckTypeNode(typeNode); base.VisitTypeNode(typeNode); this.invariantCallChecker.VisitMemberList(typeNode.Members); } finally { this.currentState = savedState; } }
public void PrintMyStatus() { Console.WriteLine("state= " + CurrentState.ToString()); Console.WriteLine("lever_position=" + CurrentLeverPosition.ToString()); }
public MoveGenerator(CurrentState initialState) { m_currentState = initialState.CurrentBoard; m_playerCharacter = initialState.NextMove; }
public bool HandleMessage(Telegram telegram) { return(CurrentState?.OnMessage(_owner, telegram) == true || GlobalState?.OnMessage(_owner, telegram) == true); }
private void Open() { Console.WriteLine($"In State Machine Class : Open"); CurrentState.Init(); }
public void ExecuteCurrentState() { CurrentState.Execute(this); }