Esempio n. 1
1
 public BigInteger count(int n) {
   BigInteger[] prev = new BigInteger[k];
   Arrays.fill(prev, BigInteger.ZERO);
   prev[s] = BigInteger.ONE;
   while (n-- > 0) {
     BigInteger[] next = new BigInteger[k];
     Arrays.fill(next, BigInteger.ZERO);
     for (int i = 0; i < k; ++i) {
       if (prev[i].signum() <= 0) {
         continue;
       }
       for (int j = 0; j < z; ++j) {
         if (e[j][i] < 0) {
           continue;
         }
         next[e[j][i]] = next[e[j][i]].add(prev[i]);
       }
     }
     prev = next;
   }
   BigInteger ans = BigInteger.ZERO;
   for (int term : t) {
     ans = ans.add(prev[term]);
   }
   return ans;
 }
Esempio n. 2
1
  public int count(int b1, int q1, int n1, int b2, int q2, int n2) {
    if (b2 == 0 || q2 <= 1) {
      int tb = b1;
      int tq = q1;
      int tn = n1;
      b1 = b2;
      q1 = q2;
      n1 = n2;
      b2 = tb;
      q2 = tq;
      n2 = tn;
    }

    if (b1 == 0 || q1 <= 1) {
      HashSet<Integer> set = new HashSet<Integer>();
      set.add(b1);
      if (n1 > 1) {
        set.add(b1 * q1);
      }

      long curr = b2;
      for (int i = 0; i < n2; i++) {
        set.add((int) curr);
        curr *= q2;
        if (curr > 500000000) {
          return (n2 - i - 1) + set.size();
        }
      }

      return set.size();
    } else {
      HashSet<String> set = new HashSet<String>();

      int factors[] = findFactors(b1, q1, b2, q2);
      int repb1[] = decompose(b1, factors);
      int repb2[] = decompose(b2, factors);
      int repq1[] = decompose(q1, factors);
      int repq2[] = decompose(q2, factors);

      for (int i = 0; i < n1; i++) {
        set.add(Arrays.toString(repb1));
        for (int j = 0; j < repb1.length; j++) {
          repb1[j] += repq1[j];
        }
      }

      for (int i = 0; i < n2; i++) {
        set.add(Arrays.toString(repb2));
        for (int j = 0; j < repb2.length; j++) {
          repb2[j] += repq2[j];
        }
      }

      return set.size();
    }
  }
Esempio n. 3
1
 static List<Answer> solve(int[] numbers) {
   int n = numbers.length;
   Element[] a = new Element[n];
   for (int i = 0; i < n; i++) {
     a[i] = new Element(numbers[i], i);
   }
   int id = -1;
   for (int i = 0; i < n; i++) {
     if (luckies.contains(a[i].x)) {
       id = i;
       break;
     }
   }
   Element[] b = a.clone();
   Arrays.sort(b);
   if (Arrays.equals(a, b)) {
     return new ArrayList<Answer>();
   }
   if (id == -1) {
     return null;
   }
   boolean[] did = new boolean[n];
   for (int i = 0; i < n; i++) {
     if (a[i] == b[i]) {
       did[i] = true;
     }
   }
   List<Answer> ans = new ArrayList<Answer>();
   int cur = 0;
   while (cur < n) {
     while (b[id] != a[id]) {
       int newId = b[id].n;
       swap(id, b[id].n, ans, a);
       did[id] = true;
       id = newId;
     }
     while (cur < n && did[cur] || cur == id) {
       cur++;
     }
     if (cur < n) {
       int newId = cur;
       swap(cur, id, ans, a);
       id = newId;
     }
   }
   // for (int i = 1; i < n; i++) {
   // if (a[i].x < a[i - 1].x) {
   // throw new AssertionError();
   // }
   // }
   // if (ans.size() > 2 * n) {
   // throw new AssertionError();
   // }
   return ans;
 }
    @Test
    public void nemesisBlockCannotBeLoadedFromInvalidBlob() {
      // Arrange:
      final byte[] buffer = loadNemesisBlockBlobObject();
      final byte[] badBuffer1 =
          ByteBuffer.allocate(3 + buffer.length).put("bad".getBytes()).put(buffer).array();
      final byte[] badBuffer2 =
          ByteBuffer.allocate(3 + buffer.length)
              .put(Arrays.copyOfRange(buffer, 0, 100))
              .put("bad".getBytes())
              .put(Arrays.copyOfRange(buffer, 100, buffer.length))
              .array();

      // Act:
      ExceptionAssert.assertThrows(
          v ->
              NemesisBlock.fromBlobObject(
                  NEMESIS_BLOCK_INFO,
                  badBuffer1,
                  new DeserializationContext(new MockAccountLookup())),
          IllegalArgumentException.class);
      ExceptionAssert.assertThrows(
          v ->
              NemesisBlock.fromBlobObject(
                  NEMESIS_BLOCK_INFO,
                  badBuffer2,
                  new DeserializationContext(new MockAccountLookup())),
          SerializationException.class);
    }
Esempio n. 5
0
 public DictionaryEntry lookup(byte utfBytes[], int hashCode, int charLength) {
   int res = Arrays.binarySearch(hashCodes, hashCode);
   if (res < 0) {
     return null;
   }
   DictionaryEntry entry = entries[res];
   if (Arrays.equals(entry.entryBytes, utfBytes)) {
     return entry;
   }
   int pos = res - 1;
   while ((pos >= 0) && (hashCodes[pos] == hashCode)) {
     entry = entries[pos];
     if (Arrays.equals(entry.entryBytes, utfBytes)) {
       return entry;
     }
     --pos;
   }
   pos = res + 1;
   while ((pos < entries.length) && (hashCodes[pos] == hashCode)) {
     entry = entries[pos];
     if (Arrays.equals(entry.entryBytes, utfBytes)) {
       return entry;
     }
     ++pos;
   }
   return UNKNOWN;
 }
Esempio n. 6
0
 // [algo] hungary BipartiteMaximumMatching
 // [module] hungary
 public static int hungary(int nu, int nv, int[][] e, int[] mu, int[] mv) {
   Arrays.fill(mu, -1);
   Arrays.fill(mv, -1);
   int[] q = new int[nu];
   int[] p = new int[nv];
   int ret = 0;
   for (int i = 0; i < nu; ++i) {
     Arrays.fill(p, -1);
     q[0] = i;
     BFS:
     for (int begin = 0, end = 1; begin < end; ++begin) {
       int u = q[begin];
       for (int v : e[u]) {
         if (p[v] == -1) {
           p[v] = u;
           if (mv[v] == -1) {
             int t = v;
             while (t != -1) {
               u = p[t];
               v = t;
               t = mu[u];
               mu[u] = v;
               mv[v] = u;
             }
             ++ret;
             break BFS;
           } else {
             q[end++] = mv[v];
           }
         }
       }
     }
   }
   return ret;
 }
Esempio n. 7
0
 /**
  * get parameter names of given {@code constructor}
  *
  * <p>depends on MethodParameterNamesScanner configured
  */
 public List<String> getConstructorParamNames(Constructor constructor) {
   Iterable<String> names =
       store.get(index(MethodParameterNamesScanner.class), Utils.name(constructor));
   return !Iterables.isEmpty(names)
       ? Arrays.asList(Iterables.getOnlyElement(names).split(", "))
       : Arrays.<String>asList();
 }
Esempio n. 8
0
 /**
  * Adds a record to the table and the ID index.
  *
  * @param i index in the table where the record should be inserted
  * @param pre pre value
  * @param fid first ID value
  * @param nid last ID value
  * @param inc increment value
  * @param oid original ID value
  */
 private void add(
     final int i, final int pre, final int fid, final int nid, final int inc, final int oid) {
   if (rows == pres.length) {
     final int s = Array.newSize(rows);
     pres = Arrays.copyOf(pres, s);
     fids = Arrays.copyOf(fids, s);
     nids = Arrays.copyOf(nids, s);
     incs = Arrays.copyOf(incs, s);
     oids = Arrays.copyOf(oids, s);
   }
   if (i < rows) {
     final int destPos = i + 1;
     final int length = rows - i;
     System.arraycopy(pres, i, pres, destPos, length);
     System.arraycopy(fids, i, fids, destPos, length);
     System.arraycopy(nids, i, nids, destPos, length);
     System.arraycopy(incs, i, incs, destPos, length);
     System.arraycopy(oids, i, oids, destPos, length);
   }
   pres[i] = pre;
   fids[i] = fid;
   nids[i] = nid;
   incs[i] = inc;
   oids[i] = oid;
   ++rows;
 }
 public static void main(String[] args) {
   LetterToSound text = LetterToSound.getInstance();
   System.out.println(Arrays.asList(text.getPhones("laggin", "n")));
   System.out.println(Arrays.asList(text.getPhones("dragon", "n")));
   System.out.println(Arrays.asList(text.getPhones("hello", "n")));
   // System.out.println(Arrays.asList(text.getPhones("antelope", "n")));
 }
Esempio n. 10
0
  /**
   * Copy from the copy method in StructUtil. Did not want to drag that code in. maybe this actually
   * should go to struct.
   *
   * @param from
   * @param to
   * @param excludes
   * @return
   * @throws Exception
   */
  public static <T extends struct> T xcopy(struct from, T to, String... excludes) throws Exception {
    Arrays.sort(excludes);
    for (Field f : from.fields()) {
      if (Arrays.binarySearch(excludes, f.getName()) >= 0) continue;

      Object o = f.get(from);
      if (o == null) continue;

      Field tof = to.getField(f.getName());
      if (tof != null)
        try {
          tof.set(to, Converter.cnv(tof.getGenericType(), o));
        } catch (Exception e) {
          System.out.println(
              "Failed to convert "
                  + f.getName()
                  + " from "
                  + from.getClass()
                  + " to "
                  + to.getClass()
                  + " value "
                  + o
                  + " exception "
                  + e);
        }
    }

    return to;
  }
Esempio n. 11
0
  static double[] similarity(LatentDirichletAllocation lda0, LatentDirichletAllocation lda1) {

    int numTopics = lda0.numTopics();

    int numPairs = numTopics * (numTopics - 1);
    @SuppressWarnings({"unchecked", "rawtypes"}) // ok given use w. erasure
    ScoredObject<int[]>[] pairs = (ScoredObject<int[]>[]) new ScoredObject[numPairs];
    int pos = 0;
    for (int i = 0; i < numTopics; ++i) {
      for (int j = 0; j < numTopics; ++j) {
        if (i == j) continue;
        double divergence =
            Statistics.symmetrizedKlDivergence(
                lda0.wordProbabilities(i), lda1.wordProbabilities(j));
        pairs[pos++] = new ScoredObject<int[]>(new int[] {i, j}, divergence);
      }
    }
    Arrays.sort(pairs, ScoredObject.comparator());
    boolean[] taken0 = new boolean[numTopics];
    Arrays.fill(taken0, false);
    boolean[] taken1 = new boolean[numTopics];
    Arrays.fill(taken1, false);
    double[] scores = new double[numTopics];
    int scorePos = 0;
    for (pos = 0; pos < numPairs && scorePos < numTopics; ++pos) {
      int[] pair = pairs[pos].getObject();
      if (!taken0[pair[0]] && !taken1[pair[1]]) {
        taken0[pair[0]] = true;
        taken1[pair[1]] = true;
        scores[scorePos++] = pairs[pos].score();
      }
    }
    return scores;
  }
Esempio n. 12
0
  @Override
  public boolean removeMetadataBlob(
      UserPublicKey owner, byte[] encodedWritingPublicKey, byte[] writingKeySignedMapKeyPlusBlob) {
    UserPublicKey writingKey = new UserPublicKey(encodedWritingPublicKey);

    try {
      byte[] payload = writingKey.unsignMessage(writingKeySignedMapKeyPlusBlob);
      byte[] mapKey = Arrays.copyOfRange(payload, 0, 32);
      byte[] metadataBlob =
          Arrays.copyOfRange(
              payload,
              32,
              payload
                  .length); // will be zero length for now // TODO  change to the current blob hash
      MetadataBlob blob = new MetadataBlob(writingKey.getPublicKeys(), mapKey, metadataBlob);
      return blob.delete();
    } catch (TweetNaCl.InvalidSignatureException e) {
      System.err.println(
          "Invalid signature during removeMetadataBlob for owner: "
              + owner
              + " and sharer: "
              + writingKey);
      return false;
    }
  }
Esempio n. 13
0
  void test(String[] opts, String className) throws Exception {
    count++;
    System.err.println("Test " + count + " " + Arrays.asList(opts) + " " + className);
    Path testSrcDir = Paths.get(System.getProperty("test.src"));
    Path testClassesDir = Paths.get(System.getProperty("test.classes"));
    Path classes = Paths.get("classes." + count);
    classes.createDirectory();

    Context ctx = new Context();
    PathFileManager fm = new JavacPathFileManager(ctx, true, null);
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    List<String> options = new ArrayList<String>();
    options.addAll(Arrays.asList(opts));
    options.addAll(Arrays.asList("-verbose", "-XDverboseCompilePolicy", "-d", classes.toString()));
    Iterable<? extends JavaFileObject> compilationUnits =
        fm.getJavaFileObjects(testSrcDir.resolve(className + ".java"));
    StringWriter sw = new StringWriter();
    PrintWriter out = new PrintWriter(sw);
    JavaCompiler.CompilationTask t =
        compiler.getTask(out, fm, null, options, null, compilationUnits);
    boolean ok = t.call();
    System.err.println(sw.toString());
    if (!ok) {
      throw new Exception("compilation failed");
    }

    File expect = new File("classes." + count + "/" + className + ".class");
    if (!expect.exists()) throw new Exception("expected file not found: " + expect);
    long expectedSize = new File(testClassesDir.toString(), className + ".class").length();
    long actualSize = expect.length();
    if (expectedSize != actualSize)
      throw new Exception("wrong size found: " + actualSize + "; expected: " + expectedSize);
  }
  int Query() {
    int minimum = 100001;

    visited = new boolean[V];
    Arrays.fill(visited, false);

    depth = new int[V];
    Arrays.fill(depth, -1);

    low = new int[V];
    Arrays.fill(low, -1);

    parent = new int[V];
    Arrays.fill(parent, -1);

    articulationPoints = new TreeMap<Integer, Boolean>();

    getArticulationPoints(0, 0);

    for (Map.Entry<Integer, Boolean> entry : articulationPoints.entrySet()) {
      int i = (int) entry.getKey();
      if (RatingScore[i] < minimum) {
        minimum = RatingScore[i];
      }
    }

    return minimum != 100001 ? minimum : -1;
  }
Esempio n. 15
0
  public int minimalPlanets(int[] A, int[] B) {
    this.A = A.length > B.length ? A : B;
    this.B = A.length > B.length ? B : A;

    int[][] memo = new int[this.A.length][this.B.length];
    for (int[] m : memo) {
      Arrays.fill(m, -1);
    }

    int best = find(memo, 0, 0, 1, 1);
    for (int i = 0; i < this.A.length; i++) {
      for (int j = 0; j < this.B.length; j++) {
        if (this.A[i] != this.B[j]) {

          memo = new int[this.A.length][this.B.length];
          for (int[] m : memo) {
            Arrays.fill(m, -1);
          }

          best = Math.max(best, find(memo, 0, 0, this.B[j], this.A[i]));
        }
      }
    }

    return A.length + (B.length - best);
  }
  public List<String> find() throws IOException {
    //		Set<String> g1 = new HashSet<String>(Arrays.asList("HRAS", "NRAS", "KRAS"));
    //		Set<String> g2 = new HashSet<String>(Arrays.asList("BRAF"));

    Set<String> g1 = new HashSet<String>(Arrays.asList("HRAS"));
    Set<String> g2 = new HashSet<String>(Arrays.asList("NRAS", "KRAS"));

    Map<String, Double> pvals = calcDifferencePvals(g1, g2);

    System.out.println("pvals.size() = " + pvals.size());

    List<String> list = FDR.select(pvals, null, fdrThr);
    System.out.println("result size = " + list.size());

    Map<String, Boolean> dirs = getChangeDirections(list, g1, g2);

    int up = 0;
    int dw = 0;

    for (String gene : dirs.keySet()) {
      Boolean d = dirs.get(gene);
      if (d) up++;
      else dw++;
    }

    System.out.println("up = " + up);
    System.out.println("dw = " + dw);

    return list;
  }
Esempio n. 17
0
    public static void main(String args[]) throws Exception {
        Scanner keyb = new Scanner(new File("jorge.dat"));

        while (keyb.hasNextLine()) {
            String dat[] = keyb.nextLine().split(" ");
            int ints[] = new int[dat.length];
            for (int i = 0; i < dat.length; i++) {
                ints[i] = Integer.parseInt(dat[i]);
            }
            int mods[] = new int[dat.length];
            for (int i = 0; i < dat.length; i++) {
                mods[i] = Integer.parseInt(dat[i]) % 13;
            }
            Arrays.sort(ints);
            Arrays.sort(mods);
            System.out.println(Arrays.toString(ints));
            if (asd(mods)) {
                System.out.println("FOUR OF A KIND");
            } else if (dannyTanner(mods)) {
                System.out.println("FULL HOUSE");
            } else if (toilet(ints)) {
                System.out.println("FLUSH");
            } else if (yag(ints, mods)  {
                System.out.println("STRAIGHT");
            } else if (tres()) {

            }
        }
Esempio n. 18
0
  public static void main(String[] args) throws IOException {
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    StringTokenizer st;
    int cases = 1;
    while (true) {
      st = new StringTokenizer(in.readLine());
      n = Integer.parseInt(st.nextToken());
      m = Integer.parseInt(st.nextToken());
      if (n == 0 && m == 0) break;
      a = new int[n];
      b = new int[m];
      dp = new int[n + 1][m + 1];
      st = new StringTokenizer(in.readLine());
      for (int i = 0; i < n; i++) {
        a[i] = Integer.parseInt(st.nextToken());
        Arrays.fill(dp[i], -1);
      }
      Arrays.fill(dp[n], -1);
      st = new StringTokenizer(in.readLine());
      for (int i = 0; i < m; i++) b[i] = Integer.parseInt(st.nextToken());

      System.out.println("Twin Towers #" + cases);
      System.out.println("Number of Tiles : " + LCS(0, 0));
      System.out.println();
      cases++;
    }
    in.close();
    System.exit(0);
  }
Esempio n. 19
0
  /**
   * Creates a java process that executes the given main class and waits for the process to
   * terminate.
   *
   * @return a {@link ProcessOutputReader} that can be used to get the exit code and stdout+stderr
   *     of the terminated process.
   */
  public static ProcessOutputReader fg(Class main, String[] vmArgs, String[] mainArgs)
      throws IOException {
    File javabindir = new File(System.getProperty("java.home"), "bin");
    File javaexe = new File(javabindir, "java");

    int bits = Integer.getInteger("sun.arch.data.model", 0).intValue();
    String vmKindArg = (bits == 64) ? "-d64" : null;

    ArrayList argList = new ArrayList();
    argList.add(javaexe.getPath());
    if (vmKindArg != null) {
      argList.add(vmKindArg);
    }
    // argList.add("-Dgemfire.systemDirectory=" +
    // GemFireConnectionFactory.getDefaultSystemDirectory());
    argList.add("-Djava.class.path=" + System.getProperty("java.class.path"));
    argList.add("-Djava.library.path=" + System.getProperty("java.library.path"));
    if (vmArgs != null) {
      argList.addAll(Arrays.asList(vmArgs));
    }
    argList.add(main.getName());
    if (mainArgs != null) {
      argList.addAll(Arrays.asList(mainArgs));
    }
    String[] cmd = (String[]) argList.toArray(new String[argList.size()]);
    return new ProcessOutputReader(Runtime.getRuntime().exec(cmd));
  }
Esempio n. 20
0
  public static void main(String... args) throws Throwable {
    String testSrcDir = System.getProperty("test.src");
    String testClassDir = System.getProperty("test.classes");
    String self = T6361619.class.getName();

    JavacTool tool = JavacTool.create();

    final PrintWriter out = new PrintWriter(System.err, true);

    Iterable<String> flags =
        Arrays.asList(
            "-processorpath", testClassDir,
            "-processor", self,
            "-d", ".");
    DiagnosticListener<JavaFileObject> dl =
        new DiagnosticListener<JavaFileObject>() {
          public void report(Diagnostic<? extends JavaFileObject> m) {
            out.println(m);
          }
        };

    StandardJavaFileManager fm = tool.getStandardFileManager(dl, null, null);
    Iterable<? extends JavaFileObject> f =
        fm.getJavaFileObjectsFromFiles(Arrays.asList(new File(testSrcDir, self + ".java")));

    JavacTask task = tool.getTask(out, fm, dl, flags, null, f);
    MyTaskListener tl = new MyTaskListener(task);
    task.setTaskListener(tl);

    // should complete, without exceptions
    task.call();
  }
Esempio n. 21
0
  private void processChunk(
      int x,
      int z,
      byte[] data,
      int bitmask,
      int additionalBitmask,
      boolean addSkylight,
      boolean addBiomes) {
    if (data == null) return;
    int chunksChanged = 0;
    for (int i = 0; i < 16; i++) if ((bitmask & (1 << i)) != 0) chunksChanged++;
    if (chunksChanged == 0) return;
    byte[] biomes = new byte[256];
    synchronized (chunks) {
      int i = 0;
      for (int y = 0; y < 16; y++) {
        if ((bitmask & (1 << y)) == 0) continue;
        int dataIndex = i * 4096;
        byte[] blocks = Arrays.copyOfRange(data, dataIndex, dataIndex + 4096);
        dataIndex += ((chunksChanged - i) * 4096) + (i * 2048);
        byte[] metadata = Arrays.copyOfRange(data, dataIndex, dataIndex + 2048);
        dataIndex += chunksChanged * 2048;
        byte[] light = Arrays.copyOfRange(data, dataIndex, dataIndex + 2048);
        dataIndex += chunksChanged * 2048;
        byte[] skylight = null;
        if (addSkylight) skylight = Arrays.copyOfRange(data, dataIndex, dataIndex + 2048);

        byte[] perBlockMetadata = new byte[4096];
        byte[] perBlockLight = new byte[4096];
        byte[] perBlockSkylight = new byte[4096];

        for (int j = 0; j < 2048; j++) {
          int k = j * 2;
          perBlockMetadata[k] = (byte) (metadata[j] & 0x0F);
          perBlockLight[k] = (byte) (light[j] & 0x0F);
          if (addSkylight) perBlockSkylight[k] = (byte) (skylight[j] & 0x0F);
          k++;
          perBlockMetadata[k] = (byte) (metadata[j] >> 4);
          perBlockLight[k] = (byte) (light[j] >> 4);
          if (addSkylight) perBlockSkylight[k] = (byte) (skylight[j] >> 4);
        }

        ChunkLocation newLocation = new ChunkLocation(x, y, z);
        Chunk chunk =
            new Chunk(
                this,
                newLocation,
                blocks,
                perBlockMetadata,
                perBlockLight,
                perBlockSkylight,
                biomes);
        chunks.put(newLocation, chunk);
        bot.getEventManager().sendEvent(new ChunkLoadEvent(this, chunk));
        i++;
      }
      System.arraycopy(data, data.length - 256, biomes, 0, 256);
    }
  }
Esempio n. 22
0
 public Iterable<ZipEntry> getEntriesInPhysicalOrder(final String name) {
   ZipEntry[] entriesOfThatName = new ZipEntry[0];
   if (this.nameMap.containsKey(name)) {
     entriesOfThatName = this.nameMap.get(name).toArray(entriesOfThatName);
     Arrays.sort(entriesOfThatName, this.OFFSET_COMPARATOR);
   }
   return Arrays.asList(entriesOfThatName);
 }
Esempio n. 23
0
 private void updateJsonJob(ApplicationInfo appInfo, CIJob job) throws PhrescoException {
   try {
     deleteJsonJobs(appInfo, Arrays.asList(job));
     writeJsonJobs(appInfo, Arrays.asList(job), CI_APPEND_JOBS);
   } catch (Exception e) {
     throw new PhrescoException(e);
   }
 }
Esempio n. 24
0
  ///////////
  // Methods//
  ///////////
  public void createServerFile(
      HashMap<String, DataObj> dataObjsMap, HashMap<String, PageObj> pageObjsMap) {
    // Copy files over
    try {
      FileUtils.copyFile(sourceConfig, new File("Output/config.js"));
    } catch (IOException e) {
      System.out.println("Error copying over config file for");
      System.out.println(e);
    }
    out.write(genDbConnection());
    // For each data object, get object by ID
    Iterator it = dataObjsMap.entrySet().iterator();
    while (it.hasNext()) {
      Map.Entry one = (Map.Entry) it.next();
      DataObj curDataObj = (DataObj) one.getValue();
      String name = curDataObj.getName();
      out.write("\n /* " + name + ": CRUD GET, DELETE, UPDATE, POST BY ID*/\n");
      out.write(genGetById(curDataObj));
      out.write(genDelById(curDataObj));
      out.write(genUpdateById(curDataObj));
      out.write(genAdd(curDataObj));
    }
    // Hack to get a necessary API call for OAuth stuff
    out.write(
        genGetByPageParam(
            null,
            new Section(
                "View",
                new ArrayList<String>(Arrays.asList(new String[] {"OAuthID"})),
                new ArrayList<String>(Arrays.asList(new String[] {"User"}))),
            dataObjsMap));

    // For each page, generate the calls necessery to make
    // the view/create params work
    it = pageObjsMap.entrySet().iterator();
    while (it.hasNext()) {
      Map.Entry one = (Map.Entry) it.next();
      PageObj curPageObj = (PageObj) one.getValue();
      String name = curPageObj.getName();
      out.write("\n /* " + name + ": CRUD GET,DELETE,UPDATE,POST *NOT* BY ID */\n");
      List<Section> sections = curPageObj.getSections();
      for (Section section : sections) {
        switch ((Section.Type) section.getType()) {
          case VIEW:
            out.write(genGetByPageParam(curPageObj, section, dataObjsMap));
            break;
          case CREATE:
            // out.write(genPostByPageParam(curPageObj, section));
            break;
          case MODIFY:
            break;
          case DELETE:
            break;
        }
      }
    }
    out.write(genServerListen());
  }
Esempio n. 25
0
  /**
   * setupPlayZone.
   *
   * @param p a {@link arcane.ui.PlayArea} object.
   * @param c an array of {@link forge.Card} objects.
   */
  public static void setupPlayZone(PlayArea p, Card c[]) {
    List<Card> tmp, diff;
    tmp = new ArrayList<Card>();
    for (arcane.ui.CardPanel cpa : p.cardPanels) tmp.add(cpa.gameCard);
    diff = new ArrayList<Card>(tmp);
    diff.removeAll(Arrays.asList(c));
    if (diff.size() == p.cardPanels.size()) p.clear();
    else {
      for (Card card : diff) {
        p.removeCardPanel(p.getCardPanel(card.getUniqueNumber()));
      }
    }
    diff = new ArrayList<Card>(Arrays.asList(c));
    diff.removeAll(tmp);

    arcane.ui.CardPanel toPanel = null;
    for (Card card : diff) {
      toPanel = p.addCard(card);
      Animation.moveCard(toPanel);
    }

    for (Card card : c) {
      toPanel = p.getCardPanel(card.getUniqueNumber());
      if (card.isTapped()) {
        toPanel.tapped = true;
        toPanel.tappedAngle = arcane.ui.CardPanel.TAPPED_ANGLE;
      } else {
        toPanel.tapped = false;
        toPanel.tappedAngle = 0;
      }
      toPanel.attachedPanels.clear();
      if (card.isEnchanted()) {
        ArrayList<Card> enchants = card.getEnchantedBy();
        for (Card e : enchants) {
          arcane.ui.CardPanel cardE = p.getCardPanel(e.getUniqueNumber());
          if (cardE != null) toPanel.attachedPanels.add(cardE);
        }
      }

      if (card.isEquipped()) {
        ArrayList<Card> enchants = card.getEquippedBy();
        for (Card e : enchants) {
          arcane.ui.CardPanel cardE = p.getCardPanel(e.getUniqueNumber());
          if (cardE != null) toPanel.attachedPanels.add(cardE);
        }
      }

      if (card.isEnchanting()) {
        toPanel.attachedToPanel = p.getCardPanel(card.getEnchanting().get(0).getUniqueNumber());
      } else if (card.isEquipping()) {
        toPanel.attachedToPanel = p.getCardPanel(card.getEquipping().get(0).getUniqueNumber());
      } else toPanel.attachedToPanel = null;

      toPanel.setCard(toPanel.gameCard);
    }
    p.invalidate();
    p.repaint();
  }
 public void clear() {
   super.clear();
   final int[] keys = this._set;
   final Object[] vals = this._values;
   final byte[] states = this._states;
   Arrays.fill(this._set, 0, this._set.length, 0);
   Arrays.fill(this._values, 0, this._values.length, null);
   Arrays.fill(this._states, 0, this._states.length, (byte) 0);
 }
Esempio n. 27
0
  public Collection<String> getArguments() {
    Collection<String> args = new ArrayList<>();
    Optional.ofNullable(username).ifPresent(s -> args.addAll(Arrays.asList("-u", s)));
    Optional.ofNullable(password).ifPresent(s -> args.addAll(Arrays.asList("-p", s)));
    Optional.ofNullable(from)
        .ifPresent(d -> args.addAll(Arrays.asList("-f", d.format(DateTimeFormatter.ISO_DATE))));

    return args;
  }
 /** descendingkeySet.toArray returns contains all keys */
 public void testDescendingDescendingKeySetToArray() {
   ConcurrentNavigableMap map = dmap5();
   Set s = map.descendingKeySet();
   Object[] ar = s.toArray();
   assertEquals(5, ar.length);
   assertTrue(s.containsAll(Arrays.asList(ar)));
   ar[0] = m10;
   assertFalse(s.containsAll(Arrays.asList(ar)));
 }
Esempio n. 29
0
  /**
   * Return either (a) the children files in a directory, or (b) files listed in the input, assuming
   * inputFileOrDir is a text file with 1 file listing per line.
   *
   * @param inputFileOrDir
   * @return
   */
  private List<File> getFilesFromDirOrList(File inputFileOrDir) {

    if (inputFileOrDir.isDirectory()) {
      File[] files = inputFileOrDir.listFiles();
      Arrays.sort(
          files,
          new Comparator<File>() {
            public int compare(File file, File file1) {
              return file.getName().compareTo(file1.getName());
            }
          });
      return Arrays.asList(files);
    } else {
      // Must be a "list" file
      BufferedReader br = null;
      try {
        ArrayList<File> files = new ArrayList<File>();
        br = new BufferedReader(new FileReader(inputFileOrDir));
        File parentDirectory = inputFileOrDir.getParentFile();
        String nextLine;
        while ((nextLine = br.readLine()) != null) {
          File f = new File(nextLine);
          if (f.exists()) {
            if (f.isDirectory()) {
              continue; // Skip directories
            }
            files.add(f);
          } else {
            // Might be relative path
            f = new File(parentDirectory, nextLine);
            if (f.exists()) {
              files.add(f);
            } else {
              System.out.println("File not found: " + nextLine);
            }
          }
        }
        return files;
      } catch (Exception e) {
        // todo -- someday create reasonable excpetion classes.  Althought, this one works
        e.printStackTrace();
        throw new RuntimeException(
            "Error parsing input file: " + inputFileOrDir.getAbsolutePath() + " " + e.getMessage());
      } finally {
        if (br != null)
          try {
            br.close();
          } catch (IOException e) {
            e
                .printStackTrace(); // To change body of catch statement use File | Settings | File
                                    // Templates.
          }
      }
    }
  }
  public final int readCharacter(final char[] allowed) throws IOException {
    // if we restrict to a limited set and the current character
    // is not in the set, then try again.
    char c;

    Arrays.sort(allowed); // always need to sort before binarySearch

    while (Arrays.binarySearch(allowed, c = (char) readVirtualKey()) < 0) ;

    return c;
  }