Пример #1
0
  /**
   * Método para reconocer los tokens más simples
   *
   * @param regex
   * @param conjuntoAut
   * @return boolean true si se crea un token, false si no es aceptado por ninguno.
   */
  public boolean tokenSimple(String regex, ArrayList<Automata> conjuntoAut) {
    TreeMap<String, Automata> aceptados =
        new TreeMap(
            new Comparator<String>() {
              @Override
              public int compare(String o1, String o2) {
                Integer a1 = o1.length();
                Integer a2 = o2.length();
                return a2 - a1;
              }
            });

    for (Automata automata : conjuntoAut) {
      if (sim.simular(regex, automata)) {
        aceptados.put(regex, automata);
      }
    }
    if (!aceptados.isEmpty()) {
      tokens.add(
          new Token(
              aceptados.firstEntry().getValue().getTipo(),
              aceptados.firstKey(),
              aceptados.firstEntry().getValue().isExceptKeywords()));

      return true;
    }

    return false;
  }
  @Test
  public void test2Categorias() {
    TreeMap<CategoryRestaurant, CategoryRestaurantRanking> list = ranking.getList();

    Assert.assertEquals(crA, list.firstEntry().getKey());
    list.remove(crA);

    Assert.assertEquals(crB, list.firstEntry().getKey());
    list.remove(crB);

    Assert.assertTrue(list.isEmpty());
  }
Пример #3
0
 void run() {
   int[] is = in.nextIntArray(6);
   TreeMap<Integer, Integer> cnt = new TreeMap<Integer, Integer>();
   for (int i : is) {
     Num.inc(cnt, i);
   }
   if (cnt.size() == 1) {
     out.println("Elephant");
   } else if (cnt.size() == 2) {
     int a = cnt.firstEntry().getValue();
     int b = cnt.lastEntry().getValue();
     if (a == 2 || b == 2) out.println("Elephant");
     else if (a == 1 || b == 1) out.println("Bear");
     else out.println("Alien");
   } else if (cnt.size() == 3) {
     int[] cs = new int[3];
     int i = 0;
     for (Map.Entry<Integer, Integer> es : cnt.entrySet()) {
       cs[i++] = es.getValue();
     }
     if ((cs[0] == 1 || cs[1] == 1) && (cs[0] == 4 || cs[1] == 4 || cs[2] == 4)) {
       out.println("Bear");
     } else {
       out.println("Alien");
     }
   } else {
     out.println("Alien");
   }
 }
Пример #4
0
  @Override
  protected void onBindViewHolder(Holder holder, Gist gist) {
    TreeMap<String, GistFile> filesMap = new TreeMap<>(gist.files);

    GistFile firstFile = filesMap.firstEntry().getValue();

    holder.textFileName.setText(firstFile.filename);

    holder.textNumFiles.setText(
        holder.itemView.getContext().getString(R.string.num_of_files, gist.files.size()));

    TextView textDescription = (TextView) holder.itemView.findViewById(R.id.textDescription);

    if (!TextUtils.isEmpty(gist.description)) {
      textDescription.setVisibility(View.VISIBLE);
      textDescription.setText(gist.description);
    } else {
      textDescription.setVisibility(View.GONE);
    }

    if (gist.isPublic) {
      holder.gistPrivate.setVisibility(View.GONE);
    } else {
      holder.gistPrivate.setVisibility(View.VISIBLE);
    }
  }
Пример #5
0
 // Pull the next message that needs an IGNORING response.  Once this
 // starts returning messages, poll() will always return null
 public VoltMessage drain() {
   if (!m_mustDrain || m_replayEntries.isEmpty()) {
     return null;
   }
   VoltMessage head = m_replayEntries.firstEntry().getValue().drain();
   while (head == null) {
     m_replayEntries.pollFirstEntry();
     if (!m_replayEntries.isEmpty()) {
       // This will end up null if the next ReplayEntry was just a sentinel.
       // We'll keep going.
       head = m_replayEntries.firstEntry().getValue().drain();
     } else {
       break;
     }
   }
   return head;
 }
Пример #6
0
  // Return the next correctly sequenced message or null if none exists.
  public VoltMessage poll() {
    if (m_mustDrain || m_replayEntries.isEmpty()) {
      return null;
    }
    if (m_replayEntries.firstEntry().getValue().isEmpty()) {
      m_replayEntries.pollFirstEntry();
    }
    // All the drain conditions depend on being blocked, which
    // we will only really know for sure when we try to poll().
    checkDrainCondition();
    if (m_mustDrain || m_replayEntries.isEmpty()) {
      return null;
    }

    VoltMessage m = m_replayEntries.firstEntry().getValue().poll();
    updateLastPolledTxnId(m_replayEntries.firstEntry().getKey(), (TransactionInfoBaseMessage) m);
    return m;
  }
 private Type getType(String msg) {
   if (msg == null) {
     return Type.TEXT;
   }
   Type[] types = type.values();
   TreeMap<Integer, Type> typesLastIndexInMsg = buildIndexMap(msg);
   if (typesLastIndexInMsg.size() == 0) {
     return Type.TEXT;
   } else {
     Map.Entry<Integer, Type> lastType = typesLastIndexInMsg.firstEntry();
     return lastType.getValue();
   }
 }
Пример #8
0
 void compute() {
   NavigableMap<GregorianCalendar, run> briefName = scores.descendingMap();
   double differentials[] = new double[20];
   for (i = 0, iterator = scores.firstEntry(); i < 20; i++) {
     tmp = courses.get(iterator.getValue().course);
     differentials[i] = (iterator.getValue().score - tmp.rating) * 113.0 / tmp.slope;
     iterator = scores.higherEntry(iterator.getKey());
   }
   Arrays.sort(differentials);
   score = 0.0;
   for (i = 0; i < 10; i++) {
     score += differentials[i];
   }
   score /= 10;
 }
Пример #9
0
    @Override
    public int propose(int value) {
      int myId = system.getProcessId();
      boolean amIAlive;
      if (amIAlive = alives.isEmpty()) alives.put(myId, value);

      for (int neighbour : system.getProcessNeighbourhood())
        system.sendMessage(neighbour, round, amIAlive ? value : null);

      while (awaitingMessages > 0) system.yield();

      int numOfAlives = alives.size();
      while (true) {
        if (alives.size() == 1) return alives.firstEntry().getValue();

        round++;

        if (alives.size() > 0) numOfAlives = alives.size();
        awaitingMessages = numOfAlives;

        if (!receivedForTheNextRounds.isEmpty())
          for (Map.Entry<Integer, Integer> entry :
              receivedForTheNextRounds.removeFirst().entrySet()) {
            awaitingMessages--;
            if (entry.getValue() == null) alives.remove(entry.getKey());
            else alives.put(entry.getKey(), entry.getValue());
          }

        if (amIAlive) {
          awaitingMessages--;
          if (random.nextInt(numOfAlives) == 0) {
            alives.put(myId, value);
            for (int neighbour : system.getProcessNeighbourhood())
              system.sendMessage(neighbour, round, value);
          } else {
            alives.remove(myId);
            for (int neighbour : system.getProcessNeighbourhood())
              system.sendMessage(neighbour, round, null);
          }
        }

        while (awaitingMessages > 0) system.yield();

        if (!alives.isEmpty() && !alives.containsKey(myId)) amIAlive = false;
      }
    }
 /**
  * Magic is like %html %text.
  *
  * @param msg
  * @return
  */
 private String getData(String msg) {
   if (msg == null) {
     return null;
   }
   Type[] types = type.values();
   TreeMap<Integer, Type> typesLastIndexInMsg = buildIndexMap(msg);
   if (typesLastIndexInMsg.size() == 0) {
     return msg;
   } else {
     Map.Entry<Integer, Type> lastType = typesLastIndexInMsg.firstEntry();
     // add 1 for the % char
     int magicLength = lastType.getValue().name().length() + 1;
     // 1 for the last \n or space after magic
     int subStringPos = magicLength + lastType.getKey() + 1;
     return msg.substring(subStringPos);
   }
 }
Пример #11
0
 public static void main(String[] args) {
   TreeMap tm = new TreeMap();
   tm.put(new R(3), "轻量级Java EE企业应用实战");
   tm.put(new R(-5), "疯狂Java讲义");
   tm.put(new R(9), "疯狂Android讲义");
   System.out.println(tm);
   // 返回该TreeMap的第一个Entry对象
   System.out.println(tm.firstEntry());
   // 返回该TreeMap的最后一个key值
   System.out.println(tm.lastKey());
   // 返回该TreeMap的比new R(2)大的最小key值。
   System.out.println(tm.higherKey(new R(2)));
   // 返回该TreeMap的比new R(2)小的最大的key-value对。
   System.out.println(tm.lowerEntry(new R(2)));
   // 返回该TreeMap的子TreeMap
   System.out.println(tm.subMap(new R(-1), new R(4)));
 }
Пример #12
0
 private void checkDrainCondition() {
   // Don't ever go backwards once the drain decision is made.
   if (m_mustDrain) {
     return;
   }
   // if we've got things to sequence, check to if we're blocked
   if (!m_replayEntries.isEmpty()) {
     ReplayEntry head = m_replayEntries.firstEntry().getValue();
     if (!head.isReady()) {
       // if we're blocked, see if we have a sentinel or a fragment.
       // we know we have one or the other but not both.  Neither
       // means we wouldn't exist, and both would make us ready.
       // if it's the sentinel, see if the MPI's command log is done
       if (head.hasSentinel() && m_mpiEOLReached) {
         m_mustDrain = true;
       }
     }
   }
 }
Пример #13
0
  public double getValue(double x) {
    Map.Entry<Double, Double> e1, e2;
    double x1, x2;
    double y1, y2;

    if (Double.isNaN(x)) return Double.NaN;

    e1 = sortMap.floorEntry(x);

    if (e1 == null) {
      // x smaller than any value in the set
      e1 = sortMap.firstEntry();
      if (e1 == null) {
        return Double.NaN;
      }
      e2 = sortMap.higherEntry(e1.getKey());
      if (e2 == null) {
        // only one value in the set
        return e1.getValue();
      }
    } else {

      e2 = sortMap.higherEntry(e1.getKey());
      if (e2 == null) {
        // x larger than any value in the set
        e2 = e1;
        e1 = sortMap.lowerEntry(e2.getKey());
        if (e1 == null) {
          // only one value in the set
          return e2.getValue();
        }
      }
    }

    x1 = e1.getKey();
    x2 = e2.getKey();
    y1 = e1.getValue();
    y2 = e2.getValue();

    return (x - x1) / (x2 - x1) * (y2 - y1) + y1;
  }
Пример #14
0
 public Map.Entry<K, V> firstEntry() {
   return realMap.firstEntry();
 }
Пример #15
0
  private static List<String> buildTableDecls(
      List<DataType> dataTypes, List<ColumnAttribute> attrTypes) {
    LinkedHashMap<String, ColumnDecl> uniqueDecls = new LinkedHashMap<String, ColumnDecl>();
    TreeMap<String, ColumnDecl> regularDecls = new TreeMap<String, ColumnDecl>();
    // unique decls are those that are declared autoincrement or primary key
    // there is one of each where appropriate; these all go in the uniqueDecls set.
    // regular decls involve every combo of non pk/autoinc attributes.  if there are multiple
    // variants
    // then we do one of each variant.
    ColumnAttribute pk = null;
    ColumnAttribute ai = null;
    List<ColumnAttribute> variables = new ArrayList<ColumnAttribute>();
    for (Iterator<ColumnAttribute> iter = attrTypes.iterator(); iter.hasNext(); ) {
      ColumnAttribute ca = iter.next();
      if (ca.getType() == AttributeType.AUTOINCREMENT) {
        ai = ca;
        iter.remove();
      } else if (ca.getType() == AttributeType.PRIMARY) {
        pk = ca;
        iter.remove();
      } else if (ca.getVariants() > 1) variables.add(ca);
    }
    List<List<AttributeValue>> nakedUniverse = new ArrayList<List<AttributeValue>>();
    List<List<AttributeValue>> pkUniverse = new ArrayList<List<AttributeValue>>();
    List<List<AttributeValue>> aiUniverse = new ArrayList<List<AttributeValue>>();
    for (ColumnAttribute ca : variables) {
      for (int i = 0; i < ca.getVariants(); i++) {
        List<AttributeValue> combo = new ArrayList<AttributeValue>();
        for (ColumnAttribute ica : attrTypes) {
          if (ica == ca) {
            combo.add(new AttributeValue(ica, i));
          } else {
            combo.add(new AttributeValue(ica, 0));
          }
        }
        nakedUniverse.add(combo);
        List<AttributeValue> pkPrefix = new ArrayList<AttributeValue>();
        pkPrefix.add(new AttributeValue(pk, 0));
        pkPrefix.addAll(combo);
        pkUniverse.add(pkPrefix);
        List<AttributeValue> aiPrefix = new ArrayList<AttributeValue>();
        aiPrefix.add(new AttributeValue(ai, 0));
        aiPrefix.addAll(combo);
        aiUniverse.add(aiPrefix);
      }
    }

    Set<Set<ColumnAttribute>> ps = Sets.powerSet(new LinkedHashSet<ColumnAttribute>(attrTypes));
    List<List<AttributeValue>> vps = new ArrayList<List<AttributeValue>>();
    for (Set<ColumnAttribute> s : ps) {
      // also off of the powerset arrange for variants
      List<AttributeValue> entry = new ArrayList<AttributeValue>();
      List<ColumnAttribute> variants = new ArrayList<ColumnAttribute>();
      for (ColumnAttribute ca : s) {
        entry.add(new AttributeValue(ca, 0));
        if (ca.getVariants() > 1) {
          variants.add(ca);
        }
      }
      vps.add(entry);
      for (ColumnAttribute oca : variants) {
        for (int i = 1; i < oca.getVariants(); i++) {
          List<AttributeValue> ventry = new ArrayList<AttributeValue>();
          for (ColumnAttribute ica : s) {
            if (ica == oca) {
              ventry.add(new AttributeValue(ica, i));
            } else {
              ventry.add(new AttributeValue(ica, 0));
            }
          }
          vps.add(ventry);
        }
      }
    }

    System.out.println("|nakedUniverse|=" + nakedUniverse.size());
    System.out.println("|pkUniverse|=" + pkUniverse.size());
    System.out.println("|aiUniverse|=" + aiUniverse.size());
    System.out.println("|vps|=" + vps.size());

    List<List<AttributeValue>> pkOnly = buildSingleList(pk);

    List<DataType> nonTextTypes =
        Functional.select(
            dataTypes,
            new UnaryPredicate<DataType>() {

              @Override
              public boolean test(DataType object) {
                return !(object.isTextType() || object.isBlobType());
              }
            });

    // pk decls with a ton of attributes; note that we don't generate for text types
    // due to the key length thing, will have to come back to this
    buildColumnDecls(nonTextTypes, pkUniverse, uniqueDecls);
    // ai decls with a ton of attributes
    buildColumnDecls(nonTextTypes, aiUniverse, uniqueDecls);
    // pk only decls
    buildColumnDecls(nonTextTypes, pkOnly, uniqueDecls);
    // no attributes
    buildColumnDecls(dataTypes, null, regularDecls);
    // all combos of attributes
    buildColumnDecls(dataTypes, vps, regularDecls);

    System.out.println("|uniqueDecls|=" + uniqueDecls.size());
    System.out.println("|regularDecls|=" + regularDecls.size());

    int nreg = (regularDecls.size() / uniqueDecls.size()) + 1;

    List<String> out = new ArrayList<String>(uniqueDecls.size());
    int tcounter = 0;
    for (ColumnDecl cd : uniqueDecls.values()) {
      StringBuilder buf = new StringBuilder();
      buf.append("create table `t")
          .append(++tcounter)
          .append("` (")
          .append(PEConstants.LINE_SEPARATOR);
      buf.append("`c0` ").append(cd.getDecl());
      for (int i = 0; i < nreg; i++) {
        if (!regularDecls.isEmpty()) {
          buf.append(",").append(PEConstants.LINE_SEPARATOR);
          ColumnDecl icd = regularDecls.firstEntry().getValue();
          regularDecls.remove(icd.getDecl());
          buf.append("`c").append(i + 1).append("` ").append(icd.getDecl());
        }
      }
      buf.append(")");
      out.add(buf.toString());
    }

    return out;
  }
Пример #16
0
 /** Return the endpoint that has the lowest token greater than this ep's token */
 EndPoint getTokenAfter(EndPoint ep) {
   BigInteger token = endPointToTokenMap_.get(ep);
   Map.Entry<BigInteger, EndPoint> entry = tokenToEndPointMap_.higherEntry(token);
   if (entry != null) return entry.getValue();
   return tokenToEndPointMap_.firstEntry().getValue(); // wrap
 }
Пример #17
0
  public static void main(String[] args) {
    MovesReader reader = new MovesReader();
    // reader.setNewFomat(true);
    // reader.setFilterDays("0,1,2,3,4,5");
    reader.load("/Users/emilio/Desktop/GraphStreamTest/files/export_lunesCOPY.txt");

    Graph g = reader.getG();
    Iterator<Node> it = reader.getG().iterator();
    ArrayList<ClusterWert> services = new ArrayList<ClusterWert>();

    Date date = new Date();

    try {
      BufferedWriter writer =
          new BufferedWriter(new FileWriter("resultado" + date.toString() + ".csv"));

      // Transforming data stored into GraphStream into ClusterWert data structure
      while (it.hasNext()) {
        Node next = it.next();
        Service s = new Service(next.getId());
        if (s.fillIn(next)) {
          ClusterWert cluster = new ClusterWert(s);
          services.add(cluster);
        } else System.out.println("Error al procesar " + s.toString());
      }

      CachedDistance cache = CachedDistance.getInstance();
      double lastBestdistance = Double.MAX_VALUE;
      long startTime = System.nanoTime();
      if (true) {

        // HashSet<ClusterWertDistance> distances = new HashSet<ClusterWertDistance>();
        TreeMap<ClusterWertDistance, Double> distances = new TreeMap<ClusterWertDistance, Double>();
        do {
          if (services.size() == 497) System.out.println("a");

          int bestPosI = 0;
          int bestPosJ = 0;
          double bestDistance = Double.MAX_VALUE;
          ClusterWertDistance best = new ClusterWertDistance();
          int skiped = 0;

          for (int j = 0; j < services.size(); j++) {

            ClusterWert cIni = services.get(j);
            ClusterWertDistance distance = new ClusterWertDistance(cIni);
            // Distance measured in milliseconds.
            double lowerBoundDistance =
                (cIni.getDistance() == -1)
                    ? cIni.getServices().get(0).getDuration() * 60 * 1000
                    : cIni.getDistance();
            double lowerDistance =
                (distances.firstEntry() != null)
                    ? distances.firstEntry().getValue()
                    : Double.MAX_VALUE;

            if (!distances.containsKey(distance) && lowerBoundDistance < lowerDistance) {

              for (int i = j + 1; i < services.size(); i++) {
                // lowerBoundDistance += (services.get(j).getDistance()==-1) ?
                // services.get(j).getServices().get(0).getDuration()*60*1000 :
                // services.get(j).getDistance();
                // if(lowerBoundDistance < lowerDistance){
                ClusterWert aux = cache.getMinimumDistanceOther(cIni, services.get(i));
                double auxDistance = aux.getDistance();
                if (auxDistance != -1) {
                  distance.addElement(auxDistance, aux, services.get(i));
                }
                // }
              }
              if (distance.getBest_distance() != -1)
                distances.put(distance, distance.getBest_distance());
            } else skiped++;
          }
          Iterator<Map.Entry<ClusterWertDistance, Double>> iter = distances.entrySet().iterator();

          while (iter.hasNext()) {
            Map.Entry<ClusterWertDistance, Double> pair = iter.next();
            ClusterWertDistance aux = pair.getKey();
            double auxDistance = aux.getBest_distance();
            if (auxDistance != -1 && auxDistance < bestDistance) {
              if (services.contains(aux.getOrigin())) {
                bestDistance = auxDistance;
                best = pair.getKey();
              } else distances.remove(pair.getKey());
            }
          }

          if (bestDistance < lastBestdistance) System.out.println("ERRROR ");

          ArrayList<ClusterWert> toDelete = new ArrayList<ClusterWert>();
          if (bestDistance != Double.MAX_VALUE) {
            Double firstKey = best.getDistances().firstKey();
            ClusterWert original = best.getOriginal().get(best.getDistances().get(firstKey));

            System.out.println(
                "MIx "
                    + services.indexOf(best.getOrigin())
                    + " con "
                    + services.indexOf(original)
                    + " currentSize "
                    + services.size()
                    + " distance: "
                    + bestDistance
                    + " skipped: "
                    + skiped);
            System.out.println(
                "Cache Size "
                    + cache.getCache1().size()
                    + " A: "
                    + cache.getAciertos()
                    + " F: "
                    + cache.getFallos());

            services.remove(best.getOrigin());
            toDelete.add(best.getOrigin());
            services.remove(original);
            toDelete.add(original);
            Double bestKey = best.getDistances().firstKey();
            services.add(0, best.getDistances().get(bestKey));
            distances.remove(best);
            lastBestdistance = bestDistance;
          } else {
            System.out.println("TODOS LEJOS");
            break;
          }

          iter = distances.entrySet().iterator();
          /*
          while(iter.hasNext())
          {
              Map.Entry<ClusterWertDistance,Double> pair = iter.next();
              ClusterWertDistance aux = pair.getKey();
              double auxDistance = aux.getBest_distance();
              if(auxDistance!=-1 && auxDistance < bestDistance){
                  if(services.contains(aux.getOrigin())){
                      bestDistance = auxDistance;
                      best = pair.getKey();
                  }else
                      distances.remove(pair);
              }
          }  */

          while (iter.hasNext()) {
            Map.Entry<ClusterWertDistance, Double> pair = iter.next();
            double auxDistance = pair.getValue();
            ClusterWertDistance aux = pair.getKey();
            for (ClusterWert w : toDelete) aux.removeOriginalCluster(w);
            if (!services.contains(aux.getOrigin()) || aux.getDistances().size() == 0)
              iter.remove();
            pair.setValue(pair.getKey().getBest_distance());
          }

          // equals.remove(i);

          // TODO iterate over equals in order to mix all other elements up.
        } while (services.size() > 1);
      }
      String strLine;
      int i = 1;
      writer.write(
          "ID\tIDServices\tNum Services\tH first \tH last\tLast Service  Time (includes duration)\tDistance\tService Time\tTravel Time\tWaiting time");
      writer.newLine();
      for (ClusterWert c : services) {
        writer.write(i + "\t" + c.toCSV());
        writer.newLine();
        i++;
      }
      long elapsedTime = System.nanoTime() - startTime;

      writer.write(String.valueOf(elapsedTime / 1000000));
      writer.flush();
      writer.close();

      GoogleMaps google = new GoogleMaps(false);

      date = new Date();
      google.generateHtml(services, "prueba" + date.toString() + ".html");

      System.out.print("ASDASD");
    } catch (IOException e) {
      e.printStackTrace();
    }
  }