/** * Returns the states by Continent id * * @param continentID : id of the continent * @return : Arraylist of States */ public ArrayList<State> getStatesByContinentID(int continentID) { ArrayList<State> stateList = new ArrayList<State>(); for (State tempState : this.myStateList) { if (tempState.getContinentID() == continentID) stateList.add(tempState); } return stateList; }
public static void main(String args[]) { if (args.length < 3) usage(null); try { int nThreads = parseInt(args[1], 1, Integer.MAX_VALUE); int nTransitions = parseInt(args[2], 0, Integer.MAX_VALUE); byte maxval = (byte) parseInt(args[3], 0, 127); byte[] value = new byte[args.length - 4]; for (int i = 4; i < args.length; i++) value[i - 4] = (byte) parseInt(args[i], 0, maxval); byte[] stateArg = value.clone(); State s; if (args[0].equals("Null")) s = new NullState(stateArg, maxval); else if (args[0].equals("Synchronized")) s = new SynchronizedState(stateArg, maxval); else if (args[0].equals("UnSynchronized")) s = new UnSynchronizedState(stateArg, maxval); else if (args[0].equals("GetNSet")) s = new GetNSet(stateArg, maxval); else if (args[0].equals("BetterSafe")) s = new BetterSafe(stateArg, maxval); else if (args[0].equals("BetterSorry")) s = new BetterSorry(stateArg, maxval); else throw new Exception(args[0]); dowork(nThreads, nTransitions, s); test(value, s.current(), maxval); System.exit(0); } catch (Exception e) { usage(e); } }
private static void initializeAndModify( TypesCache temporaryTypes, ObjectType type, List<Class<?>> modifications) { State typeState = type.getState(); Map<String, Object> typeOriginals = typeState.getSimpleValues(); try { type.initialize(); temporaryTypes.add(type); // Apply type-specific modifications. if (modifications != null) { for (Class<?> modification : modifications) { type.modify(modification); } } } catch (IncompatibleClassChangeError ex) { LOGGER.info( "Skipped initializing [{}] because its class is in an inconsistent state! ([{}])", type.getInternalName(), ex.getMessage()); } if (typeState.isNew()) { type.save(); } else if (!typeState.getSimpleValues().equals(typeOriginals)) { temporaryTypes.changed.add(type.getId()); } }
/** * Print usage information about threads from this factory to logger with the provided priority * * @param logger */ public synchronized void printUsageInformation(final Logger logger, final Priority priority) { logger.debug("Number of threads monitored: " + getnThreadsAnalyzed()); logger.debug( "Total runtime " + new AutoFormattingTime(TimeUnit.MILLISECONDS.toNanos(getTotalTime()))); for (final State state : State.values()) { logger.debug( String.format( "\tPercent of time spent %s is %.2f", state.getUserFriendlyName(), getStatePercent(state))); } logger.log( priority, String.format( "CPU efficiency : %6.2f%% of time spent %s", getStatePercent(State.USER_CPU), State.USER_CPU.getUserFriendlyName())); logger.log( priority, String.format( "Walker inefficiency : %6.2f%% of time spent %s", getStatePercent(State.BLOCKING), State.BLOCKING.getUserFriendlyName())); logger.log( priority, String.format( "I/O inefficiency : %6.2f%% of time spent %s", getStatePercent(State.WAITING_FOR_IO), State.WAITING_FOR_IO.getUserFriendlyName())); logger.log( priority, String.format( "Thread inefficiency : %6.2f%% of time spent %s", getStatePercent(State.WAITING), State.WAITING.getUserFriendlyName())); }
/** * Compares this LTS to another for debugging purposes. * * @param other the other LTS to compare to * @return <code>true</code> if these are equivalent */ public boolean compare(LetterToSound other) { // compare letter index table // for (Iterator i = letterIndex.keySet().iterator(); i.hasNext(); ) { String key = (String) i.next(); Integer thisIndex = (Integer) letterIndex.get(key); Integer otherIndex = (Integer) other.letterIndex.get(key); if (!thisIndex.equals(otherIndex)) { if (RiTa.PRINT_LTS_INFO) System.err.println("[WARN] LTSengine -> Bad index: " + key); return false; } } // compare states // for (int i = 0; i < stateMachine.length; i++) { State state = getState(i); State otherState = other.getState(i); if (!state.compare(otherState)) { if (RiTa.PRINT_LTS_INFO) System.err.println("[WARN] LTSengine -> Bad state: " + i); return false; } } return true; }
@Override public void handleStart(Operation start) { ServiceUtils.logInfo(this, "Starting service %s", getSelfLink()); State startState = start.getBody(State.class); InitializationUtils.initialize(startState); if (null == startState.queryCreateVmTaskInterval) { startState.queryCreateVmTaskInterval = HostUtils.getDeployerContext(this).getTaskPollDelay(); } validateState(startState); if (TaskState.TaskStage.CREATED == startState.taskState.stage) { startState.taskState.stage = TaskState.TaskStage.STARTED; } start.setBody(startState).complete(); try { if (ControlFlags.isOperationProcessingDisabled(startState.controlFlags)) { ServiceUtils.logInfo(this, "Skipping patch handling (disabled)"); } else if (TaskState.TaskStage.STARTED == startState.taskState.stage) { TaskUtils.sendSelfPatch(this, buildPatch(startState.taskState.stage, (Throwable) null)); } } catch (Throwable t) { failTask(t); } }
@Override protected void handleUpdateState(State state, Object arg) { state.visible = true; state.label = mContext.getString(R.string.quick_settings_visualizer_label); mUiHandler.post(mUpdateVisibilities); }
protected int maxValue(State s, int alpha, int beta, int counter) { // System.out.println(counter); if (s.isTerminal() || counter > maxdepth) return utility(s); else if (!s.isTerminal()) { List<Move> moves = s.getPossibleMoves(); int maxv = Integer.MIN_VALUE; // System.out.println(moves.size()); for (Move move : moves) { // System.out.println("max"); int v = minValue(result(s, move), alpha, beta, counter + 1); // utility(s); /*int m = minValue(result(s,move),alpha,beta,counter++); if( m > v) v = m;*/ // System.out.println(); if (v > maxv) { maxv = v; } if (maxv >= beta) return maxv; alpha = Math.max(alpha, maxv); } return maxv; } else return 0; }
void backup(State s) { try { int len = s.getGroupLength(n); s.offset -= len; } catch (NoSuchMatchException e) { } }
public TransitionIterator( State source, FeatureSequence inputSeq, int inputPosition, String output, HMM hmm) { this.source = source; this.hmm = hmm; this.inputSequence = inputSeq; this.inputFeature = new Integer(inputSequence.getIndexAtPosition(inputPosition)); this.inputPos = inputPosition; this.weights = new double[source.destinations.length]; for (int transIndex = 0; transIndex < source.destinations.length; transIndex++) { if (output == null || output.equals(source.labels[transIndex])) { weights[transIndex] = 0; // xxx should this be emission of the _next_ observation? // double logEmissionProb = // hmm.emissionMultinomial[source.getIndex()].logProbability // (inputSeq.get (inputPosition)); int destIndex = source.getDestinationState(transIndex).getIndex(); double logEmissionProb = hmm.emissionMultinomial[destIndex].logProbability(inputSeq.get(inputPosition)); double logTransitionProb = hmm.transitionMultinomial[source.getIndex()].logProbability( source.destinationNames[transIndex]); // weight = logProbability weights[transIndex] = (logEmissionProb + logTransitionProb); assert (!Double.isNaN(weights[transIndex])); } else weights[transIndex] = IMPOSSIBLE_WEIGHT; } nextIndex = 0; while (nextIndex < source.destinations.length && weights[nextIndex] == IMPOSSIBLE_WEIGHT) nextIndex++; }
public Action absearch(State state, int d) { int score; int mi = 0; int mj = 0; alpha = Integer.MIN_VALUE; beta = Integer.MAX_VALUE; int best = alpha; startTime = System.currentTimeMillis(); for (int i = 0; i < state.board.length; i++) { for (int j = 0; j < state.board.length; j++) { if (state.board[i][j] == 0) { state.move(i, j, false); score = minValue(state, d - 1); state.undo(i, j); // undo move // System.out.printf("%+4d", score); if (score > best) { mi = i; mj = j; best = score; } } // else // System.out.print(" [] "); // Potential random choice area. need list and PRNG } System.out.println(); } // System.out.println(best); return new Action(mi, mj); }
/** * Adds a state to the FSM. The name of the state is taken from the state object. The first state * added automatically becomes the initial state that the FSM starts in. * * @param state state behavior. */ public void add(State state) { if (states.containsKey(state.name)) throw new FjageError("Duplicate state name: " + state.name); states.put(state.getName(), state); state.fsm = this; state.log = log; if (initial == FINAL) initial = state; }
/** * This method finds the adjacent countries of a country * * @param opponentStates The states which we want to find their countries * @return Countries which are adjacent to a specific country */ public ArrayList<Country> getAdjacentCountries(ArrayList<State> opponentStates) { ArrayList<Country> opponentCountries = new ArrayList<Country>(); ArrayList<Integer> opponentCountriesID = new ArrayList<Integer>(); for (State state : opponentStates) { opponentCountriesID.add(state.getCountryID()); } // Creating a hashset to remove duplicate IDs HashSet countryHashSet = new HashSet(opponentCountriesID); opponentCountriesID.clear(); opponentCountriesID = new ArrayList(countryHashSet); // Finding countries which correspond to the IDs for (Integer countryID : opponentCountriesID) { for (Country country : this.myCountryList) { if (countryID == country.getCountryID()) { opponentCountries.add(country); break; } } } return opponentCountries; }
/** * This method finds the adjacent opponent states of a country * * @param countryID The ID of the country which we want to find its neighboring states * @return List of neighbouring states */ public ArrayList<State> getAdjacentOpponentStates(int countryID) { ArrayList<State> ownStates = new ArrayList<State>(); ArrayList<State> opponentStates = new ArrayList<State>(); ownStates = getStatesByCountryID(countryID); for (State myState : ownStates) { // Checking if the source state is our state for (Link tempLink : this.myLinkList) { if (tempLink.getSourceState().getStateID() == myState.getStateID()) // Check if adjacent state is an opponent state if (tempLink.getDestintionState().getCountryID() != countryID) opponentStates.add(tempLink.getDestintionState()); } // Checking if the destination state is our state for (Link tempLink : this.myLinkList) { if (tempLink.getDestintionState().getStateID() == myState.getStateID()) // Check if adjacent state is an opponent state if (tempLink.getSourceState().getCountryID() != countryID) opponentStates.add(tempLink.getSourceState()); } } // Creating a hashset to remove duplicate states HashSet stateHashSet = new HashSet(opponentStates); opponentStates.clear(); opponentStates = new ArrayList(stateHashSet); return opponentStates; }
public static float trajectoryReward( State initialState, Policy p, int nbOfSteps, LinkedList<State> statesTrajectory, LinkedList<Action> actionsTrajectory, LinkedList<Float> rewardsTrajectory) { State s = initialState; Action a = p.chooseAction(s); float trajectoryReward = reward(s, a); if (statesTrajectory != null) { statesTrajectory.add(s); actionsTrajectory.add(a); rewardsTrajectory.add(reward(s, a)); } int nbOfIterations = 1; while (!s.isTerminal() && nbOfIterations < nbOfSteps) { s = MarkovDecisionProcess.nextState(s, a); a = p.chooseAction(s); trajectoryReward += reward(s, a); if (statesTrajectory != null) { statesTrajectory.add(s); actionsTrajectory.add(a); rewardsTrajectory.add(reward(s, a)); } nbOfIterations++; } return trajectoryReward; }
static { for (State state : State.values()) { mapping.put(state.getNodeName(), state); mapping2.put(state.getName(), state); mapping3.put(state.getId(), state); } }
/** * Have the computer play against itself, putting output int the default Java console. You can * also have your new AI player play from here, with no GUI output. It may be useful for testing. * If you want a human to play, use GUI.main. */ public static void main(String[] args) { /* p1 is the first player, p2 is the second player. This is set to * have to Dummy players--playing randomly. * To play the game with your own AI object, use assignments like you * see in the comments after these two assignments. In those assignments, * the second argument of the constructor is the depth to which AI * searches the game space. */ Solver p1 = new Dummy(Board.Player.RED); Solver p2 = new Dummy(Board.Player.YELLOW); // Solver p1= new AI(Board.Player.RED, 5); // Solver p2= new AI(Board.Player.YELLOW, 5); Game game = new Game(p1, p2); game.runGame(); // testGetPossibleMoves(); // Board a = new Board(); // State y = new State(Board.Player.RED, a, null); // y.initializeChildren(); // testInitializeChildren(y); Board b = new Board(); State newState = new State(Board.Player.RED, b, null); AI ai = new AI(Board.Player.RED, 2); ai.createGameTree(newState, 2); ai.minimax(newState); newState.writeToFile(); }
public void actionPerformed(ActionEvent e) { if (e.getSource() == btnReset) { stateGraphGraphics.auto.decolore(); stateGraphGraphics.repaint(); } if (e.getSource() == btnCycle) { stateGraphGraphics.auto.decolore(); stateGraphGraphics.auto.colore(cycles.get(cyclesBox.getSelectedIndex()), true); stateGraphGraphics.repaint(); } if (e.getSource() == btnPath) { stateGraphGraphics.auto.decolore(); Path path = new Path( lines, combinasion.get(oneState.getSelectedIndex()), combinasion.get(twoStates.getSelectedIndex())); if (path.paths.size() != 0) { for (int i = 0; i < path.paths.size(); i++) { stateGraphGraphics.auto.colore(path.paths.get(i), false); } } for (State etat : stateGraphGraphics.auto.vStates) { if (etat.label.equals(combinasion.get(oneState.getSelectedIndex()).toString()) || etat.label.equals(combinasion.get(twoStates.getSelectedIndex()).toString())) etat.couleurFond = Color.green; } stateGraphGraphics.repaint(); } }
/** * Add a new state to the state machine. Bottom up addition of states is allowed but the same * state may only exist in one hierarchy. * * @param state the state to add * @param parent the parent of state * @return stateInfo for this state */ private final StateInfo addState(State state, State parent) { if (mDbg) { Log.d( TAG, "addStateInternal: E state=" + state.getName() + ",parent=" + ((parent == null) ? "" : parent.getName())); } StateInfo parentStateInfo = null; if (parent != null) { parentStateInfo = mStateInfo.get(parent); if (parentStateInfo == null) { // Recursively add our parent as it's not been added yet. parentStateInfo = addState(parent, null); } } StateInfo stateInfo = mStateInfo.get(state); if (stateInfo == null) { stateInfo = new StateInfo(); mStateInfo.put(state, stateInfo); } // Validate that we aren't adding the same state in two different hierarchies. if ((stateInfo.parentStateInfo != null) && (stateInfo.parentStateInfo != parentStateInfo)) { throw new RuntimeException("state already added"); } stateInfo.state = state; stateInfo.parentStateInfo = parentStateInfo; stateInfo.active = false; if (mDbg) Log.d(TAG, "addStateInternal: X stateInfo: " + stateInfo); return stateInfo; }
@Override public double evaluate(State<Position> s1, State<Position> s2) { return Math.abs( (s2.getState().getX() - s1.getState().getX()) + (s2.getState().getY() - s1.getState().getY()) + (s2.getState().getZ() - s1.getState().getZ())); }
public void leaveElement(UnmarshallingContext.State state, TagName ea) throws SAXException { State s = (State) state.target; UnmarshallingContext context = state.getContext(); try { s.handler.endElement(ea.uri, ea.local, ea.getQname()); s.undeclarePrefixes(context.getNewlyDeclaredPrefixes()); } catch (SAXException e) { context.handleError(e); throw e; } if ((--s.depth) == 0) { // emulate the end of the document try { s.undeclarePrefixes(context.getAllDeclaredPrefixes()); s.handler.endDocument(); } catch (SAXException e) { context.handleError(e); throw e; } // we are done state.target = s.getElement(); } }
private static void solve(State initState) { Set<State> visited = new HashSet<State>(); Map<State, State> pred = new HashMap<State, State>(); Map<State, Integer> dist = new HashMap<State, Integer>(); Deque<State> bfs = new ArrayDeque<State>(); bfs.offer(initState); dist.put(initState, 0); while (bfs.size() > 0) { State s = bfs.poll(); int n = dist.get(s); visited.add(s); if (s.isFinal()) { outputState(s, pred); return; } for (State child : s.getChildren()) { if (visited.contains(child)) continue; if (!pred.containsKey(child)) pred.put(child, s); if (!dist.containsKey(child)) { dist.put(child, n + 1); bfs.offer(child); } } } System.out.printf("%d %d %d\n", initState.a, initState.b, initState.c); System.out.println("============"); }
protected <T> boolean match( int bid, SequenceMatcher.MatchedStates<T> matchedStates, boolean consume) { matchedStates .getBranchStates() .setMatchStateInfo( bid, this, new ConjMatchStateInfo(bid, childCount, matchedStates.curPosition)); // Start of conjunction, mark start boolean allMatch = true; if (next != null) { int i = 0; for (State s : next) { i++; boolean m = s.match( matchedStates.getBranchStates().getBranchId(bid, i, next.size()), matchedStates, consume); if (!m) { allMatch = false; break; } } } return allMatch; }
@Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { // Are we finished, if so, clean up if (roundEnv.processingOver()) { state = null; return false; } // Newly initialized or being reused? if (state == null) { state = forceErrors ? new State.ForTesting(processingEnv) : new State(processingEnv); if (state.isPoisoned()) { // Could not initialize State object, bail out return false; } // Produce a "lite" map just for JRE-only clients state.setClientOnly(clientOnly); // Disallow @ProxyForName or @ServiceName that can't be resolved state.setMustResolveAllMappings(mustResolveAllMappings); } try { // Bootstrap the State's work queue new Finder().scan(getTypesToProcess(state, roundEnv), state); // Execute the work items state.executeJobs(); } catch (HaltException ignored) { // Already logged. Let any unhandled RuntimeExceptions fall out. } return false; }
private void convertToDFA(NFA nfa) { DFAState curr, temp; List<String> tokens = new ArrayList<String>(); LinkedList<DFAState> queue = new LinkedList<DFAState>(); findStart(nfa); queue.add(start); MAINWHILE: while (!queue.isEmpty()) { curr = queue.removeFirst(); for (DFAState sta : checked) { if (curr.equals(sta)) { // System.out.println("NOPE"); continue MAINWHILE; } } checked.add(curr); // Pull out all keys for (State s : curr.getStates()) { for (String k : s.getTransitionTable().keySet()) { tokens.add(k); // System.out.println(tokens); } } // Iterate over all possible iterations and link states together for (String j : tokens) { if (!j.equals("")) { temp = goTo(curr, j); queue.add(temp); } } } }
private static State replicateStateSequenceBranch( HashMap<Long, State> stateMap, State curRef, State startRef, State endRef) { if (stateMap == null || curRef == null) return null; State addTo = createOrGetStateFromMap(stateMap, curRef); for (Connection c : curRef.connections) { State newS = null; if (c.cyclic) { if (curRef.name == startRef.name) continue; newS = createOrGetStateFromMap(stateMap, c.to); } else { if (endRef != null && curRef.name == endRef.name) continue; newS = replicateStateSequenceBranch(stateMap, c.to, startRef, endRef); } if (newS == null) continue; addTo.connect(newS, c.character, c.cyclic); } return addTo; }
/** Called when the activity is first created. */ @Override public void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); // set language MainActivity.setLocale(this); setContentView(R.layout.map); finishing = new AtomicBoolean(false); // media volume this.setVolumeControlStream(AudioManager.STREAM_MUSIC); final Object stored = getLastNonConfigurationInstance(); IGeoPoint oldCenter = null; int oldZoom = Integer.MIN_VALUE; if (stored != null && stored instanceof State) { // pry an orientation change, which calls destroy, but we set this in // onRetainNonConfigurationInstance final State retained = (State) stored; state.locked = retained.locked; state.firstMove = retained.firstMove; oldCenter = retained.oldCenter; oldZoom = retained.oldZoom; } setupMapView(oldCenter, oldZoom); setupTimer(); }
/** * Initialises the renderer. * * <p>This method will be called before the first item is rendered, giving the renderer an * opportunity to initialise any state information it wants to maintain. The renderer can do * nothing if it chooses. * * @param g2 the graphics device. * @param dataArea the area inside the axes. * @param plot the plot. * @param data the data. * @param info an optional info collection object to return data back to the caller. * @return The renderer state. */ public XYItemRendererState initialise( Graphics2D g2, Rectangle2D dataArea, XYPlot plot, XYDataset data, PlotRenderingInfo info) { State state = new State(info); state.seriesPath = new GeneralPath(); return state; }
/** * Runs the FSM until a FinalState is reached * * @param in the Input * @return the final state the validator has reached */ private State validate(Input in) { State s = States.Init; while (!(s instanceof FinalState)) { s = s.next(in); } return s; }
@Override public void format(HtmlWriter writer) throws IOException { writer.writeStart("pre"); State state = getState(); ObjectType type = state.getType(); if (type != null) { writer.writeHtml(type.getInternalName()); writer.writeHtml(": "); } writer.writeStart( "a", "target", "_blank", "href", StringUtils.addQueryParameters( "/_debug/query", "where", "id = " + state.getId(), "action", "Run")); writer.writeHtml(getLabel()); writer.writeEnd(); writer.writeElement("br"); writer.writeHtml(ObjectUtils.toJson(state.getSimpleValues(), true)); writer.writeEnd(); }