@Override
    public int compare(HashMap<String, String> object1, HashMap<String, String> object2) {
      try {
        int result = 0;
        switch (mOrder) {
          case CARD_ORDER_SFLD:
            result = object1.get("sfld").compareToIgnoreCase(object2.get("sfld"));
            if (result == 0) {
              result = object1.get("tmpl").compareToIgnoreCase(object2.get("tmpl"));
            }
            break;

          case CARD_ORDER_DUE:
            result = Long.valueOf(object1.get("due")).compareTo(Long.valueOf(object2.get("due")));
            if (result == 0) {
              result = object1.get("sfld").compareToIgnoreCase(object2.get("sfld"));
            }
            break;
        }
        return result;
      } catch (Exception e) {
        Log.e(AnkiDroidApp.TAG, "Error on sorting cards: " + e);
        return 0;
      }
    }
  /**
   * Returns all Weight Reading objects that fall within the time range specified (inclusive)
   *
   * @param leftBound The Date object specifying the earliest date boundary
   * @param rightBound The Date object specifying the latest date boundary
   * @param c The application context
   * @note Recreates only the new objects, since Identity Map is no longer applied: the reason for
   *     this is because whenever data is fetched, we know its usage right away and will not need to
   *     keep it in proximity for later usage, but rather direct usage
   * @return The ArrayList of all weighteReading in the database that fall within range
   * @throws MapperException Thrown when there is either a problem with mapping or if the
   *     Persistence layer returns an error
   */
  public static ArrayList<WeightReading> findAllWithinRangeInclusive(
      Date iLeftBound, Date iRightBound, Context iC) throws MapperException {
    try {
      ArrayList<ArrayList<String>> resultTable =
          WeightTDG.selectBetweenDatesInclusive(
              String.valueOf(iLeftBound.getTime()), String.valueOf(iRightBound.getTime()), iC);
      ArrayList<WeightReading> resultReadings = new ArrayList<WeightReading>(resultTable.size());
      for (int i = 0; i < resultTable.size(); ++i) {
        ArrayList<String> values = resultTable.get(i);
        WeightReading r;
        Long id = Long.valueOf(values.get(0));

        Date date = new Date(Long.valueOf(values.get(1)));
        /** Converts from Unix time to Java Date */
        int sourceInt = Integer.valueOf(values.get(2));
        ReadingSource source = sourceFromInt(sourceInt);
        float weight = Float.valueOf(values.get(3));

        r = new WeightReading(id, date, source, weight);

        resultReadings.add(r);
      }
      return resultReadings;
    } catch (PersistenceException iE) {
      throw new MapperException(
          "The Mapper failed to obtain the Weight Readings from the persistence layer. The TDG returned the following error: "
              + iE.getMessage());
    } catch (Exception iE) {
      throw new MapperException(
          "The mapper failed to complete an operation for the following unforeseen reason: "
              + iE.getMessage());
    }
  }
  public void execute(Long farmNo, Long loadBalancerNo) {
    Map<String, String> parameters = new LinkedHashMap<String, String>();
    parameters.put("FarmNo", farmNo.toString());
    parameters.put("LoadBalancerNo", loadBalancerNo.toString());

    requester.execute("/StartLoadBalancer", parameters);
  }
 public static String getGoalText(
     final ChallengeGoalData goal, final ChallengeData data, final ChallengeDataModel model) {
   String rawText = goal.getFormattedString();
   if (rawText == null || rawText.length() == 0) {
     return null;
   }
   rawText =
       (String)
           ChallengeFormatter.extractValue(
               rawText, ChallengeFormatter.Type.STRING, model.getParams());
   for (Matcher match = ChallengeGoalView.GOAL_BREED_PATTERN.matcher(rawText);
       match.find();
       match = ChallengeGoalView.GOAL_BREED_PATTERN.matcher(rawText)) {
     final String name =
         WakfuTranslator.getInstance()
             .getString(7, PrimitiveConverter.getInteger(match.group(1)), new Object[0]);
     rawText = match.replaceFirst(name);
   }
   for (Matcher match = ChallengeGoalView.GOAL_RESOURCE_PATTERN.matcher(rawText);
       match.find();
       match = ChallengeGoalView.GOAL_RESOURCE_PATTERN.matcher(rawText)) {
     final String name =
         WakfuTranslator.getInstance()
             .getString(12, PrimitiveConverter.getInteger(match.group(1)), new Object[0]);
     rawText = match.replaceFirst(name);
   }
   for (Matcher match = ChallengeGoalView.GOAL_VAR_PATTERN.matcher(rawText);
       match.find();
       match = ChallengeGoalView.GOAL_VAR_PATTERN.matcher(rawText)) {
     final Long value = data.getVarValue(match.group().substring(1, match.group().length() - 1));
     rawText = match.replaceFirst(value.toString());
   }
   return rawText;
 }
  @Test
  public void testResetOriginalValues() throws Exception {
    CalendarResource newCalendarResource = addCalendarResource();

    _persistence.clearCache();

    CalendarResource existingCalendarResource =
        _persistence.findByPrimaryKey(newCalendarResource.getPrimaryKey());

    Assert.assertTrue(
        Validator.equals(
            existingCalendarResource.getUuid(),
            ReflectionTestUtil.invoke(
                existingCalendarResource, "getOriginalUuid", new Class<?>[0])));
    Assert.assertEquals(
        Long.valueOf(existingCalendarResource.getGroupId()),
        ReflectionTestUtil.<Long>invoke(
            existingCalendarResource, "getOriginalGroupId", new Class<?>[0]));

    Assert.assertEquals(
        Long.valueOf(existingCalendarResource.getClassNameId()),
        ReflectionTestUtil.<Long>invoke(
            existingCalendarResource, "getOriginalClassNameId", new Class<?>[0]));
    Assert.assertEquals(
        Long.valueOf(existingCalendarResource.getClassPK()),
        ReflectionTestUtil.<Long>invoke(
            existingCalendarResource, "getOriginalClassPK", new Class<?>[0]));
  }
 private void init() {
   String s = settings.get(LAST_TRANSACTION_ID);
   if (s != null) {
     lastTransactionId = Long.parseLong(s);
     lastTransactionIdStored = lastTransactionId;
   }
   Long lastKey = openTransactions.lastKey();
   if (lastKey != null && lastKey.longValue() > lastTransactionId) {
     throw DataUtils.newIllegalStateException("Last transaction not stored");
   }
   Cursor<Long> cursor = openTransactions.keyIterator(null);
   while (cursor.hasNext()) {
     long id = cursor.next();
     Object[] data = openTransactions.get(id);
     int status = (Integer) data[0];
     String name = (String) data[1];
     long[] next = {id + 1, -1};
     long[] last = undoLog.floorKey(next);
     if (last == null) {
       // no entry
     } else if (last[0] == id) {
       Transaction t = new Transaction(this, id, status, name, last[1]);
       t.setStored(true);
       openTransactionMap.put(id, t);
     }
   }
 }
  public synchronized void transferProgress(
      TransferEvent transferEvent, byte[] buffer, int length) {
    Resource resource = transferEvent.getResource();
    if (!downloads.containsKey(resource)) {
      downloads.put(resource, new Long(length));
    } else {
      Long complete = (Long) downloads.get(resource);
      complete = new Long(complete.longValue() + length);
      downloads.put(resource, complete);
    }

    StringBuffer buf = new StringBuffer();
    for (Iterator i = downloads.entrySet().iterator(); i.hasNext(); ) {
      Map.Entry entry = (Map.Entry) i.next();
      Long complete = (Long) entry.getValue();
      String status =
          getDownloadStatusForResource(
              complete.longValue(), ((Resource) entry.getKey()).getContentLength());
      buf.append(status);
      if (i.hasNext()) {
        buf.append(" ");
      }
    }

    if (buf.length() > maxLength) {
      maxLength = buf.length();
    }

    out.print(buf.toString() + "\r");
  }
  public void map(
      Object unused,
      Text line,
      OutputCollector<LongWritable, PostingSongArrayWritable> output,
      Reporter reporter)
      throws IOException {

    StringTokenizer str = new StringTokenizer(line.toString(), " |\t");

    if (nRatings == 0) {
      userId = Long.parseLong(str.nextToken());
      nRatings = Integer.parseInt(str.nextToken());
      songsRatings.clear();
      totalRate = 0;
    } else {
      long songId = Long.parseLong(str.nextToken());
      int rate = Integer.parseInt(str.nextToken());
      songsRatings.add(new PostingSong(songId, rate));
      totalRate += rate;
      nRatings--;
      if (nRatings == 0) {
        nRatings = songsRatings.size();
        songsValue.setArray(songsRatings);
        output.collect(userIdKey, songsValue);
        nRatings = 0;
      }
    }
  }
  /**
   * Populate data from this array as if it was in local file data.
   *
   * @param data an array of bytes
   * @param offset the start offset
   * @param length the number of bytes in the array from offset
   * @since 1.1
   * @throws ZipException on error
   */
  public void parseFromLocalFileData(byte[] data, int offset, int length) throws ZipException {

    long givenChecksum = ZipLong.getValue(data, offset);
    byte[] tmp = new byte[length - WORD];
    System.arraycopy(data, offset + WORD, tmp, 0, length - WORD);
    crc.reset();
    crc.update(tmp);
    long realChecksum = crc.getValue();
    if (givenChecksum != realChecksum) {
      throw new ZipException(
          "bad CRC checksum "
              + Long.toHexString(givenChecksum)
              + " instead of "
              + Long.toHexString(realChecksum));
    }

    int newMode = ZipShort.getValue(tmp, 0);
    // CheckStyle:MagicNumber OFF
    byte[] linkArray = new byte[(int) ZipLong.getValue(tmp, 2)];
    uid = ZipShort.getValue(tmp, 6);
    gid = ZipShort.getValue(tmp, 8);

    if (linkArray.length == 0) {
      link = "";
    } else {
      System.arraycopy(tmp, 10, linkArray, 0, linkArray.length);
      link = new String(linkArray);
    }
    // CheckStyle:MagicNumber ON
    setDirectory((newMode & DIR_FLAG) != 0);
    setMode(newMode);
  }
  public Image loadImage(String id, String path, String transparentColor) throws SlickException {
    if (path == null || path.length() == 0)
      throw new SlickException("Image resource [" + id + "] has invalid path");

    Integer filterValue = null;

    try {
      if (transparentColor != null && transparentColor.length() > 0) {
        Long value = Long.parseLong(transparentColor, 16);
        filterValue = value.intValue();
      }
    } catch (NumberFormatException e) {
      throw new SlickException("Can't parse image filter color number. Resource ID " + id, e);
    }

    Image image = null;
    try {
      if (filterValue != null) {
        Color color = new Color(filterValue);
        image = new Image(path, color);
      } else {
        image = new Image(path);
      }
    } catch (SlickException e) {
      throw new SlickException("Could not load image", e);
    }

    this.imageMap.put(id, image);

    return image;
  }
 public void releaseAndUpdateInlineStudiesValue(Long id, List<VDCGroup> groups) {
   // String dataversevalue;
   String itemid = null;
   Iterator iterator = groups.iterator();
   Long newTotal;
   long localTotal;
   NetworkStatsState networkStatsState;
   for (int i = 0; i < searchItemBeans.length; i++) {
     NetworkStatsItemBean itembean = (NetworkStatsItemBean) searchItemBeans[i];
     if (itembean.getItemID().equals("item0")) { // increment the top level -- item0;
       localTotal = new Long(itembean.getStudyTotal());
       newTotal = localTotal + 1;
       networkStatsState = NetworkStatsState.getInstance();
       if (null != networkStatsState) {
         networkStatsState.fireNetworkStatsEvent(new ReleaseEvent("item0", newTotal.toString()));
         NetworkStatsState.getNetworkStatsMap().put("item0.studyTotal", newTotal.toString());
       }
     }
     while (iterator.hasNext()) {
       VDCGroup group = (VDCGroup) iterator.next();
       itemid = "item" + group.getId().toString();
       if (itembean.getItemID().equals(itemid)) {
         localTotal = new Long(itembean.getStudyTotal());
         newTotal = localTotal + 1;
         networkStatsState = NetworkStatsState.getInstance();
         if (null != networkStatsState) {
           networkStatsState.fireNetworkStatsEvent(new ReleaseEvent(itemid, newTotal.toString()));
           NetworkStatsState.getNetworkStatsMap().put(itemid + ".studyTotal", newTotal.toString());
         }
       }
     }
   }
 }
Example #12
0
  void preInit(XCreateWindowParams params) {
    super.preInit(params);
    if (!resize_request.isInterned()) {
      resize_request.intern(false);
    }
    winAttr.initialFocus = true;

    currentInsets = new Insets(0, 0, 0, 0); // replacemenet for wdata->top, left, bottom, right

    applyGuessedInsets();
    Rectangle bounds = (Rectangle) params.get(BOUNDS);
    dimensions = new WindowDimensions(bounds, getRealInsets(), false);
    params.put(BOUNDS, dimensions.getClientRect());

    if (insLog.isLoggable(Level.FINE)) {
      insLog.log(Level.FINE, "Initial dimensions {0}", new Object[] {String.valueOf(dimensions)});
    }

    // Deny default processing of these events on the shell - proxy will take care of
    // them instead
    Long eventMask = (Long) params.get(EVENT_MASK);
    params.add(
        EVENT_MASK,
        Long.valueOf(eventMask.longValue() & ~(FocusChangeMask | KeyPressMask | KeyReleaseMask)));
  }
 public synchronized void addSession(long id, int sessionTimeout) {
   sessionsWithTimeout.put(id, sessionTimeout);
   if (sessionsById.get(id) == null) {
     SessionImpl s = new SessionImpl(id, sessionTimeout, 0);
     sessionsById.put(id, s);
     if (LOG.isTraceEnabled()) {
       ZooTrace.logTraceMessage(
           LOG,
           ZooTrace.SESSION_TRACE_MASK,
           "SessionTrackerImpl --- Adding session 0x"
               + Long.toHexString(id)
               + " "
               + sessionTimeout);
     }
   } else {
     if (LOG.isTraceEnabled()) {
       ZooTrace.logTraceMessage(
           LOG,
           ZooTrace.SESSION_TRACE_MASK,
           "SessionTrackerImpl --- Existing session 0x"
               + Long.toHexString(id)
               + " "
               + sessionTimeout);
     }
   }
   touchSession(id, sessionTimeout);
 }
Example #14
0
  // DrawingPartListener methods
  public void stateChanged(DrawingPartEvent event) {
    String colors[] = {
      GradientColorModule.GREEN_GRADIENT_CONTEXT, GradientColorModule.RED_GRADIENT_CONTEXT,
    };

    Object key = event.getSource();
    MutableDrawingPart entry = actEntries_.get(key);
    // LongInterval li = (LongInterval)entry.getInterval()[0];
    // int idx = (int)(Math.round(Math.random()));
    // System.out.println("range:"+li.getRangeValue()+" idx:"+idx);
    // entry.setContext(key, colors[idx]);

    List changes = (List) (event.changes().next());

    int changeType = ((Integer) changes.get(0)).intValue();
    Long newValue = (Long) changes.get(1);
    Calendar calValue = new GregorianCalendar();
    calValue.setTime(new java.util.Date(newValue.longValue()));

    switch (changeType) {
      case MutableIntervalListener.START_CHANGED:
        model_.setActivityStart(key, calValue);
        break;
      case MutableIntervalListener.FINISH_CHANGED:
        model_.setActivityFinish(key, calValue);
        break;
      default:
        System.err.println("ERROR:Unknow MutableIntervalListener change:" + changeType);
    }
  }
 @Bean
 public RedeliveryPolicy osgpResponsesRedeliveryPolicy() {
   final RedeliveryPolicy redeliveryPolicy = new RedeliveryPolicy();
   redeliveryPolicy.setInitialRedeliveryDelay(
       Long.parseLong(
           this.environment.getRequiredProperty(
               PROPERTY_NAME_JMS_OSGP_RESPONSES_INITIAL_REDELIVERY_DELAY)));
   redeliveryPolicy.setMaximumRedeliveries(
       Integer.parseInt(
           this.environment.getRequiredProperty(
               PROPERTY_NAME_JMS_OSGP_RESPONSES_MAXIMUM_REDELIVERIES)));
   redeliveryPolicy.setMaximumRedeliveryDelay(
       Long.parseLong(
           this.environment.getRequiredProperty(
               PROPERTY_NAME_JMS_OSGP_RESPONSES_MAXIMUM_REDELIVERY_DELAY)));
   redeliveryPolicy.setRedeliveryDelay(
       Long.parseLong(
           this.environment.getRequiredProperty(
               PROPERTY_NAME_JMS_OSGP_RESPONSES_REDELIVERY_DELAY)));
   redeliveryPolicy.setDestination(this.dlmsRequestsQueue());
   redeliveryPolicy.setBackOffMultiplier(
       Double.parseDouble(
           this.environment.getRequiredProperty(
               PROPERTY_NAME_JMS_OSGP_RESPONSES_BACK_OFF_MULTIPLIER)));
   redeliveryPolicy.setUseExponentialBackOff(
       Boolean.parseBoolean(
           this.environment.getRequiredProperty(
               PROPERTY_NAME_JMS_OSGP_RESPONSES_USE_EXPONENTIAL_BACK_OFF)));
   return redeliveryPolicy;
 }
  @Bean
  public RedeliveryPolicy defaultRedeliveryPolicy() {
    final RedeliveryPolicy redeliveryPolicy = new RedeliveryPolicy();
    redeliveryPolicy.setInitialRedeliveryDelay(
        Long.parseLong(
            this.environment.getRequiredProperty(
                PROPERTY_NAME_JMS_DEFAULT_INITIAL_REDELIVERY_DELAY)));
    redeliveryPolicy.setMaximumRedeliveries(
        Integer.parseInt(
            this.environment.getRequiredProperty(PROPERTY_NAME_JMS_DEFAULT_MAXIMUM_REDELIVERIES)));
    redeliveryPolicy.setMaximumRedeliveryDelay(
        Long.parseLong(
            this.environment.getRequiredProperty(
                PROPERTY_NAME_JMS_DEFAULT_MAXIMUM_REDELIVERY_DELAY)));
    redeliveryPolicy.setRedeliveryDelay(
        Long.parseLong(
            this.environment.getRequiredProperty(PROPERTY_NAME_JMS_DEFAULT_REDELIVERY_DELAY)));
    redeliveryPolicy.setBackOffMultiplier(
        Double.parseDouble(
            this.environment.getRequiredProperty(PROPERTY_NAME_JMS_DEFAULT_BACK_OFF_MULTIPLIER)));
    redeliveryPolicy.setUseExponentialBackOff(
        Boolean.parseBoolean(
            this.environment.getRequiredProperty(
                PROPERTY_NAME_JMS_DEFAULT_USE_EXPONENTIAL_BACK_OFF)));

    return redeliveryPolicy;
  }
Example #17
0
  /** Loads stats from /proc/[pid]/stat and /proc/[pid]/statm files */
  public static ProcessStatus getProcStats(String pid) {

    // using a space as the delimeter.
    String data;

    // get the /proc/[pid]/stat as a string and them split into string array
    // using a space as the delimeter.
    try {
      data = FileReadUtil.readFirstLine(String.format(STAT_FILE, pid));
      String[] procStatData = data.split(SPACE_VALUE);
      long startTimeSecs =
          UnsignedLong.valueOf(procStatData[STAT_STARTTIME])
              .dividedBy(UnsignedLong.fromLongBits(HZ))
              .longValue();
      long currTimeSecs = new Date().getTime() / 1000;
      long upTimeSecs = currTimeSecs - (getBootTime() + startTimeSecs);
      return new ProcessStatus(
          upTimeSecs,
          Long.parseLong(procStatData[STAT_NUM_THREADS]),
          startTimeSecs,
          Integer.parseInt(procStatData[STAT_PID]),
          Long.parseLong(procStatData[STAT_RSS]) * getPageSize(),
          Long.parseLong(procStatData[STAT_VSIZE]));
    } catch (Exception e) {
      _log.error("Error occurred while getting service stats from /stats file: {}", e);
    }

    return null;
  }
Example #18
0
    @Override
    protected void onSuccess(TokenInfo tokenInfo) {
      super.onSuccess(tokenInfo);

      if (tokenInfo != null
          && account.getUser().getIdstr().equalsIgnoreCase(AppContext.getUser().getIdstr())) {
        long validSecond =
            Long.parseLong(tokenInfo.getCreate_at()) + Long.parseLong(tokenInfo.getExpire_in());
        if (System.currentTimeMillis() > validSecond * 1000) {
          new AlertDialogWrapper.Builder(MainActivity.this)
              .setTitle(R.string.remind)
              .setMessage(R.string.account_expired)
              .setNegativeButton(R.string.no, null)
              .setPositiveButton(
                  R.string.yes,
                  new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                      LoginFragment.launch(
                          MainActivity.this, account.getAccount(), account.getPassword(), 2000);
                    }
                  })
              .show();
        }
      }
    }
        @Override
        public void onClick(DialogInterface dialog, int which) {
          switch (which) {
            case CONTEXT_MENU_MARK:
              DeckTask.launchDeckTask(
                  DeckTask.TASK_TYPE_MARK_CARD,
                  mUpdateCardHandler,
                  new DeckTask.TaskData(
                      mCol.getSched(),
                      mCol.getCard(Long.parseLong(mCards.get(mPositionInCardsList).get("id"))),
                      0));
              return;

            case CONTEXT_MENU_SUSPEND:
              DeckTask.launchDeckTask(
                  DeckTask.TASK_TYPE_DISMISS_NOTE,
                  mSuspendCardHandler,
                  new DeckTask.TaskData(
                      mCol.getSched(),
                      mCol.getCard(Long.parseLong(mCards.get(mPositionInCardsList).get("id"))),
                      1));
              return;

            case CONTEXT_MENU_DELETE:
              Resources res = getResources();
              StyledDialog.Builder builder = new StyledDialog.Builder(CardBrowser.this);
              builder.setTitle(res.getString(R.string.delete_card_title));
              builder.setIcon(android.R.drawable.ic_dialog_alert);
              builder.setMessage(
                  res.getString(
                      R.string.delete_card_message, mCards.get(mPositionInCardsList).get("sfld")));
              builder.setPositiveButton(
                  res.getString(R.string.yes),
                  new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                      Card card =
                          mCol.getCard(Long.parseLong(mCards.get(mPositionInCardsList).get("id")));
                      deleteNote(card);
                      DeckTask.launchDeckTask(
                          DeckTask.TASK_TYPE_DISMISS_NOTE,
                          mDeleteNoteHandler,
                          new DeckTask.TaskData(mCol.getSched(), card, 3));
                    }
                  });
              builder.setNegativeButton(res.getString(R.string.no), null);
              builder.create().show();
              return;

            case CONTEXT_MENU_DETAILS:
              Card tempCard =
                  mCol.getCard(Long.parseLong(mCards.get(mPositionInCardsList).get("id")));
              Themes.htmlOkDialog(
                      CardBrowser.this,
                      getResources().getString(R.string.card_browser_card_details),
                      tempCard.getCardDetails(CardBrowser.this))
                  .show();
              return;
          }
        }
 private void botaoInserirActionPerformed(
     java.awt.event.ActionEvent evt) { // GEN-FIRST:event_botaoInserirActionPerformed
   try {
     String[] opcoes = {"sim", "não"};
     String rg = JOptionPane.showInputDialog("Digite seu RG");
     controllerCliente = new ClienteControllerUI();
     if (controllerCliente.clienteExiste(Long.parseLong(rg))) {
       int op =
           JOptionPane.showOptionDialog(
               this,
               "Deseja alugar este livro?",
               "Cliente encontrado!",
               JOptionPane.YES_NO_OPTION,
               JOptionPane.QUESTION_MESSAGE,
               null,
               opcoes,
               opcoes[0]);
       if (op == 0) {
         JOptionPane.showMessageDialog(this, "Processando Dados...");
         controller.salvarAluguel(Long.parseLong(rg));
       } else {
         JOptionPane.showMessageDialog(this, "Livro não pode ser alugado!");
       }
     } else {
       JOptionPane.showMessageDialog(this, "Cliente não encontrado!");
     }
   } catch (Exception e) {
     JOptionPane.showMessageDialog(this, "Campo inválido!");
   }
 } // GEN-LAST:event_botaoInserirActionPerformed
  @Override
  public double[] createDistancesVector(Long myUserId) {
    int totalNoUsers = countAllUsers().intValue() + 1;
    double[] distances = new double[totalNoUsers];
    Iterable<User> users = userRepository.findAll();
    Iterator<User> iterator = users.iterator();
    double[] myRatings = createActivityVector(myUserId);

    while (iterator.hasNext()) {
      User u = iterator.next();
      Long userId = u.getId();
      if (userId != myUserId) {
        double[] userRatings = createActivityVector(userId);
        if (RecommendationUtils.intersect(myRatings, userRatings)) {
          distances[userId.intValue()] =
              RecommendationUtils.cosineSimilarity(myRatings, userRatings);
        } else {
          distances[userId.intValue()] = Double.MIN_VALUE;
        }
      } else {
        distances[userId.intValue()] = Double.MIN_VALUE;
      }
    }

    return distances;
  }
 @Override
 public final int compare(String[] o1, String[] o2) {
   String t1 = o1[this.index];
   String t2 = o2[this.index];
   if (StringUtils.isEmpty(t1) && StringUtils.isEmpty(t2)) {
     return 0;
   }
   if (StringUtils.isEmpty(t1)) {
     return 1;
   }
   if (StringUtils.isEmpty(t2)) {
     return -1;
   }
   if (StringUtils.isNumeric(t1) && StringUtils.isNumeric(t2)) {
     // 数値文字列の場合
     Long o1l = Long.valueOf(t1);
     Long o2l = Long.valueOf(t2);
     return this.compareTo(o1l, o2l, this.order);
   } else if (t1.matches("(?:\\d+日)?(?:\\d+時間)?(?:\\d+分)?(?:\\d+秒)?")) {
     try {
       // 時刻文字列の場合
       // SimpleDateFormatは24時間超えるような時刻でも正しく?パースしてくれる
       Date o1date = DateUtils.parseDate(t1, "ss秒", "mm分ss秒", "HH時間mm分", "dd日HH時間mm分");
       Date o2date = DateUtils.parseDate(t2, "ss秒", "mm分ss秒", "HH時間mm分", "dd日HH時間mm分");
       return this.compareTo(o1date, o2date, this.order);
     } catch (ParseException e) {
       e.printStackTrace();
     }
   }
   // 文字列の場合
   return this.compareTo(t1, t2, this.order);
 }
  @Override
  public Cursor getTrackPointCursor(
      long trackId, long startTrackPointId, int maxLocations, boolean descending) {
    if (trackId < 0) {
      return null;
    }

    String selection;
    String[] selectionArgs;
    if (startTrackPointId >= 0) {
      String comparison = descending ? "<=" : ">=";
      selection =
          TrackPointsColumns.TRACKID + "=? AND " + TrackPointsColumns._ID + comparison + "?";
      selectionArgs = new String[] {Long.toString(trackId), Long.toString(startTrackPointId)};
    } else {
      selection = TrackPointsColumns.TRACKID + "=?";
      selectionArgs = new String[] {Long.toString(trackId)};
    }

    String sortOrder = TrackPointsColumns._ID;
    if (descending) {
      sortOrder += " DESC";
    }
    if (maxLocations > 0) {
      sortOrder += " LIMIT " + maxLocations;
    }
    return getTrackPointCursor(null, selection, selectionArgs, sortOrder);
  }
Example #24
0
 public static int compareVersion(String curVer, String serVer) {
   if (curVer.equals(serVer) || serVer == null) {
     return 0;
   }
   String[] version1Array = curVer.split("\\.");
   String[] version2Array = serVer.split("\\.");
   int index = 0;
   int minLen = Math.min(version1Array.length, version2Array.length);
   long diff = 0;
   while (index < minLen
       && (diff =
               Long.parseLong(getStringNum(version1Array[index]))
                   - Long.parseLong(getStringNum(version2Array[index])))
           == 0) {
     index++;
   }
   if (diff == 0) {
     for (int i = index; i < version1Array.length; i++) {
       if (i >= 4 || Integer.parseInt(version1Array[i]) > 0) {
         // 没有新版本
         return 1;
       }
     }
     for (int i = index; i < version2Array.length; i++) {
       if (Integer.parseInt(version2Array[i]) > 0) {
         // 有新版本更新
         return -1;
       }
     }
     return 0;
   } else {
     return diff > 0 ? 1 : -1;
   }
 }
  /**
   * Returns the number of class names.
   *
   * @return the number of class names
   * @throws SystemException if a system exception occurred
   */
  public int countAll() throws SystemException {
    Long count = (Long) FinderCacheUtil.getResult(FINDER_PATH_COUNT_ALL, FINDER_ARGS_EMPTY, this);

    if (count == null) {
      Session session = null;

      try {
        session = openSession();

        Query q = session.createQuery(_SQL_COUNT_CLASSNAME);

        count = (Long) q.uniqueResult();
      } catch (Exception e) {
        throw processException(e);
      } finally {
        if (count == null) {
          count = Long.valueOf(0);
        }

        FinderCacheUtil.putResult(FINDER_PATH_COUNT_ALL, FINDER_ARGS_EMPTY, count);

        closeSession(session);
      }
    }

    return count.intValue();
  }
Example #26
0
  /**
   * 回复微信服务器"文本消息"
   *
   * @param request
   * @param response
   * @param content
   * @param toUserName
   * @param fromUserName
   * @throws DocumentException
   * @throws IOException
   */
  public void replyTextMessage(
      HttpServletRequest request,
      HttpServletResponse response,
      String content,
      String toUserName,
      String fromUserName)
      throws DocumentException, IOException {
    Long createTime = Calendar.getInstance().getTimeInMillis() / 1000;
    StringBuffer sb = new StringBuffer();
    sb.append("<xml>");
    sb.append("<ToUserName><![CDATA[" + fromUserName + "]]></ToUserName>");
    sb.append("<FromUserName><![CDATA[" + toUserName + "]]></FromUserName>");
    sb.append("<CreateTime>" + createTime + "</CreateTime>");
    sb.append("<MsgType><![CDATA[text]]></MsgType>");
    sb.append("<Content><![CDATA[" + content + "]]></Content>");
    sb.append("</xml>");
    String replyMsg = sb.toString();

    String returnvaleue = "";
    try {
      WXBizMsgCrypt pc =
          new WXBizMsgCrypt(COMPONENT_TOKEN, COMPONENT_ENCODINGAESKEY, COMPONENT_APPID);
      returnvaleue = pc.encryptMsg(replyMsg, createTime.toString(), "easemob");
      //            System.out.println("------------------加密后的返回内容 returnvaleue: "+returnvaleue);
    } catch (AesException e) {
      e.printStackTrace();
    }
    output(response, returnvaleue);
  }
  private void sendResults(Long attemptId) {
    dbHelper = new DbHelper(this);
    Cursor cur = dbHelper.getUnsubmitted(attemptId.intValue());
    cur.moveToFirst();
    String content = "";
    while (cur.isAfterLast() == false) {
      content = dbHelper.createSubmitResponseObject(cur);
      cur.moveToNext();
    }
    cur.close();
    dbHelper.close();

    APIRequest[] resultsToSend = new APIRequest[1];
    APIRequest r = new APIRequest();
    r.fullurl =
        prefs.getString("prefServer", getString(R.string.prefServerDefault))
            + "api/?method=submit&format=json";
    r.rowId = attemptId.intValue();
    r.username = prefs.getString("prefUsername", "");
    r.password = prefs.getString("prefPassword", "");
    r.timeoutConnection = Integer.parseInt(prefs.getString("prefServerTimeoutConnection", "10000"));
    r.timeoutSocket = Integer.parseInt(prefs.getString("prefServerTimeoutResponse", "10000"));
    r.content = content;
    resultsToSend[0] = r;

    Toast.makeText(this, "Sending results", Toast.LENGTH_SHORT).show();

    // send results to server
    SubmitResultsTask task = new SubmitResultsTask(QuizActivityEnd.this);
    task.setDownloaderListener(this);
    task.execute(resultsToSend);
  }
  protected Long getOrAddLong(long longKey) {

    Long testValue;
    int index = hashIndex.getHashIndex((int) (longKey ^ (longKey >>> 32)));
    int lookup = hashIndex.hashTable[index];
    int lastLookup = -1;

    for (; lookup >= 0; lastLookup = lookup, lookup = hashIndex.getNextLookup(lookup)) {
      testValue = (Long) objectKeyTable[lookup];

      if (testValue.longValue() == longKey) {
        accessTable[lookup] = accessCount++;

        return testValue;
      }
    }

    if (hashIndex.elementCount >= threshold) {
      reset();

      return getOrAddLong(longKey);
    }

    lookup = hashIndex.linkNode(index, lastLookup);
    testValue = new Long(longKey);
    objectKeyTable[lookup] = testValue;
    accessTable[lookup] = accessCount++;

    return testValue;
  }
  /**
   * Returns the number of projects entries.
   *
   * @return the number of projects entries
   * @throws SystemException if a system exception occurred
   */
  @Override
  public int countAll() throws SystemException {
    Long count = (Long) FinderCacheUtil.getResult(FINDER_PATH_COUNT_ALL, FINDER_ARGS_EMPTY, this);

    if (count == null) {
      Session session = null;

      try {
        session = openSession();

        Query q = session.createQuery(_SQL_COUNT_PROJECTSENTRY);

        count = (Long) q.uniqueResult();

        FinderCacheUtil.putResult(FINDER_PATH_COUNT_ALL, FINDER_ARGS_EMPTY, count);
      } catch (Exception e) {
        FinderCacheUtil.removeResult(FINDER_PATH_COUNT_ALL, FINDER_ARGS_EMPTY);

        throw processException(e);
      } finally {
        closeSession(session);
      }
    }

    return count.intValue();
  }
Example #30
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;
  }