Esempio n. 1
0
  boolean tryDrive() {
    lastdir = 5;
    positions.clear();

    for (int z = 0; z < MAX_TRAFFIC_DISTANCE; z++) // maximum distance to try
    {
      if (tryGo(z)) {
        // got a road
        if (driveDone()) {
          // destination reached
          return true;
        }
      } else {
        // deadend, try backing up
        if (!positions.isEmpty()) {
          positions.pop();
          z += 3;
        } else {
          return false;
        }
      }
    }

    // gone maxdis
    return false;
  }
Esempio n. 2
0
  /** Create a random Json document with random values */
  public String getRandomJson(int nbNodes) {
    // init
    sb.setLength(0);
    sb.append("{");
    states.clear();
    states.add(OBJECT_ATT);
    images.clear();
    nodes.clear();
    incr.clear();
    datatypes.clear();
    types.clear();
    curNodePath.length = 1;
    curNodePath.offset = 0;
    Arrays.fill(curNodePath.ints, -1);
    shouldFail = false;
    nestedObjs = 0;

    // <= so that when nbNodes == 1, the json is still valid
    /*
     * the generated json might be uncomplete, if states is not empty, and
     * the maximum number of nodes has been reached.
     */
    for (final int i = 0; i <= nbNodes && !states.empty(); nbNodes++) {
      sb.append(this.getWhitespace()).append(this.getNextNode()).append(this.getWhitespace());
    }
    shouldFail = shouldFail ? true : !states.empty();
    return sb.toString();
  }
Esempio n. 3
0
  /**
   * 清除所有buffers,常用于显示出错信息。
   *
   * @throws IllegalStateException 如果response已经commit
   */
  public void resetBuffer() {
    if (buffering) {
      flushBufferAdapter();

      if (stream != null) {
        bytesStack.clear();
        bytesStack.add(new ByteArrayOutputStream());
        ((BufferedServletOutputStream) stream).updateOutputStream(bytesStack.peek());
      }

      if (writer != null) {
        charsStack.clear();
        charsStack.add(new StringWriter());
        ((BufferedServletWriter) writer).updateWriter(charsStack.peek());
      }
    }

    super.resetBuffer();
  }
  // 建立语法树
  public void buildSymbolTree() {
    offset = 0;
    braceNesting = 0; // 花括号嵌套
    scopes.clear(); // 清空栈
    indexedScopes.clear(); // 清空哈希表
    indexedScopes.put(new Integer(0), globalScope); // gloabalScope为ScriptOrFnScope对象,构造函数参数为-1,null
    mode = BUILDING_SYMBOL_TREE; // (BUILDING_SYMBOL_TREE值为1)
    parseScope(globalScope);

    globalScope.warning();
  }
  public static void main(String[] args) throws IOException {
    br = new BufferedReader(new InputStreamReader(System.in));
    out = new PrintWriter(new OutputStreamWriter(System.out));
    // br = new BufferedReader(new FileReader("in.txt"));
    // out = new PrintWriter(new FileWriter("out.txt"));

    N = readInt();

    val = new int[N];
    hi = new int[N];
    lo = new int[N];
    poss = new ArrayList<ArrayList<Integer>>();
    intervals = new TreeSet<Interval>();

    for (int i = 0; i < N; i++) val[i] = readInt();

    for (int i = 0; i < 2 * N; i++) poss.add(new ArrayList<Integer>());

    Stack<State> s = new Stack<State>();

    // processing upper bound (first number less than the current number)
    for (int i = N - 1; i >= 0; i--) {
      while (!s.isEmpty() && val[i] < s.peek().val) s.pop();
      if (s.isEmpty()) hi[val[i]] = N;
      else hi[val[i]] = s.peek().index;
      s.push(new State(val[i], i));
    }

    s.clear();
    // processing lower bound (last number greater than the current number)
    for (int i = 0; i < N; i++) {
      while (!s.isEmpty() && val[i] > s.peek().val) s.pop();
      if (s.empty()) lo[val[i]] = -1;
      else lo[val[i]] = s.peek().index;
      s.push(new State(val[i], i));
    }

    for (int i = 0; i < N; i++) {
      int diff = val[i] - i + N - 1;
      poss.get(diff).add(i);
    }

    for (int i = 0; i < 2 * N; i++) {
      sweep(poss.get(i));
    }

    out.println(intervals.size());
    for (Interval i : intervals) out.printf("%d %d\n", i.l + 1, i.r + 1);

    out.close();
  }
Esempio n. 6
0
  /** Resets the Push interpreter state by clearing all of the stacks. */
  public void ClearStacks() {
    _intStack.clear();
    _floatStack.clear();
    _execStack.clear();
    _nameStack.clear();
    _boolStack.clear();
    _codeStack.clear();
    _inputStack.clear();

    // Clear all custom stacks
    for (Stack s : _customStacks) {
      s.clear();
    }
  }
  public void mungeSymboltree(boolean analyzed) {

    if (!munge) {
      return;
    }

    // One problem with obfuscation resides in the use of undeclared
    // and un-namespaced global symbols that are 3 characters or less
    // in length. Here is an example:
    //
    // var declaredGlobalVar;
    //
    // function declaredGlobalFn() {
    // var localvar;
    // localvar = abc; // abc is an undeclared global symbol
    // }
    //
    // In the example above, there is a slim chance that localvar may be
    // munged to 'abc', conflicting with the undeclared global symbol
    // abc, creating a potential bug. The following code detects such
    // global symbols. This must be done AFTER the entire file has been
    // parsed, and BEFORE munging the symbol tree. Note that declaring
    // extra symbols in the global scope won't hurt.
    //
    // Note: Since we go through all the tokens to do this, we also use
    // the opportunity to count how many times each identifier is used.

    offset = 0;
    braceNesting = 0;
    scopes.clear();
    mode = CHECKING_SYMBOL_TREE;
    parseScope(globalScope);

    if (analyzed) { // 进行了分析,说明用户想主动输入混淆变量,优先使用用户输入的混淆变量
      manMung();
    }
    globalScope.munge();
  }
 /**
  * Resets the state of this transform; this clears the stack and pushes an empty list onto it, and
  * clears the flag that indicates there has been at least one change.
  *
  * <p>This method is called at the beginning of {@link #transform}.
  *
  * <p>This method is <em>not</em> called at the end of {@link #transform}. Though the contents of
  * the resulting output list may have been written to the PDF page already, clients may wish to
  * inspect the final result without having to re-parse the token stream of the PDF page. However,
  * the result list may be quite large and the stack will hold on to it until the next call to this
  * method, which may represent a memory issue. Thus clients <em>may</em> call {@link #reset} after
  * a call to {@link #transform} to clear the output list stack.
  */
 public synchronized void reset() {
   logger.debug3("Resetting the page stream transform");
   atLeastOneChange = false;
   listStack.clear();
   listStack.push(new ArrayList()); // FIXME: initial capacity?
 }
 void endTask() {
   current_transaction = null;
   nest_level = 0;
   output_stack.clear();
 }
  public StringBuffer printSymbolTree(int linebreakpos, boolean preserveAllSemiColons)
      throws IOException {

    offset = 0;
    braceNesting = 0;
    scopes.clear();

    String symbol;
    JavaScriptToken token;
    // begin
    if (tokens.size() == 0) {
      StringBuffer result = new StringBuffer();
      return result;
    }
    // end
    JavaScriptToken lastToken = getToken(0);
    ScriptOrFnScope currentScope;
    JavaScriptIdentifier identifier;

    int length = tokens.size(); // 文本的长度
    StringBuffer result = new StringBuffer();

    int linestartpos = 0;

    enterScope(globalScope); // 将globalScope压入栈scopes中

    while (offset < length) {

      token = consumeToken();
      symbol = token.getValue();
      currentScope = getCurrentScope();
      switch (token.getType()) {
        case Token.GET:
        case Token.SET:
          lastToken = token; // 注意没有break;

        case Token.NAME:
          if (offset >= 2 && getToken(-2).getType() == Token.DOT
              || getToken(0).getType() == Token.OBJECTLIT) {

            result.append(symbol);

          } else {
            identifier = getIdentifier(symbol, currentScope);
            if (identifier != null) {
              if (identifier.getMungedValue() != null) {
                result.append(identifier.getMungedValue());
              } else {
                result.append(symbol);
              }
              if (currentScope != globalScope // 全局域中的变量可能被HTML文档使用,不需要发出警告
                  && identifier.getRefcount() == 0) {
                warn("标识符" + symbol + "已经声明但未使用 ", true);
              }
            } else {
              result.append(symbol);
            }
          }
          break;

        case Token.REGEXP:
        case Token.STRING:
          result.append(symbol);
          break;

        case Token.NUMBER:
          if (getToken(0).getType() == Token.DOT) {
            // calling methods on int requires a leading dot so JS
            // doesn't
            // treat the method as the decimal component of a float
            result.append('(');
            result.append(symbol);
            result.append(')');
          } else {
            result.append(symbol);
          }
          break;

        case Token.ADD:
        case Token.SUB:
          result.append(literals.get(new Integer(token.getType())));
          if (offset < length) {
            token = getToken(0);
            if (token.getType() == Token.INC
                || token.getType() == Token.DEC
                || token.getType() == Token.ADD
                || token.getType() == Token.DEC) {
              // Handle the case x +/- ++/-- y
              // We must keep a white space here. Otherwise, x +++ y
              // would be
              // interpreted as x ++ + y by the compiler, which is a
              // bug (due
              // to the implicit(隐式的) assignment being done on the
              // wrong variable)
              result.append(' ');
            } else if (token.getType() == Token.POS && getToken(-1).getType() == Token.ADD
                || token.getType() == Token.NEG && getToken(-1).getType() == Token.SUB) {
              // Handle the case x + + y and x - - y
              result.append(' ');
            }
          }
          break;

        case Token.FUNCTION:
          if (lastToken.getType() != Token.GET && lastToken.getType() != Token.SET) {
            result.append("function");
          }
          lastToken = token;
          token = consumeToken();
          if (token.getType() == Token.NAME) {
            result.append(' ');
            symbol = token.getValue();
            identifier = getIdentifier(symbol, currentScope);
            assert identifier != null;
            if (identifier.getMungedValue() != null) {
              result.append(identifier.getMungedValue());
            } else {
              result.append(symbol);
            }
            if (currentScope != globalScope && identifier.getRefcount() == 0) {
              warn("标识符" + symbol + "已经声明但未使用", true);
            }
            token = consumeToken();
          }
          assert token.getType() == Token.LP;
          result.append('(');
          currentScope = indexedScopes.get(new Integer(offset)); // 根据左圆括号的下一个索引映射得到函数作用域
          enterScope(currentScope);
          while ((token = consumeToken()).getType() != Token.RP) {
            assert token.getType() == Token.NAME || token.getType() == Token.COMMA;
            if (token.getType() == Token.NAME) {
              symbol = token.getValue();
              identifier = getIdentifier(symbol, currentScope);
              assert identifier != null;
              if (identifier.getMungedValue() != null) {
                result.append(identifier.getMungedValue());
              } else {
                result.append(symbol);
              }
            } else if (token.getType() == Token.COMMA) {
              result.append(',');
            }
          }
          result.append(')');
          token = consumeToken(); // 得到左花括号
          assert token.getType() == Token.LC;
          result.append("{"); // nomodify
          braceNesting++;
          token = getToken(0);
          if (token.getType() == Token.STRING && getToken(1).getType() == Token.SEMI) {
            // This is a hint. Skip it!
            consumeToken();
            consumeToken();
          }
          break;

        case Token.RETURN:
        case Token.TYPEOF:
          result.append(literals.get(new Integer(token.getType())));
          // No space needed after 'return' and 'typeof' when followed
          // by '(', '[', '{', a string or a regexp.
          if (offset < length) {
            token = getToken(0);
            if (token.getType() != Token.LP
                && token.getType() != Token.LB
                && token.getType() != Token.LC
                && token.getType() != Token.STRING
                && token.getType() != Token.REGEXP
                && token.getType() != Token.SEMI) {
              result.append(' ');
            }
          }
          break;

        case Token.CASE:
        case Token.THROW:
          result.append(literals.get(new Integer(token.getType())));
          // White-space needed after 'case' and 'throw' when not followed
          // by a string.
          if (offset < length && getToken(0).getType() != Token.STRING) {
            result.append(' ');
          }
          break;

        case Token.BREAK:
        case Token.CONTINUE:
          result.append(literals.get(new Integer(token.getType())));
          if (offset < length && getToken(0).getType() != Token.SEMI) {
            // If 'break' or 'continue' is not followed by a
            // semi-colon(分号), it must
            // be followed by a label, hence(因此) the need for a white
            // space.
            result.append(' ');
          }
          break;

        case Token.LC:
          result.append("{"); // nomodify
          braceNesting++;
          break;

        case Token.RC:
          result.append('}');
          braceNesting--;
          assert braceNesting >= currentScope.getBraceNesting();
          if (braceNesting == currentScope.getBraceNesting()) {
            leaveCurrentScope();
          }
          break;

        case Token.SEMI:
          // No need to output a semi-colon if the next character is a
          // right-curly...
          if (preserveAllSemiColons || offset < length && getToken(0).getType() != Token.RC) {
            result.append(';');
          }

          if (linebreakpos >= 0 && result.length() - linestartpos > linebreakpos) {
            // Some source control tools don't like it when files
            // containing lines longer
            // than, say 8000 characters, are checked in. The linebreak
            // option is used in
            // that case to split long lines after a specific column.
            result.append('\n');
            linestartpos = result.length();
          }
          break;

        case Token.COMMA:
          // No need to output a comma if the next character is a
          // right-curly or a right-square bracket
          if (offset < length
              && getToken(0).getType() != Token.RC
              && getToken(0).getType() != Token.RB) {
            result.append(',');
          }
          break;

        case Token.CONDCOMMENT:
        case Token.KEEPCOMMENT:
          if (result.length() > 0 && result.charAt(result.length() - 1) != '\n') {
            result.append("\n");
          }
          result.append("/*");
          if (token.getType() == Token.KEEPCOMMENT) {
            result.append("!");
          }
          result.append(symbol);
          result.append("*/\n");
          break;

          // begin--这个分支用于实现压扁控制流
          // 此分支将if(expression){...}else if(expression){...}else{...}转化为
          // switch(expression){case true:原if块;break;case false:原else块;break;}
        case Token.IF:
          if (!EditOptionPanel.checkBoxFlatten.isSelected()) {
            result.append(symbol);
            break;
          }
          FlattenIF flattenIF = new FlattenIF(offset, length, tokens, currentScope);
          String switchBlock = flattenIF.flattenIF();
          result.append(switchBlock);
          offset = flattenIF.offset;
          break;
        case Token.WHILE:
          if (!EditOptionPanel.checkBoxOpacity.isSelected()) {
            result.append(symbol);
            break;
          }
          result.append(symbol);
          OpacityPredicate opacityPredicateWhile =
              new OpacityPredicate(offset, tokens, currentScope);
          String whileBlock = opacityPredicateWhile.opacityPredicateWhile();
          result.append(whileBlock);
          offset = opacityPredicateWhile.offset;
          break;
        case Token.DO:
          if (!EditOptionPanel.checkBoxOpacity.isSelected()) {
            result.append(symbol);
            break;
          }
          result.append(symbol);
          OpacityPredicate opacityPredicateDoWhile =
              new OpacityPredicate(offset, tokens, currentScope);
          String doWhileBlock = opacityPredicateDoWhile.opacityPredicateDoWhile();
          result.append(doWhileBlock);
          offset = opacityPredicateDoWhile.offset;
          break;
          // end
        default:
          String literal = literals.get(new Integer(token.getType()));
          if (literal != null) {
            result.append(literal);
          } else {
            warn("此标志符不能被打印出来:" + symbol, true);
          }
          break;
      }
    }

    // Append a semi-colon at the end, even if unnecessary semi-colons are
    // supposed to be removed. This is especially useful when concatenating
    // several minified files (the absence of an ending semi-colon at the
    // end of one file may very likely cause a syntax error)
    /*if (!preserveAllSemiColons && result.length() > 0
    		&& getToken(-1).getType() != Token.CONDCOMMENT
    		&& getToken(-1).getType() != Token.KEEPCOMMENT) {
    	if (result.charAt(result.length() - 1) == '\n') {
    		result.setCharAt(result.length() - 1, ';');
    	} else {
    		result.append(';');
    	}
    }*/
    // 暂时用不上,注释掉

    return result;
  }
Esempio n. 11
0
 public void clearStacks() {
   callStack.clear();
   expStack.clear();
 }
Esempio n. 12
0
  public void buttonPressed(Button button) {
    if (button.getId() == TitleMenu.RESTART_GAME_ID) {
      clearMenus();
      TitleMenu menu = new TitleMenu(GAME_WIDTH, GAME_HEIGHT);
      addMenu(menu);

    } else if (button.getId() == TitleMenu.START_GAME_ID) {
      clearMenus();
      isMultiplayer = false;

      localId = 0;
      synchronizer = new TurnSynchronizer(this, null, 0, 1);
      synchronizer.setStarted(true);

      createLevel(TitleMenu.level);
    } else if (button.getId() == TitleMenu.SELECT_LEVEL_ID) {
      addMenu(new LevelSelect(false));
    } else if (button.getId() == TitleMenu.SELECT_HOST_LEVEL_ID) {
      addMenu(new LevelSelect(true));
    } else if (button.getId() == TitleMenu.HOST_GAME_ID) {
      addMenu(new HostingWaitMenu());
      isMultiplayer = true;
      isServer = true;
      try {
        if (isServer) {
          localId = 0;
          serverSocket = new ServerSocket(3000);
          serverSocket.setSoTimeout(1000);

          hostThread =
              new Thread() {

                public void run() {
                  boolean fail = true;
                  try {
                    while (!isInterrupted()) {
                      Socket socket = null;
                      try {
                        socket = serverSocket.accept();
                      } catch (SocketTimeoutException e) {

                      }
                      if (socket == null) {
                        System.out.println("asdf");
                        continue;
                      }
                      fail = false;

                      packetLink = new NetworkPacketLink(socket);

                      createServerState = 1;
                      break;
                    }
                  } catch (Exception e) {
                    e.printStackTrace();
                  }
                  if (fail) {
                    try {
                      serverSocket.close();
                    } catch (IOException e) {
                    }
                  }
                };
              };
          hostThread.start();
        }
      } catch (Exception e) {
        e.printStackTrace();
      }
    } else if (button.getId() == TitleMenu.JOIN_GAME_ID) {
      addMenu(new JoinGameMenu());
    } else if (button.getId() == TitleMenu.CANCEL_JOIN_ID) {
      popMenu();
      if (hostThread != null) {
        hostThread.interrupt();
        hostThread = null;
      }
    } else if (button.getId() == TitleMenu.PERFORM_JOIN_ID) {
      menuStack.clear();
      isMultiplayer = true;
      isServer = false;

      try {
        localId = 1;
        packetLink = new ClientSidePacketLink(TitleMenu.ip, 3000);
        synchronizer = new TurnSynchronizer(this, packetLink, localId, 2);
        packetLink.setPacketListener(this);
      } catch (Exception e) {
        e.printStackTrace();
        // System.exit(1);
        addMenu(new TitleMenu(GAME_WIDTH, GAME_HEIGHT));
      }
    } else if (button.getId() == TitleMenu.SELECT_DIFFICULTY_ID) {
      addMenu(new DifficultySelect());
    } else if (button.getId() == TitleMenu.EXIT_GAME_ID) {
      System.exit(0);
    }
  }
Esempio n. 13
0
 void popAll() {
   stackSize = 0;
   stack.clear();
 }