Пример #1
1
 private Map<String, Object> query(HttpServletRequest req) {
   final Map<String, Object> map = new HashMap<>();
   for (Map.Entry<String, String[]> entry : req.getParameterMap().entrySet()) {
     map.put(entry.getKey(), entry.getValue());
   }
   return map;
 }
Пример #2
1
 /** {@inheritDoc} */
 public void putAll(Map<? extends Integer, ? extends Integer> map) {
   ensureCapacity(map.size());
   // could optimize this for cases when map instanceof THashMap
   for (Map.Entry<? extends Integer, ? extends Integer> entry : map.entrySet()) {
     this.put(entry.getKey().intValue(), entry.getValue().intValue());
   }
 }
Пример #3
1
  static void serTest(Map s, int size) throws Exception {
    if (!(s instanceof Serializable)) return;
    System.out.print("Serialize              : ");

    for (int i = 0; i < size; i++) {
      s.put(new Integer(i), Boolean.TRUE);
    }

    long startTime = System.currentTimeMillis();

    FileOutputStream fs = new FileOutputStream("MapCheck.dat");
    ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(fs));
    out.writeObject(s);
    out.close();

    FileInputStream is = new FileInputStream("MapCheck.dat");
    ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(is));
    Map m = (Map) in.readObject();

    long endTime = System.currentTimeMillis();
    long time = endTime - startTime;

    System.out.print(time + "ms");

    if (s instanceof IdentityHashMap) return;
    reallyAssert(s.equals(m));
  }
Пример #4
1
  /**
   * Handles the move put from a Client.
   *
   * @param params is a String array containing the blocks to place
   */
  public void doMovePut(String[] params) {
    Map<Point, Block> moves = new HashMap<>();

    for (String move : params) {
      String[] moveArg = move.split("@");
      int blockId = Integer.parseInt(moveArg[0]);
      int moveX = Integer.parseInt(moveArg[1].split(",")[0]);
      int moveY = Integer.parseInt(moveArg[1].split(",")[1]);

      moves.put(new Point(moveX, moveY), new Block(blockId));
    }

    try {
      game.doMovePut(moves);
      System.out.println("[Server] (ClientHandler) - Current game situation:");
      System.out.println(game.getBoard().toString());
    } catch (InvalidMoveException e) {
      sendError(IProtocol.Error.MOVE_INVALID.ordinal() + " Invalid move");
      game.sendPlayerTurn();
    } catch (TilesUnownedException e) {
      sendError(
          IProtocol.Error.MOVE_TILES_UNOWNED.ordinal() + " Player tried to place unowned tile");
      game.sendPlayerTurn();
    } catch (NullPointerException e) {
      System.out.println("[Server] ClientHandler - Game ended during turn.");
    }
  }
  /**
   * Creates a new Socket connected to the given IP address. The method uses connection settings
   * supplied in the constructor for connecting the socket.
   *
   * @param address the IP address to connect to
   * @return connected socket
   * @throws java.net.UnknownHostException if the hostname of the address or the proxy cannot be
   *     resolved
   * @throws java.io.IOException if an I/O error occured while connecting to the remote end or to
   *     the proxy
   */
  private Socket createSocket(InetSocketAddress address, int timeout) throws IOException {
    String socksProxyHost = System.getProperty("socksProxyHost");
    System.getProperties().remove("socksProxyHost");
    try {
      ConnectivitySettings cs = lastKnownSettings.get(address);
      if (cs != null) {
        try {
          return createSocket(cs, address, timeout);
        } catch (IOException e) {
          // not good anymore, try all proxies
          lastKnownSettings.remove(address);
        }
      }

      URI uri = addressToURI(address, "socket");
      try {
        return createSocket(uri, address, timeout);
      } catch (IOException e) {
        // we will also try https
      }

      uri = addressToURI(address, "https");
      return createSocket(uri, address, timeout);

    } finally {
      if (socksProxyHost != null) {
        System.setProperty("socksProxyHost", socksProxyHost);
      }
    }
  }
Пример #6
0
  /**
   * ** Returns an I18N instance based on the specified package name and Locale ** @param pkgName
   * The resource package name ** @param loc The Locale resource from with the localized text is
   * loaded
   */
  public static I18N getI18N(String pkgName, Locale loc) {
    if (pkgName != null) {
      loc = I18N.getLocale(loc);

      /* get package map for specific Locale */
      Map<String, I18N> packageMap = localeMap.get(loc);
      if (packageMap == null) {
        packageMap = new HashMap<String, I18N>();
        localeMap.put(loc, packageMap);
      }

      /* get I18N instance for package */
      I18N i18n = packageMap.get(pkgName);
      if (i18n == null) {
        i18n = new I18N(pkgName, loc);
        packageMap.put(pkgName, i18n);
      }
      return i18n;

    } else {

      /* no package specified */
      return null;
    }
  }
Пример #7
0
 public void testAsCollectionWithMap() {
   Map map = new HashMap();
   map.put("A", "abc");
   map.put("B", "def");
   map.put("C", "xyz");
   assertAsCollection(map, 3);
 }
Пример #8
0
  public AddNodeWindow(AbstractQuestionRelation p) {
    this.setParent(p);

    // create ui from template
    Executions.createComponents("/WEB-INF/zk/survey/design/AddNodeWindow.zul", this, null);
    Selectors.wireVariables(this, this, Selectors.newVariableResolvers(getClass(), Div.class));
    Selectors.wireComponents(this, this, false);
    Selectors.wireEventListeners(this, this);

    // type box and default selection
    ntds = nodeRO.getNodeTypeDescriptions();
    ListModelList<String> typeModel = new ListModelList<String>();
    for (Map<String, String> ntd : ntds) {
      String nodeTypeLabel = ntd.get("label");
      typeModel.add(nodeTypeLabel);
    }
    String defaultContactType = p.getQuestion().getDefaultNewContactType();
    if (defaultContactType != null) {
      Map<String, String> ntd = GeneralUtil.getNodeDescription(ntds, defaultContactType);
      if (ntd != null) {
        String nodeTypeLabel = ntd.get("label");
        typeModel.addToSelection(nodeTypeLabel);
      }
    }
    typeBox.setModel(typeModel);
    onNodeTypeChanged();

    this.setWidth("200px");
    this.setVflex("1");
    this.setClosable(true);
  }
Пример #9
0
 private Map<String, String> parseHeaders(HttpURLConnection conn) {
   Map<String, String> headers = new HashMap<String, String>();
   for (String key : conn.getHeaderFields().keySet()) {
     headers.put(key, conn.getHeaderFields().get(key).get(0));
   }
   return headers;
 }
Пример #10
0
    /**
     * Returns a <code>ThrowableSet</code> representing the set of exceptions included in <code>
     * include</code> minus the set of exceptions included in <code>exclude</code>. Creates a new
     * <code>ThrowableSet</code> only if there was not already one whose contents correspond to
     * <code>include</code> - <code>exclude</code>.
     *
     * @param include A set of {@link RefLikeType} objects representing exception types included in
     *     the result; may be <code>null</code> if there are no included types.
     * @param exclude A set of {@link AnySubType} objects representing exception types excluded from
     *     the result; may be <code>null</code> if there are no excluded types.
     * @return a <code>ThrowableSet</code> representing the set of exceptions corresponding to
     *     <code>include</code> - <code>exclude</code>.
     */
    private ThrowableSet registerSetIfNew(Set include, Set exclude) {
      if (INSTRUMENTING) {
        registrationCalls++;
      }
      if (include == null) {
        include = Collections.EMPTY_SET;
      }
      if (exclude == null) {
        exclude = Collections.EMPTY_SET;
      }
      int size = include.size() + exclude.size();
      Integer sizeKey = new Integer(size);

      List sizeList = (List) sizeToSets.get(sizeKey);
      if (sizeList == null) {
        sizeList = new LinkedList();
        sizeToSets.put(sizeKey, sizeList);
      }
      for (Iterator i = sizeList.iterator(); i.hasNext(); ) {
        ThrowableSet set = (ThrowableSet) i.next();
        if (set.exceptionsIncluded.equals(include) && set.exceptionsExcluded.equals(exclude)) {
          return set;
        }
      }
      if (INSTRUMENTING) {
        registeredSets++;
      }
      ThrowableSet result = new ThrowableSet(include, exclude);
      sizeList.add(result);
      return result;
    }
Пример #11
0
 /**
  * removes session for user
  *
  * @param userId user id
  */
 public static void removeUserSession(Long userId) {
   UserSessionsOutput userSessionsOutput = userSessionsOutputMap.get(userId);
   if (userSessionsOutput != null) {
     userSessionsOutput.getSessionOutputMap().clear();
   }
   userSessionsOutputMap.remove(userId);
 }
  /**
   * This method builds a decision tree model
   *
   * @param sparkContext JavaSparkContext initialized with the application
   * @param modelID Model ID
   * @param trainingData Training data as a JavaRDD of LabeledPoints
   * @param testingData Testing data as a JavaRDD of LabeledPoints
   * @param workflow Machine learning workflow
   * @param mlModel Deployable machine learning model
   * @throws MLModelBuilderException
   */
  private ModelSummary buildDecisionTreeModel(
      JavaSparkContext sparkContext,
      long modelID,
      JavaRDD<LabeledPoint> trainingData,
      JavaRDD<LabeledPoint> testingData,
      Workflow workflow,
      MLModel mlModel,
      SortedMap<Integer, String> includedFeatures,
      Map<Integer, Integer> categoricalFeatureInfo)
      throws MLModelBuilderException {
    try {
      Map<String, String> hyperParameters = workflow.getHyperParameters();
      DecisionTree decisionTree = new DecisionTree();
      DecisionTreeModel decisionTreeModel =
          decisionTree.train(
              trainingData,
              getNoOfClasses(mlModel),
              categoricalFeatureInfo,
              hyperParameters.get(MLConstants.IMPURITY),
              Integer.parseInt(hyperParameters.get(MLConstants.MAX_DEPTH)),
              Integer.parseInt(hyperParameters.get(MLConstants.MAX_BINS)));

      // remove from cache
      trainingData.unpersist();
      // add test data to cache
      testingData.cache();

      JavaPairRDD<Double, Double> predictionsAndLabels =
          decisionTree.test(decisionTreeModel, testingData).cache();
      ClassClassificationAndRegressionModelSummary classClassificationAndRegressionModelSummary =
          SparkModelUtils.getClassClassificationModelSummary(
              sparkContext, testingData, predictionsAndLabels);

      // remove from cache
      testingData.unpersist();

      mlModel.setModel(new MLDecisionTreeModel(decisionTreeModel));

      classClassificationAndRegressionModelSummary.setFeatures(
          includedFeatures.values().toArray(new String[0]));
      classClassificationAndRegressionModelSummary.setAlgorithm(
          SUPERVISED_ALGORITHM.DECISION_TREE.toString());

      MulticlassMetrics multiclassMetrics =
          getMulticlassMetrics(sparkContext, predictionsAndLabels);

      predictionsAndLabels.unpersist();

      classClassificationAndRegressionModelSummary.setMulticlassConfusionMatrix(
          getMulticlassConfusionMatrix(multiclassMetrics, mlModel));
      Double modelAccuracy = getModelAccuracy(multiclassMetrics);
      classClassificationAndRegressionModelSummary.setModelAccuracy(modelAccuracy);
      classClassificationAndRegressionModelSummary.setDatasetVersion(workflow.getDatasetVersion());

      return classClassificationAndRegressionModelSummary;
    } catch (Exception e) {
      throw new MLModelBuilderException(
          "An error occurred while building decision tree model: " + e.getMessage(), e);
    }
  }
 public void deleteTaxByTenantIdx(long TenantId) {
   CFAccTaxByTenantIdxKey key =
       ((ICFAccSchema) schema.getBackingStore()).getFactoryTax().newTenantIdxKey();
   key.setRequiredTenantId(TenantId);
   if (indexByTenantIdx == null) {
     indexByTenantIdx = new HashMap<CFAccTaxByTenantIdxKey, Map<CFAccTaxPKey, ICFAccTaxObj>>();
   }
   if (indexByTenantIdx.containsKey(key)) {
     Map<CFAccTaxPKey, ICFAccTaxObj> dict = indexByTenantIdx.get(key);
     ((ICFAccSchema) schema.getBackingStore())
         .getTableTax()
         .deleteTaxByTenantIdx(schema.getAuthorization(), TenantId);
     Iterator<ICFAccTaxObj> iter = dict.values().iterator();
     ICFAccTaxObj obj;
     List<ICFAccTaxObj> toForget = new LinkedList<ICFAccTaxObj>();
     while (iter.hasNext()) {
       obj = iter.next();
       toForget.add(obj);
     }
     iter = toForget.iterator();
     while (iter.hasNext()) {
       obj = iter.next();
       obj.forget(true);
     }
     indexByTenantIdx.remove(key);
   } else {
     ((ICFAccSchema) schema.getBackingStore())
         .getTableTax()
         .deleteTaxByTenantIdx(schema.getAuthorization(), TenantId);
   }
 }
 public ICFAccTaxObj readTaxByUNameIdx(long TenantId, String Name, boolean forceRead) {
   if (indexByUNameIdx == null) {
     indexByUNameIdx = new HashMap<CFAccTaxByUNameIdxKey, ICFAccTaxObj>();
   }
   CFAccTaxByUNameIdxKey key =
       ((ICFAccSchema) schema.getBackingStore()).getFactoryTax().newUNameIdxKey();
   key.setRequiredTenantId(TenantId);
   key.setRequiredName(Name);
   ICFAccTaxObj obj = null;
   if ((!forceRead) && indexByUNameIdx.containsKey(key)) {
     obj = indexByUNameIdx.get(key);
   } else {
     CFAccTaxBuff buff =
         ((ICFAccSchema) schema.getBackingStore())
             .getTableTax()
             .readDerivedByUNameIdx(schema.getAuthorization(), TenantId, Name);
     if (buff != null) {
       obj = schema.getTaxTableObj().newInstance();
       obj.setPKey(((ICFAccSchema) schema.getBackingStore()).getFactoryTax().newPKey());
       obj.setBuff(buff);
       obj = (ICFAccTaxObj) obj.realize();
     } else if (schema.getCacheMisses()) {
       indexByUNameIdx.put(key, null);
     }
   }
   return (obj);
 }
 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 forgetTaxByTenantIdx(long TenantId) {
    if (indexByTenantIdx == null) {
      return;
    }
    CFAccTaxByTenantIdxKey key =
        ((ICFAccSchema) schema.getBackingStore()).getFactoryTax().newTenantIdxKey();
    key.setRequiredTenantId(TenantId);
    if (indexByTenantIdx.containsKey(key)) {
      Map<CFAccTaxPKey, ICFAccTaxObj> mapTenantIdx = indexByTenantIdx.get(key);
      if (mapTenantIdx != null) {
        List<ICFAccTaxObj> toForget = new LinkedList<ICFAccTaxObj>();
        ICFAccTaxObj cur = null;
        Iterator<ICFAccTaxObj> iter = mapTenantIdx.values().iterator();
        while (iter.hasNext()) {
          cur = iter.next();
          toForget.add(cur);
        }
        iter = toForget.iterator();
        while (iter.hasNext()) {
          cur = iter.next();
          cur.forget(true);
        }
      }

      indexByTenantIdx.remove(key);
    }
  }
Пример #17
0
  /**
   * Utility method used in the construction of {@link UnitGraph}s, to be called only after the
   * unitToPreds and unitToSuccs maps have been built.
   *
   * <p><code>UnitGraph</code> provides an implementation of <code>buildHeadsAndTails()</code> which
   * defines the graph's set of heads to include the first {@link Unit} in the graph's body,
   * together with any other <tt>Unit</tt> which has no predecessors. It defines the graph's set of
   * tails to include all <tt>Unit</tt>s with no successors. Subclasses of <code>UnitGraph</code>
   * may override this method to change the criteria for classifying a node as a head or tail.
   */
  protected void buildHeadsAndTails() {
    List tailList = new ArrayList();
    List headList = new ArrayList();

    for (Iterator unitIt = unitChain.iterator(); unitIt.hasNext(); ) {
      Unit s = (Unit) unitIt.next();
      List succs = (List) unitToSuccs.get(s);
      if (succs.size() == 0) {
        tailList.add(s);
      }
      List preds = (List) unitToPreds.get(s);
      if (preds.size() == 0) {
        headList.add(s);
      }
    }

    // Add the first Unit, even if it is the target of
    // a branch.
    Unit entryPoint = (Unit) unitChain.getFirst();
    if (!headList.contains(entryPoint)) {
      headList.add(entryPoint);
    }

    tails = Collections.unmodifiableList(tailList);
    heads = Collections.unmodifiableList(headList);
  }
Пример #18
0
 public TreeNode buildTree(int[] inorder, int[] postorder) {
   Map<Integer, Integer> map = new HashMap<>();
   for (int i = 0; i < inorder.length; ++i) {
     map.put(inorder[i], i);
   }
   return helper(map, inorder, 0, inorder.length - 1, postorder, 0, postorder.length - 1);
 }
Пример #19
0
  /**
   * Compares the specified object with this map for equality. Returns <tt>true</tt> if the given
   * object is also a map and the two maps represent the same mappings. More formally, two maps
   * <tt>m1</tt> and <tt>m2</tt> represent the same mappings if
   * <tt>m1.entrySet().equals(m2.entrySet())</tt>. This ensures that the <tt>equals</tt> method
   * works properly across different implementations of the <tt>Map</tt> interface.
   *
   * <p>This implementation first checks if the specified object is this map; if so it returns
   * <tt>true</tt>. Then, it checks if the specified object is a map whose size is identical to the
   * size of this map; if not, it returns <tt>false</tt>. If so, it iterates over this map's
   * <tt>entrySet</tt> collection, and checks that the specified map contains each mapping that this
   * map contains. If the specified map fails to contain such a mapping, <tt>false</tt> is returned.
   * If the iteration completes, <tt>true</tt> is returned.
   *
   * @param o object to be compared for equality with this map
   * @return <tt>true</tt> if the specified object is equal to this map
   */
  public boolean equals(Object o) {
    if (o == this) return true;

    if (!(o instanceof Map)) return false;
    Map<K, V> m = (Map<K, V>) o;
    if (m.size() != size()) return false;

    try {
      Iterator<Entry<K, V>> i = entrySet().iterator();
      while (i.hasNext()) {
        Entry<K, V> e = i.next();
        K key = e.getKey();
        V value = e.getValue();
        if (value == null) {
          if (!(m.get(key) == null && m.containsKey(key))) return false;
        } else {
          if (!value.equals(m.get(key))) return false;
        }
      }
    } catch (ClassCastException unused) {
      return false;
    } catch (NullPointerException unused) {
      return false;
    }

    return true;
  }
Пример #20
0
 /**
  * @description: Decodes the supplied lzw encoded string
  * @method decode
  * @param {string} s
  * @param {function} callback
  */
 public static String decode(List<Integer> encoded) {
   // Build the dictionary.
   int dictSize = 256;
   Map<Integer, String> dictionary = new HashMap<Integer, String>();
   for (int i = 0; i < 256; i++) {
     dictionary.put(i, "" + (char) i);
   }
   String w = "" + (char) (int) encoded.remove(0);
   StringBuffer result = new StringBuffer(w);
   for (int k : encoded) {
     String entry;
     if (dictionary.containsKey(k)) {
       entry = dictionary.get(k);
     } else if (k == dictSize) {
       entry = w + w.charAt(0);
     } else {
       throw new IllegalArgumentException("Bad compressed k: " + k);
     }
     result.append(entry);
     // Add w+entry[0] to the dictionary.
     dictionary.put(dictSize++, w + entry.charAt(0));
     w = entry;
   }
   return result.toString();
 }
 /**
  * Sorts inventories by rating and returns these ratings.
  *
  * @param inventories inventories.
  * @return ratings.
  */
 public Map<String, Double> sortInventoriesByRelativity(
     int pathId, List<InventoryDto> inventories) {
   Map<RoadType, Double> pathMap = pathService.getRoadTypesWithPcts(pathId);
   final double averageSpeedCoeff =
       speedLimitsAnalyzer.getSpeedLimitsAverageCoeff(
           pathMap.get(RoadType.HIGHWAY_RURAL),
           pathMap.get(RoadType.HIGHWAY_URBAN),
           pathMap.get(RoadType.RESIDENTIAL));
   fillEngineHorsePowerMap(inventories);
   Map<String, Double> ratingMap = new HashMap<>();
   for (InventoryDto inventoryDto : inventories) {
     double delta = Math.abs(getInventoryHorsePowerCoeff(inventoryDto) - averageSpeedCoeff);
     ratingMap.put(inventoryDto.getId(), (1 - delta) * MAX_RATING);
   }
   Collections.sort(
       inventories,
       new Comparator<InventoryDto>() {
         @Override
         public int compare(InventoryDto o1, InventoryDto o2) {
           Double rating1 = ratingMap.get(o1.getId());
           Double rating2 = ratingMap.get(o2.getId());
           return rating2.compareTo(rating1);
         }
       });
   return ratingMap;
 }
Пример #22
0
  /**
   * This method gives the review information of a state
   *
   * @return stateReview(StateReview) corresponding to the state review code.
   */
  private StateReview getStateReview() {
    Map<String, String> eoStateReview = s2sUtilService.getEOStateReview(pdDoc);
    StateReviewCodeTypeDataType.Enum stateReviewCodeType = null;
    String strReview = eoStateReview.get(S2SConstants.YNQ_ANSWER);
    String stateReviewData = null;
    String stateReviewDate = null;

    if (STATE_REVIEW_YES.equals(strReview)) {
      stateReviewCodeType = StateReviewCodeTypeDataType.Y_YES;
      stateReviewDate = eoStateReview.get(S2SConstants.YNQ_REVIEW_DATE);
    } else if (STATE_REVIEW_NO.equals(strReview)) {
      stateReviewData = eoStateReview.get(S2SConstants.YNQ_STATE_REVIEW_DATA);
      if (stateReviewData != null && S2SConstants.YNQ_STATE_NOT_COVERED.equals(stateReviewData)) {
        stateReviewCodeType = StateReviewCodeTypeDataType.PROGRAM_IS_NOT_COVERED_BY_E_O_12372;
      } else if (stateReviewData != null
          && S2SConstants.YNQ_STATE_NOT_SELECTED.equals(stateReviewData)) {
        stateReviewCodeType =
            StateReviewCodeTypeDataType.PROGRAM_HAS_NOT_BEEN_SELECTED_BY_STATE_FOR_REVIEW;
      }
    }
    StateReview stateReview = StateReview.Factory.newInstance();
    stateReview.setStateReviewCodeType(stateReviewCodeType);
    if (stateReviewDate != null) {
      stateReview.setStateReviewDate(s2sUtilService.convertDateStringToCalendar(stateReviewDate));
    }
    return stateReview;
  }
Пример #23
0
 static void clrTest(int n, Map s) {
   String nm = "Remove Present         ";
   timer.start(nm, n);
   s.clear();
   timer.finish();
   reallyAssert(s.isEmpty());
 }
  public static void main(String[] args) throws IOException {

    if (args.length == 2) {

      File file = new File(args[1]);
      if (file.exists()) {
        file.delete();
      }

      Map<String, Map<String, Long>> invertedIndex = getInvertedIndex(args[0]);
      invertedIndex
          .entrySet()
          .forEach(
              entry -> {
                String line = serializeIndexEntry(entry);
                FileUtils.appendToFile(args[1], line);
              });

      FileUtils.appendToFile(args[1], DOC_LENGTH_SEPARATOR);
      Map<String, Long> documentAndLength = getDocumentAndLength(args[0]);
      documentAndLength
          .entrySet()
          .forEach(
              entry -> {
                String doc = entry.getKey();
                Long length = entry.getValue();
                FileUtils.appendToFile(args[1], String.format("%s=%d", doc, length));
              });

    } else {
      System.out.println("Usage: input_file output_file");
    }
  }
Пример #25
0
 /**
  * Tries to calculate given line's indent column assuming that there might be a comment at the
  * given indent offset (see {@link #getCommentPrefix(IElementType)}).
  *
  * @param line target line
  * @param indentOffset start indent offset to use for the given line
  * @param lineEndOffset given line's end offset
  * @param fallbackColumn column to return if it's not possible to apply comment-specific indent
  *     calculation rules
  * @return given line's indent column to use
  */
 private int calcIndent(int line, int indentOffset, int lineEndOffset, int fallbackColumn) {
   final HighlighterIterator it = myEditor.getHighlighter().createIterator(indentOffset);
   IElementType tokenType = it.getTokenType();
   Language language = tokenType.getLanguage();
   TokenSet comments = myComments.get(language);
   if (comments == null) {
     ParserDefinition definition = LanguageParserDefinitions.INSTANCE.forLanguage(language);
     if (definition != null) {
       comments = definition.getCommentTokens();
     }
     if (comments == null) {
       return fallbackColumn;
     } else {
       myComments.put(language, comments);
     }
   }
   if (comments.contains(tokenType) && indentOffset == it.getStart()) {
     String prefix = COMMENT_PREFIXES.get(tokenType);
     if (prefix == null) {
       prefix = getCommentPrefix(tokenType);
     }
     if (!NO_COMMENT_INFO_MARKER.equals(prefix)) {
       final int indentInsideCommentOffset =
           CharArrayUtil.shiftForward(
               myChars, indentOffset + prefix.length(), lineEndOffset, " \t");
       if (indentInsideCommentOffset < lineEndOffset) {
         int indent = myEditor.calcColumnNumber(indentInsideCommentOffset, line);
         indentAfterUncomment.put(line, indent - prefix.length());
         return indent;
       }
     }
   }
   return fallbackColumn;
 }
Пример #26
0
 /**
  * Copies the key/value mappings in <tt>map</tt> into this map. Note that this will be a
  * <b>deep</b> copy, as storage is by primitive value.
  *
  * @param map a <code>Map</code> value
  */
 public void putAll(Map<? extends Character, ? extends Double> map) {
   Iterator<? extends Entry<? extends Character, ? extends Double>> it = map.entrySet().iterator();
   for (int i = map.size(); i-- > 0; ) {
     Entry<? extends Character, ? extends Double> e = it.next();
     this.put(e.getKey(), e.getValue());
   }
 }
Пример #27
0
  protected Map getChannelMap(ConsoleInput ci) {
    Map channel_map = new HashMap();

    PluginInterface[] pis = ci.azureus_core.getPluginManager().getPluginInterfaces();

    for (int i = 0; i < pis.length; i++) {

      LoggerChannel[] logs = pis[i].getLogger().getChannels();

      if (logs.length > 0) {

        if (logs.length == 1) {

          channel_map.put(pis[i].getPluginName(), logs[0]);

        } else {

          for (int j = 0; j < logs.length; j++) {

            channel_map.put(pis[i].getPluginName() + "." + logs[j].getName(), logs[j]);
          }
        }
      }
    }

    return (channel_map);
  }
Пример #28
0
  private static Map<String, Double> sortByComparator(
      Map<String, Double> map, final boolean order) {
    List<Entry<String, Double>> list = new LinkedList<Entry<String, Double>>(map.entrySet());

    // Sorting the list based on values
    Collections.sort(
        list,
        new Comparator<Entry<String, Double>>() {
          public int compare(Entry<String, Double> o1, Entry<String, Double> o2) {
            if (order) {
              return o1.getValue().compareTo(o2.getValue());
            } else {
              return o2.getValue().compareTo(o1.getValue());
            }
          }
        });

    // Maintaining insertion order with the help of LinkedList
    Map<String, Double> sortedMap = new LinkedHashMap<String, Double>();
    for (Entry<String, Double> entry : list) {
      sortedMap.put(entry.getKey(), entry.getValue());
    }

    return sortedMap;
  }
  protected boolean receiveBeacon(InetAddress sender, byte[] buffer, int length) {
    if (is_enabled) {

      try {
        Map<String, String> map = decodeBeacon(buffer, length);

        String id = map.get("identity");

        if (id == null || id.equals(uid)) {

          return (false);
        }

        String platform = map.get("platform");

        if (platform != null && platform.toLowerCase().startsWith("tcd/")) {

          String classification = "tivo." + platform.substring(4).toLowerCase();

          foundTiVo(sender, id, classification, (String) map.get("machine"));

          return (true);
        }
      } catch (Throwable e) {

        log("Failed to decode beacon", e);
      }
    }

    return (false);
  }
Пример #30
0
  Entry encode(final T o, final String parentDN) throws LDAPPersistException {
    // Get the attributes that should be included in the entry.
    final LinkedHashMap<String, Attribute> attrMap = new LinkedHashMap<String, Attribute>();
    attrMap.put("objectClass", objectClassAttribute);

    for (final Map.Entry<String, FieldInfo> e : fieldMap.entrySet()) {
      final FieldInfo i = e.getValue();
      if (!i.includeInAdd()) {
        continue;
      }

      final Attribute a = i.encode(o, false);
      if (a != null) {
        attrMap.put(e.getKey(), a);
      }
    }

    for (final Map.Entry<String, GetterInfo> e : getterMap.entrySet()) {
      final GetterInfo i = e.getValue();
      if (!i.includeInAdd()) {
        continue;
      }

      final Attribute a = i.encode(o);
      if (a != null) {
        attrMap.put(e.getKey(), a);
      }
    }

    final String dn = constructDN(o, parentDN, attrMap);
    final Entry entry = new Entry(dn, attrMap.values());

    if (postEncodeMethod != null) {
      try {
        postEncodeMethod.invoke(o, entry);
      } catch (Throwable t) {
        debugException(t);

        if (t instanceof InvocationTargetException) {
          t = ((InvocationTargetException) t).getTargetException();
        }

        throw new LDAPPersistException(
            ERR_OBJECT_HANDLER_ERROR_INVOKING_POST_ENCODE_METHOD.get(
                postEncodeMethod.getName(), type.getName(), getExceptionMessage(t)),
            t);
      }
    }

    setDNAndEntryFields(o, entry);

    if (superclassHandler != null) {
      final Entry e = superclassHandler.encode(o, parentDN);
      for (final Attribute a : e.getAttributes()) {
        entry.addAttribute(a);
      }
    }

    return entry;
  }