Example #1
0
    /**
     * Tests promises for a normal reference.
     */
    static private <T extends Receiver<?>> Promise<?>
    testNormal(final Eventual _, final T x) throws Exception {
        final Promise<T> p = ref(x);
        check(p.equals(p));
        check(ref(x).equals(p));
        check(x.equals(p.call()));
        class EQ extends Do<T,Promise<Boolean>> implements Serializable {
            static private final long serialVersionUID = 1L;

            public Promise<Boolean>
            fulfill(final T arg) throws Exception {
                check(x.equals(arg));
                return ref(true);
            }
        }
        final Promise<?> a = _.when(p, new EQ());
        final Promise<?> b = _.when(x, new EQ());
        final Promise<?> c = _.when(new Sneaky<T>(x), new EQ());

        final T x_ = _._(x);
        check(x_.equals(x_));
        check(_._(x_).equals(x_));
        check(_._(x).equals(x_));
        check(ref(x_).equals(p));
        final Promise<?> d = _.when(x_, new EQ());

        return join(_, a, b, c, d);
    }
Example #2
0
  /** Returns true if the key was removed. */
  public boolean remove(T key) {
    int hashCode = key.hashCode();
    int index = hashCode & mask;
    if (key.equals(keyTable[index])) {
      keyTable[index] = null;
      size--;
      return true;
    }

    index = hash2(hashCode);
    if (key.equals(keyTable[index])) {
      keyTable[index] = null;
      size--;
      return true;
    }

    index = hash3(hashCode);
    if (key.equals(keyTable[index])) {
      keyTable[index] = null;
      size--;
      return true;
    }

    return removeStash(key);
  }
 protected void verifyComparableToVsEquals(T o1, T o2) {
   assertNotNull(o1);
   assertNotNull(o2);
   assertTrue((o1.compareTo(o2) == 0) == (o1.equals(o2)));
   assertTrue((o2.compareTo(o1) == 0) == (o2.equals(o1)));
   assertTrue((o1.compareTo(o2) == 0) == (o2.compareTo(o1) == 0));
 }
  /**
   * 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;
  }
 @Override
 public double getPerturbationPenalty(
     Assignment<V, T> assignment, Model<V, T> model, T selectedValue, Collection<T> conflicts) {
   double penalty = 0;
   Set<T> violations =
       (getViolatedInitials() == null
           ? null
           : getViolatedInitials().getViolatedInitials(selectedValue));
   if (violations != null)
     for (T aValue : violations) {
       if (assignment.getValue(aValue.variable()) == null)
         penalty += getPenaltyA(assignment, selectedValue, aValue);
     }
   if (conflicts != null) {
     for (T conflictValue : conflicts) {
       T initialValue = conflictValue.variable().getInitialAssignment();
       if (initialValue != null) {
         if (initialValue.equals(conflictValue))
           penalty += getPenaltyB(assignment, selectedValue, conflictValue, initialValue);
         else {
           if (violations == null || !violations.contains(initialValue))
             penalty += getPenaltyC(assignment, selectedValue, conflictValue, initialValue);
         }
       }
     }
   }
   if (selectedValue.variable().getInitialAssignment() != null
       && !selectedValue.equals(selectedValue.variable().getInitialAssignment()))
     penalty +=
         getPenaltyD(assignment, selectedValue, selectedValue.variable().getInitialAssignment());
   return penalty;
 }
Example #6
0
 public Matrix<T> getKernelBasis() {
   Matrix<T> reducedRowEchelonForm = getReducedRowEchelonForm();
   boolean[] hasLeadingOne = new boolean[n];
   List<Integer> indices = new ArrayList<Integer>();
   int j = 0;
   for (int i = 0; i < m; i++)
     while (j < n) {
       T aij = reducedRowEchelonForm.get(i, j);
       if (!aij.equals(zero)) {
         if (!aij.equals(one)) throw new Error();
         indices.add(j);
         hasLeadingOne[j] = true;
         j++;
         break;
       }
       j++;
     }
   InvertibleBinaryOperation<T> addition = ring.addition();
   Matrix<T> kernelBasis = new Matrix<T>(ring, n, n - indices.size());
   kernelBasis.zero();
   int k = 0;
   for (int i = 0; i < n; i++)
     if (!hasLeadingOne[i]) {
       kernelBasis.set(i, k, one);
       for (int l = 0; l < indices.size(); l++)
         kernelBasis.set(indices.get(l), k, addition.inverse(reducedRowEchelonForm.get(l, i)));
       k++;
     }
   if (k != kernelBasis.n) throw new Error(k + " / " + indices.size());
   return kernelBasis;
 }
  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);
    }
  }
 /**
  * This is the main entry point for retrieving an object from this cache.
  *
  * @see org.broadleafcommerce.common.cache.StatisticsService
  * @param responseClass the class representing the type of the cache item
  * @param cacheName the name of the cache - the ehcache region name
  * @param statisticsName the name to use for cache hit statistics
  * @param retrieval the block of code to execute if a cache miss is not found in this cache
  * @param params the appropriate params comprising a unique key for this cache item
  * @param <T> the type of the cache item
  * @return The object retrieved from the executiom of the PersistentRetrieval, or null if a cache
  *     miss was found in this cache
  */
 protected <T> T getCachedObject(
     Class<T> responseClass,
     String cacheName,
     String statisticsName,
     PersistentRetrieval<T> retrieval,
     String... params) {
   T nullResponse = getNullObject(responseClass);
   BroadleafRequestContext context = BroadleafRequestContext.getBroadleafRequestContext();
   String key = buildKey(params);
   T response = null;
   if (context.isProductionSandBox()) {
     response = getObjectFromCache(key, cacheName);
   }
   if (response == null) {
     response = retrieval.retrievePersistentObject();
     if (response == null) {
       response = nullResponse;
     }
     // only handle null, non-hits. Otherwise, let level 2 cache handle it
     if (context.isProductionSandBox() && response.equals(nullResponse)) {
       statisticsService.addCacheStat(statisticsName, false);
       getCache(cacheName).put(new Element(key, response));
       if (getLogger().isTraceEnabled()) {
         getLogger().trace("Caching [" + key + "] as null in the [" + cacheName + "] cache.");
       }
     }
   } else {
     statisticsService.addCacheStat(statisticsName, true);
   }
   if (response.equals(nullResponse)) {
     return null;
   }
   return response;
 }
  public List<T> find(T start, T goal, StopDemander stop) {
    Node<T> startNode = new Node<T>(start, null);
    if (start.equals(goal)) {
      return startNode.getPathElements();
    }

    List<Node<T>> queue = new LinkedList<Node<T>>();
    Set<T> visited = new HashSet<T>();

    queue.add(startNode);
    visited.add(start);

    while (!queue.isEmpty()) {
      Node<T> node = queue.remove(0);

      List<T> successors = ProductionUtil.getSuccessors(node.getElement(), productions);
      for (T successor : successors) {
        if (!visited.contains(successor)) {
          Node<T> subNode = new Node(successor, node);
          if (successor.equals(goal)) {
            // The goal is found
            return subNode.getPathElements();
          }
          queue.add(subNode);
          visited.add(successor);
        }
      }
    }
    // Not found
    return null;
  }
Example #10
0
  public boolean equals(Object o) {
    if (o == null || !(o instanceof SearchRange)) {
      return false;
    }

    SearchRange range = (SearchRange) o;
    return _from.equals(range._from) && _to.equals(range._to);
  }
  /**
   * Modify is whether to make room for the new key if it doesn't exist. If a new entry is created,
   * the value at that position will be Double.NaN. Here's where all the magic happens.
   */
  private int find(T key, boolean modify) {
    // System.out.println("find " + key + " " + modify + " " + mapType + " " + capacity());

    if (mapType == MapType.SORTED_LIST) {
      // Binary search
      int i = binarySearch(key);
      if (i < num && keys[i] != null && key.equals(keys[i])) return i;
      if (modify) {
        if (locked)
          throw new RuntimeException(
              "Cannot make new entry for " + key + ", because map is locked");

        if (num == capacity()) changeSortedListCapacity(getCapacity(num + 1, false));

        // Shift everything forward
        for (int j = num; j > i; j--) {
          keys[j] = keys[j - 1];
          values[j] = values[j - 1];
        }
        num++;
        values[i] = Double.NaN;
        return i;
      } else return -1;
    } else if (mapType == MapType.HASH_TABLE) {
      int capacity = capacity();
      int keyHash = hash(key);
      int i = keyHash % capacity;
      if (i < 0) i = -i; // Arbitrary transformation

      // Make sure big enough
      if (!locked && modify && (num > loadFactor * capacity || capacity <= num + 1)) {
        /*if(locked)
        throw new RuntimeException("Cannot make new entry for " + key + ", because map is locked");*/

        switchMapType(MapType.HASH_TABLE);
        return find(key, modify);
      }

      // System.out.println("!!! " + keyHash + " " + capacity);
      if (num == capacity) throw new RuntimeException("Hash table is full: " + capacity);
      while (keys[i] != null && !keys[i].equals(key)) { // Collision
        // Warning: infinite loop if the hash table is full
        // (but this shouldn't happen based on the check above)
        i++;
        numCollisions++;
        if (i == capacity) i = 0;
      }
      if (keys[i] != null) { // Found
        assert key.equals(keys[i]);
        return i;
      }
      if (modify) { // Not found
        num++;
        values[i] = Double.NaN;
        return i;
      } else return -1;
    } else throw new RuntimeException("Internal bug: " + mapType);
  }
Example #12
0
 @Override
 public boolean equals(Object o) {
   if (o instanceof SymmetricPair<?>) {
     final SymmetricPair<?> p = (SymmetricPair<?>) o;
     return (mFst.equals(p.mFst) && mSnd.equals(p.mSnd))
         || (mFst.equals(p.mSnd) && mSnd.equals(p.mFst));
   }
   return false;
 }
 @Override
 public boolean check() {
   lastValue = element.getValue();
   if (lastValue.equals(pulsedValue)) {
     pulses++;
   } else if (pulses >= maxPulses && lastValue.equals(nonPulsedValue)) {
     return true;
   }
   return false;
 }
Example #14
0
  @Override
  public boolean equals(Object o) {
    if (this == o) return true;

    if (!(o instanceof Pair)) return false;
    @SuppressWarnings("unchecked")
    Pair<T> p = (Pair<T>) o;

    return first.equals(p.first) && second.equals(p.second);
  }
Example #15
0
 public boolean equals(Object o) {
   try {
     @SuppressWarnings("unchecked")
     Pair<T> other = (Pair<T>) o;
     return (first == other.first || (first != null && first.equals(other.first)))
         && (second == other.second || (second != null && second.equals(other.second)));
   } catch (Exception e) {
     return false;
   }
 }
Example #16
0
 /**
  * Compares this range to another object to test if they are equal..
  *
  * <p>To be equal, the minimum and maximum values must be equal, which ignores any differences in
  * the comparator.
  *
  * @param obj the reference object with which to compare
  * @return true if this object is equal
  */
 @Override
 public boolean equals(Object obj) {
   if (obj == this) {
     return true;
   } else if (obj == null || obj.getClass() != getClass()) {
     return false;
   } else {
     @SuppressWarnings("unchecked") // OK because we checked the class above
     Range<T> range = (Range<T>) obj;
     return minimum.equals(range.minimum) && maximum.equals(range.maximum);
   }
 }
Example #17
0
 public boolean contains(T key) {
   int hashCode = key.hashCode();
   int index = hashCode & mask;
   if (!key.equals(keyTable[index])) {
     index = hash2(hashCode);
     if (!key.equals(keyTable[index])) {
       index = hash3(hashCode);
       if (!key.equals(keyTable[index])) return containsKeyStash(key);
     }
   }
   return true;
 }
Example #18
0
  @Override
  @SuppressWarnings("unchecked")
  public <T> T promptChoiceTyped(
      final String message, final List<T> options, final T defaultIfEmpty) {
    if ((options == null) || options.isEmpty()) {
      throw new IllegalArgumentException(
          "promptChoice() Cannot ask user to select from a list of nothing. Ensure you have values in your options list.");
    }
    if (options.size() == 1) {
      return options.get(0);
    }

    println(message);

    Object result = InvalidInput.INSTANCE;

    while (result instanceof InvalidInput) {
      int count = 1;
      println();
      for (T entry : options) {
        if ((entry != null) && entry.equals(defaultIfEmpty)) {
          print(ShellColor.BOLD, "  " + count + " - [" + entry + "]");
        } else if (entry != null) {
          print("  " + count + " - [" + entry + "]");
        } else if (defaultIfEmpty == null) {
          print(ShellColor.BOLD, "  " + count + " - (none)");
        }

        if ((entry == defaultIfEmpty) || ((entry != null) && entry.equals(defaultIfEmpty))) {
          print("*");
        }
        println();
        count++;
      }
      println();
      int input =
          prompt(
                  "Choose an option by typing the number of the selection "
                      + renderColor(ShellColor.BOLD, "[*-default] "),
                  Integer.class,
                  0)
              - 1;
      if ((input >= 0) && (input < options.size())) {
        result = options.get(input);
      } else if (input == -1) {
        result = defaultIfEmpty;
      } else {
        println("Invalid selection, please try again.");
      }
    }
    return (T) result;
  }
Example #19
0
 @Override
 public boolean equals(Object obj) {
   if (this == obj) return true;
   if (obj == null) return false;
   if (getClass() != obj.getClass()) return false;
   Pair other = (Pair) obj;
   if (left == null) {
     if (other.left != null) return false;
   } else if (!left.equals(other.left)) return false;
   if (right == null) {
     if (other.right != null) return false;
   } else if (!right.equals(other.right)) return false;
   return true;
 }
Example #20
0
  @Override
  public boolean equals(Object obj) {
    Pair other = (Pair) obj;

    if (t1.equals(other.getT1()) && t2.equals(other.getT2())) {
      return true;
    }

    if (t1.equals(other.getT2()) && t2.equals(other.getT1())) {
      return true;
    }

    return false;
  }
 private <T> void assertMultivalue(
     String message, T expectedVals[], Collection<T> actualVals, OperationResult result) {
   if (expectedVals.length != actualVals.size()) {
     fail(
         message
             + ": expected "
             + expectedVals.length
             + " values but has "
             + actualVals.size()
             + " values: "
             + actualVals,
         result);
     return;
   }
   for (T expected : expectedVals) {
     boolean found = false;
     for (T actual : actualVals) {
       if (expected.equals(actual)) {
         found = true;
         break;
       }
     }
     if (!found) {
       fail(
           message
               + ": expected value '"
               + expected
               + "' not found in actual values "
               + actualVals,
           result);
       return;
     }
   }
 }
Example #22
0
 /** sets value's explanation */
 public void setNoGood(T value, Set<T> reason) {
   sLogger.debug(
       "    -- set nogood "
           + value.variable().getName()
           + " = "
           + value.getName()
           + "(expl:"
           + expl2str(reason)
           + ")");
   if (value.equals(value.variable().getAssignment())) {
     try {
       throw new Exception(
           "An assigned value "
               + value.variable().getName()
               + " = "
               + value.getName()
               + " become no good (noGood:"
               + reason
               + ")!!");
     } catch (Exception e) {
       sLogger.warn(e.getMessage(), e);
     }
     checkExpl(reason);
     printAssignments();
   }
   Set<T> noGood = noGood(value);
   if (noGood != null) for (T v : noGood) removeSupport(v.variable(), value);
   value.setExtra(reason);
   for (T aValue : reason) {
     addSupport(aValue.variable(), value);
   }
   goodnessChanged(value);
 }
Example #23
0
 @Override
 public boolean equals(Object obj) {
   if (this == obj) {
     return true;
   }
   if (obj == null) {
     return false;
   }
   if (getClass() != obj.getClass()) {
     return false;
   }
   Event<?> other = (Event<?>) obj;
   if (param == null) {
     if (other.param != null) {
       return false;
     }
   } else if (!param.equals(other.param)) {
     return false;
   }
   if (type == null) {
     if (other.type != null) {
       return false;
     }
   } else if (!type.equals(other.type)) {
     return false;
   }
   return true;
 }
Example #24
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 #25
0
  /**
   * After a value is assigned: explanations of other values of the value's variable are reset (to
   * contain only the assigned value), propagation over the assigned variable takes place.
   */
  @Override
  public void afterAssigned(long iteration, T value) {
    sLogger.debug("After assign " + value.variable().getName() + " = " + value.getName());
    iIteration = iteration;
    if (!isGood(value)) {
      sLogger.warn(
          value.variable().getName()
              + " = "
              + value.getName()
              + " -- not good value assigned (noGood:"
              + noGood(value)
              + ")");
      setGood(value);
    }

    Set<T> noGood = new HashSet<T>(1);
    noGood.add(value);
    List<T> queue = new ArrayList<T>();
    for (Iterator<T> i = value.variable().values().iterator(); i.hasNext(); ) {
      T anotherValue = i.next();
      if (anotherValue.equals(value) || !isGood(anotherValue)) continue;
      setNoGood(anotherValue, noGood);
      queue.add(anotherValue);
    }
    propagate(queue);
  }
Example #26
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++;
     }
   }
 }
  /**
   * Used to do a simple object.equals(lastObject) test. Simply call it like this:
   * compareObjects(ec2.describeTags(), "ec2.DescribeTags") Internally this will also update the
   * stateChanged count.
   *
   * @param object result of the AWS API method call
   * @param methodName english version of the method just called
   * @return true if the state was changed
   */
  @SuppressWarnings("unchecked")
  protected <T extends Object> boolean compareObjects(
      T object, String methodName, String accoundId) {
    SSCRecord record = RecordBuilder.createRecord(object, methodName, accoundId);
    String lastKnown = state.getLastKnown(record.key);

    // never seen before, must be new!
    if (lastKnown == null) {
      LOG.debug("new Record: " + record.key.toString());
      state.writeNewRecord(record);
      stateChanges += 1;
      return true;
    }

    //		LOG.debug("LAST RECORD: " + (lastKnown.length() >
    // 500?lastKnown.substring(0,500)+"...":lastKnown));

    SSCRecord last = RecordBuilder.read(lastKnown);
    T value = (T) last.value;
    if (!object.equals(value)) {
      LOG.debug("new Record: " + record.key.toString());
      state.writeNewRecord(record);
      stateChanges += 1;
      return true;
    } else {
      LOG.debug(methodName + " no state change");
      return false;
    }
  }
Example #28
0
  /**
   * Return true if the keys and the values are identical
   *
   * @param container The container
   * @return If the two objects are equals.
   */
  @Override
  public boolean equals(Object container) {

    Container cont = (Container) container;

    return (key == cont.key && value.equals(cont.value));
  }
  private Character[][] returnMatrixToCharacterFromCharacter(T[][] originalFieldMatrix) {

    if (originalFieldMatrix == null) return null;
    fieldSize = originalFieldMatrix.length;
    Character[][] fieldMatrixCharacter = new Character[fieldSize][fieldSize];
    for (int i = 0; i < fieldSize; i++) {
      for (int j = 0; j < fieldSize; j++) {
        T sign = originalFieldMatrix[i][j];
        //                    System.out.println("Converter::Character sign = " + sign);
        if (sign.equals(SIGN_X)) fieldMatrixCharacter[i][j] = SIGN_X;
        else if (sign.equals(SIGN_O)) fieldMatrixCharacter[i][j] = SIGN_O;
        else fieldMatrixCharacter[i][j] = SIGN_EMPTY;
      }
    }
    return fieldMatrixCharacter;
  }
 public void quitarDuplicados() {
   Nodo<T> aux = inicio;
   Nodo<T> aux2 = null;
   T dato = null;
   while (aux.getLiga() != null) {
     dato = aux.getInfo();
     aux2 = inicio;
     int indice = 0;
     boolean duplicado = false;
     while (aux2 != null) {
       if (dato.equals(aux2.getInfo())) {
         if (!duplicado) {
           duplicado = true;
           aux2 = aux2.getLiga();
           indice++;
         } else {
           aux2 = aux2.getLiga();
           borrar(indice);
           indice++;
         }
       } else {
         indice++;
         aux2 = aux2.getLiga();
       }
     }
     aux = aux.getLiga();
   }
 }