@Override
  public Map<MaterialCategory, StatValue<Integer, Double>> calculate() {
    List<Material> materialList = manager.getMaterials();
    Map<MaterialCategory, Integer> map = new HashMap<MaterialCategory, Integer>();
    for (MaterialCategory cat : MaterialCategory.values()) {
      map.put(cat, 0);
    }

    for (Material m : materialList) {
      MaterialCategory category = m.getMaterialType().getCategory();
      int number = map.get(category);
      number++;
      map.put(category, number);
    }

    int sizeStock = materialList.size();
    MaterialCategory[] listCategory = MaterialCategory.values();
    Map<MaterialCategory, StatValue<Integer, Double>> numberAndPourcent =
        new HashMap<MaterialCategory, StatValue<Integer, Double>>();
    for (MaterialCategory mc : listCategory) {
      int numberCat = map.get(mc);
      double pourcent = (numberCat * 1.0) / sizeStock;
      numberAndPourcent.put(mc, new StatValue<Integer, Double>(numberCat, pourcent));
    }
    return numberAndPourcent;
  }
Exemple #2
1
 /**
  * @description: Lzw encodes the supplied input
  * @method encode
  * @param {string} s
  * @param {function} callback
  */
 public static List<Integer> encode(String input) {
   // Build the dictionary.
   int dictSize = 256;
   Map<String, Integer> dictionary = new HashMap<String, Integer>();
   for (int i = 0; i < 256; i++) {
     dictionary.put("" + (char) i, i);
   }
   String w = "";
   List<Integer> result = new ArrayList<Integer>();
   for (char c : input.toCharArray()) {
     String wc = w + c;
     if (dictionary.containsKey(wc)) {
       w = wc;
     } else {
       result.add(dictionary.get(w));
       // Add wc to the dictionary.
       dictionary.put(wc, dictSize++);
       w = "" + c;
     }
   }
   // Output the code for w.
   if (!w.equals("")) {
     result.add(dictionary.get(w));
   }
   return result;
 }
  /**
   * 대상자를 보여준다.
   *
   * @param targetID
   * @return
   * @throws DataAccessException
   */
  public TargetList viewTargetList(int targetID) throws DataAccessException {
    TargetList targetList = new TargetList();
    Map<String, Object> resultMap = null;

    String sql = QueryUtil.getStringQuery("targetlist_sql", "target.targetui.viewtargetinfo");

    Map<String, Object> param = new HashMap<String, Object>();
    param.put("targetID", new Integer(targetID));

    // SQL문이 실행된다.
    try {
      resultMap = getSimpleJdbcTemplate().queryForMap(sql, param);
    } catch (EmptyResultDataAccessException e1) {
    }

    if (resultMap != null) {
      targetList.setTargetID(Integer.parseInt(String.valueOf(resultMap.get("targetID"))));
      targetList.setTargetName((String) resultMap.get("targetName"));
      targetList.setDescription((String) resultMap.get("description"));
      targetList.setUserID((String) resultMap.get("userID"));
      targetList.setGroupID((String) resultMap.get("groupID"));
      targetList.setBookMark((String) resultMap.get("bookMark"));
      targetList.setShareType((String) resultMap.get("shareType"));
      targetList.setShareID((String) resultMap.get("shareID"));
      targetList.setTargetType((String) resultMap.get("targetType"));
      targetList.setTargetGroupID(Integer.parseInt(String.valueOf(resultMap.get("targetGroupID"))));
    }
    return targetList;
  }
 protected SyndContent getDescription(
     Document doc, Map<String, Object> params, XWikiContext context) throws XWikiException {
   String description;
   String mapping = (String) params.get(FIELD_DESCRIPTION);
   if (mapping == null) {
     description = getDefaultDescription(doc, params, context);
   } else if (isVelocityCode(mapping)) {
     description = parseString(mapping, doc, context);
   } else {
     description =
         doc.getRenderedContent(getStringValue(mapping, doc, context), doc.getSyntaxId());
   }
   String contentType = (String) params.get(CONTENT_TYPE);
   int contentLength = ((Number) params.get(CONTENT_LENGTH)).intValue();
   if (contentLength >= 0) {
     if ("text/plain".equals(contentType)) {
       description = getPlainPreview(description, contentLength);
     } else if ("text/html".equals(contentType)) {
       description = getHTMLPreview(description, contentLength);
     } else if ("text/xml".equals(contentType)) {
       description = getXMLPreview(description, contentLength);
     }
   }
   return getSyndContent(contentType, description);
 }
  /**
   * Returns a new graph with the same structure as the one wrapped here, and with vertices
   * generated by the given {@link Function1}. Edges are copied in direction and weight.
   *
   * @param factory the vertex factory used to instantiate new vertices in the new graph
   * @param function the function used to set values of a new vertex in the new graph, from the
   *     matching spot
   * @param mappings a map that will receive mappings from {@link Spot} to the new vertices. Can be
   *     <code>null</code> if you do not want to get the mappings
   * @return a new {@link SimpleDirectedWeightedGraph}.
   */
  public <V> SimpleDirectedWeightedGraph<V, DefaultWeightedEdge> copy(
      final VertexFactory<V> factory,
      final Function1<Spot, V> function,
      final Map<Spot, V> mappings) {
    final SimpleDirectedWeightedGraph<V, DefaultWeightedEdge> copy =
        new SimpleDirectedWeightedGraph<V, DefaultWeightedEdge>(DefaultWeightedEdge.class);
    final Set<Spot> spots = graph.vertexSet();
    // To store mapping of old graph vs new graph
    Map<Spot, V> map;
    if (null == mappings) {
      map = new HashMap<Spot, V>(spots.size());
    } else {
      map = mappings;
    }

    // Generate new vertices
    for (final Spot spot : Collections.unmodifiableCollection(spots)) {
      final V vertex = factory.createVertex();
      function.compute(spot, vertex);
      map.put(spot, vertex);
      copy.addVertex(vertex);
    }

    // Generate new edges
    for (final DefaultWeightedEdge edge : graph.edgeSet()) {
      final DefaultWeightedEdge newEdge =
          copy.addEdge(map.get(graph.getEdgeSource(edge)), map.get(graph.getEdgeTarget(edge)));
      copy.setEdgeWeight(newEdge, graph.getEdgeWeight(edge));
    }

    return copy;
  }
  /**
   * Uses the command line arguments to authenticate the GoogleService and build the basic feed URI,
   * then invokes all the other methods to demonstrate how to interface with the Translator toolkit
   * service.
   *
   * @param args See the usage method.
   */
  public static void main(String[] args) {
    try {
      // Connect to the Google translator toolkit service
      GttService service = new GttService("sample.gtt.GttClient");

      // Login if there is a command line argument for it.
      if (args.length >= 1 && NAME_TO_COMMAND_MAP.get(args[0]) == GttCommand.LOGIN) {
        GttCommand.LOGIN.execute(service, args);
      }

      // Input stream to get user input
      BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

      // Do some actions based on user input
      while (true) {
        // Get user input
        System.out.print(USER_PROMPT);
        System.out.flush();
        String userInput = in.readLine();
        System.out.println();

        // Do action corresponding to user input
        String[] commandArgs = userInput.split("\\s+");
        GttCommand command = NAME_TO_COMMAND_MAP.get(commandArgs[0]);
        if (command != null) {
          command.execute(service, commandArgs);
        } else {
          System.out.println("Sorry I did not understand that.");
        }
      }
    } catch (IOException ioe) {
      ioe.printStackTrace();
    }
  }
  @SuppressWarnings("unchecked")
  @RequestMapping(
      value = "/postfriendlabledelete",
      method = RequestMethod.POST,
      produces = "text/plain;charset=UTF-8")
  @ResponseBody
  public static String put(HttpServletRequest request) throws Exception {
    String data = request.getParameter("info");
    String content = AESUtils.decrypt4AES(data, AESUtils.key);
    LogRecord.info("SolrFriendLableDelete类postfriendlabledelete接口接收的参数:" + content);
    long start = System.currentTimeMillis();
    String middletimes = "";
    String bug_one = "";
    String ccid = "";
    String ffid = "";
    String fflid = "";
    List<Map<String, FriendLabel>> lists = Transformation.friendlableLol(content);
    for (Map<String, FriendLabel> cardMap : lists) {
      for (String key : cardMap.keySet()) {
        switch (key) {
          case "cid":
            ccid = cardMap.get(key) + "";
            break;
          case "fid":
            ffid = cardMap.get(key) + "";
            break;
          case "flid":
            fflid = cardMap.get(key) + "";
            break;
          default:
            break;
        }
      }
    }
    try {
      SolrUpdateFriendLabel.solrqueryresult(fflid, ffid, ccid);
    } catch (Exception e) {
      bug_one = e.getMessage();
      LogRecord.info("Exception :" + e + ",Msg :" + e.getMessage());
    }

    long end = System.currentTimeMillis();
    middletimes = (end - start) + "";

    // 计算当前的时间,格式为"yyyy/MM/dd HH:mm:ss"可以任意修改格式
    Date now = new Date();
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); // 可以方便地修改日期格式
    String messageid = dateFormat.format(now);

    ResultDelete result = new ResultDelete(true, messageid, "删除成功!", "000000", middletimes);
    ResultDelete resultfalse = new ResultDelete(true, messageid, "删除失败!", "060002", middletimes);

    String cardjsonsucess = AESUtils.encrypt4AES(JSON.toJSONString(result), AESUtils.key);
    String cardjsonfalse = AESUtils.encrypt4AES(JSON.toJSONString(resultfalse), AESUtils.key);
    String str = bug_one.length() > 0 ? cardjsonfalse : cardjsonsucess;
    LogRecord.info(
        "SolrFriendLableDelete类postfriendlabledelete接口返回的值:"
            + AESUtils.decrypt4AES(str, AESUtils.key));
    return str;
  }
  public int a(String var1) {
    Short var2 = (Short) d.get(var1);
    if (var2 == null) {
      var2 = Short.valueOf((short) 0);
    } else {
      var2 = Short.valueOf((short) (var2.shortValue() + 1));
    }

    d.put(var1, var2);
    if (b == null) {
      return var2.shortValue();
    } else {
      try {
        File var3 = b.a("idcounts");
        if (var3 != null) {
          class_dn var4 = new class_dn();
          Iterator var5 = d.keySet().iterator();

          while (var5.hasNext()) {
            String var6 = (String) var5.next();
            short var7 = ((Short) d.get(var6)).shortValue();
            var4.a(var6, var7);
          }

          DataOutputStream var9 = new DataOutputStream(new FileOutputStream(var3));
          class_dx.a(var4, (DataOutput) var9);
          var9.close();
        }
      } catch (Exception var8) {
        var8.printStackTrace();
      }

      return var2.shortValue();
    }
  }
  private static void applyGroupMatching(TestNG testng, Map options) throws TestSetFailedException {
    String groups = (String) options.get(ProviderParameterNames.TESTNG_GROUPS_PROP);
    String excludedGroups = (String) options.get(ProviderParameterNames.TESTNG_EXCLUDEDGROUPS_PROP);

    if (groups == null && excludedGroups == null) {
      return;
    }

    // the class is available in the testClassPath
    String clazzName = "org.apache.maven.surefire.testng.utils.GroupMatcherMethodSelector";
    // looks to need a high value
    testng.addMethodSelector(clazzName, 9999);
    try {
      Class clazz = Class.forName(clazzName);

      // HORRIBLE hack, but TNG doesn't allow us to setup a method selector instance directly.
      Method method = clazz.getMethod("setGroups", new Class[] {String.class, String.class});
      method.invoke(null, new Object[] {groups, excludedGroups});
    } catch (ClassNotFoundException e) {
      throw new TestSetFailedException(e.getMessage(), e);
    } catch (SecurityException e) {
      throw new TestSetFailedException(e.getMessage(), e);
    } catch (NoSuchMethodException e) {
      throw new TestSetFailedException(e.getMessage(), e);
    } catch (IllegalArgumentException e) {
      throw new TestSetFailedException(e.getMessage(), e);
    } catch (IllegalAccessException e) {
      throw new TestSetFailedException(e.getMessage(), e);
    } catch (InvocationTargetException e) {
      throw new TestSetFailedException(e.getMessage(), e);
    }
  }
Exemple #10
0
  @Override
  public CloneableRecord get(
      ExecutionContext context, CloneableRecord key, IndexMeta indexMeta, String dbName) {

    DatabaseEntry keyEntry = new DatabaseEntry();
    DatabaseEntry valueEntry = new DatabaseEntry();
    keyEntry.setData(indexCodecMap.get(indexMeta.getName()).getKey_codec().encode(key));
    OperationStatus status =
        getDatabase(dbName)
            .get(
                context.getTransaction() == null
                    ? null
                    : ((JE_Transaction) context.getTransaction()).txn,
                keyEntry,
                valueEntry,
                LockMode.DEFAULT);
    if (OperationStatus.SUCCESS != status) {
      return null;
    }
    if (valueEntry.getSize() != 0) {
      return indexCodecMap.get(indexMeta.getName()).getValue_codec().decode(valueEntry.getData());
    } else {
      return null;
    }
  }
  private void doMatches(Map<String, Object> ret, BagQueryResult bqr) {

    for (Entry<Integer, List> pair : bqr.getMatches().entrySet()) {
      Map<String, Object> resultItem;
      InterMineObject imo;
      try {
        imo = im.getObjectStore().getObjectById(pair.getKey());
      } catch (ObjectStoreException e) {
        throw new IllegalStateException("Could not retrieve object reported as match", e);
      }
      String idKey = String.valueOf(imo.getId());
      if (ret.containsKey(idKey)) {
        resultItem = (Map<String, Object>) ret.get(idKey);
      } else {
        resultItem = new HashMap<String, Object>();
        resultItem.put("identifiers", new HashMap<String, Object>());
      }
      if (!resultItem.containsKey("summary")) {
        resultItem.put("summary", getObjectDetails(imo));
      }
      Map<String, Object> identifiers = (Map<String, Object>) resultItem.get("identifiers");
      for (Object o : pair.getValue()) {
        String ident = (String) o;
        if (!identifiers.containsKey(ident)) {
          identifiers.put(ident, new HashSet<String>());
        }
        Set<String> categories = (Set<String>) identifiers.get(ident);
        categories.add("MATCH");
      }
      String className = DynamicUtil.getSimpleClassName(imo.getClass());
      resultItem.put("type", className.replaceAll("^.*\\.", ""));
      ret.put(idKey, resultItem);
    }
  }
Exemple #12
0
  @Override
  public void updateThing(String type) throws SQLException {
    if (type.equals("BannerCount")) {
      SqlMapClient ibatis = Mapper.getSqlMapper();
      ibatis.update("updateBannerCount", bid);
    }
    if (type.equals("BannerImage")) {
      try {
        uploadFile();
      } catch (IOException e) {
        e.printStackTrace();
      }

      bb = new BannerBean();

      bb.setBanner_num(bid);
      bb.setAdmin_num(Integer.parseInt(session.get("admin_num")));
      bb.setBanner_image_url(uploadFileName);

      SqlMapClient ibatis = Mapper.getSqlMapper();
      ibatis.update("updateBannerImage", bb);
    }

    if (type.equals("BannerInfo")) {
      bb.setAdmin_num(Integer.parseInt(session.get("admin_num")));
      SqlMapClient ibatis = Mapper.getSqlMapper();
      ibatis.update("updateBannerInfo", bb);
    }
  }
  static void sendJSONResponse(HttpServletResponse response, Map<String, String> responseMap) {
    if (!Boolean.parseBoolean(responseMap.get("success"))) {
      int serverCode = 500;
      if (responseMap.containsKey("serverCode")) {
        serverCode = Integer.parseInt(responseMap.get("serverCode"));
      }
      response.setStatus(serverCode);
    }

    String responseContent = new Gson().toJson(responseMap);
    response.setContentType("application/json");
    response.setCharacterEncoding("utf-8");
    response.setHeader("Content-Length", Integer.toString(responseContent.length()));

    Writer writer = null;
    try {
      writer = response.getWriter();
      writer.write(responseContent);
    } catch (IOException ex) {
      Logger.getLogger(RequestResponseHelper.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
      if (writer != null) {
        try {
          writer.close();
        } catch (IOException ex) {
          Logger.getLogger(RequestResponseHelper.class.getName()).log(Level.SEVERE, null, ex);
        }
      }
    }
  }
Exemple #14
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;
  }
  /** Test of sliding mode with pre-defined slide-in sizes */
  public void testLoadMode06() throws Exception {
    System.out.println("");
    System.out.println("ModeParserTest.testLoadMode06 START");

    ModeParser modeParser = createModeParser("data/valid/Windows/Modes", "mode06");

    ModeConfig modeCfg = modeParser.load();

    // Check loaded data
    assertNotNull("Could not load data.", modeCfg);

    // Check data
    assertEquals("Mode kind", Constants.MODE_KIND_SLIDING, modeCfg.kind);
    assertEquals("Mode sliding side", Constants.LEFT, modeCfg.side);

    assertEquals("Active TC", "output", modeCfg.selectedTopComponentID);
    assertTrue("Permanent", modeCfg.permanent);

    Map<String, Integer> slideInSizes = modeCfg.slideInSizes;
    assertNotNull(slideInSizes);
    assertEquals(2, slideInSizes.size());
    assertEquals(Integer.valueOf(123), slideInSizes.get("output"));
    assertEquals(Integer.valueOf(321), slideInSizes.get("someOtherTopComponentId"));

    System.out.println("ModeParserTest.testLoadMode06 FINISH");
  }
 /**
  * Calculate data values from raw ingest data
  *
  * @param recHdr java.util.Map object with values for calculation
  * @param dty type of data ( "Total_Power", "Reflectivity", "Velocity", "Width",
  *     "Differential_Reflectivity")
  * @param data 1-byte input value
  * @return float value with precision of two decimal
  */
 static float calcData(Map<String, Number> recHdr, short dty, byte data) {
   short[] coef = {1, 2, 3, 4}; // MultiPRF modes
   short multiprf = recHdr.get("multiprf").shortValue();
   float vNyq = recHdr.get("vNyq").floatValue();
   double temp = -999.99;
   switch (dty) {
     default: // dty=1,2 -total_power, reflectivity (dBZ)
       if (data != 0) {
         temp = (((int) data & 0xFF) - 64) * 0.5;
       }
       break;
     case 3: // dty=3 - mean velocity (m/sec)
       if (data != 0) {
         temp = ((((int) data & 0xFF) - 128) / 127.0) * vNyq * coef[multiprf];
       }
       break;
     case 4: // dty=4 - spectrum width (m/sec)
       if (data != 0) {
         double v = ((((int) data & 0xFF) - 128) / 127.0) * vNyq * coef[multiprf];
         temp = (((int) data & 0xFF) / 256.0) * v;
       }
       break;
     case 5: // dty=5 - differential reflectivity (dB)
       if (data != 0) {
         temp = ((((int) data & 0xFF) - 128) / 16.0);
       }
       break;
   }
   BigDecimal bd = new BigDecimal(temp);
   BigDecimal result = bd.setScale(2, RoundingMode.HALF_DOWN);
   return result.floatValue();
 }
  public static void countWords() {

    try {
      WordGrabber wordgrabber =
          new WordGrabber("H:/k/klostermann_aiko/P1/aufgabenblatt_6/pg62.txt"); // Pfad angeben

      Map<Word, Counter> map = new HashMap<Word, Counter>();
      Word word = null;
      while (wordgrabber.hasNext()) {
        word = new Word(wordgrabber.next());
        if (map.containsKey(word)) {
          map.get(word).inc();
        } else {
          map.put(word, new Counter());
        } // else
      } // while

      Map<Word, Counter> tree = new TreeMap<Word, Counter>();
      for (Word outputWord : map.keySet()) {
        tree.put(outputWord, map.get(outputWord));
      } // for

      System.out.println("contained words:");
      for (Word outputWord : tree.keySet()) {
        System.out.println(outputWord.getWord() + " (" + tree.get(outputWord).getCounter() + ")");
      } // for

    } catch (IOException e) {
      e.printStackTrace();
    } // try catch
  } // countWords
Exemple #18
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);
  }
 private void _setVFile(List<NodeShell> list) {
   // make map
   Map<T_node, NodeShell> map = new HashMap<T_node, NodeShell>();
   for (NodeShell ns : list) {
     map.put(ns.mNode, ns);
   }
   // find main node
   T_node mainNode = this.mTemp.getMainNode();
   NodeShell mainNS = map.get(mainNode);
   // set parent for NS(s)
   for (NodeShell ns : list) {
     T_node node_p, node_c;
     node_c = ns.mNode;
     if (node_c == null) {
       node_p = null;
     } else {
       node_p = node_c.getParent();
     }
     NodeShell ns_p = map.get(node_p);
     ns.setParent(ns_p);
   }
   // set path for mainNS
   mainNS.setPath(this.mFile);
   for (NodeShell ns : list) {
     ns.getVFile();
   }
 }
Exemple #20
0
  /**
   * Returns an instance of NativeLibrary for the specified name. The library is loaded if not
   * already loaded. If already loaded, the existing instance is returned.
   *
   * <p>More than one name may map to the same NativeLibrary instance; only a single instance will
   * be provided for any given unique file path.
   *
   * @param libraryName The library name to load. This can be short form (e.g. "c"), an explicit
   *     version (e.g. "libc.so.6" or "QuickTime.framework/Versions/Current/QuickTime"), or the full
   *     (absolute) path to the library (e.g. "/lib/libc.so.6").
   * @param options native library options for the given library (see {@link Library}).
   */
  public static final NativeLibrary getInstance(String libraryName, Map options) {
    options = new HashMap(options);
    if (options.get(Library.OPTION_CALLING_CONVENTION) == null) {
      options.put(Library.OPTION_CALLING_CONVENTION, new Integer(Function.C_CONVENTION));
    }

    // Use current process to load libraries we know are already
    // loaded by the VM to ensure we get the correct version
    if ((Platform.isLinux() || Platform.isAIX()) && Platform.C_LIBRARY_NAME.equals(libraryName)) {
      libraryName = null;
    }
    synchronized (libraries) {
      WeakReference ref = (WeakReference) libraries.get(libraryName + options);
      NativeLibrary library = ref != null ? (NativeLibrary) ref.get() : null;

      if (library == null) {
        if (libraryName == null) {
          library =
              new NativeLibrary("<process>", null, Native.open(null, openFlags(options)), options);
        } else {
          library = loadLibrary(libraryName, options);
        }
        ref = new WeakReference(library);
        libraries.put(library.getName() + options, ref);
        File file = library.getFile();
        if (file != null) {
          libraries.put(file.getAbsolutePath() + options, ref);
          libraries.put(file.getName() + options, ref);
        }
      }
      return library;
    }
  }
 /**
  * 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;
 }
 @Test
 public void testClientId() {
   Map<String, ?> result = endpoint.checkToken(accessToken.getValue());
   assertEquals("client", result.get(Claims.AZP));
   assertEquals("client", result.get(Claims.CID));
   assertEquals("client", result.get(Claims.CLIENT_ID));
 }
Exemple #23
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);
  }
Exemple #24
0
 /*
  * (non-Javadoc)
  *
  * @see com.rbt.dao.ISubjectDao#getWebSubjectCount(java.util.Map)
  */
 public int getWebSubjectCount(Map map) {
   Map infoMap =
       (Map) this.getSqlMapClientTemplate().queryForObject("subject.getWebSubjectCount", map);
   return (infoMap != null && infoMap.get("ct") != null)
       ? Integer.parseInt(infoMap.get("ct").toString())
       : 0;
 }
  @Override
  public void setModelAttributes(Map<String, Object> attributes) {
    String uuid = (String) attributes.get("uuid");

    if (uuid != null) {
      setUuid(uuid);
    }

    Long pollsChoiceId = (Long) attributes.get("pollsChoiceId");

    if (pollsChoiceId != null) {
      setPollsChoiceId(pollsChoiceId);
    }

    Long pollsQuestionId = (Long) attributes.get("pollsQuestionId");

    if (pollsQuestionId != null) {
      setPollsQuestionId(pollsQuestionId);
    }

    String name = (String) attributes.get("name");

    if (name != null) {
      setName(name);
    }

    String description = (String) attributes.get("description");

    if (description != null) {
      setDescription(description);
    }
  }
  /**
   * Returns a JavaParameter for a given property.
   *
   * @param name Name
   * @param p Property
   * @param namespace Namespace
   * @param klass Class
   * @return Parameter
   */
  private JavaAttribute getParam(String name, Property p, Namespace namespace, JavaClass klass) {
    final JavaAttribute jp;
    final PropertyController pc = new PropertyController(name, p);
    if (p.isEnum()) {
      final JavaEnum e = pc.getEnum(namespace, name);
      jp = new JavaAttribute(name, e, klass);
      klass.linkInnerEnum(e);
    } else {
      final JavaClass type = pc.getClass(namespace, name, klass);
      jp = new JavaAttribute(name, type, klass);

      type.setUsedAsParameter();
      if (type.isInner()) {
        final String k = type.getName();
        if (innerClassDupes.containsKey(k)) {
          if (innerClassDupes.get(k) != null) {
            // update "old" type with new name and set null
            innerClassDupes.get(k).suffixName(getSuffixFromMembers(innerClassDupes.get(k)));
            innerClassDupes.put(k, null);
          }
          // update type with new name
          type.suffixName(getSuffixFromMembers(type));
        } else {
          innerClassDupes.put(k, type);
        }
        klass.linkInnerType(type);
      }
    }
    jp.setDescription(p.getDescription());
    jp.setRequired(p.isRequired());
    jp.resolveType();
    return jp;
  }
  /**
   * Check that EquipmentSetFacadeImpl when initialised with a dataset containing equipment hides
   * and shows the correct weapon slots.
   */
  public void testSlotManagementOnInitWithEquipment() {
    PlayerCharacter pc = getCharacter();
    EquipSet es = new EquipSet("0.1", "Unit Test Equip");
    Equipment weapon = new Equipment();
    weapon.setName("Morningstar");

    addEquipToEquipSet(pc, es, weapon, 1.0f, LOC_PRIMARY);

    EquipmentSetFacadeImpl esfi = new EquipmentSetFacadeImpl(uiDelegate, pc, es, dataset);
    ListFacade<EquipNode> nodes = esfi.getNodes();
    Map<String, EquipNode> nodeMap = new HashMap<String, EquipNode>();
    for (EquipNode equipNode : nodes) {
      nodeMap.put(equipNode.toString(), equipNode);
    }

    EquipNode testNode = nodeMap.get("Morningstar");
    assertNotNull("Morningstar should be present", testNode);
    assertEquals("Morningstar type", EquipNode.NodeType.EQUIPMENT, testNode.getNodeType());
    assertEquals("Morningstar location", LOC_PRIMARY, esfi.getLocation(testNode));

    // Test for removed slots
    String removedSlots[] = new String[] {"Primary Hand", "Double Weapon", "Both Hands"};
    for (String slotName : removedSlots) {
      testNode = nodeMap.get(slotName);
      assertNull(slotName + " should not be present", testNode);
    }

    // Test for still present slots
    String retainedSlots[] = new String[] {"Secondary Hand", "Ring"};
    for (String slotName : retainedSlots) {
      testNode = nodeMap.get(slotName);
      assertNotNull(slotName + " should be present", testNode);
    }
  }
  public static void fixAsEJB(ILaunchConfiguration config) {
    try {
      LaunchConfigurationInfo info =
          (LaunchConfigurationInfo) BeanUtils.invokeMethod(config, "getInfo");
      Map map = (Map) BeanUtils.getFieldValue(info, "fAttributes");

      String projectName = (String) map.get(ATTR_PROJECT_NAME);
      IJavaModel jModel = JavaCore.create(ResourcesPlugin.getWorkspace().getRoot());
      IJavaProject jp = jModel.getJavaProject(projectName);
      Assert.notNull(jp);

      File root = jp.getProject().getLocation().toFile();
      map.put("org.eclipse.jdt.launching.MAIN_TYPE", "jef.database.JefClassLoader");

      String arg = (String) map.get(ATTR_PROGRAM_ARGUMENTS);
      if (arg == null) {
        File openEjbFolder = findOpenEjbFolder();
        String projectPath = root.getAbsolutePath();
        String openEjbPath = openEjbFolder.getAbsolutePath();
        map.put(
            ATTR_PROGRAM_ARGUMENTS,
            "jef.ejb.server.OpenejbServer " + projectPath + " " + openEjbPath);
      }

    } catch (ReflectionException e) {
      e.printStackTrace();
    }
  }
  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);
  }
  public ExecutionPlanPartBean getPartBeansTree(ExecutionPlan plan) {

    List<ExecutionPlanPart> planParts = ExecutionPlanPartHelper.getInstance().findAllParts(plan);
    Map<Integer, ExecutionPlanPartBean> mapPlanPartIdToPlanPart =
        new HashMap<Integer, ExecutionPlanPartBean>();
    ExecutionPlanPartBean rootPartBean = null;
    for (ExecutionPlanPart executionPlanPart : planParts) {
      int planPartId = executionPlanPart.getId();
      ExecutionPlanPartBean executionPlanPartBean = mapPlanPartIdToPlanPart.get(planPartId);
      if (executionPlanPartBean == null) {
        executionPlanPartBean = hib2Gwt(executionPlanPart);
      }
      mapPlanPartIdToPlanPart.put(planPartId, executionPlanPartBean);

      ExecutionPlanPart parentPart = executionPlanPart.getParent();
      if (parentPart == null) {
        rootPartBean = executionPlanPartBean;
      } else {
        int parentPartId = parentPart.getId();
        ExecutionPlanPartBean parentPartBean = mapPlanPartIdToPlanPart.get(parentPartId);
        List<ExecutionPlanPartBean> childrenParts = parentPartBean.getChildrenParts();
        if (childrenParts == null) {
          childrenParts = new ArrayList<ExecutionPlanPartBean>();
          parentPartBean.setChildrenParts(childrenParts);
        }
        childrenParts.add(executionPlanPartBean);
      }
    }
    return rootPartBean;
  }