Пример #1
0
  /**
   * 写文件
   *
   * @param 文件路径
   * @param 内容列表
   * @param 附加是附加的 ,如果这是真的,其他写的文件,明确内容的文件和写进去
   * @return 否则返回假如果contentList是空的,真的
   * @throws RuntimeException if an error occurs while operator FileWriter
   */
  public static boolean writeFile(String filePath, List<String> contentList, boolean append) {
    if (ListUtils.isEmpty(contentList)) {
      return false;
    }

    FileWriter fileWriter = null;
    try {
      makeDirs(filePath);
      fileWriter = new FileWriter(filePath, append);
      int i = 0;
      for (String line : contentList) {
        if (i++ > 0) {
          fileWriter.write("\r\n");
        }
        fileWriter.write(line);
      }
      fileWriter.close();
      return true;
    } catch (IOException e) {
      throw new RuntimeException("IOException occurred. ", e);
    } finally {
      if (fileWriter != null) {
        try {
          fileWriter.close();
        } catch (IOException e) {
          throw new RuntimeException("IOException occurred. ", e);
        }
      }
    }
  }
Пример #2
0
  /**
   * Test method for {@link fhdw.ipscrum.shared.utils.ListUtils#filter(java.util.List,
   * fhdw.ipscrum.shared.utils.ListUtils.Predicate)} .
   */
  @Test
  public final void testFilter() {
    final Integer one = Integer.valueOf(1);
    final Integer two = Integer.valueOf(2);
    final Integer three = Integer.valueOf(3);
    final Integer four = Integer.valueOf(4);

    final List<Integer> first = new ArrayList<Integer>();
    first.add(one);
    first.add(two);
    first.add(three);
    first.add(four);

    final List<Integer> list =
        ListUtils.filter(
            first,
            new ListUtils.Predicate<Integer>() {

              @Override
              public boolean test(final Integer element) {
                return element.compareTo(Integer.valueOf(3)) > 0;
              }
            });
    Assert.assertEquals(1, list.size());
    Assert.assertTrue(list.contains(four));
    Assert.assertFalse(list.contains(three));
  }
Пример #3
0
 public void solve(int testNumber, InputReader in, OutputWriter out) {
   long money = in.readLong();
   long fee = in.readLong();
   int count = in.readInt();
   long[] price = new long[count];
   long[] stale = new long[count];
   IOUtils.readLongArrays(in, price, stale);
   long currentDeliveryCost = fee;
   long lastStale = -1;
   long[] antiStale = stale.clone();
   for (int i = 0; i < count; i++) antiStale[i] = -antiStale[i];
   Integer[] order = ListUtils.order(Array.wrap(price), Array.wrap(antiStale));
   long answer = 0;
   for (int i : order) {
     if (lastStale >= stale[i]) continue;
     long p1 = currentDeliveryCost;
     long p2 = price[i];
     long q = stale[i] - lastStale;
     long c = lastStale + 1;
     if (p1 / p2 >= c) {
       if (money / q >= price[i]) {
         long alpha1 = money / (currentDeliveryCost + q * price[i]);
         long beta1 = q * alpha1;
         if (alpha1 * p1 + beta1 * p2 > money) throw new RuntimeException();
         if (beta1 > q * alpha1) throw new RuntimeException();
         answer = Math.max(answer, c * alpha1 + beta1);
         long alpha2 = alpha1 + 1;
         if (alpha2 * currentDeliveryCost <= money) {
           long remainingMoney = money - alpha2 * p1;
           long beta2 = remainingMoney / p2;
           if (alpha2 * p1 + beta2 * p2 > money) throw new RuntimeException();
           if (beta2 > q * alpha2) throw new RuntimeException();
           answer = Math.max(answer, c * alpha2 + beta2);
         }
       } else {
         long alpha = 1;
         long beta = (money - currentDeliveryCost) / p2;
         if (alpha * p1 + beta * p2 > money) throw new RuntimeException();
         if (beta > q * alpha) throw new RuntimeException();
         answer = Math.max(answer, c * alpha + beta);
       }
     } else {
       long alpha = money / p1;
       long remainingMoney = money - alpha * p1;
       long beta = remainingMoney / p2;
       if (remainingMoney / q >= alpha) beta = Math.min(beta, alpha * q);
       if (alpha * p1 + beta * p2 > money) throw new RuntimeException();
       if (beta > q * alpha) throw new RuntimeException();
       answer = Math.max(answer, c * alpha + beta);
     }
     if (money / price[i] >= stale[i] - lastStale) {
       currentDeliveryCost += (stale[i] - lastStale) * price[i];
       lastStale = stale[i];
     } else break;
     if (currentDeliveryCost > money) break;
   }
   out.printLine("Case #" + testNumber + ":", answer);
 }
Пример #4
0
 // This should be all we need to put in a main function.
 // args are the commandline arguments
 // First object is the Runnable object to call run on.
 // All of them are objects whose options args is to supposed to populate.
 public static void run(String[] args, Object... objects) {
   init(args, objects);
   if (makeThunk) {
     setExecStatus("thunk", true);
     printOutputMap(Execution.getFile("output.map"));
     List<String> cmd = new ArrayList();
     cmd.add("java");
     if (thunkJavaOpts != null) cmd.add(thunkJavaOpts);
     cmd.add("-cp " + StrUtils.join(jarFiles, ":") + ":" + System.getProperty("java.class.path"));
     cmd.addAll(
         ListUtils.newList(
             objects[0].getClass().getName(),
             "++" + virtualExecDir, // Load these options
             // Next time when we run, just run in the same path that we used to create the thunk
             "-execDir",
             virtualExecDir,
             "-overwriteExecDir"));
     IOUtils.printLinesHard(
         Execution.getFile("job.map"),
         ListUtils.newList(
             "workingDir\t" + SysInfoUtils.getcwd(), // Run from current directory
             "command\t" + StrUtils.join(cmd, "\t"),
             "priority\t" + thunkPriority));
   } else {
     if (dontCatchExceptions) {
       ((Runnable) objects[0]).run();
     } else {
       try {
         ((Runnable) objects[0]).run();
       } catch (Throwable t) {
         raiseException(t);
       }
     }
   }
   finish();
 }
Пример #5
0
  /**
   * whether the app whost package's name is packageName is on the top of the stack
   *
   * <ul>
   *   <strong>Attentions:</strong>
   *   <li>You should add <strong>android.permission.GET_TASKS</strong> in manifest
   * </ul>
   *
   * @param context
   * @param packageName
   * @return if params error or task stack is null, return null, otherwise retun whether the app is
   *     on the top of stack
   */
  public static Boolean isTopActivity(Context context, String packageName) {
    if (context == null || StringUtils.isEmpty(packageName)) {
      return null;
    }

    ActivityManager activityManager =
        (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    List<RunningTaskInfo> tasksInfo = activityManager.getRunningTasks(1);
    if (ListUtils.isEmpty(tasksInfo)) {
      return null;
    }
    try {
      return packageName.equals(tasksInfo.get(0).topActivity.getPackageName());
    } catch (Exception e) {
      e.printStackTrace();
      return false;
    }
  }
Пример #6
0
  /**
   * Test method for {@link
   * fhdw.ipscrum.shared.utils.ListUtils#convertObjListToIdList(java.util.List)}.
   */
  @Test
  public final void testConvertObjListToIdList() {
    final Hint hint1 = new Hint(this.getModel(), "Hint 1");
    final Hint hint2 = new Hint(this.getModel(), "Hint 2");
    final Hint hint3 = new Hint(this.getModel(), "Hint 3");
    final Hint hint4 = new Hint(this.getModel(), "Hint 4");

    final List<IdentifiableObject> list = new ArrayList<IdentifiableObject>();
    list.add(hint1);
    list.add(hint2);
    list.add(hint3);
    list.add(hint4);

    final List<String> idList = ListUtils.convertObjListToIdList(list);
    Assert.assertTrue(idList.contains(hint1.getId()));
    Assert.assertTrue(idList.contains(hint2.getId()));
    Assert.assertTrue(idList.contains(hint3.getId()));
    Assert.assertTrue(idList.contains(hint4.getId()));
  }
Пример #7
0
  /**
   * Test method for {@link
   * fhdw.ipscrum.shared.utils.ListUtils#convertIdListToObjList(java.util.List,
   * fhdw.ipscrum.shared.model.Model)} .
   *
   * @throws NoObjectFindException object not found
   */
  @Test
  public final void testConvertIdListToObjList() throws NoObjectFindException {
    final Hint hint1 = new Hint(this.getModel(), "Hint 1");
    final Hint hint2 = new Hint(this.getModel(), "Hint 2");
    final Hint hint3 = new Hint(this.getModel(), "Hint 3");
    final Hint hint4 = new Hint(this.getModel(), "Hint 4");

    final List<String> list = new ArrayList<String>();
    list.add(hint1.getId());
    list.add(hint2.getId());
    list.add(hint3.getId());
    list.add(hint4.getId());

    final List<IdentifiableObject> objectList =
        ListUtils.convertIdListToObjList(list, this.getModel());
    Assert.assertTrue(objectList.contains(hint1));
    Assert.assertTrue(objectList.contains(hint2));
    Assert.assertTrue(objectList.contains(hint3));
    Assert.assertTrue(objectList.contains(hint4));
  }
Пример #8
0
  /**
   * Test method for {@link fhdw.ipscrum.shared.utils.ListUtils#difference(java.util.List,
   * java.util.List)}.
   */
  @Test
  public final void testDifference() {
    final Integer one = Integer.valueOf(1);
    final Integer two = Integer.valueOf(2);
    final Integer three = Integer.valueOf(3);
    final Integer four = Integer.valueOf(4);

    final List<Integer> first = new ArrayList<Integer>();
    first.add(one);
    first.add(two);
    first.add(three);
    final List<Integer> second = new ArrayList<Integer>();
    second.add(four);
    second.add(two);
    second.add(three);

    final List<Integer> difference = ListUtils.difference(first, second);
    Assert.assertTrue(difference.contains(one));
    Assert.assertFalse(difference.contains(two));
    Assert.assertFalse(difference.contains(three));
  }
Пример #9
0
  /**
   * whether this process is named with processName
   *
   * @param context
   * @param processName
   * @return
   *     <ul>
   *       return whether this process is named with processName
   *       <li>if context is null, return false
   *       <li>if {@link ActivityManager#getRunningAppProcesses()} is null, return false
   *       <li>if one process of {@link ActivityManager#getRunningAppProcesses()} is equal to
   *           processName, return true, otherwise return false
   *     </ul>
   */
  public static boolean isNamedProcess(Context context, String processName) {
    if (context == null) {
      return false;
    }

    int pid = android.os.Process.myPid();
    ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    List<RunningAppProcessInfo> processInfoList = manager.getRunningAppProcesses();
    if (ListUtils.isEmpty(processInfoList)) {
      return false;
    }

    for (RunningAppProcessInfo processInfo : processInfoList) {
      if (processInfo != null
          && processInfo.pid == pid
          && ObjectUtils.isEquals(processName, processInfo.processName)) {
        return true;
      }
    }
    return false;
  }
Пример #10
0
  /**
   * Test method for {@link fhdw.ipscrum.shared.utils.ListUtils#intersection(java.util.List,
   * java.util.List)}.
   */
  @Test
  public final void testIntersection() {
    final Integer one = Integer.valueOf(1);
    final Integer two = Integer.valueOf(2);
    final Integer three = Integer.valueOf(3);
    final Integer four = Integer.valueOf(4);

    final List<Integer> first = new ArrayList<Integer>();
    first.add(one);
    first.add(two);
    first.add(three);
    final List<Integer> second = new ArrayList<Integer>();
    second.add(four);
    second.add(two);
    second.add(three);

    final List<Integer> intersection = ListUtils.intersection(first, second);
    Assert.assertTrue(intersection.contains(two));
    Assert.assertTrue(intersection.contains(three));
    Assert.assertFalse(intersection.contains(one));
    Assert.assertFalse(intersection.contains(four));
  }
 @Override
 public String toString() {
   return ListUtils.toString(this);
 }
 @Override
 public boolean equals(Object obj) {
   return ListUtils.equals(this, obj);
 }
 @Override
 public IStrategoTerm toStrategoTerm(ITermFactory factory) {
   return ListUtils.toStrategoTerm(this, factory);
 }
 @Override
 public int hashCode() {
   return ListUtils.hashCode(this);
 }
Пример #15
0
  /**
   * @param dbfFile a list of DBF files to merge
   * @param conn a database connection
   * @param sqlSchema schema to store table
   * @param sqlTable table name to store data
   * @return The number of rows affected after sql INSERT queries
   * @throws IOException,SQLException
   */
  public static void storeAttributes(
      File[] dbfFiles,
      Connection conn,
      String sqlSchema,
      String sqlTable,
      boolean overwriteTables,
      String[] nullValues)
      throws IOException, SQLException {
    if (!overwriteTables && SQLUtils.tableExists(conn, sqlSchema, sqlTable))
      throw new SQLException("SQL Tables already exist and overwriteTables is false.");

    // read records from each file
    List<String> fieldNames = new Vector<String>(); // order corresponds to fieldTypes order
    List<String> fieldTypes = new Vector<String>(); // order corresponds to fieldNames order

    FileInputStream[] inputStreams = new FileInputStream[dbfFiles.length];
    DbaseFileHeader[] headers = new DbaseFileHeader[dbfFiles.length];
    DbaseFileReader[] readers = new DbaseFileReader[dbfFiles.length];

    // open each file, read each header, get the complete list of field names and types
    for (int i = 0; i < dbfFiles.length; i++) {
      inputStreams[i] = new FileInputStream(dbfFiles[i]);
      readers[i] =
          new DbaseFileReader(inputStreams[i].getChannel(), false, Charset.forName("ISO-8859-1"));
      headers[i] = readers[i].getHeader();

      int numFields = headers[i].getNumFields();
      // keep track of the full set of field names
      for (int col = 0; col < numFields; col++) {
        String newFieldName = headers[i].getFieldName(col);
        if (ListUtils.findString(newFieldName, fieldNames) < 0) {
          fieldNames.add(newFieldName);
          fieldTypes.add(getSQLDataType(conn, headers[i], col));
        }
      }
    }

    // begin SQL code
    try {
      conn.setAutoCommit(false);

      // create the table
      if (overwriteTables) SQLUtils.dropTableIfExists(conn, sqlSchema, sqlTable);
      fieldNames.add(0, "the_geom_id");
      fieldTypes.add(0, SQLUtils.getSerialPrimaryKeyTypeString(conn));
      SQLUtils.createTable(conn, sqlSchema, sqlTable, fieldNames, fieldTypes);

      // import data from each file
      for (int f = 0; f < dbfFiles.length; f++) {
        int numFields = headers[f].getNumFields();
        int numRecords = headers[f].getNumRecords();
        // insert records from this file
        for (int r = 0; r < numRecords; r++) {
          Map<String, Object> record = new HashMap<String, Object>();
          Object[] entry = readers[f].readEntry();
          for (int c = 0; c < numFields; c++) {
            if (ListUtils.findIgnoreCase(entry[c].toString(), nullValues) < 0)
              record.put(headers[f].getFieldName(c), entry[c]);
          }

          // insert the record in the table
          try {
            SQLUtils.insertRow(conn, sqlSchema, sqlTable, record);
          } catch (SQLException e) {
            System.out.println(
                String.format(
                    "Insert failed on row %s of %s: %s", r, dbfFiles[f].getName(), record));
            throw e;
          }
        }
        // close the file
        readers[f].close();
        inputStreams[f].close();
        // clean up pointers
        readers[f] = null;
        inputStreams[f] = null;
        headers[f] = null;
      }
    } finally {
      conn.setAutoCommit(true);
    }
  }
Пример #16
0
  public static void init(String[] args, Object... objects) {
    // Parse options
    parser = new OptionsParser();
    parser.doRegister("log", LogInfo.class);
    parser.doRegister("exec", Execution.class);
    parser.doRegisterAll(objects);
    // These options are specific to the execution, so we don't want to overwrite them
    // with a previous execution's.
    parser.setDefaultDirFileName("options.map");
    parser.setIgnoreOptsFromFileName(
        "options.map",
        ListUtils.newList(
            "log.file",
            "exec.execDir",
            "exec.execPoolDir",
            "exec.actualPoolDir",
            "exec.makeThunk"));
    if (!parser.doParse(args)) System.exit(1);

    // Load classes
    if (jarFiles.size() > 0) {
      List<String> names = new ArrayList();
      for (String jarFile : jarFiles) names.add(new File(jarFile).getName());
      stderr.println("Loading JAR files: " + StrUtils.join(names));
      for (String jarFile : jarFiles) // Load classes
      ClassInitializer.initializeJar(jarFile);
    }
    // Set character encoding
    if (charEncoding != null) CharEncUtils.setCharEncoding(charEncoding);

    if (printOptionsAndExit) { // Just print options and exit
      parser.doGetOptionPairs().print(stdout);
      System.exit(0);
    }

    // Create a new directory
    if (create) {
      createVirtualExecDir();
      stderr.println(virtualExecDir);
      if (!makeThunk) LogInfo.file = getFile("log");

      // Copy the Jar files for reference
      if (!makeThunk) {
        for (String jarFile : jarFiles)
          Utils.systemHard(String.format("cp %s %s", jarFile, virtualExecDir));
      }
    } else {
      LogInfo.file = "";
    }

    if (!makeThunk) {
      LogInfo.init();
      if (startMainTrack) track("main()", true);
    }

    // Output options
    if (!makeThunk && virtualExecDir != null) logs("Execution directory: " + virtualExecDir);
    if (!makeThunk) getInfo().printEasy(getFile("info.map"));
    printOptions();
    if (create && addToView.size() > 0)
      IOUtils.printLinesHard(Execution.getFile("addToView"), addToView);

    // Start monitoring
    if (!makeThunk && monitor) {
      monitorThread = new MonitorThread();
      monitorThread.start();
    }

    if (!makeThunk) Record.init(Execution.getFile("record"));
  }