/** Optionally expects boolean params 'deleted' and 'privilegeInheritanceBlocked' */
  @Override
  public <T extends FsSecureBusinessObject> Object putRepresentation(
      T sbo, Object params, FsAccessToken token) {
    JSONObject data = (JSONObject) params;

    try {
      boolean deleted = data.getBoolean("deleted");

      if (sbo.isDeleted() != deleted) {
        sbo.setDeleted(deleted);
      }
    } catch (JSONException e) {
      // do nothing, because we do not force a client to always send this information back to the
      // server
    }

    try {
      boolean privInheritanceBlocked = data.getBoolean("privilegeInheritanceBlocked");

      if (sbo.isPrivilegeInheritanceBlocked() != privInheritanceBlocked) {
        sbo.setPrivilegeInheritanceBlocked(privInheritanceBlocked);
      }
    } catch (JSONException e) {
      // do nothing, because we do not force a client to always send this information back to the
      // server
    }

    return getRepresentation(sbo, params, token);
  }
 @Override
 public int read() throws IOException {
   if (nonNull(charSequence) && index < charSequence.length()) {
     return charSequence.charAt(index++);
   }
   return -1;
 }
Example #3
0
  public void save(T media) throws IOException {

    if (!canSaveType(media.getClass())) {
      return;
    }

    String preName = media.getPreviousName();
    File f = null;

    if (fileCache.containsKey(media)) {
      f = fileCache.get(media);
    } else {
      f = generateSaveFile(media);
    }

    Gson gson =
        new GsonBuilder().excludeFieldsWithoutExposeAnnotation().setPrettyPrinting().create();
    media.setSaved(true);
    String json = gson.toJson(media);

    BufferedWriter bfw = new BufferedWriter(new FileWriter(f));
    bfw.write(json);
    bfw.close();

    if (MediaBase.class.isAssignableFrom(media.getClass())) {
      ((MediaBase) media).save();
      System.out.println("Thumb saved");
    }

    if (preName != null && !preName.equals(media.getSaveString())) {
      deleteOldVersion(media, preName);
    }
  }
Example #4
0
  @Override
  public T selectChild(T node) {

    double max = Double.NEGATIVE_INFINITY;
    StatisticsNode maxChild = null;
    for (StatisticsNode childNode : node.getChildren()) {

      double childScore = getNodeScore(node, (T) childNode);
      // System.out.println(node);
      if (childScore >= max) {
        maxChild = childNode;
        max = childScore;
      }
    }

    if (maxChild == null) {
      for (StatisticsNode childNode : node.getChildren()) {

        double childScore = getNodeScore(node, (T) childNode);
        System.out.println(node + " " + childScore);
      }
    }

    assert (maxChild != null);
    return (T) maxChild;
  }
 /**
  * 比較する
  *
  * @param o1
  * @param o2
  * @param order
  * @return
  */
 private <T extends Comparable<? super T>> int compareTo(T o1, T o2, boolean order) {
   if (this.order) {
     return o1.compareTo(o2);
   } else {
     return o2.compareTo(o1);
   }
 }
 public String getPreferredStringForItem(Object o) {
   if (o == null) {
     return null;
   }
   T t = (T) o;
   return t.getId() == null ? "" : t.getId();
 }
  @NotNull
  public TIntObjectHashMap<T> preLoadCommitData(@NotNull TIntHashSet commits) throws VcsException {
    TIntObjectHashMap<T> result = new TIntObjectHashMap<>();
    final MultiMap<VirtualFile, String> rootsAndHashes = MultiMap.create();
    commits.forEach(
        commit -> {
          CommitId commitId = myHashMap.getCommitId(commit);
          if (commitId != null) {
            rootsAndHashes.putValue(commitId.getRoot(), commitId.getHash().asString());
          }
          return true;
        });

    for (Map.Entry<VirtualFile, Collection<String>> entry : rootsAndHashes.entrySet()) {
      VcsLogProvider logProvider = myLogProviders.get(entry.getKey());
      if (logProvider != null) {
        List<? extends T> details =
            readDetails(logProvider, entry.getKey(), ContainerUtil.newArrayList(entry.getValue()));
        for (T data : details) {
          int index = myHashMap.getCommitIndex(data.getId(), data.getRoot());
          result.put(index, data);
        }
        saveInCache(result);
      } else {
        LOG.error(
            "No log provider for root "
                + entry.getKey().getPath()
                + ". All known log providers "
                + myLogProviders);
      }
    }

    return result;
  }
 @NotNull
 public static <T extends Named & ExternalConfigPathAware & Identifiable> ExternalProjectPojo from(
     @NotNull T data) {
   String projectUniqueName =
       StringUtil.isEmpty(data.getId()) ? data.getExternalName() : data.getId();
   return new ExternalProjectPojo(projectUniqueName, data.getLinkedExternalProjectPath());
 }
  private AANode<T> remove(T element, AANode<T> node) {
    if (node == null) {
      return node;
    } else if (element.compareTo(node.getValue()) > 0) {
      node.setRight(remove(element, node.getRight()));
    } else if (element.compareTo(node.getValue()) < 0) {
      node.setLeft(remove(element, node.getLeft()));
    } else {
      if (node.getLevel() == 1) {
        return null;
      } else if (node.getLeft() == null) {
        AANode<T> left = getSuccessor(node);
        node.setRight(remove(left.getValue(), node.getRight()));
        node.setValue(left.getValue());
      } else {
        AANode<T> left = getPredecessor(node);
        node.setLeft(remove(left.getValue(), node.getLeft()));
        node.setValue(left.getValue());
      }
    }

    node = decreaseLevel(node);
    node = skew(node);
    node.setRight(skew(node.getRight()));
    if (node.getRight() != null) {
      node.getRight().setRight(skew(node.getRight().getRight()));
    }

    node = split(node);
    node.setRight(split(node).getRight());

    return node;
  }
  /** Sets the view to show if the adapter is empty */
  public void setEmptyView(View emptyView) {
    mEmptyView = emptyView;

    final T adapter = getAdapter();
    final boolean empty = ((adapter == null) || adapter.isEmpty());
    updateEmptyStatus(empty);
  }
  @Override
  public String describe() {
    List<String> returns = Lists.newArrayList();
    for (T r : values) returns.add(r.toString());

    return "{" + Joiner.on(',').join(returns) + "}";
  }
 /** Remember enough information to restore the screen state when the data has changed. */
 void rememberSyncState() {
   if (getChildCount() > 0) {
     mNeedSync = true;
     mSyncHeight = mLayoutHeight;
     if (mSelectedPosition >= 0) {
       // Sync the selection state
       View v = getChildAt(mSelectedPosition - mFirstPosition);
       mSyncRowId = mNextSelectedRowId;
       mSyncPosition = mNextSelectedPosition;
       if (v != null) {
         mSpecificTop = v.getTop();
       }
       mSyncMode = SYNC_SELECTED_POSITION;
     } else {
       // Sync the based on the offset of the first view
       View v = getChildAt(0);
       T adapter = getAdapter();
       if (mFirstPosition >= 0 && mFirstPosition < adapter.getCount()) {
         mSyncRowId = adapter.getItemId(mFirstPosition);
       } else {
         mSyncRowId = NO_ID;
       }
       mSyncPosition = mFirstPosition;
       if (v != null) {
         mSpecificTop = v.getTop();
       }
       mSyncMode = SYNC_FIRST_POSITION;
     }
   }
 }
  protected <T extends RealFieldElement<T>> void doInterpolationInside(
      final Field<T> field, double epsilonSin, double epsilonCos) {

    RungeKuttaFieldStepInterpolator<T> interpolator =
        setUpInterpolator(field, new SinCos<T>(field), 0.0, new double[] {0.0, 1.0}, 0.0125);

    int n = 100;
    double maxErrorSin = 0;
    double maxErrorCos = 0;
    for (int i = 0; i <= n; ++i) {
      T t =
          interpolator
              .getPreviousState()
              .getTime()
              .multiply(n - i)
              .add(interpolator.getCurrentState().getTime().multiply(i))
              .divide(n);
      FieldODEStateAndDerivative<T> state = interpolator.getInterpolatedState(t);
      maxErrorSin =
          FastMath.max(maxErrorSin, state.getState()[0].subtract(t.sin()).abs().getReal());
      maxErrorCos =
          FastMath.max(maxErrorCos, state.getState()[1].subtract(t.cos()).abs().getReal());
    }
    Assert.assertEquals(0.0, maxErrorSin, epsilonSin);
    Assert.assertEquals(0.0, maxErrorCos, epsilonCos);
  }
Example #14
0
 @Override
 public String toString() {
   // General representation: value/mask
   StringBuilder sb = new StringBuilder();
   sb.append(value.toString()).append('/').append(mask.toString());
   return sb.toString();
 }
Example #15
0
 @SuppressWarnings("unchecked")
 public Pair<Chip<P, B, T>, Integer> clean(int chipIndex) {
   List<T> cleanPlanes = new ArrayList<T>(getPlanesNum());
   int moved = 0;
   int i = 0;
   boolean cleaningInvoked = false;
   for (T plane : getPlanes()) {
     Pair<? extends Plane<P, B>, Integer> clean = plane.clean();
     if (clean == null) {
       cleanPlanes.add(plane);
     } else {
       cleaningInvoked = true;
       moved += clean.getValue1();
       ActionLog.addAction(new CleanAction(chipIndex, i, clean.getValue1()));
       cleanPlanes.add((T) clean.getValue0());
     }
     i++;
   }
   if (!cleaningInvoked) {
     return null;
   }
   Builder<P, B, T> builder = getSelfBuilder();
   builder.setPlanes(cleanPlanes).setTotalGCInvocations(getTotalGCInvocations() + 1);
   return new Pair<Chip<P, B, T>, Integer>(builder.build(), moved);
 }
  private T addMessageLocationImpl(boolean buttonAddedLocation, MessageLocation messageLocation) {
    for (T locationUI : getModel().getElements()) {
      if (locationUI.getLocation().overlaps(messageLocation)) {
        View.getSingleton()
            .showWarningDialog(
                Constant.messages.getString(
                    "messagelocationspanel.add.location.warning.locations.overlap"));
        return null;
      }
    }

    MessageLocationHighlight highlight = null;
    MessageLocationHighlight highlightReference = null;
    MessageLocationHighlightsManager highlightsManager = selectMessageLocationsPanel.create();
    if (highlightsManager != null) {
      highlight = highlightsManager.getHighlight(messageLocation);
      highlightReference = selectMessageLocationsPanel.highlight(messageLocation, highlight);
    }

    T entry =
        createMessageLocationTableEntry(
            buttonAddedLocation, messageLocation, highlight, highlightReference);
    if (entry == null) {
      if (highlightsManager != null) {
        selectMessageLocationsPanel.removeHighlight(messageLocation, highlightReference);
      }
      return null;
    }
    getModel().addElement(entry);

    int row = getTable().convertRowIndexToView(getModel().getRow(entry));
    getTable().setRowSelectionInterval(row, row);

    return null;
  }
  /**
   * Given a pointer to an entity and a std container of pointers to nearby entities, this function
   * checks to see if there is an overlap between entities. If there is, then the entities are moved
   * away from each other
   */
  public static <T extends BaseGameEntity, conT extends List<? extends BaseGameEntity>>
      void EnforceNonPenetrationContraint(T entity, final conT others) {
    ListIterator<? extends BaseGameEntity> it = others.listIterator();

    // iterate through all entities checking for any overlap of bounding
    // radii
    while (it.hasNext()) {
      BaseGameEntity curOb = it.next();
      // make sure we don't check against this entity
      if (curOb == entity) {
        continue;
      }

      // calculate the distance between the positions of the entities
      Vector2D ToEntity = sub(entity.Pos(), curOb.Pos());

      double DistFromEachOther = ToEntity.Length();

      // if this distance is smaller than the sum of their radii then this
      // entity must be moved away in the direction parallel to the
      // ToEntity vector
      double AmountOfOverLap = curOb.BRadius() + entity.BRadius() - DistFromEachOther;

      if (AmountOfOverLap >= 0) {
        // move the entity a distance away equivalent to the amount of overlap.
        entity.SetPos(add(entity.Pos(), mul(div(ToEntity, DistFromEachOther), AmountOfOverLap)));
      }
    } // next entity
  }
Example #18
0
 /**
  * This method builds the custom data collections used on the form and populates the values from
  * the collection of AwardCustomData on the Award.
  *
  * @param customAttributeGroups
  */
 @SuppressWarnings("unchecked")
 public void buildCustomDataCollectionsOnExistingDocument(
     SortedMap<String, List> customAttributeGroups) {
   for (Map.Entry<String, CustomAttributeDocument> customAttributeDocumentEntry :
       getCustomAttributeDocuments().entrySet()) {
     T loopAwardCustomData = null;
     for (T awardCustomData : getCustomDataList()) {
       if (awardCustomData.getCustomAttributeId()
           == (long) customAttributeDocumentEntry.getValue().getCustomAttribute().getId()) {
         loopAwardCustomData = awardCustomData;
         break;
       }
     }
     if (loopAwardCustomData != null) {
       String groupName =
           getCustomAttributeDocuments()
               .get(loopAwardCustomData.getCustomAttributeId().toString())
               .getCustomAttribute()
               .getGroupName();
       List<CustomAttributeDocument> customAttributeDocumentList =
           customAttributeGroups.get(groupName);
       if (customAttributeDocumentList == null) {
         customAttributeDocumentList = new ArrayList<CustomAttributeDocument>();
         customAttributeGroups.put(groupName, customAttributeDocumentList);
       }
       customAttributeDocumentList.add(
           getCustomAttributeDocuments()
               .get(loopAwardCustomData.getCustomAttributeId().toString()));
       Collections.sort(customAttributeDocumentList, new LabelComparator());
     }
   }
 }
Example #19
0
 @Override
 public <T extends BaseEntity> void saveOrUpdate(T model) {
   if (model.getCreateTime() == null) {
     model.setCreateTime(new Date());
   }
   getSession().saveOrUpdate(model);
 }
Example #20
0
  /**
   * This method builds the custom data collections used on the form
   *
   * @param customAttributeGroups
   */
  @SuppressWarnings("unchecked")
  public void buildCustomDataCollectionsOnNewDocument(
      SortedMap<String, List> customAttributeGroups) {
    for (Map.Entry<String, CustomAttributeDocument> customAttributeDocumentEntry :
        getCustomAttributeDocuments().entrySet()) {
      String temp = customAttributeDocumentEntry.getValue().getCustomAttribute().getValue();
      String groupName =
          customAttributeDocumentEntry.getValue().getCustomAttribute().getGroupName();

      T newCustomData = getNewCustomData();
      newCustomData.setCustomAttribute(
          customAttributeDocumentEntry.getValue().getCustomAttribute());
      newCustomData.setCustomAttributeId(
          customAttributeDocumentEntry.getValue().getCustomAttributeId().longValue());
      newCustomData.setValue(
          customAttributeDocumentEntry.getValue().getCustomAttribute().getDefaultValue());
      getCustomDataList().add(newCustomData);

      if (StringUtils.isEmpty(groupName)) {
        groupName = "No Group";
      }

      List<CustomAttributeDocument> customAttributeDocumentList =
          customAttributeGroups.get(groupName);
      if (customAttributeDocumentList == null) {
        customAttributeDocumentList = new ArrayList<CustomAttributeDocument>();
        customAttributeGroups.put(groupName, customAttributeDocumentList);
      }
      customAttributeDocumentList.add(
          getCustomAttributeDocuments()
              .get(customAttributeDocumentEntry.getValue().getCustomAttributeId().toString()));
      Collections.sort(customAttributeDocumentList, new LabelComparator());
    }
  }
Example #21
0
  /**
   * @param <T> The Object type.
   * @param array - the array to look into.
   * @param obj - the object to search for.
   * @return {@code true} if the array contains the object, {@code false} otherwise.
   */
  public static <T> boolean contains(T[] array, T obj) {
    if (array == null || array.length == 0) return false;

    for (T element : array) if (element.equals(obj)) return true;

    return false;
  }
Example #22
0
  @Override
  public List<ItemStack> getDisplayedRecipes() {
    ArrayList<ItemStack> list = new ArrayList();
    for (T r : recipes) list.add(r.getOutput());

    return list;
  }
  private static <T> void updateIfValueChanged(
      ContentProviderStoreCoreBase<T> store, Pair<T, Uri> pair) {
    final Cursor cursor =
        store.contentResolver.query(pair.second, store.getProjection(), null, null, null);
    T newItem = pair.first;
    boolean valuesEqual = false;

    if (cursor != null) {
      if (cursor.moveToFirst()) {
        T currentItem = store.read(cursor);
        valuesEqual = newItem.equals(currentItem);

        if (!valuesEqual) {
          Log.v(TAG, "Merging values at " + pair.second);
          newItem = store.mergeValues(currentItem, newItem);
          valuesEqual = newItem.equals(currentItem);
        }
      }
      cursor.close();
    }

    if (valuesEqual) {
      Log.v(TAG, "Data already up to date at " + pair.second);
      return;
    }

    final ContentValues contentValues = store.getContentValuesForItem(newItem);

    if (store.contentResolver.update(pair.second, contentValues, null, null) == 0) {
      final Uri resultUri = store.contentResolver.insert(pair.second, contentValues);
      Log.v(TAG, "Inserted at " + resultUri);
    } else {
      Log.v(TAG, "Updated at " + pair.second);
    }
  }
  public KieWorkbenchFormRenderingSettings generateRenderingContext(T settings) {
    if (!StringUtils.isEmpty(settings.getFormContent())) {

      try {
        MapModelRenderingContext renderingContext = new MapModelRenderingContext();

        initializeContextForms(settings, renderingContext);

        if (!isValid(renderingContext.getRootForm())) {
          return null;
        }

        Map<String, Object> rawData = generateRawFormData(settings, renderingContext);

        BackendFormRenderingContext context =
            contextManager.registerContext(
                renderingContext, rawData, settings.getMarshallerContext().getClassloader());

        Map<String, Object> formData = generateFormData(rawData, context);

        renderingContext.setModel(formData);

        prepareContext(settings, renderingContext);

        return new KieWorkbenchFormRenderingSettings(context.getTimestamp(), renderingContext);

      } catch (Exception ex) {
        getLogger().debug("Unable to generate render form: ", ex);
      }
    }

    return null;
  }
Example #25
0
  private <T> void cascadeOperation(T theT, CascadeTest theCascadeTest, CascadeAction theAction) {
    // if we've already cascaded this, move on to the next thing, we don't want infinite loops
    if (mCascadePending.contains(theT)) {
      return;
    } else {
      mCascadePending.add(theT);
    }

    Collection<AccessibleObject> aAccessors = new HashSet<AccessibleObject>();

    aAccessors.addAll(getAnnotatedFields(theT.getClass()));
    aAccessors.addAll(getAnnotatedGetters(theT.getClass(), true));

    for (AccessibleObject aObj : aAccessors) {
      if (theCascadeTest.apply(aObj)) {
        try {
          Object aAccessorValue = BeanReflectUtil.safeGet(aObj, theT);

          if (aAccessorValue == null) {
            continue;
          }

          theAction.apply(aAccessorValue);
        } catch (Exception e) {
          throw new PersistenceException(e);
        }
      }
    }
  }
Example #26
0
  @NotNull
  public <T extends ATNState> T newState(@NotNull Class<T> nodeType, GrammarAST node) {
    Exception cause;
    try {
      Constructor<T> ctor = nodeType.getConstructor();
      T s = ctor.newInstance();
      if (currentRule == null) s.setRuleIndex(-1);
      else s.setRuleIndex(currentRule.index);
      atn.addState(s);
      return s;
    } catch (InstantiationException ex) {
      cause = ex;
    } catch (IllegalAccessException ex) {
      cause = ex;
    } catch (IllegalArgumentException ex) {
      cause = ex;
    } catch (InvocationTargetException ex) {
      cause = ex;
    } catch (NoSuchMethodException ex) {
      cause = ex;
    } catch (SecurityException ex) {
      cause = ex;
    }

    String message =
        String.format(
            "Could not create %s of type %s.", ATNState.class.getName(), nodeType.getName());
    throw new UnsupportedOperationException(message, cause);
  }
 @Override
 public void unbind(T target) {
   target.mTabbar = null;
   target.mTabbarLayout = null;
   target.mViewPage = null;
   target.mManageView = null;
 }
  /**
   * Use @SuppressWarnings to allow the casts below: This follows Joshua Bloch's book Effective Java
   * 2nd Edition Item 24: Eliminate unchecked warnings where it is described how to minimize scope
   * of SuppressWarnings
   */
  public <T extends Enum<T> & AzCategoryId> RequestAttributesFactory<T> getRequestAttributesFactory(
      T t) {

    if (t.equals(AzCategoryIdAction.AZ_CATEGORY_ID_ACTION)) {
      @SuppressWarnings("unchecked")
      RequestAttributesFactory<T> azWrapReqObjFac =
          (RequestAttributesFactory<T>) getActionFactory();
      return azWrapReqObjFac;
    } else if (t.equals(AzCategoryIdResource.AZ_CATEGORY_ID_RESOURCE)) {
      @SuppressWarnings("unchecked")
      RequestAttributesFactory<T> azWrapReqObjFac =
          (RequestAttributesFactory<T>) getResourceFactory();
      return azWrapReqObjFac;
    } else if (t.equals(AzCategoryIdSubjectAccess.AZ_CATEGORY_ID_SUBJECT_ACCESS)) {
      @SuppressWarnings("unchecked")
      RequestAttributesFactory<T> azWrapReqObjFac =
          (RequestAttributesFactory<T>) getSubjectFactory();
      return azWrapReqObjFac;
    } else if (t.equals(AzCategoryIdEnvironment.AZ_CATEGORY_ID_ENVIRONMENT)) {
      @SuppressWarnings("unchecked")
      RequestAttributesFactory<T> azWrapReqObjFac =
          (RequestAttributesFactory<T>) getEnvironmentFactory();
      return azWrapReqObjFac;
    }
    return null;
  }
Example #29
0
 @Override
 public int hashCode() {
   int hashCode = 17;
   hashCode = hashCode * 37 + first.hashCode();
   hashCode = hashCode * 37 + second.hashCode();
   return hashCode;
 }
Example #30
0
 public void toReducedRowEchelonForm() {
   InvertibleBinaryOperation<T> addition = ring.addition();
   InvertibleBinaryOperation<T> multiplication =
       (InvertibleBinaryOperation<T>) ring.multiplication();
   toRowEchelonForm();
   int j = 0;
   for (int i = 0; i < m; i++) {
     while (j < n) {
       T aij = get(i, j);
       if (!aij.equals(zero)) {
         aij = multiplication.inverse(aij);
         for (int k = j + 1; k < n; k++) {
           T aik = multiplication.op(get(i, k), aij);
           set(i, k, aik);
           for (int l = 0; l < i; l++)
             set(
                 l,
                 k,
                 addition.op(get(l, k), addition.inverse(multiplication.op(aik, get(l, j)))));
         }
         set(i, j, one);
         for (int l = 0; l < i; l++) set(l, j, zero);
         j++;
         break;
       }
       j++;
     }
   }
 }