@Override
  public GeneratorInstance versionSync(GeneratorInstanceVersionSyncRequest request) {
    Long id = request.getId();
    GeneratorInstance generatorInstancePersistence = generatorInstanceRepository.selectById(id);
    if (generatorInstancePersistence == null) {
      throw new AppException("实例不存在");
    }

    Long userId = request.getAuthentication().getUserId();
    if (!userId.equals(generatorInstancePersistence.getUser().getId())) {
      throw new AppException("权限不足");
    }

    Long generatorId = generatorInstancePersistence.getGenerator().getId();
    Generator generatorPersistence = generatorRepository.selectById(generatorId);
    if (generatorPersistence == null) {
      throw new AppException("生成器不存在");
    }

    if (generatorInstancePersistence.getVersion() < generatorPersistence.getVersion()) {
      generatorInstancePersistence.setVersion(generatorPersistence.getVersion());
      generatorInstancePersistence.setModifyDate(new Date());
      generatorInstanceRepository.update(generatorInstancePersistence);
    }

    return generatorInstancePersistence;
  }
  public void produceCpuEvents(NodePojo node)
      throws ExecutionException, InterruptedException, IOException {
    ChartPrettyRandomGenerator genUser = cpuUserGenerator.get(node.getIpAddress());
    if (genUser == null) {
      genUser = new ChartPrettyRandomGenerator(true, 80, 20);
      cpuUserGenerator.put(node.getIpAddress(), genUser);
    }
    ChartPrettyRandomGenerator genSys = cpuSysGenerator.get(node.getIpAddress());
    if (genSys == null) {
      genSys = new ChartPrettyRandomGenerator(true, 80, 20);
      cpuSysGenerator.put(node.getIpAddress(), genSys);
    }
    List<SamplePojo> samples = new ArrayList<SamplePojo>();

    long userCpu = Long.parseLong(genUser.getNextValue());
    long systemCpu = Long.parseLong(genSys.getNextValue());
    long idleCpu;

    if (userCpu + systemCpu > 100) {
      systemCpu = 100 - userCpu;
      idleCpu = 0;
    } else {
      idleCpu = 100 - (userCpu + systemCpu);
    }

    samples.add(new SamplePojo("User", Long.toString(userCpu)));
    samples.add(new SamplePojo("Sys", Long.toString(systemCpu)));
    samples.add(new SamplePojo("Idle", Long.toString(idleCpu)));

    listener.publishEvent(
        new EventPojo(node.getIpAddress(), symTime, TopLevelConst.CPU_LINE_CHART_DATA, samples));
  }
Пример #3
0
 /** Try to convert a string value into a numerical value. */
 private static Number createNumberFromStringValue(String value) throws NumberFormatException {
   final String suffix = value.substring(value.length() - 1);
   if ("L".equalsIgnoreCase(suffix)) {
     return Long.valueOf(value.substring(0, value.length() - 1));
   }
   if ("F".equalsIgnoreCase(suffix)) {
     return Float.valueOf(value.substring(0, value.length() - 1));
   }
   if ("D".equalsIgnoreCase(suffix)) {
     return Double.valueOf(value.substring(0, value.length() - 1));
   }
   try {
     return Integer.valueOf(value);
   } catch (NumberFormatException e) {
     // OK: Ignore exception...
   }
   try {
     return Long.valueOf(value);
   } catch (NumberFormatException e1) {
     // OK: Ignore exception...
   }
   try {
     return Double.valueOf(value);
   } catch (NumberFormatException e2) {
     // OK: Ignore exception...
   }
   throw new NumberFormatException(
       "Cannot convert string value '" + value + "' into a numerical value");
 }
  public String expandBody(MssCFGenContext genContext) {
    final String S_ProcName = "CFBamMssCFBindUuidGenDispenserId.expandBody() ";

    if (genContext == null) {
      throw CFLib.getDefaultExceptionFactory()
          .newNullArgumentException(getClass(), "expandBody", 1, "genContext");
    }

    ICFLibAnyObj genDef = genContext.getGenDef();
    if (genDef == null) {
      throw CFLib.getDefaultExceptionFactory()
          .newNullArgumentException(getClass(), "expandBody", 1, "genContext.getGenDef()");
    }

    String ret;

    if (genDef instanceof ICFBamUuidGenObj) {
      Long dispenserId = ((ICFBamUuidGenObj) genDef).getOptionalDispenserId();
      if (dispenserId == null) {
        ret = null;
      } else {
        ret = dispenserId.toString();
      }
    } else {
      throw CFLib.getDefaultExceptionFactory()
          .newUnsupportedClassException(
              getClass(), "expandBody", "genContext.getGenDef()", genDef, "ICFBamUuidGenObj");
    }

    return (ret);
  }
  public static void main(String[] args) {
    String host = args[0];
    int port = Integer.parseInt(args[1]);
    long id = Long.parseLong(args[2]);
    String character = args[3];
    long actorId = Long.parseLong(args[4]);

    // Install an RMISecurityManager, if there is not a
    // SecurityManager already installed
    if (System.getSecurityManager() == null) {
      System.setSecurityManager(new RMISecurityManager());
    }

    String name = "rmi://" + host + ":" + port + "/MovieDatabase";

    try {
      MovieDatabase db = (MovieDatabase) Naming.lookup(name);
      db.noteCharacter(id, character, actorId);

      Movie movie = db.getMovie(id);
      out.println(movie.getTitle());
      for (Map.Entry entry : movie.getCharacters().entrySet()) {
        out.println("  " + entry.getKey() + "\t" + entry.getValue());
      }

    } catch (RemoteException | NotBoundException | MalformedURLException ex) {
      ex.printStackTrace(System.err);
    }
  }
 protected void initializeTimeStamps() {
   Field timeStampField = fieldMap.get(TIMESTAMP);
   startTimestamp = Long.valueOf(timeStampField.getMinValue());
   endTimestamp = Long.valueOf(timeStampField.getMaxValue());
   stepValue = Long.valueOf(timeStampField.getStepValue());
   populateTimestampsForSplits();
 }
Пример #7
0
 public static void main(String[] args) throws Exception {
   Scanner s = new Scanner(new FileReader("pb.in"));
   while (s.hasNext()) {
     String line = s.nextLine();
     String[] rep = line.split("\\(");
     String[] nonrep = (rep[0] + "0").split("\\.");
     long num1 = Integer.parseInt(rep[1].substring(0, rep[1].length() - 1));
     String nine = "";
     while (nine.length() != rep[1].length() - 1) nine += "9";
     for (int i = 0; i < nonrep[1].length() - 1; i++) nine += "0";
     String ten = "";
     while (nonrep[1].length() != ten.length()) ten += "0";
     ten = "1" + ten;
     String nr = nonrep[0] + nonrep[1];
     long den1 = Long.parseLong(nine);
     long den2 = Long.parseLong(ten);
     long num2 = Long.parseLong(nr);
     long num = num1 * den2 + num2 * den1;
     long den = den1 * den2;
     long gcd = new BigInteger("" + num).gcd(new BigInteger("" + den)).longValue();
     num /= gcd;
     den /= gcd;
     System.out.println(line + " = " + num + " / " + den);
   }
 }
  // 删除
  @RequestMapping(value = "/delete", method = RequestMethod.POST)
  @ResponseBody
  public Object del(String ids) {
    Map map = new HashMap();
    int result = 0;
    Collection collection = new ArrayList();
    for (String id : ids.split("&")) {
      List<ControlBaseInfo> controlBaseInfos =
          controlBaseInfoService.selectByBaseMer(Long.valueOf(id));

      if (controlBaseInfos.size() == 0) {
        result = baseMerService.deleteByPrimaryKey(Long.valueOf(id));
      } else {
        collection.addAll(controlBaseInfos);
      }
    }

    map.put("state", result);
    if (!collection.isEmpty()) {
      map.put(
          "controlBaseInfos",
          BeanUtil.getCollection2JSON(collection, "controlBaseInfos", "controlmername", true));
    }

    return map;
  }
 @Override
 @SuppressWarnings("unchecked")
 public Conversation create(Conversation conv) {
   final Long id = getId(conv);
   if (template
           .opsForValue()
           .get(
               KeyUtils.conversationProductIdAndVisitorToken(
                   conv.getTopic().getProductId(), conv.getVisitor()))
       != null) {
     return findBy(id);
   }
   conv.setId(id);
   template.opsForHash().put(getIdKey(id), "id", id.toString());
   template.opsForHash().put(getIdKey(id), "topic", conv.getTopic().getId().toString());
   template.opsForHash().put(getIdKey(id), "visitor", conv.getVisitor());
   template.opsForHash().put(getIdKey(id), "visitorName", conv.getVisitorName());
   template
       .opsForHash()
       .put(getIdKey(id), "customerServiceUser", conv.getCustomerServiceUsername());
   template.opsForHash().put(getIdKey(id), "status", conv.getStatus().toString());
   template
       .opsForHash()
       .put(getIdKey(id), "createDate", String.valueOf(conv.getCreateDate().getTime()));
   template
       .opsForValue()
       .set(
           KeyUtils.conversationProductIdAndVisitorToken(
               conv.getTopic().getProductId(), conv.getVisitor()),
           id.toString());
   return conv;
 }
Пример #10
0
  private String addDocumentType(Map<String, String> parameters) throws Exception {
    DocumentType docType = new DocumentType();
    docType.setUid(Long.parseLong(parameters.get("uid")));
    docType.setName(parameters.get("name"));
    if (parameters.get("heritedfrom").isEmpty()) {
      docType.setDocumentTypeUid(-1);
    } else {
      docType.setDocumentTypeUid(Long.parseLong(parameters.get("heritedfrom")));
    }

    ArrayList<Map<String, String>> l =
        (ArrayList<Map<String, String>>)
            new JSONDeserializer().deserialize(parameters.get("jsonParameters"));
    List<Meta> metas = new ArrayList<Meta>();
    for (Map metaDatas : l) {
      Meta meta = new Meta();
      meta.setUid(-1);
      meta.setName(String.valueOf(metaDatas.get("name")));
      meta.setMetaType((Integer) metaDatas.get("metaType"));
      if (String.valueOf(metaDatas.get("metaFeedUid")).isEmpty()) {
        meta.setMetaFeedUid(-1L);
      } else {
        meta.setMetaFeedUid(((Integer) metaDatas.get("metaFeedUid")).longValue());
      }
      meta.setDocumentTypeUid(docType.getUid());
      metas.add(meta);
    }
    String xmlStream = XMLGenerators.getDocumentTypeXMLDescriptor(docType, metas);
    studioController.addDocumentType(sessionUid, xmlStream);
    return "";
  }
Пример #11
0
  public static void main(String[] args) {
    // TODO Auto-generated method stub

    Scanner in = new Scanner(System.in);
    Hashtable numbers = new Hashtable();

    N = in.nextInt();
    K = in.nextLong();

    long[] arr = new long[N];
    for (int i = 0; i < N; i++) {
      arr[i] = in.nextLong();
      numbers.put(Long.toString(arr[i]), arr[i]);
    }

    result = 0;

    for (int i = 0; i < N; i++) {
      long tmp = 0, tmp2 = 0;
      tmp = arr[i] + K;
      try {
        tmp2 = (Long) numbers.get(Long.toString(tmp));
        result++;
      } catch (Exception ex) {

      }
    }

    System.out.println(result);
  }
Пример #12
0
  private void checkStructure(final SystemEnvironment sysEnv, final Long checkId)
      throws SDMSException {
    if (checkSet.contains(checkId)) return;
    checkSet.add(checkId);

    final SDMSInterval checkIval = SDMSIntervalTable.getObject(sysEnv, checkId);
    final Long embeddedIntervalId = checkIval.getEmbeddedIntervalId(sysEnv);

    if (embeddedIntervalId != null) {
      if (embeddedIntervalId.equals(ivalId))
        throw new CommonErrorException(
            new SDMSMessage(sysEnv, "04209121544", "cyclic references not allowed"));

      checkStructure(sysEnv, embeddedIntervalId);
    }

    final Vector ihList = SDMSIntervalHierarchyTable.idx_parentId.getVector(sysEnv, checkId);
    final Iterator ihIt = ihList.iterator();
    while (ihIt.hasNext()) {
      final SDMSIntervalHierarchy ih = (SDMSIntervalHierarchy) ihIt.next();
      final Long childId = ih.getChildId(sysEnv);

      if (childId.equals(ivalId))
        throw new CommonErrorException(
            new SDMSMessage(sysEnv, "04209121547", "cyclic references not allowed"));

      checkStructure(sysEnv, childId);
    }
  }
Пример #13
0
 /** Convert a collection of ConstantSets to the format expected by GenTest.addClassLiterals. */
 public static MultiMap<Class<?>, PrimitiveOrStringOrNullDecl> toMap(
     Collection<ConstantSet> constantSets) {
   final MultiMap<Class<?>, PrimitiveOrStringOrNullDecl> map =
       new MultiMap<Class<?>, PrimitiveOrStringOrNullDecl>();
   for (ConstantSet cs : constantSets) {
     Class<?> clazz;
     try {
       clazz = Class.forName(cs.classname);
     } catch (ClassNotFoundException e) {
       throw new Error("Class " + cs.classname + " not found on the classpath.");
     }
     for (Integer x : cs.ints) {
       map.add(clazz, new PrimitiveOrStringOrNullDecl(int.class, x.intValue()));
     }
     for (Long x : cs.longs) {
       map.add(clazz, new PrimitiveOrStringOrNullDecl(long.class, x.longValue()));
     }
     for (Float x : cs.floats) {
       map.add(clazz, new PrimitiveOrStringOrNullDecl(float.class, x.floatValue()));
     }
     for (Double x : cs.doubles) {
       map.add(clazz, new PrimitiveOrStringOrNullDecl(double.class, x.doubleValue()));
     }
     for (String x : cs.strings) {
       map.add(clazz, new PrimitiveOrStringOrNullDecl(String.class, x));
     }
     for (Class<?> x : cs.classes) {
       map.add(clazz, new PrimitiveOrStringOrNullDecl(Class.class, x));
     }
   }
   return map;
 }
  @Override
  public GeneratorInstance delete(GeneratorInstanceDeleteRequest request) {
    Long id = request.getId();
    GeneratorInstance generatorInstancePersistence = generatorInstanceRepository.selectById(id);
    if (generatorInstancePersistence == null) {
      throw new AppException("实例不存在");
    }

    Long userId = request.getAuthentication().getUserId();
    if (!userId.equals(generatorInstancePersistence.getUser().getId())) {
      throw new AppException("权限不足");
    }
    generatorInstanceRepository.delete(generatorInstancePersistence);

    Long rootDataModelId = generatorInstancePersistence.getDataModel().getId();
    DataModel rootDataModePersistence = dataModelRepository.selectById(rootDataModelId);
    if (rootDataModePersistence == null) {
      throw new AppException("rootDataMode不存在");
    }
    dataModelRepository.delete(rootDataModePersistence);

    Generator generatorPersistence =
        generatorRepository.selectById(generatorInstancePersistence.getGenerator().getId());
    generatorPersistence.setInstanceCount(generatorPersistence.getInstanceCount() - 1);
    generatorRepository.update(generatorPersistence);

    return generatorInstancePersistence;
  }
Пример #15
0
  /**
   * Creates the tool context denoting the range of samples that should be analysed by a tool.
   *
   * @return a tool context, never <code>null</code>.
   */
  private ToolContext createToolContext() {
    int startOfDecode = -1;
    int endOfDecode = -1;

    final int dataLength = this.dataContainer.getValues().length;
    if (this.dataContainer.isCursorsEnabled()) {
      if (this.dataContainer.isCursorPositionSet(0)) {
        final Long cursor1 = this.dataContainer.getCursorPosition(0);
        startOfDecode = this.dataContainer.getSampleIndex(cursor1.longValue()) - 1;
      }
      if (this.dataContainer.isCursorPositionSet(1)) {
        final Long cursor2 = this.dataContainer.getCursorPosition(1);
        endOfDecode = this.dataContainer.getSampleIndex(cursor2.longValue()) + 1;
      }
    } else {
      startOfDecode = 0;
      endOfDecode = dataLength;
    }

    startOfDecode = Math.max(0, startOfDecode);
    if ((endOfDecode < 0) || (endOfDecode >= dataLength)) {
      endOfDecode = dataLength - 1;
    }

    return new DefaultToolContext(startOfDecode, endOfDecode);
  }
Пример #16
0
  public static void main(String[] args) {

    int numBombs = Integer.parseInt(getLine());

    Point[] ary = new Point[numBombs];
    for (int i = 0; i < numBombs; i++) {
      String[] inp = getLine().split("\\s+");
      ary[i] = new Point(Long.parseLong(inp[0]), Long.parseLong(inp[1]));
    }

    Arrays.sort(
        ary,
        new Comparator<Point>() {
          public int compare(Point a, Point b) {
            if (a.absx + a.absy == b.absx + b.absy) {
              return 0;
            }
            return a.absx + a.absy < b.absx + b.absy ? -1 : 1;
          }
        });

    out.append(cnt + "\n");
    for (Point p : ary) {
      remove(p);
    }
    System.out.print(out);
  }
  @Override
  public void deleteLiveStatisticsOlderThan(Date date, String accountName) {
    Long fromHoursSince1970 = date.getTime() / (15000 * 240);
    Long toHoursSince1970 = new Date().getTime() / (15000 * 240);
    logger.info("hoursSince1970: " + fromHoursSince1970);
    logger.info("toSince1970: " + toHoursSince1970);

    try {

      for (int index = fromHoursSince1970.intValue();
          index <= toHoursSince1970.intValue();
          index++) {
        int keys = 0;
        Bucket hourBucket = riakClient.fetchBucket(accountName + ";" + index).execute();
        try {
          for (String key : hourBucket.keys()) {
            hourBucket.delete(key);
            keys++;
          }
        } catch (RiakException e) {
          e
              .printStackTrace(); // To change body of catch statement use File | Settings | File
                                  // Templates.
        }

        logger.info("deleted all keys(" + keys + ") in bucket: " + accountName + ";" + index);
      }

    } catch (RiakRetryFailedException rrfe) {
      rrfe.printStackTrace();
    }

    // To change body of implemented methods use File | Settings | File Templates.
  }
Пример #18
0
  /** {@inheritDoc} */
  public String getNextSubAwardCode() {
    Long nextAwardNumber =
        sequenceAccessorService.getNextAvailableSequenceNumber(
            Constants.SUBAWARD_SEQUENCE_SUBAWARD_CODE);

    return nextAwardNumber.toString();
  }
Пример #19
0
  /**
   * Called before window creation, descendants should override to initialize the data, initialize
   * params.
   */
  void preInit(XCreateWindowParams params) {
    state_lock = new StateLock();
    initialising = InitialiseState.NOT_INITIALISED;
    embedded = Boolean.TRUE.equals(params.get(EMBEDDED));
    visible = Boolean.TRUE.equals(params.get(VISIBLE));

    Object parent = params.get(PARENT);
    if (parent instanceof XBaseWindow) {
      parentWindow = (XBaseWindow) parent;
    } else {
      Long parentWindowID = (Long) params.get(PARENT_WINDOW);
      if (parentWindowID != null) {
        parentWindow = XToolkit.windowToXWindow(parentWindowID);
      }
    }

    Long eventMask = (Long) params.get(EVENT_MASK);
    if (eventMask != null) {
      long mask = eventMask.longValue();
      mask |= SubstructureNotifyMask;
      params.put(EVENT_MASK, mask);
    }

    screen = -1;
  }
Пример #20
0
 static {
   _jspx_dependants = new java.util.HashMap<java.lang.String, java.lang.Long>(4);
   _jspx_dependants.put("/admin/../foot.jsp", Long.valueOf(1350283935831L));
   _jspx_dependants.put("/admin/../taglib.jsp", Long.valueOf(1345552994159L));
   _jspx_dependants.put("/admin/../top.jsp", Long.valueOf(1350305382989L));
   _jspx_dependants.put("/admin/left.jsp", Long.valueOf(1350298710763L));
 }
  /**
   * Record time-stamped information about the activity of the connection. This information can
   * originate from either the connector or from the framework. The reason it is here is that it is
   * viewed as 'belonging' to an individual connection, and is segregated accordingly.
   *
   * @param connectionName is the connection to which the record belongs. If the connection is
   *     deleted, the corresponding records will also be deleted. Cannot be null.
   * @param startTime is either null or the time since the start of epoch in milliseconds (Jan 1,
   *     1970). Every activity has an associated time; the startTime field records when the activity
   *     began. A null value indicates that the start time and the finishing time are the same.
   * @param activityType is a string which is fully interpretable only in the context of the
   *     connector involved, which is used to categorize what kind of activity is being recorded.
   *     For example, a web connector might record a "fetch document" activity, while the framework
   *     might record "ingest document", "job start", "job finish", "job abort", etc. Cannot be
   *     null.
   * @param dataSize is the number of bytes of data involved in the activity, or null if not
   *     applicable.
   * @param entityIdentifier is a (possibly long) string which identifies the object involved in the
   *     history record. The interpretation of this field will differ from connector to connector.
   *     May be null.
   * @param resultCode contains a terse description of the result of the activity. The description
   *     is limited in size to 255 characters, and can be interpreted only in the context of the
   *     current connector. May be null.
   * @param resultDescription is a (possibly long) human-readable string which adds detail, if
   *     required, to the result described in the resultCode field. This field is not meant to be
   *     queried on. May be null.
   * @param childIdentifiers is a set of child entity identifiers associated with this activity. May
   *     be null.
   */
  public void recordHistory(
      String connectionName,
      Long startTime,
      String activityType,
      Long dataSize,
      String entityIdentifier,
      String resultCode,
      String resultDescription,
      String[] childIdentifiers)
      throws ManifoldCFException {
    long endTimeValue = System.currentTimeMillis();
    long startTimeValue;
    if (startTime == null) startTimeValue = endTimeValue - 1L;
    else {
      startTimeValue = startTime.longValue();
      if (startTimeValue == endTimeValue) startTimeValue -= 1L; // Zero-time events are not allowed.
    }

    long dataSizeValue;
    if (dataSize == null) dataSizeValue = 0L;
    else dataSizeValue = dataSize.longValue();

    Long rowID =
        historyManager.addRow(
            connectionName,
            startTimeValue,
            endTimeValue,
            dataSizeValue,
            activityType,
            entityIdentifier,
            resultCode,
            resultDescription);
    // child identifiers are not stored, for now.
    // MHL
  }
  CheckinMemoryDao() {

    Checkin checkin =
        new Checkin(
            Long.toString(counter.incrementAndGet()),
            "Greg",
            "CVG",
            (System.currentTimeMillis() - TimeUnit.DAYS.toMillis(1)));
    contentProvider.put(checkin.getId(), checkin);

    checkin =
        new Checkin(
            Long.toString(counter.incrementAndGet()),
            "Greg",
            "ATL",
            (System.currentTimeMillis() - TimeUnit.DAYS.toMillis(2)));
    contentProvider.put(checkin.getId(), checkin);

    checkin =
        new Checkin(
            Long.toString(counter.incrementAndGet()),
            "Noah",
            "SFO",
            (System.currentTimeMillis() - TimeUnit.DAYS.toMillis(3)));
    contentProvider.put(checkin.getId(), checkin);

    checkin =
        new Checkin(
            Long.toString(counter.incrementAndGet()),
            "Noah",
            "ATL",
            (System.currentTimeMillis() - TimeUnit.DAYS.toMillis(4)));
    contentProvider.put(checkin.getId(), checkin);
  }
Пример #23
0
 protected Cache getGatewayKeyCache() {
   String apimGWCacheExpiry =
       ServiceReferenceHolder.getInstance()
           .getAPIManagerConfiguration()
           .getFirstProperty(APIConstants.TOKEN_CACHE_EXPIRY);
   if (!gatewayKeyCacheInit) {
     gatewayKeyCacheInit = true;
     if (apimGWCacheExpiry != null) {
       return APIUtil.getCache(
           APIConstants.API_MANAGER_CACHE_MANAGER,
           APIConstants.GATEWAY_KEY_CACHE_NAME,
           Long.parseLong(apimGWCacheExpiry),
           Long.parseLong(apimGWCacheExpiry));
     } else {
       long defaultCacheTimeout =
           Long.valueOf(
                   ServerConfiguration.getInstance()
                       .getFirstProperty(APIConstants.DEFAULT_CACHE_TIMEOUT))
               * 60;
       return APIUtil.getCache(
           APIConstants.API_MANAGER_CACHE_MANAGER,
           APIConstants.GATEWAY_KEY_CACHE_NAME,
           defaultCacheTimeout,
           defaultCacheTimeout);
     }
   }
   return Caching.getCacheManager(APIConstants.API_MANAGER_CACHE_MANAGER)
       .getCache(APIConstants.GATEWAY_KEY_CACHE_NAME);
 }
  public static void fromCRAWDAD(
      LinkTrace links,
      InputStream in,
      double timeMul,
      long ticsPerSecond,
      long offset,
      IdGenerator idGen)
      throws IOException {

    StatefulWriter<LinkEvent, Link> linkWriter = links.getWriter();
    BufferedReader br = new BufferedReader(new InputStreamReader(in));
    String line;

    while ((line = br.readLine()) != null) {
      String[] elems = line.split("[ \t]+");
      Integer id1 = idGen.getInternalId(elems[0]);
      Integer id2 = idGen.getInternalId(elems[1]);
      long begin = (long) (Long.parseLong(elems[2]) * timeMul) + offset;
      long end = (long) (Long.parseLong(elems[3]) * timeMul) + offset;
      linkWriter.queue(begin, new LinkEvent(id1, id2, LinkEvent.UP));
      linkWriter.queue(end, new LinkEvent(id1, id2, LinkEvent.DOWN));
    }
    linkWriter.flush();
    linkWriter.setProperty(Trace.timeUnitKey, Units.toTimeUnit(ticsPerSecond));
    idGen.writeTraceInfo(linkWriter);
    linkWriter.close();
    br.close();
  }
 public void addMemoryStatsToSnooper() {
   addData("memory_total", Long.valueOf(Runtime.getRuntime().totalMemory()));
   addData("memory_max", Long.valueOf(Runtime.getRuntime().maxMemory()));
   addData("memory_free", Long.valueOf(Runtime.getRuntime().freeMemory()));
   addData("cpu_cores", Integer.valueOf(Runtime.getRuntime().availableProcessors()));
   playerStatsCollector.addServerStatsToSnooper(this);
 }
Пример #26
0
  protected long getNextScan(Subscription sub) {
    SubscriptionHistory history = sub.getHistory();

    Long fail_count = (Long) sub.getUserData(SCHEDULER_FAILED_SCAN_CONSEC_KEY);

    if (fail_count != null) {

      long fail_time = ((Long) sub.getUserData(SCHEDULER_FAILED_SCAN_TIME_KEY)).longValue();

      long fails = fail_count.longValue();

      long backoff = FAIL_INIT_DELAY;

      for (int i = 1; i < fails; i++) {

        backoff <<= 1;

        if (backoff > FAIL_MAX_DELAY) {

          backoff = FAIL_MAX_DELAY;

          break;
        }
      }

      return (fail_time + backoff);
    }

    return (history.getNextScanTime());
  }
  public static void main(String[] args) throws IOException {
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    String[] str;
    str = in.readLine().split(" ");
    int N = Integer.parseInt(str[0]);

    long[] A = new long[N];
    long[] B = new long[N];
    long[] C = new long[N];
    long[] D = new long[N];
    for (int i = 0; i < N; i++) {
      str = in.readLine().split(" ");
      A[i] = Long.parseLong(str[0]);
      B[i] = Long.parseLong(str[1]);
      C[i] = Long.parseLong(str[2]);
      D[i] = Long.parseLong(str[3]);
    }

    long[] CD = new long[N * N];
    for (int i = 0; i < N; i++) {
      for (int j = 0; j < N; j++) {
        CD[i * N + j] = C[i] + D[j];
      }
    }
    Arrays.sort(CD);
    long count = 0;
    for (int i = 0; i < N; i++) {
      for (int j = 0; j < N; j++) {
        long sum = A[i] + B[j];
        count += upperbound(CD, -sum) - lowerbound(CD, -sum) + 1;
      }
    }
    System.out.println(count);
  }
  public String expandBody(MssCFGenContext genContext) {
    final String S_ProcName = "CFBamMssCFBindInt64DefMinValue.expandBody() ";

    if (genContext == null) {
      throw CFLib.getDefaultExceptionFactory()
          .newNullArgumentException(getClass(), "expandBody", 1, "genContext");
    }

    ICFLibAnyObj genDef = genContext.getGenDef();
    if (genDef == null) {
      throw CFLib.getDefaultExceptionFactory()
          .newNullArgumentException(getClass(), "expandBody", 1, "genContext.getGenDef()");
    }

    String ret;

    if (genDef instanceof ICFBamInt64DefObj) {
      Long minValue = ((ICFBamInt64DefObj) genDef).getOptionalMinValue();
      if (minValue == null) {
        ret = null;
      } else {
        ret = minValue.toString();
      }
    } else {
      throw CFLib.getDefaultExceptionFactory()
          .newUnsupportedClassException(
              getClass(), "expandBody", "genContext.getGenDef()", genDef, "ICFBamInt64DefObj");
    }

    return (ret);
  }
Пример #29
0
  public int getCountOfSubscribers(int forumId, int userId) {
    // TODO Auto-generated method stub
    Session session = this.sessionFactory.openSession();
    Transaction tx = null;
    int countOfSubscribers = 0;
    try {
      tx = session.beginTransaction();
      Query query = null;
      if (userId == 0) {
        query = session.createQuery("select count(*) from Subscription where forumId = :forumId");
        query.setParameter("forumId", forumId);
      } else {
        query =
            session.createQuery(
                "select count(*) from Subscription where forumId = :forumId and userId = :userId");
        query.setParameter("forumId", forumId);
        query.setParameter("userId", userId);
      }

      Long count = (Long) query.uniqueResult();
      countOfSubscribers = count.intValue();
      // System.out.println("No of subscribers.."+countOfSubscribers);
    } catch (HibernateException e) {
      if (tx != null) {
        tx.rollback();
        e.printStackTrace();
      }
    } finally {
      session.close();
    }
    return countOfSubscribers;
  }
Пример #30
0
 private boolean auto(String operation) {
   long startTime = System.currentTimeMillis();
   System.out.println("Operation: " + operation + "...");
   HibernateEntityManagerFactory emf = null;
   EntityManager em = null;
   try {
     Map<String, String> map = getPeristencePropertiesFixedMap();
     if (operation != null) {
       map.put("hibernate.hbm2ddl.auto", operation);
     }
     if (operation.equals("update")) {
       if (getDriver().equals(TestStation.Driver.derby)) {
         String url = map.get("hibernate.connection.url");
         if (!url.contains("create=true")) {
           url += ";create=true";
         }
         //                    if (!url.contains("logDevice=")) {
         //                        url += ";logDevice=" + getUserHome() + File.separator +
         // ".jtstand";
         //                    }
         map.put("hibernate.connection.url", url);
       }
     }
     emf =
         (HibernateEntityManagerFactory)
             Persistence.createEntityManagerFactory(getTestProject().getPun(), map);
     //            emf.getSessionFactory().getAllClassMetadata();
     //            System.out.println(emf.getSessionFactory().getAllClassMetadata());
     em = emf.createEntityManager();
     em.getTransaction().begin();
     em.getTransaction().commit();
     //            System.out.println("Closing entity manager");
     em.close();
     //            System.out.println("Closing entity manager factory");
     emf.close();
     System.out.println(
         "Database "
             + operation
             + " operation succeeded in "
             + Long.toString(System.currentTimeMillis() - startTime)
             + "ms");
     return true;
   } catch (Exception ex) {
     ex.printStackTrace();
     System.out.println(ex.getMessage());
     if (em != null && em.isOpen()) {
       em.close();
     }
     if (emf != null && emf.isOpen()) {
       emf.close();
     }
   }
   System.out.println(
       "Database "
           + operation
           + " operation failed in "
           + Long.toString(System.currentTimeMillis() - startTime)
           + "ms");
   return false;
 }