/// <summary> /// Initializes a new instance. /// </summary> /// <param name="createModel">Creates the model that should be checked.</param> /// <param name="output">The callback that should be used to output messages.</param> /// <param name="configuration">The analysis configuration that should be used.</param> internal ModelTraverser(Func<AnalysisModel> createModel, Action<string> output, AnalysisConfiguration configuration) { Requires.NotNull(createModel, nameof(createModel)); Requires.NotNull(output, nameof(output)); TransitionCollection.ValidateTransitionSizes(); var tasks = new Task[configuration.CpuCount]; var stacks = new StateStack[configuration.CpuCount]; _loadBalancer = new LoadBalancer(stacks); Context = new TraversalContext(_loadBalancer, configuration, output); _workers = new Worker[configuration.CpuCount]; for (var i = 0; i < configuration.CpuCount; ++i) { var index = i; tasks[i] = Task.Factory.StartNew(() => { stacks[index] = new StateStack(configuration.StackCapacity); _workers[index] = new Worker(index, Context, stacks[index], createModel()); }); } Task.WaitAll(tasks); _states = new StateStorage(_workers[0].Model.StateVectorSize, configuration.StateCapacity); Context.States = _states; }
public static Vector3 StoredPosition(Transform element) { StateStorage storage = element.gameObject.GetComponent <StateStorage>(); if (storage != null) { return(storage.position); } else { return(Vector3.zero); } }
public static StateStorage Revert(this Transform t) { StateStorage storer = t.GetComponent <StateStorage>(); if (storer == null) { storer = t.gameObject.AddComponent <StateStorage>(); storer.Store(); } return(storer); }
IScannerState IScannerState.Read(TokenConstruction Current, char Read, StateStorage States) { if (Read == '*') { level.Increase(); return(States.Comment); } if (level.IsInNestedComment) { return(States.Comment); } throw new LexerException("Invalid comment start", Current.Line); }
/** Writes all static game data to storage with optional compression */ public static void WriteStaticDataToStorage(bool compression = false) { StateStorage.SaveData("Dungeon", Dungeon, compression); StateStorage.SaveData("Guilds", Guilds, compression); StateStorage.SaveData("Races", Races, compression); StateStorage.SaveData("ItemClasses", ItemClasses, compression); StateStorage.SaveData("ItemTypes", ItemTypes, compression); StateStorage.SaveData("Items", Items, compression); StateStorage.SaveData("MonsterClasses", MonsterClasses, compression); StateStorage.SaveData("MonsterTypes", MonsterTypes, compression); StateStorage.SaveData("Monsters", Monsters, compression); StateStorage.SaveData("SpellClasses", SpellClasses, compression); StateStorage.SaveData("Spells", Spells, compression); }
IScannerState IScannerState.Read(TokenConstruction Current, char Read, StateStorage States) { if (Read == 'h') { Current.Append(Read); return(States.While); } if (Read == 'r') { Current.Append(Read); return(States.Write); } return(States.Identifier.Read(Current, Read, States)); }
IScannerState IScannerState.Read(TokenConstruction Current, char Read, StateStorage States) { if (Read == 'c') { Current.Append(Read); return(States.PROcedure); } if (Read == 'g') { Current.Append(Read); return(States.PROgram); } return(States.Identifier.Read(Current, Read, States)); }
IScannerState IScannerState.Read(TokenConstruction Current, char Read, StateStorage States) { if (Read == 'o') { Current.Append(Read); return(States.Boolean); } if (Read == 'e') { Current.Append(Read); return(States.Begin); } return(States.Identifier.Read(Current, Read, States)); }
IScannerState IScannerState.Read(TokenConstruction Current, char Read, StateStorage States) { if (Read == 'l') { Current.Append(Read); return(States.Else); } if (Read == 'n') { Current.Append(Read); return(States.End); } return(States.Identifier.Read(Current, Read, States)); }
IScannerState IScannerState.Read(TokenConstruction Current, char Read, StateStorage States) { if (char.IsNumber(Read)) { Current.Append(Read); return(this); } if (Read == '.') { Current.Append(Read); return(States.RealLiteral); } Current.End(Symbol.IntegerLiteral); return(States.Base.Read(Current, Read, States)); }
IScannerState IScannerState.Read(TokenConstruction Current, char Read, StateStorage States) { if (Read == '=') { Current.End(Symbol.LessOrEqualThan); return(States.Base); } if (Read == '>') { Current.End(Symbol.NotEquals); return(States.Base); } Current.End(Symbol.LessThan); return(States.Base.Read(Current, Read, States)); }
private static void CleanStateCache(object o, CancellationToken cancellationToken) { try { foreach (var c in StateStorage.Where(i => i.Value.Created < DateTime.UtcNow.AddHours(-3)).ToArray()) { StardustContextProvider deprecatedItem; lock (StateStorage) StateStorage.TryRemove(c.Key, out deprecatedItem); } } catch { } }
public RaftState(MemberId myself, StateStorage <TermState> termStorage, RaftMembership membership, RaftLog entryLog, StateStorage <VoteState> voteStorage, InFlightCache inFlightCache, LogProvider logProvider, bool supportPreVoting, bool refuseToBeLeader) { this._myself = myself; this._termStorage = termStorage; this._voteStorage = voteStorage; this._membership = membership; this._entryLog = entryLog; this._inFlightCache = inFlightCache; this._supportPreVoting = supportPreVoting; this._log = logProvider.getLog(this.GetType()); // Initial state this._isPreElection = supportPreVoting; this._refuseToBeLeader = refuseToBeLeader; }
void OnTriggerEnter2D(Collider2D col) { if (col.name == "Feet") { this.GetComponent <StateStorage>().UpdateState(); foreach (Transform child in transform) { if (child.gameObject.layer == LayerMask.NameToLayer("Default")) { childLock = child.GetComponent <StateStorage>(); childLock.UpdateState(); } } } }
public RaftMachine(MemberId myself, StateStorage <TermState> termStorage, StateStorage <VoteState> voteStorage, RaftLog entryLog, LeaderAvailabilityTimers leaderAvailabilityTimers, Outbound <MemberId, RaftMessages_RaftMessage> outbound, LogProvider logProvider, RaftMembershipManager membershipManager, RaftLogShippingManager logShipping, InFlightCache inFlightCache, bool refuseToBecomeLeader, bool supportPreVoting, Monitors monitors) { this._myself = myself; this._leaderAvailabilityTimers = leaderAvailabilityTimers; this._outbound = outbound; this._logShipping = logShipping; this._log = logProvider.getLog(this.GetType()); this._membershipManager = membershipManager; this._inFlightCache = inFlightCache; this._state = new RaftState(myself, termStorage, membershipManager, entryLog, voteStorage, inFlightCache, logProvider, supportPreVoting, refuseToBecomeLeader); _raftMessageTimerResetMonitor = monitors.NewMonitor(typeof(RaftMessageTimerResetMonitor)); }
public void WriteStorage(DirectoryInfo directory, StateStorage storage) { directory .GetFiles(Fileter, SearchOption.AllDirectories) .ToList() .ForEach( e => e.Delete() ); foreach (var elem in storage.FilesData) { var fullPath = Path.Combine(directory.FullName, elem.Value.Relative, elem.Value.Name); FileProvider.CreateWithDirectory(fullPath, () => { File.WriteAllLines(fullPath, elem.Value.Text); }); } }
private bool CheckForMotorOnUp(StateStorage stateStorage) { uint nearestFloor = (uint)Math.Round(stateStorage.YPosition / SettingsStorage.Settings.FLOOR_Y_SIZE); int upCount = stateStorage.LiftCalls.Count(lc => lc.Floor >= nearestFloor) + stateStorage.FloorCalls.Count(fc => fc >= nearestFloor); if (upCount == 0) { return(false); } int totalCount = stateStorage.LiftCalls.Count + stateStorage.FloorCalls.Count; return(totalCount / 2.0 <= upCount); }
/// <summary> /// Initializes a new instance. /// </summary> /// <param name="context">The context of the traversal process.</param> /// <param name="transitionSizeInBytes">The size of a transition in bytes.</param> /// <param name="model">The runtime model the state graph is generated for.</param> /// <param name="createModel"> /// The factory function that should be used to create instances of the <see cref="RuntimeModel" /> /// the state graph is generated for. /// </param> internal StateGraph(TraversalContext context, int transitionSizeInBytes, TExecutableModel model, CoupledExecutableModelCreator <TExecutableModel> createModel) { Requires.NotNull(context, nameof(context)); TransitionSize = transitionSizeInBytes; RuntimeModel = model; RuntimeModelCreator = createModel; _stateStorage = context.States; _transitionCapacity = context.ModelCapacity.MemoryLimitTransitions.Value; _transitionsBuffer.Resize(_transitionCapacity, zeroMemory: false); _stateMapBuffer.Resize(context.ModelCapacity.NumberOfStates * sizeof(TransitionRange), zeroMemory: false); _transitions = _transitionsBuffer.Pointer; _stateMap = (TransitionRange *)_stateMapBuffer.Pointer; }
/// <summary> /// Initializes a new instance. /// </summary> /// <param name="context">The context of the traversal process.</param> /// <param name="stateFormulas">The state formulas that can be evaluated over the generated state graph.</param> /// <param name="transitionSizeInBytes">The size of a transition in bytes.</param> /// <param name="model">The runtime model the state graph is generated for.</param> /// <param name="createModel"> /// The factory function that should be used to create instances of the <see cref="RuntimeModel" /> /// the state graph is generated for. /// </param> internal StateGraph(TraversalContext context, Formula[] stateFormulas, int transitionSizeInBytes, RuntimeModel model, Func<RuntimeModel> createModel) { Requires.NotNull(context, nameof(context)); StateFormulas = stateFormulas; TransitionSize = transitionSizeInBytes; RuntimeModel = model; RuntimeModelCreator = createModel; _stateStorage = context.States; _transitionCapacity = context.Configuration.TransitionCapacity; _transitionsBuffer.Resize(TransitionSize * _transitionCapacity, zeroMemory: false); _stateMapBuffer.Resize(context.Configuration.StateCapacity * sizeof(TransitionRange), zeroMemory: false); _transitions = _transitionsBuffer.Pointer; _stateMap = (TransitionRange*)_stateMapBuffer.Pointer; }
/// <summary> /// Computes the model's initial states. /// </summary> public void ComputeInitialStates() { try { _states = _context._states; _model.ComputeInitialStates(_transitions); AddStates(); } catch (Exception e) { _context._loadBalancer.Terminate(); _context._exception = e; var trace = new[] { _model.ConstructionState, new byte[_model.StateVectorSize] }; var choices = new[] { _model.GetLastChoices() }; _context._counterExample = new CounterExample(_model, trace, choices, endsWithException: true); } }
void OnClickStart(long videoId, byte index) { CustomAudio.GetInstance().PlayCustomAudio(1002); string key = videoId + ":" + index; List <VideoAction> list = StateStorage.LoadData <List <VideoAction> >(key); if (list == null || list.Count == 0) { UMessage msg = new UMessage((uint)GameCity.EMSG_ENUM.CCVideoMsg_ApplyGetStepInfo); msg.Add(videoId); msg.Add(index); HallMain.videotcpclient.SendMsg(msg); } else { m_ActionsList = new List <VideoAction>(list); StartPlay(index); } }
/** Writes out each object in library, reads it back in, and makes sure they are the same */ private bool Validate <T>(DataLibrary <T> library) where T : NamedDataObject { List <string> differences = new List <string>(); foreach (NamedDataObject item in library) { StateStorage.SaveData("validationtest", item); object loadedItem = StateStorage.LoadData <T>("validationtest"); if (!Util.CompareProperites(item, loadedItem, ref differences)) { Trace.LogWarning("Validation failed on " + typeof(T) + ": " + String.Join(",", differences.ToArray()) + "]"); return(false); } } Trace.Log("Validation passed for " + typeof(T)); return(true); }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void shouldSetInitialPendingRequestToInitialState() public virtual void ShouldSetInitialPendingRequestToInitialState() { // Given //JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @SuppressWarnings("unchecked") org.neo4j.causalclustering.core.state.storage.StateStorage<ReplicatedLockTokenState> storage = mock(org.neo4j.causalclustering.core.state.storage.StateStorage.class); StateStorage <ReplicatedLockTokenState> storage = mock(typeof(StateStorage)); MemberId initialHoldingCoreMember = member(0); ReplicatedLockTokenState initialState = new ReplicatedLockTokenState(123, new ReplicatedLockTokenRequest(initialHoldingCoreMember, 3)); when(storage.InitialState).thenReturn(initialState); // When ReplicatedLockTokenStateMachine stateMachine = new ReplicatedLockTokenStateMachine(storage); // Then LockToken initialToken = stateMachine.CurrentToken(); assertEquals(initialState.Get().owner(), initialToken.Owner()); assertEquals(initialState.Get().id(), initialToken.Id()); }
void OnToggleChanged(Toggle t, string name, PageType pt, bool isOn, GameObject child) { if (isOn) { m_CurContestRankingToggle = null; CustomAudio.GetInstance().PlayCustomAudio(1003); if (pt == PageType.ePT_Chess) { m_CurContestRankingToggle = t.gameObject; if (ContestGameDataDictionary.ContainsKey(t.gameObject)) { string [] ValueString = ContestGameDataDictionary[t.gameObject].Split('|'); if (ValueString.Length == 2) { long ContestID = 0; long.TryParse(ValueString[0], out ContestID); int PlayetNumber = 0; int.TryParse(ValueString[1], out PlayetNumber); CGameContestRankingTifings.GetChessRankingInstance().SetSelectContestID(ContestID); CGameContestRankingTifings.GetChessRankingInstance().CreateGameRankingPlayerUIOjbect(PlayetNumber, true); } } CGameContestRankingTifings.GetChessRankingInstance().ResetChessRanking(); } else if (pt == PageType.ePT_Activity) { GameObject obj = t.transform.Find("ImageSpot").gameObject; if (obj.activeSelf) { NeedClick--; obj.SetActive(false); StateStorage.SaveData(pt + ":" + name, true); } } } if (child != null) { child.SetActive(isOn); } }
/** * Loads a file from storage and returns it. * Provides validiation and logging. * If the type is a library the library will be set as the global library for that type. * If min version is set an exception will be thrown if data doesn't meet minimum version. */ private static T LoadData <T>(string source, float minVersion = 0.0f, bool silent = false) where T : DataObject { if (!StateStorage.HasData(source)) { throw new Exception("Source not found [" + source + "]"); } T result = StateStorage.LoadData <T>(source); if (result.Version < minVersion) { throw new Exception(String.Format("File {0} has an old version, expecting {1} but found {2}", source, minVersion, result.Version)); } if (!silent) { Trace.Log(" - Loaded [" + source + "] (v" + result.Version.ToString("0.0") + ")"); } return(result); }
/// <summary> /// Checks whether the model's invariant holds for all states. /// </summary> public void Check() { _states = _context._states; try { while (_context._loadBalancer.LoadBalance(_index)) { int state; if (!_stateStack.TryGetState(out state)) { continue; } _transitions.Clear(); _model.ComputeSuccessorStates(_transitions, _states[state]); AddStates(); InterlockedExchangeIfGreaterThan(ref _context._levelCount, _stateStack.FrameCount, _stateStack.FrameCount); if (InterlockedExchangeIfGreaterThan(ref _context._nextReport, _context._stateCount, _context._nextReport + ReportStateCountDelta)) { _context.Report(); } } } catch (OutOfMemoryException e) { _context._loadBalancer.Terminate(); _context._exception = e; } catch (Exception e) { _context._loadBalancer.Terminate(); _context._exception = e; CreateCounterExample(endsWithException: true); } }
bool HandleStepInfo(uint _msgType, UMessage _ms) { m_ActionsList.Clear(); long nVideoid = _ms.ReadLong(); //录像ID byte nIndex = _ms.ReadByte(); //第几局 byte res = _ms.ReadByte(); //是否成功 1成功有数据 0没有 if (res == 0) { return(false); } ushort nSize = _ms.ReaduShort(); //有多少条数据 for (int i = 0; i < nSize; i++) { VideoAction ac = new VideoAction(); float nTime = _ms.ReadSingle(); //发生时间 ac.userId = _ms.ReadUInt(); //做这个事件的useid ushort nAction = _ms.ReaduShort(); //事件编号 ac.vai = (VideoActionInfo_Enum)nAction; ushort nParameterNum = _ms.ReaduShort(); //有多少参数 for (int k = 0; k < nParameterNum; k++) { int nParameter = _ms.ReadInt(); // ac.list.Add(nParameter); } m_ActionsList.Add(ac); } String key = nVideoid + ":" + nIndex; StateStorage.SaveData(key, m_ActionsList); StartPlay(nIndex); return(true); }
public static void SaveSettings() { if (!IsLoaded) { Trace.LogWarning("Tried saving settings, but settings are not yet loaded."); return; } XElement node = new XElement("Settings"); XElement subNode; subNode = new XElement("General"); General.WriteNode(subNode); node.Add(subNode); subNode = new XElement("Advanced"); Advanced.WriteNode(subNode); node.Add(subNode); StateStorage.SaveData("Settings", node); PlayerPrefs.Save(); }
/** Reads all settings from XML file */ public static void ReadSettings() { bool hasSettingsFile = StateStorage.HasData("Settings"); General = new GeneralSettings(); Advanced = new AdvancedSettings(); Information = new InformationSettings(); try { if (hasSettingsFile) { XElement rootNode = StateStorage.LoadXML("Settings"); if (rootNode == null) { Trace.LogWarning("No settings in file, resetting to default"); ResetSettings(); } else { Trace.Log("Reading settings"); General.Load(rootNode.Element("General")); Advanced.Load(rootNode.Element("Advanced")); } } else { Trace.Log("No settings file present, setting to default"); ResetSettings(); } } catch (Exception e) { Trace.LogWarning("Error while reading settings file:" + e.Message); ResetSettings(); } IsLoaded = true; }
public StateStorage ReadStorage(DirectoryInfo rootDirectory) { StateStorage storage = new StateStorage(); var files = rootDirectory.GetFiles(Fileter, SearchOption.AllDirectories); foreach (var elem in files) { var elemRelativePath = RelativePathFinder .GetRelativePath(elem.FullName, rootDirectory.FullName); storage.FilesData.Add( Path.Combine(elemRelativePath, elem.Name), new StorageData() { //FullName = elem.FullName, Name = elem.Name, Relative = elemRelativePath, Text = FileProvider.TryReadAllLines(elem.FullName) }); } return(storage); }
private static void runSteps(SchemaConnection connection, IOutput output, SchemaChangeOptions options, string phaseName, IEnumerable <ISchemaProvider> providers, ref DatabaseState currentState, ref ImmutableHashSet <ObjectType> objectTypes, ref StateStorage storage) { using (var progress = output.ProgressBlock()) { output.Message(phaseName + ": Starting..."); // Get object types, get steps, get desired state, get current state, everything else var chunks = progress.GetChunks(1, 1, 5, 5, 1, 50).ToList(); var oldTypes = objectTypes; using (chunks[0].Start()) { objectTypes = (from provider in providers from objectType in provider.GetObjectTypes(connection.SchemaDriver) select objectType).ToImmutableHashSet(); output.Verbose(phaseName + ": Object types: " + string.Join(", ", objectTypes)); } // Get all the steps and organize them into order IImmutableList <StepBase> steps; using (chunks[1].Start()) { steps = sortSteps(from objectType in objectTypes from step in objectType.Steps select step); output.Verbose(phaseName + ": Steps: " + string.Join(", ", steps)); } // Get the desired state DatabaseState desiredState; using (chunks[2].Start()) { output.Verbose(phaseName + ": Determining desired database state..."); desiredState = DatabaseState.Create(from provider in providers from state in provider.GetDesiredState(connection, chunks[2]) select state); foreach (var overrideProvider in providers.OfType <ISchemaOverrideProvider>()) { desiredState = overrideProvider.ApplyOverrides(connection, desiredState); } output.Message(phaseName + ": " + counted(desiredState.Count, "object") + " desired."); } ObjectTypeHelper helper; using (chunks[3].Start()) { // Get the current state output.Verbose(phaseName + ": Determining current database state..."); helper = new ObjectTypeHelper(objectTypes, storage != null, connection.DbDriver); currentState = currentState.With(from objectType in objectTypes where !oldTypes.Contains(objectType) from state in objectType.GetExistingObjects(connection, helper) select state); output.Verbose(phaseName + ": " + counted(currentState.Count, "object") + " existing."); } // Filter to only things that are relevant here using (chunks[4].Start()) { output.Verbose(phaseName + ": Filtering..."); if (storage != null) { var priorKnownRoots = storage.GetKnownRoots(helper); var priorKnownSubs = storage.GetKnownSubs(helper); // Anything that exists in *both* current and desired is treated as known and assumed to be in-scope for consideration var knownRoots = priorKnownRoots.Union(from root in currentState.RootObjects where desiredState.Contains(root) select root.Identifier); foreach (var extra in knownRoots.Except(priorKnownRoots)) { storage.PutRoot(extra); } // FIXME: remove from storage anything that's of a type that's under consideration but is neither current nor desired var knownSubs = priorKnownSubs.Union(from sub in currentState.AllChildren where desiredState.Contains(sub) select Tuple.Create(sub.ParentIdentifier, sub.Identifier)); foreach (var extra in knownSubs.Except(priorKnownSubs)) { storage.PutSub(extra.Item1, extra.Item2); } // FIXME: remove from storage anything that's of a type that's under consideration but is neither current nor desired var _storage = storage; var initialState = currentState; currentState = currentState.WithFilters((root) => desiredState.ContainsRoot(root) || Objects.Tables.TableRenameType.ContainsRenameTo(desiredState, root) || Objects.Tables.PendingReorderTableType.IsTablePendingReorder(initialState, root) || (options.PreserveUnknownObjects ? !initialState.ContainsRoot(root) : _storage.ContainsRoot(root)), null); } else { // FIXME this doesn't allow for any flexibility in whether the nrdo_ tables live in dbo currentState = currentState.WithFilters(root => root.Name.StartsWith("dbo.nrdo_", StringComparison.OrdinalIgnoreCase), null); } output.Message(phaseName + ": " + counted(currentState.Count, "applicable existing object") + "."); } var isFullRun = storage != null; if (isFullRun) { // Sanity check for any before statements that will be skipped due to the associated step not existing var stepSet = new HashSet <string>(from step in steps select step.Identifier, Nstring.DBEquivalentComparer); var current = currentState; // Can't use ref parameter directly inside linq query var unknownBefores = from stmt in BeforeStatementType.AllFrom(desiredState) where !stepSet.Contains(stmt.State.Step) && !current.Contains(stmt) select stmt; foreach (var stmt in unknownBefores) { output.Warning(stmt.Name + " on " + stmt.ParentIdentifier + " will not be executed because there is no such step as " + stmt.State.Step); } } var changes = SchemaChanges.Create(currentState, desiredState, connection, chunks[5], options, storage); changes.PerformSteps(steps, phaseName, isFullRun); currentState = changes.Current.WithoutFilters(); storage = changes.Storage; if (changes.HasFailed) { throw new ApplicationException("Schema update failed"); } output.Message(phaseName + ": Completed."); output.Message(phaseName + ": " + counted(changes.StatementCount, "statement") + " executed."); output.Message(phaseName + ": " + counted(currentState.Count, "object") + " existing."); } }
/// <summary> /// 加载游戏排行榜数据 /// </summary> public void LoadContestRankingData(List <long> ContestIDList) { if (ContestIDList.Count == 0) { return; } SerializableDictionary <long, SerializableDictionary <int, CPlayerRankingInfo> > ContestRankingDictionary = StateStorage.LoadData <SerializableDictionary <long, SerializableDictionary <int, CPlayerRankingInfo> > >(Key); if (ContestRankingDictionary != null) { ContestRankingDataDictionary = ContestRankingDictionary; } List <long> RemoveIDList = new List <long>(); foreach (var value in ContestRankingDataDictionary.Keys) { if (ContestIDList.FindIndex(id => { return(value == id); }) == -1) { RemoveIDList.Add(value); } } foreach (var keyId in RemoveIDList) { ContestRankingDataDictionary.Remove(keyId); } }