Ejemplo n.º 1
0
  // Test the change plan when trying to change a student plan
  @Test
  public void transferpairtest() {
    Backend b = new Backend();
    String[] args = new String[1];
    args[0] = "MasterBankAccounts.txt";

    tlist.clear();

    Transaction t = new Transaction();
    t.setCode("10");
    t.setMisc("A");
    t.setName("");

    Transaction t2 = new Transaction();
    t2.setCode("02");
    t2.setNum("00005");

    Transaction t3 = new Transaction();
    t3.setCode("00");

    tlist.add(t);
    tlist.add(t2);
    tlist.add(t3);

    b.load(args);
    b.setTransactions(tlist);
    b.handletransactions();
    assertEquals("Transfer transactions must come in pairs\n", outContent.toString());
  }
  public void setup() {
    size(600, 400);
    smooth();
    f = createFont("Georgia", 12, true);

    obstacles = new ArrayList();
    boids = new ArrayList();

    // A little algorithm to pick a bunch of random obstacles that don't overlap
    for (int i = 0; i < 100; i++) {
      float x = random(width);
      float y = random(height);
      float r = random(50 - i / 2, 50);
      boolean ok = true;
      for (int j = 0; j < obstacles.size(); j++) {
        Obstacle o = (Obstacle) obstacles.get(j);
        if (dist(x, y, o.loc.x, o.loc.y) < o.radius + r + 20) {
          ok = false;
        }
      }
      if (ok) obstacles.add(new Obstacle(x, y, r));
    }

    // Starting with three boids
    boids.add(new Boid(new PVector(random(width), random(height)), 3f, 0.2f));
    boids.add(new Boid(new PVector(random(width), random(height)), 3f, 0.1f));
    boids.add(new Boid(new PVector(random(width), random(height)), 2f, 0.05f));
  }
Ejemplo n.º 3
0
  public void getSavedLocations() {
    // System.out.println("inside getSavedLocations");				//CONSOLE * * * * * * * * * * * * *
    loc.clear(); // clear locations.  helps refresh the list when reprinting all the locations
    BufferedWriter f = null; // just in case file has not been created yet
    BufferedReader br = null;
    try {
      // attempt to open the locations file if it doesn't exist, create it
      f =
          new BufferedWriter(
              new FileWriter("savedLocations.txt", true)); // evaluated true if file does not exist
      br = new BufferedReader(new FileReader("savedLocations.txt"));

      String line; // each line is one index of the list
      loc.add("Saved Locations");
      // loop and read a line from the file as long as we don't get null
      while ((line = br.readLine()) != null)
        // add the read word to the wordList
        loc.add(line);
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      try {
        // attempt the close the file

        br.close(); // close bufferedwriter
      } catch (IOException ex) {
        ex.printStackTrace();
      }
    }
  }
  public static void main(String[] args) {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */

    try {

      Scanner sc = new Scanner(new File("/home/santosh/Desktop/testData"));

      int testCases = sc.nextInt();
      int i = 0;
      ArrayList<ArrayList<Integer>> inputArraysList = new ArrayList<ArrayList<Integer>>();
      ArrayList<Integer> list;
      while (i++ < testCases) {

        int n = sc.nextInt();
        int k = 0;
        list = new ArrayList<Integer>();
        while (k < n) {
          list.add(sc.nextInt());
          k++;
        }
        inputArraysList.add(list);
      }

      // System.out.println(inputArraysList.size());
      for (ArrayList<Integer> arr : inputArraysList) {
        countPairs(arr.toArray(new Integer[arr.size()]));
      }

    } catch (Exception e) {

    }
  }
Ejemplo n.º 5
0
  /**
   * 从表保存操作
   *
   * @param request 网页的请求对象
   * @param response 网页的响应对象
   * @return 返回HTML或javascipt的语句
   * @throws Exception 异常
   */
  private final void putDetailInfo(HttpServletRequest request) {
    RowMap rowInfo = getMasterRowinfo();
    // 保存网页的所有信息
    rowInfo.put(request);
    int rownum = d_RowInfos.size();
    RowMap detailRow = null;
    for (int i = 0; i < rownum; i++) {
      detailRow = (RowMap) d_RowInfos.get(i);
      detailRow.put("wzdjid", rowInfo.get("wzdjid_" + i));
      detailRow.put("dmsxid", rowInfo.get("dmsxid_" + i));
      detailRow.put("hssl", formatNumber(rowInfo.get("hssl_" + i), qtyFormat)); //
      detailRow.put("sl", formatNumber(rowInfo.get("sl_" + i), qtyFormat)); //

      detailRow.put("zk", formatNumber(rowInfo.get("zk_" + i), priceFormat)); //
      detailRow.put("dj", formatNumber(rowInfo.get("dj_" + i), priceFormat)); // 含税单价

      detailRow.put("xsje", formatNumber(rowInfo.get("xsje_" + i), sumFormat));
      detailRow.put("jje", formatNumber(rowInfo.get("jje_" + i), sumFormat)); // 无税单价
      detailRow.put("jzj", formatNumber(rowInfo.get("jzj_" + i), sumFormat)); // 基准价
      detailRow.put("cjtcl", formatNumber(rowInfo.get("cjtcl_" + i), sumFormat)); // 差价提成率
      detailRow.put("jxts", formatNumber(rowInfo.get("jxts_" + i), qtyFormat)); // 计息天数
      detailRow.put("hlts", formatNumber(rowInfo.get("hlts_" + i), qtyFormat)); // 回笼天数
      detailRow.put("hltcl", formatNumber(rowInfo.get("hltcl_" + i), sumFormat)); // 回笼提成率
      detailRow.put("bz", rowInfo.get("bz_" + i)); // 备注
      detailRow.put("jhrq", rowInfo.get("jhrq_" + i)); //
      detailRow.put("xsj", rowInfo.get("xsj_" + i)); //
      // 保存用户自定义的字段
      FieldInfo[] fields = detailProducer.getBakFieldCodes();
      for (int j = 0; j < fields.length; j++) {
        String fieldCode = fields[j].getFieldcode();
        detailRow.put(fieldCode, rowInfo.get(fieldCode + "_" + i));
      }
    }
  }
 public List<ICFAccTaxObj> readAllTax(boolean forceRead) {
   final String S_ProcName = "readAllTax";
   if ((allTax == null) || forceRead) {
     Map<CFAccTaxPKey, ICFAccTaxObj> map = new HashMap<CFAccTaxPKey, ICFAccTaxObj>();
     allTax = map;
     CFAccTaxBuff[] buffList =
         ((ICFAccSchema) schema.getBackingStore())
             .getTableTax()
             .readAllDerived(schema.getAuthorization());
     CFAccTaxBuff buff;
     ICFAccTaxObj obj;
     for (int idx = 0; idx < buffList.length; idx++) {
       buff = buffList[idx];
       obj = newInstance();
       obj.setPKey(((ICFAccSchema) schema.getBackingStore()).getFactoryTax().newPKey());
       obj.setBuff(buff);
       ICFAccTaxObj realized = (ICFAccTaxObj) obj.realize();
     }
   }
   Comparator<ICFAccTaxObj> cmp =
       new Comparator<ICFAccTaxObj>() {
         public int compare(ICFAccTaxObj lhs, ICFAccTaxObj rhs) {
           if (lhs == null) {
             if (rhs == null) {
               return (0);
             } else {
               return (-1);
             }
           } else if (rhs == null) {
             return (1);
           } else {
             CFAccTaxPKey lhsPKey = lhs.getPKey();
             CFAccTaxPKey rhsPKey = rhs.getPKey();
             int ret = lhsPKey.compareTo(rhsPKey);
             return (ret);
           }
         }
       };
   int len = allTax.size();
   ICFAccTaxObj arr[] = new ICFAccTaxObj[len];
   Iterator<ICFAccTaxObj> valIter = allTax.values().iterator();
   int idx = 0;
   while ((idx < len) && valIter.hasNext()) {
     arr[idx++] = valIter.next();
   }
   if (idx < len) {
     throw CFLib.getDefaultExceptionFactory()
         .newArgumentUnderflowException(getClass(), S_ProcName, 0, "idx", idx, len);
   } else if (valIter.hasNext()) {
     throw CFLib.getDefaultExceptionFactory()
         .newArgumentOverflowException(getClass(), S_ProcName, 0, "idx", idx, len);
   }
   Arrays.sort(arr, cmp);
   ArrayList<ICFAccTaxObj> arrayList = new ArrayList<ICFAccTaxObj>(len);
   for (idx = 0; idx < len; idx++) {
     arrayList.add(arr[idx]);
   }
   List<ICFAccTaxObj> sortedList = arrayList;
   return (sortedList);
 }
 public void init() {
   Scanner scan = new Scanner(System.in);
   count = scan.nextInt();
   x0 = scan.nextLong();
   y0 = scan.nextLong();
   int result = 0;
   boolean special = false;
   for (int i = 0; i < count; i++) {
     long tempx = scan.nextLong();
     long tempy = scan.nextLong();
     if (tempx == x0 && tempy == y0) {
       special = true;
       continue;
     }
     boolean isDuplicate = false;
     for (int j = 0; j < result; j++) {
       long x1 = xList.get(j);
       long y1 = yList.get(j);
       if ((x1 - x0) * (tempy - y0) == (y1 - y0) * (tempx - x0)) {
         isDuplicate = true;
         break;
       }
     }
     if (!isDuplicate) {
       xList.add(tempx);
       yList.add(tempy);
       result++;
     }
   }
   if (special && result == 0) result = 1;
   System.out.println(result);
   scan.close();
 }
Ejemplo n.º 8
0
  // Executes the given action
  public void executeAction(Action a) {

    // For each state variable, retrieve the DD for it, evaluate it
    // w.r.t. the current state and build a new state.
    ArrayList new_state = new ArrayList();
    int c;
    for (c = 0; c < (_nVars << 1); c++) {
      new_state.add("-");
    }
    for (c = 0; c < (_nVars << 1); c++) {
      Object cur_assign = _state.get(c);
      if (cur_assign instanceof Boolean) {
        // System.out.println(a._tmID2DD);
        int nonprime_id = c + 1;
        int prime_id = nonprime_id - _nVars;
        Object DD = a._tmID2DD.get(new Integer(prime_id));
        _state.set(prime_id - 1, TRUE);
        double p_true = _mdp._context.evaluate(DD, _state);
        // System.out.println("ID: " + nonprime_id + ", " + prime_id + ": " +
        //		   _mdp._context.printNode(DD) + " -> " +
        //		   _mdp._df.format(p_true));
        new_state.set(c, (_r.nextFloat() < p_true) ? TRUE : FALSE);
      }
    }

    _state = new_state;
  }
    public void trace(float x, float y) {

      println(x);

      if (frameCounter > 2 && mousePressed) {
        coords.add(new PVector(x, y));
        frameCounter = 0;
        if (coordCounter > 0) {
          PVector tempCoord = (PVector) coords.get(coordCounter - 1);
          line(x, y, tempCoord.x, tempCoord.y);
        }
        coordCounter++;
      }
      // println(coordCounter);

      for (int i = 0; i < coords.size(); i++) {
        PVector tempCoordnear = (PVector) coords.get(i);
        float coordDist = dist(x, y, tempCoordnear.x, tempCoordnear.y);
        if (coordDist < distance) {
          stroke(255, 0, 0);
          line(x, y, tempCoordnear.x, tempCoordnear.y);
        }
      }
      frameCounter++;
    }
Ejemplo n.º 10
0
  // Derives QFunctions for the given value function and simulates the
  // greedy policy for the given number of trials and steps per trial.
  // Returns final value of every trial.
  public ArrayList simulate(int trials, int steps, long rand_seed) {
    ArrayList values = new ArrayList();
    _r = new Random(rand_seed);

    for (int trial = 1; trial <= trials; trial++) {

      System.out.println("\n -----------\n   Trial " + trial + "\n -----------");

      // Initialize state
      _state = new ArrayList();
      _nVars = _mdp._alVars.size();
      for (int c = 0; c < (_nVars << 1); c++) {
        _state.add("-");
      }
      Iterator i = _mdp._alVars.iterator();
      _vars = new TreeSet();
      while (i.hasNext()) {
        String s = (String) i.next();
        if (!s.endsWith("\'")) {
          Integer gid = (Integer) _mdp._tmVar2ID.get(s);
          _vars.add(gid);

          // Note: assign level (level is gid-1 b/c gids in order)
          _state.set(gid.intValue() - 1, _r.nextBoolean() ? TRUE : FALSE);
        }
      }
      // System.out.println(_mdp._context.printNode(_mdp._valueDD) + "\n" + _state);
      double reward = _mdp._context.evaluate(_mdp._rewardDD, _state);
      System.out.print(" " + PrintState(_state) + "  " + MDP._df.format(reward));

      // Run steps
      for (int step = 1; step <= steps; step++) {

        // Get action
        Action a;
        if (_bUseBasis) {
          a = getBasisAction();
        } else {
          a = getAction();
        }

        // Execute action
        executeAction(a);

        // Update reward
        reward =
            (_mdp._bdDiscount.doubleValue() * reward)
                + _mdp._context.evaluate(_mdp._rewardDD, _state);

        System.out.println(", a=" + a._sName);
        System.out.print(
            " " + PrintState(_state) + "  " + MDP._df.format(reward) + ": " + "Step " + step);
      }
      values.add(new Double(reward));
      System.out.println();
    }

    return values;
  }
Ejemplo n.º 11
0
 public void process(ArrayList<ListData> files) {
   for (int i = 0; i < files.size(); i++) {
     System.out.println("File " + (i + 1));
     dataList = new ArrayList<Data>();
     extractInfo(files.get(i).getFilePath());
     createExcel(files.get(i).getFileName());
   }
 }
Ejemplo n.º 12
0
    public ArrayList getPastObjectStates() {
      ArrayList alPast = new ArrayList();
      for (int i = intTimeIdx; i > 0 && i > intTimeIdx - 100; i--) {
        alPast.add(this.alObjectStateArchive.get(i));
      }

      return alPast;
    }
Ejemplo n.º 13
0
 public double getInvoiceTotal() {
   double invoiceTotal = 0.0;
   for (int i = 0; i < lineItems.size(); i++) {
     LineItem item = lineItems.get(i);
     invoiceTotal += item.getTotal();
   }
   return invoiceTotal;
 }
Ejemplo n.º 14
0
    // Does a deepcopy of an array list
    public static ArrayList cloneArrayList(ArrayList al) {
      ArrayList alNew = new ArrayList(al.size());
      for (int i = 0; i < al.size(); i++) {
        alNew.add(((CelestialObject) al.get(i)).clone());
      }

      return alNew;
    }
Ejemplo n.º 15
0
 private static ArrayList<PairInfo> getPairListFromStr(String str) {
   String[] nodes = str.split(":");
   ArrayList<PairInfo> pairList = new ArrayList<PairInfo>();
   for (int i = 0; i < nodes.length; i++) {
     PairInfo pair = getPairFromStr(nodes[i]);
     pairList.add(pair);
   }
   return pairList;
 }
Ejemplo n.º 16
0
    // Does a deepcopy of an array list
    public ArrayList cloneArrayList(ArrayList al) {
      ArrayList alNew = new ArrayList(al.size());
      for (int i = 0; i < al.size(); i++) {
        PVector pv = (PVector) al.get(i);
        alNew.add(new PVector(pv.x, pv.y));
      }

      return alNew;
    }
    public void avoid(ArrayList obstacles) {

      // Make a vector that will be the position of the object
      // relative to the Boid rotated in the direction of boid's velocity
      PVector closestRotated = new PVector(sight + 1, sight + 1);
      float closestDistance = 99999;
      Obstacle avoid = null;

      // Let's look at each obstacle
      for (int i = 0; i < obstacles.size(); i++) {
        Obstacle o = (Obstacle) obstacles.get(i);

        float d = PVector.dist(loc, o.loc);
        PVector dir = vel.get();
        dir.normalize();
        PVector diff = PVector.sub(o.loc, loc);

        // Now we use the dot product to rotate the vector that points from boid to obstacle
        // Velocity is the new x-axis
        PVector rotated = new PVector(diff.dot(dir), diff.dot(getNormal(dir)));

        // Is the obstacle in our path?
        if (PApplet.abs(rotated.y) < (o.radius + r)) {
          // Is it the closest obstacle?
          if ((rotated.x > 0) && (rotated.x < closestRotated.x)) {
            closestRotated = rotated;
            avoid = o;
          }
        }
      }

      // Can we actually see the closest one?
      if (PApplet.abs(closestRotated.x) < sight) {

        // The desired vector should point away from the obstacle
        // The closer to the obstacle, the more it should steer
        PVector desired =
            new PVector(closestRotated.x, -closestRotated.y * sight / closestRotated.x);
        desired.normalize();
        desired.mult(closestDistance);
        desired.limit(maxspeed);
        // Rotate back to the regular coordinate system
        rotateVector(desired, vel.heading2D());

        // Draw some debugging stuff
        if (debug) {
          stroke(0);
          line(loc.x, loc.y, loc.x + desired.x * 10, loc.y + desired.y * 10);
          avoid.highlight(true);
        }

        // Apply Reynolds steering rules
        desired.sub(vel);
        desired.limit(maxforce);
        acc.add(desired);
      }
    }
Ejemplo n.º 18
0
 public static double Average(ArrayList l) {
   double accum = 0.0d;
   Iterator i = l.iterator();
   while (i.hasNext()) {
     Double d = (Double) i.next();
     accum += d.doubleValue();
   }
   return (accum / (double) l.size());
 }
Ejemplo n.º 19
0
  public NeuralNetwork(int input, int hidden, int output) {
    this.layers = new int[] {input, hidden, output};
    df = new DecimalFormat("#0.000#");
    ef = new DecimalFormat("#");

    /** Create all neurons and connections Connections are created in the neuron class */
    for (int i = 0; i < layers.length; i++) {
      if (i == 0) { // input layer
        for (int j = 0; j < layers[i]; j++) {
          Neuron neuron = new Neuron();
          inputLayer.add(neuron);
        }
      } else if (i == 1) { // hidden layer
        for (int j = 0; j < layers[i]; j++) {
          Neuron neuron = new Neuron();
          neuron.addInConnectionsS(inputLayer);
          neuron.addBiasConnection(bias);
          hiddenLayer.add(neuron);
        }
      } else if (i == 2) { // output layer
        for (int j = 0; j < layers[i]; j++) {
          Neuron neuron = new Neuron();
          neuron.addInConnectionsS(hiddenLayer);
          neuron.addBiasConnection(bias);
          outputLayer.add(neuron);
        }
      } else {
        System.out.println("!Error NeuralNetwork init");
      }
    }

    // initialize random weights
    for (Neuron neuron : hiddenLayer) {
      ArrayList<Connection> connections = neuron.getAllInConnections();
      for (Connection conn : connections) {
        double newWeight = getRandom();
        conn.setWeight(newWeight);
      }
    }
    for (Neuron neuron : outputLayer) {
      ArrayList<Connection> connections = neuron.getAllInConnections();
      for (Connection conn : connections) {
        double newWeight = getRandom();
        conn.setWeight(newWeight);
      }
    }

    // reset id counters
    Neuron.counter = 0;
    Connection.counter = 0;

    if (isTrained) {
      trainedWeights();
      updateAllWeights();
    }
  }
  public void draw() {

    background(255);

    for (int i = 0; i < balls.size(); i++) {
      Ball ball = (Ball) balls.get(i);
      ball.calc();
      ball.display();
    }
  }
 private List<String> fastSplit(String s) {
   ArrayList<String> tokens = new ArrayList<String>();
   int index, lastIndex = 0;
   while ((index = s.indexOf(',', lastIndex)) != -1) {
     tokens.add(s.substring(lastIndex, index));
     lastIndex = index + 1;
   }
   tokens.add(s.substring(lastIndex));
   return tokens;
 }
Ejemplo n.º 22
0
 public void mouseClicked() {
   ArrayList objects = timeline.getStatefulObjects();
   for (int i = 0; i < objects.size(); i++) {
     CelestialObject obj = (CelestialObject) objects.get(i);
     if (obj.isMouseOver()) {
       println(obj.getName() + " clicked!");
       break;
     }
   }
 }
Ejemplo n.º 23
0
    public ArrayList getFutureObjectStates() {
      ArrayList alFutureArchive = new ArrayList();
      ArrayList alFutureObjects = cloneArrayList(alStatefulObjects);

      for (int i = 0; i < 100; i++) {
        sim.calculateForces(alFutureObjects);

        alFutureArchive.add(cloneArrayList(alFutureObjects));
      }

      return alFutureArchive;
    }
Ejemplo n.º 24
0
  /** Update all of the Ball's and draw them */
  public void update() {

    if (balls.size() != 0) {

      for (int i = 0; i < balls.size(); i++) {
        Ball b = (Ball) balls.get(i);
        b.update();
        b.attract = kelly;
        b.drawBall();
      }
    }
  }
Ejemplo n.º 25
0
  private ArrayList GetFolderTree(String s_Dir, String s_Flag, int n_Indent, int n_TreeIndex) {
    String s_List = "";
    ArrayList aSubFolders = new ArrayList();

    File file = new File(s_Dir);
    File[] filelist = file.listFiles();

    if (filelist != null && filelist.length > 0) {
      for (int i = 0; i < filelist.length; i++) {
        if (filelist[i].isDirectory()) {
          aSubFolders.add(filelist[i].getName());
        }
      }

      int n_Count = aSubFolders.size();
      String s_LastFlag = "";
      String s_Folder = "";
      for (int i = 1; i <= n_Count; i++) {
        if (i < n_Count) {
          s_LastFlag = "0";
        } else {
          s_LastFlag = "1";
        }

        s_Folder = aSubFolders.get(i - 1).toString();
        s_List =
            s_List
                + "arr"
                + s_Flag
                + "["
                + String.valueOf(n_TreeIndex)
                + "]=new Array(\""
                + s_Folder
                + "\","
                + String.valueOf(n_Indent)
                + ", "
                + s_LastFlag
                + ");\n";
        n_TreeIndex = n_TreeIndex + 1;
        ArrayList a_Temp =
            GetFolderTree(s_Dir + s_Folder + sFileSeparator, s_Flag, n_Indent + 1, n_TreeIndex);
        s_List = s_List + a_Temp.get(0).toString();
        n_TreeIndex = Integer.valueOf(a_Temp.get(1).toString()).intValue();
      }
    }

    ArrayList a_Return = new ArrayList();
    a_Return.add(s_List);
    a_Return.add(String.valueOf(n_TreeIndex));
    return a_Return;
  }
Ejemplo n.º 26
0
 private static void displayPhoneBooks(ArrayList<String> phoneBooks)
     throws IOException, ParseException {
   if (phoneBooks.size() == 0) {
     System.out.println("\nNO PHONEBOOK AVAILABLE.CREATE A NEW PHONEBOOK.\n");
     return;
   } else {
     System.out.println("FOLLOWING ARE THE AVAILABLE PHONEBOOKS.");
     System.out.println("----------------------------------------\n");
     Scanner sc = new Scanner(System.in);
     for (int i = 0; i < phoneBooks.size(); i++) {
       String s = phoneBooks.get(i);
       System.out.println(s + "\t->PRESS " + (i + 1) + " LOAD THIS.");
     }
     System.out.println("TO GO BACK TO THE PREVIOUS MENU->PRESS " + (phoneBooks.size() + 1));
     int ch = 0;
     while (ch < 1 || ch > (phoneBooks.size() + 1)) {
       while (!sc.hasNextInt()) {
         System.out.println("\nONLY NUMBERS LISTED ABOVE SHOULD BE ENTERED..RETRY..");
         sc.nextLine();
       }
       ch = sc.nextInt();
       if (ch < 1 || ch > phoneBooks.size())
         System.out.println("\nONLY NUMBERS LISTED ABOVE SHOULD BE ENTERED..RETRY..");
     }
     if (ch == (phoneBooks.size() + 1)) return;
     contactBookOperations(phoneBooks.get(ch - 1) + ".txt");
   }
 }
Ejemplo n.º 27
0
  public static void main(String[] args) {
    long start = System.currentTimeMillis();
    Scanner input = new Scanner(System.in);
    int numberOfTestCases = input.nextInt();
    ArrayList<Integer> order = new ArrayList<Integer>(numberOfTestCases);
    int previousKey = -1;
    int previousValue = 0;
    int cycleNumber = 0;

    Map<Integer, Integer> testCases = new TreeMap<Integer, Integer>();

    for (int i = 0; i < numberOfTestCases; i++) {
      int numberOfCycles = input.nextInt();
      testCases.put(numberOfCycles, 1);
      order.add(numberOfCycles);
    }

    for (Map.Entry<Integer, Integer> entry : testCases.entrySet()) {
      int numberOfCycles;
      int initialHeight;

      if (previousKey == -1) {
        numberOfCycles = entry.getKey();
        initialHeight = entry.getValue();
      } else {
        numberOfCycles = entry.getKey() - previousKey;
        initialHeight = previousValue;
      }

      for (int i = 0; i < numberOfCycles; i++) {
        if (cycleNumber % 2 == 0) {
          initialHeight *= 2;
        } else {
          initialHeight += 1;
        }
        cycleNumber++;
      }

      entry.setValue(initialHeight);
      previousKey = entry.getKey();
      previousValue = initialHeight;
    }

    for (Integer element : order) {
      System.out.println(testCases.get(element));
    }

    long elapsed = System.currentTimeMillis() - start;
    System.out.println("time: " + elapsed);
  }
Ejemplo n.º 28
0
  public static void main(String[] args) {
    try {
      BufferedReader br = new BufferedReader(new FileReader(args[0]));
      int tIndex = 0;
      int pIndex = 0;

      // This will probably change soon (name and implementation)
      NgramParser tnp = new NgramParser(args[1]);

      ArrayList<String> triplet = tnp.getTriplet();
      ArrayList<String> polarity = tnp.getPolarity();

      FileWriter sw = new FileWriter(args[2]);
      String line = null;

      while (((line = br.readLine()) != null)
          && (tIndex < triplet.size())
          && (pIndex < polarity.size())) {
        if (line.matches("^[\\d]*:")) {
          // System.out.println(line);
          sw.write(line + "\n");
        } else {
          Scanner sc = new Scanner(line);
          String trip = sc.findInLine(Pattern.compile("[a-zA-Z]+#[a-z]+[#]?[0-9]*"));
          // if (trip != null && trip.equals(triplet.get(tIndex))) {
          System.out.println(trip);
          if (trip != null && !trip.toLowerCase().contains("no#cl")) {
            // System.out.println(triplet.get(tIndex) + ":" +polarity.get(pIndex));
            String pol = polarity.get(pIndex);
            sw.write(line + " " + pol + "\n");
            sc.close();
            tIndex++;
            pIndex++;
          } else {
            String pol = "neg";
            sw.write("no#a#1" + " " + pol + "\n");
            sc.close();
          }
        }

        // sw.flush();
      }

      sw.close();

    } catch (IOException e) {
      e.printStackTrace();
    }
  }
Ejemplo n.º 29
0
 /**
  * @return an ArrayList containing recent file names, fetched from the given key (e.g.
  *     PEMenuBar.KEY_RECENT_FILE)
  */
 public static ArrayList<String> parseRecentFiles(Properties preferences) {
   int i = 1;
   String fileName;
   ArrayList<String> list = new ArrayList<String>();
   // build key by appending ".X" where "X" runs from 1 to ...
   // i.e. fetch as many names as possible, until no key is found :
   while ((fileName = preferences.getProperty(KEY_RECENT_FILE + "." + Integer.toString(i++)))
       != null) {
     // System.out.println("filename=" + fileName + ";");
     if (!fileName.equals("") && !fileName.equals(" ")) {
       list.add(fileName);
     }
   }
   return list;
 }
Ejemplo n.º 30
0
 /** Execute the system command 'cmd' and fill an ArrayList with the results. */
 public static ArrayList<String> executeSystemCommand(String cmd) {
   if (debug) System.out.println("cmd: " + cmd);
   ArrayList<String> list = new ArrayList<>();
   try (BufferedReader br =
       new BufferedReader(
           new InputStreamReader(RUNTIME.exec(/*comSpec +*/ cmd).getInputStream()))) {
     for (String line = null; (line = br.readLine()) != null; ) {
       if (debug) System.out.println(line);
       list.add(line);
     }
   } catch (IOException e) {
     e.printStackTrace();
   }
   return list;
 }