Beispiel #1
0
  /**
   * rounds the element to the nearest element towards zero.
   *
   * @param operands[0] = value to round
   * @return a matrix of the same size as the operands
   */
  public OperandToken evaluate(Token[] operands) {

    // exactly one operand
    if (getNArgIn(operands) != 1) throwMathLibException("fix: number of arguments != 1");

    // only works on numbers
    if (!(operands[0] instanceof DoubleNumberToken))
      throwMathLibException("fix: only works on numbers");

    DoubleNumberToken matrix = ((DoubleNumberToken) operands[0]);
    OperandToken temp = ((OperandToken) matrix.clone());

    double[][] reValues = matrix.getValuesRe();
    double[][] imValues = matrix.getValuesIm();
    for (int y = 0; y < matrix.getSizeY(); y++) {
      for (int x = 0; x < matrix.getSizeX(); x++) {
        if (reValues[y][x] >= 0) {
          // e.g. fix(3.2) => 3
          reValues[y][x] = java.lang.Math.floor(reValues[y][x]);
        } else {
          // e.g. fix(-3.2) => -3
          reValues[y][x] = java.lang.Math.ceil(reValues[y][x]);
        }
        if (imValues[y][x] >= 0) {
          // e.g. fix(3.2i) => 3
          imValues[y][x] = java.lang.Math.floor(imValues[y][x]);
        } else {
          // e.g. fix(-3.2i) => -3
          imValues[y][x] = java.lang.Math.ceil(imValues[y][x]);
        }
      }
    }
    return new DoubleNumberToken(reValues, imValues);
  }
  // Deze method maakt activities aan
  public List<Activity> createActivity(
      Course course,
      Integer activitiesPerWeek,
      Integer maxNumberStudents,
      String nameLectureType,
      boolean hoorcollege) {
    List<Activity> activities = new ArrayList<>();
    // Algoritme om (werk)groepen aan te maken
    for (int i = 1; i <= activitiesPerWeek; i++) {
      if (!hoorcollege && activitiesPerWeek >= 1) {

        // Verdeelt studenten over groepen als er meer studenten zijn dan capaciteit van 1
        // (werk)groep
        if (course.courseStudents.size() > maxNumberStudents) {
          int numberGroups =
              (int)
                  Math.ceil(((double) course.courseStudents.size()) / ((double) maxNumberStudents));
          int numberStudentsGroup =
              (int) Math.ceil(((double) course.courseStudents.size()) / ((double) numberGroups));

          course.numberOfGroups = numberGroups;
          int j;
          for (j = 1; j < numberGroups; j++) {
            List<Student> studentsWorkGroup =
                course.courseStudents.subList(
                    (j - 1) * numberStudentsGroup, j * numberStudentsGroup);
            Activity workGroup = new Activity(course, nameLectureType, i, j, studentsWorkGroup);
            activities.add(workGroup);
          }
          List<Student> studentsWorkGroup =
              course.courseStudents.subList(
                  numberStudentsGroup * (j - 1), course.courseStudents.size());
          Activity workGroup = new Activity(course, nameLectureType, i, j, studentsWorkGroup);
          activities.add(workGroup);

        }
        // Maakt 1 (werk)groep
        else {
          Activity subGroup = new Activity(course, nameLectureType, i, 1, course.courseStudents);
          activities.add(subGroup);
        }
        // Maakt 1 hoorcollege
      } else if (hoorcollege && activitiesPerWeek >= 1) {
        Activity hoorCollege = new Activity(course, nameLectureType, i, 1, course.courseStudents);
        activities.add(hoorCollege);
      }
    }
    return activities;
  }
  /**
   * Prints final output including the frequency count for each character and then finally prints
   * the index of coincidence for all the characters in the inptu text.
   *
   * @param table takes in map of character frequencies
   */
  private void print_output(LinkedHashMap<String, Integer> table) {
    System.out.printf("Total chars: %d\n", total_num);

    // if total_num is 0, then we divide by 0, which we don't want
    if (total_num == 0) {
      total_num = 1;
    }

    for (Map.Entry entry : table.entrySet()) {
      double percent = ((double) (Integer) entry.getValue() / total_num);
      System.out.printf(" %s:%9d ( %5.2f", entry.getKey(), entry.getValue(), percent * 100);
      System.out.print("%)  ");
      for (int i = 0; i < Math.ceil(percent * 100); i++) {
        System.out.print("*");
      }
      System.out.print("\n");
    }

    // print IC
    ic ic_gen = new ic();

    // gets the index of coincidence for the input text
    double ic_val = ic_gen.calc_ic(shortened_input, shortened_input.length());

    System.out.printf("\nIndex of Coincidence: %5.4f \n", ic_val);
  }
 public Integer getNbFiles() {
   if (this.openfile != null && this.nbLines > 0 && this.splitSize > 0) {
     Double d = Math.ceil(this.nbLines / new Double(this.splitSize));
     return d.intValue();
   }
   return 0;
 }
 // @Test
 public void ErrorCorrect() {
   int size = 100;
   double eps = 1.0 / size;
   double delta = .01;
   CountMin countmin = new CountMin(eps, delta);
   for (long key = 0L; key < 10000L; key++) {
     countmin.update(key, 1);
     Assert.assertTrue(countmin.getMaxError() == (long) (Math.ceil((key + 1) * eps)));
   }
 }
Beispiel #6
0
  public OperandToken evaluate(Token[] operands) {

    // exactly one operand
    if (getNArgIn(operands) != 1) throwMathLibException("fix: number of arguments != 1");

    // only works on numbers
    if (!(operands[0] instanceof DoubleNumberToken))
      throwMathLibException("fix: only works on numbers");

    Frame f = new Frame();
    ModalDialog m =
        new ModalDialog(f, "kk", "What do you want?", new String[] {"ok", "not ok", "maybe"});

    // f.show();
    m.show();

    debugLine("questdlg: " + m.str);

    DoubleNumberToken matrix = ((DoubleNumberToken) operands[0]);
    OperandToken temp = ((OperandToken) matrix.clone());

    double[][] reValues = matrix.getValuesRe();
    double[][] imValues = matrix.getValuesIm();
    for (int y = 0; y < matrix.getSizeY(); y++) {
      for (int x = 0; x < matrix.getSizeX(); x++) {
        if (reValues[y][x] >= 0) {
          // e.g. fix(3.2) => 3
          reValues[y][x] = java.lang.Math.floor(reValues[y][x]);
        } else {
          // e.g. fix(-3.2) => -3
          reValues[y][x] = java.lang.Math.ceil(reValues[y][x]);
        }
        if (imValues[y][x] >= 0) {
          // e.g. fix(3.2i) => 3
          imValues[y][x] = java.lang.Math.floor(imValues[y][x]);
        } else {
          // e.g. fix(-3.2i) => -3
          imValues[y][x] = java.lang.Math.ceil(imValues[y][x]);
        }
      }
    }
    return new DoubleNumberToken(reValues, imValues);
  }
  private void carveCanyon(int x, int y, double direction, int depth) {
    int nextX = x;
    int nextY = y;
    while (nextX > 0 && nextY > 0 && nextY < m_height - 1 && nextX < m_width - 1 && depth > 0) {
      sculptHill(nextX, nextY, -depth, 10, true);
      /*for(int i = Math.max(0,nextX-6);i<Math.min(m_width-1, nextX+6);i++) {
      	for(int j = Math.max(0,nextY-6);j<Math.min(m_height-1,nextY+6);j++) {
      		m_contour[i][j] = -depth;
      	}
      }*/
      double choice = m_random.nextGaussian();
      choice = 0;
      if (choice > 0.7) direction += m_random.nextDouble() * Math.PI * 2;
      if (choice < -0.7) direction -= m_random.nextDouble() * Math.PI * 2;

      double dx = Math.cos(direction);
      double dy = Math.sin(direction);
      nextX += Math.ceil(Math.abs(dx)) * ((dx < 0) ? -1 : 1);
      nextY += Math.ceil(Math.abs(dy)) * ((dy < 0) ? -1 : 1);
    }
  }
 @Override
 public void map(
     LongWritable key,
     IndexItemArrayWritable value,
     OutputCollector<GenericKey, GenericValue> output,
     Reporter reporter)
     throws IOException {
   IndexItem[] postingList = value.toIndexItemArray();
   for (int i = 1; i < postingList.length; i++) {
     for (int j = 0; j < i; j++) {
       IndexItem x = postingList[i];
       IndexItem y = postingList[j];
       // |y| >= t / maxweight(x) && |x| >= t / maxweight(y)
       if (compare(x.vectorLength(), Math.ceil(threshold / y.vectorMaxWeight())) >= 0
           && compare(y.vectorLength(), Math.ceil(threshold / x.vectorMaxWeight())) >= 0
           // tight upper bound on similarity score
           && compare(
                   min(x.vectorMaxWeight() * y.vectorSum(), y.vectorMaxWeight() * x.vectorSum()),
                   threshold)
               >= 0) {
         // positional filter
         // && compare(
         // min(x.positionalMaxWeight() * y.positionalSum(),
         // y.positionalMaxWeight() * x.positionalSum())
         // + x.getWeight() * y.getWeight(), threshold) >= 0)
         if (j % REPORTER_INTERVAL == 0) reporter.progress();
         int lpv = IndexItem.getLeastPrunedVectorID(x, y);
         int mpv = IndexItem.getMostPrunedVectorID(x, y);
         float psim = (float) (x.getWeight() * y.getWeight());
         outKey.set(lpv, mpv);
         payload.set(mpv, psim);
         outValue.set(payload);
         output.collect(outKey, outValue);
         reporter.incrCounter(APS.ADDEND, 1);
       }
     }
   }
 }
  private void setIapSize(int width, int height) {
    iap.setPreferredSize(width, height);
    Global.getPref().log("[AttributesSelector:changeIapSize]  pref. area: " + width + "x" + height);

    int anzPerWidth = width / (TILESIZE + 2) - 1;
    virtualWidth = anzPerWidth * (TILESIZE + 2);
    double max = Attribute.maxAttRef;
    int anzPerHeight = (int) java.lang.Math.ceil(max / anzPerWidth);
    iap.virtualSize.set(0, 0, virtualWidth, anzPerHeight * (TILESIZE + 2));
    Global.getPref()
        .log(
            "[AttributesSelector:setIapSize] virt. area: "
                + virtualWidth
                + "x"
                + anzPerHeight * (TILESIZE + 2));
  }
Beispiel #10
0
  // ---------------------------------------------------------------------------
  private String Calculate1(String oper, String str1) throws Exception {
    double n1 = Values.StringToDouble(str1);
    double val = 0;

    if (oper.equalsIgnoreCase("SEN")) val = java.lang.Math.sin(n1);
    else if (oper.equalsIgnoreCase("COS")) val = java.lang.Math.cos(n1);
    else if (oper.equalsIgnoreCase("TAN")) val = java.lang.Math.tan(n1);
    else if (oper.equalsIgnoreCase("CTG")) val = 1.0 / java.lang.Math.tan(n1);
    else if (oper.equalsIgnoreCase("ASEN")) val = java.lang.Math.asin(n1);
    else if (oper.equalsIgnoreCase("ACOS")) val = java.lang.Math.acos(n1);
    else if (oper.equalsIgnoreCase("ATAN")) val = java.lang.Math.atan(n1);
    else if (oper.equalsIgnoreCase("ACTG")) val = 1.0 / java.lang.Math.atan(n1);
    else if (oper.equalsIgnoreCase("SENH")) val = java.lang.Math.sinh(n1);
    else if (oper.equalsIgnoreCase("COSH")) val = java.lang.Math.cosh(n1);
    else if (oper.equalsIgnoreCase("TANH")) val = java.lang.Math.tanh(n1);
    else if (oper.equalsIgnoreCase("CTGH")) val = 1.0 / java.lang.Math.tanh(n1);
    else if (oper.equalsIgnoreCase("EXP")) val = java.lang.Math.exp(n1);
    // valor absoluto de inteiros s�o inteiros
    else if (oper.equalsIgnoreCase("ABS")) {
      val = java.lang.Math.abs(n1);
      if (Values.IsInteger(str1)) return Values.IntegerToString(val);
    } else if (oper.equalsIgnoreCase("RAIZ")) val = java.lang.Math.sqrt(n1);
    else if (oper.equalsIgnoreCase("LOG")) val = java.lang.Math.log10(n1);
    else if (oper.equalsIgnoreCase("LN")) val = java.lang.Math.log(n1);
    // parte inteira do numeros
    else if (oper.equalsIgnoreCase("INT")) {
      return Values.IntegerToString(n1);
    }
    // parte real
    else if (oper.equalsIgnoreCase("FRAC")) {
      String num = Values.DoubleToString(n1);
      return num.substring(num.indexOf('.') + 1);
    }

    // parte real
    else if (oper.equalsIgnoreCase("ARRED")) {
      double vm = java.lang.Math.ceil(n1);
      if (n1 - vm >= 0.5) return Values.IntegerToString((int) n1 + 1);
      return Values.IntegerToString((int) n1);
    } else throw new Exception("ERRO fun��o Desconhecida 1 [" + oper + "]");
    return Values.DoubleToString(val);
  }
  private int procentajeCubierto(Long suma, Long cuota) {
    int porcentaje = 0;
    double cuotaDou = new Double(cuota != null ? cuota : 0L);
    double sumaDou = new Double(suma != null ? suma : 0L);
    double div = new Double(sumaDou / cuotaDou);
    if (div >= 0) {
      if (div <= 1) {
        porcentaje =
            (int) java.lang.Math.ceil(div * 100); // El techo para que la aprox. sea por arriba
        if (logger.isDebugEnabled()) logger.debug("El porcentaje cubierto:[" + porcentaje);
      } else {
        porcentaje = 100;
        if (logger.isDebugEnabled()) logger.debug("Si no es 100");
      }
    } else {
      porcentaje = 0; // Para que no haya posiblidad de ningún número negativo
    }

    return porcentaje;
  }
Beispiel #12
0
 @Override
 public void handleCommand(InsteonPLMBindingConfig conf, Command cmd, InsteonDevice dev) {
   try {
     PercentType pc = (PercentType) cmd;
     logger.debug("changing level of {} to {}", dev.getAddress(), pc.intValue());
     int level = (int) Math.ceil((pc.intValue() * 255.0) / 100); // round up
     if (level > 0) { // make light on message with given level
       level = getMaxLightLevel(conf, level);
       Msg m = dev.makeStandardMessage((byte) 0x0f, (byte) 0x11, (byte) level);
       dev.enqueueMessage(m, m_feature);
       logger.info("{}: sent msg to set {} to {}", nm(), dev.getAddress(), level);
     } else { // switch off
       Msg m = dev.makeStandardMessage((byte) 0x0f, (byte) 0x13, (byte) 0x00);
       dev.enqueueMessage(m, m_feature);
       logger.info("{}: sent msg to set {} to zero by switching off", nm(), dev.getAddress());
     }
   } catch (IOException e) {
     logger.error("{}: command send i/o error: ", nm(), e);
   } catch (FieldException e) {
     logger.error("{}: command send message creation error ", nm(), e);
   }
 }
Beispiel #13
0
  protected int getMaxLightLevel(InsteonPLMBindingConfig conf, int defaultLevel) {
    HashMap<String, String> params = conf.getParameters();
    if (conf.getFeature().contains("dimmer") && params.containsKey("dimmermax")) {
      String item = conf.getItemName();
      String dimmerMax = params.get("dimmermax");
      try {
        int i = Integer.parseInt(dimmerMax);
        if (i > 1 && i <= 99) {
          int level = (int) Math.ceil((i * 255.0) / 100); // round up
          if (level < defaultLevel) {
            logger.info("item {}: using dimmermax value of {}", item, dimmerMax);
            return level;
          }
        } else {
          logger.error("item {}: dimmermax must be between 1-99 inclusive: {}", item, dimmerMax);
        }
      } catch (NumberFormatException e) {
        logger.error("item {}: invalid int value for dimmermax: {}", item, dimmerMax);
      }
    }

    return defaultLevel;
  }
 private int ceilInt(double val) {
   return (int) (Math.ceil(Math.abs(val)) * ((val < 0) ? -1 : 1));
 }
  public int findMedianSortedArrays(int A[], int B[]) {
    int lenA = A.length;
    int lenB = B.length;

    // Cheese case, lenB MUST be even 1 2 3 4 5 6 7 8 9 10
    if (lenA == 1) {
      // If A is bigger than all of B or less than all of B
      if (A[0] > B[lenB - 1]) {
        return B[lenB / 2];
      } else if (A[0] < B[0]) {
        return B[(lenB / 2) - 1];
      }
      // If A is somewhere in the middle
      else {
        // Upper and lower median values for evens
        int medBHigh = B[lenB / 2];
        int medBLow = B[(lenB / 2) - 1];

        if (A[0] < medBLow) {
          return medBLow;
        } else if (A[0] > medBHigh) {
          return medBHigh;
        } else if (A[0] > medBLow && A[0] < medBHigh) {
          return A[0];
        } else if (A[0] == medBLow || A[0] == medBHigh) {
          return A[0];
        }
      }
    }
    // Cheese case, lenA MUST be even
    else if (lenB == 1) {
      // If B is bigger than all of A
      if (B[0] >= A[lenB - 1]) {
        return A[lenA / 2];
      } else if (B[0] <= A[0]) {
        return A[(lenA / 2) - 1];
      }
      // If B is somewhere in the middle, adjust the median by one index based on where B is
      else {
        // Upper and lower median values for evens
        int medAHigh = A[lenA / 2];
        int medALow = A[(lenA / 2) - 1];

        if (B[0] < medALow) {
          return medALow;
        } else if (B[0] > medAHigh) {
          return medAHigh;
        } else if (B[0] > medALow && A[0] < medAHigh) {
          return B[0];
        } else if (B[0] == medALow || B[0] == medAHigh) {
          return B[0];
        }
      }
    }
    // Entirety of A is smaller than B, find the median of the whole sequence
    else if (A[lenA - 1] < B[0]) {
      int medIndex = (int) (Math.ceil((double) ((lenA - 1) + (lenB - 1)) / 2));

      if (medIndex > lenA - 1) {
        return B[medIndex - lenA];
      } else if (medIndex > lenB - 1) {
        return A[medIndex];
      }
    }
    // Entirety of B is smaller than A, find the median of the whole sequence
    else if (B[lenB - 1] < A[0]) {
      int medIndex = (int) Math.ceil((double) ((lenA - 1) + (lenB - 1)) / 2);

      if (medIndex > lenB - 1) {
        return A[medIndex - lenB];
      } else if (medIndex > lenA - 1) {
        return B[medIndex];
      }
    }
    // Mixed, comparing the medians of both arrays and truncating parts of the arrays based on
    // result
    else {
      int total = lenA + lenB;
      int aPtr, bPtr;
      // If A is even
      if (lenA % 2 == 0) {
        aPtr = lenA / 2;
        bPtr = (lenB - 1) / 2;
        int choppedA = lenA;
        int choppedB = lenB;
        int numCuts = 0;

        if ((double) B[bPtr] == (double) (A[aPtr] + A[aPtr - 1]) / 2) {
          return B[bPtr];
        }

        while (choppedA >= 1 && choppedB >= 1) {
          // Two elements left in even array
          if (choppedA == 2) {
            double medA = (double) ((A[aPtr - 1] + A[aPtr]) / 2);
            double medB = (double) ((B[bPtr - 1]) + B[bPtr] / 2);

            if (medB > medA) {
              return A[aPtr + 1];
            } else if (medB < medA) {
              return A[aPtr - 1];
            } else if (medB == medA) {
              return (int) medB;
            }
          }
          // One element left in odd array
          if (choppedB == 2) {
            double medA = (double) ((A[aPtr - 1] + A[aPtr]) / 2);
            double medB = (double) ((B[bPtr - 1]) + B[bPtr] / 2);
            aPtr--;

            // If B is between the medians
            if (medB > medA) {
              return A[aPtr + 1];
            } else if (medB < medA) {
              return A[aPtr - 1];
            } else if (medB == medA) {
              return (int) medB;
            }
          }

          // mid(A) > mid(B)
          if ((double) (A[aPtr] + A[aPtr - 1]) / 2 > (double) B[bPtr]) {
            aPtr -= (((lenB - 1) - bPtr) / 2);
            choppedA -= (((lenB - 1) - bPtr) / 2);

            bPtr += (((lenB - 1) - bPtr) / 2);
            choppedB -= choppedB / 2;
          }
          // mid(A) < mid(B)
          else if ((double) (A[aPtr] + A[aPtr - 1]) / 2 < (double) B[bPtr]) {
            numCuts++;
            aPtr += ((lenA - aPtr) / 2);
            choppedA = choppedA / 2;

            if ((lenA - aPtr) / 2 == 0) {
              if (A[aPtr] > B[bPtr - numCuts] + 1) {
                return B[bPtr - numCuts];
              } else if (A[aPtr] < B[bPtr - numCuts]) {
                return B[aPtr - numCuts + 1];
              } else if (A[aPtr] < B[bPtr - numCuts + 1] && A[aPtr] > B[bPtr - numCuts]) {
                return A[aPtr];
              } else if (A[aPtr] == B[bPtr - numCuts] || A[aPtr] == B[bPtr - numCuts + 1]) {
                return A[aPtr];
              }
            }

            bPtr -= ((lenA) - aPtr) / 2;
          }
        }
      }
      // If B is even
      else {
        bPtr = lenB / 2;
        aPtr = (lenA - 1) / 2;
        int choppedB = lenB;
        int choppedA = lenA;
        int numCuts = 0;

        if ((double) A[aPtr] == (double) (B[bPtr] + B[bPtr - 1]) / 2) {
          return A[aPtr];
        }

        while (choppedA >= 1 && choppedB >= 1) {
          // Two elements left in even array
          if (choppedB == 2) {
            double medB = (double) ((B[bPtr - 1] + B[bPtr]) / 2);
            double medA = (double) ((A[aPtr - 1]) + A[aPtr] / 2);

            if (medA > medB) {
              return B[bPtr + 1];
            } else if (medA < medB) {
              return B[bPtr - 1];
            } else if (medB == medA) {
              return (int) medB;
            }
          }
          // Two elements left in odd array
          if (choppedA == 2) {
            double medB = (double) ((B[bPtr - 1] + B[bPtr]) / 2); // LOL
            double medA = (double) ((A[bPtr - 1]) + A[bPtr] / 2);
            bPtr--;

            // Calculating shifts
            if (medA > medB) {
              return B[bPtr + 1];
            } else if (medA < medB) {
              return B[bPtr - 1];
            } else if (medB == medA) {
              return (int) medB;
            }
          }

          // mid(B) > mid(A)
          if ((double) (B[bPtr] + B[bPtr - 1]) / 2 > (double) A[bPtr]) {
            bPtr -= (((lenA - 1) - aPtr) / 2);
            choppedB -= (((lenA - 1) - aPtr) / 2);

            aPtr += (((lenA - 1) - aPtr) / 2);
            choppedA -= choppedA / 2;
          }
          // mid(B) < mid(A)
          else if ((double) (B[bPtr] + B[bPtr - 1]) / 2 < (double) A[aPtr]) {
            numCuts++;
            bPtr += ((lenB - bPtr) / 2);
            choppedB = choppedB / 2;

            if ((lenB - bPtr) / 2 == 0) {
              if (B[bPtr] > A[aPtr - numCuts] + 1) {
                return A[aPtr - numCuts];
              } else if (B[bPtr] < A[aPtr - numCuts]) {
                return A[aPtr - numCuts + 1];
              } else if (B[bPtr] < A[aPtr - numCuts + 1] && B[bPtr] > A[aPtr - numCuts]) {
                return B[bPtr];
              } else if (B[bPtr] == A[aPtr - numCuts] || B[bPtr] == A[aPtr - numCuts + 1]) {
                return B[bPtr];
              }
            }

            aPtr -= ((lenB) - bPtr) / 2;
          }
        }
      }
    }
    return 100000000;
  }
Beispiel #16
0
    @Override
    public void update(double t) {
      if (getTimeRemaining(t) > 0) {

        edu.cmu.cs.stage3.math.Matrix44 asSeenByTrans =
            m_asSeenBy.getTransformation(subject.getWorld());
        ((edu.cmu.cs.stage3.alice.core.Transformable) m_asSeenBy)
            .standUpRightNow(subject.getWorld());

        double portion = getTimeElapsed(t) / (getTimeElapsed(t) + getTimeRemaining(t));

        if (portion <= 1.0) {
          double x;
          double y;
          double z;
          double dx;
          double dy;
          double dz;

          // get the appropriate position
          x = m_xHermite.evaluate(portion);
          y = m_yHermite.evaluate(portion);
          z = m_zHermite.evaluate(portion);

          subject.setPositionRightNow(x, y, z, m_asSeenBy);

          // face the direction you are moving
          dx = m_xHermite.evaluateDerivative(portion);
          // dy = m_yHermite.evaluateDerivative(portion);
          dy = 0.0;
          dz = m_zHermite.evaluateDerivative(portion);

          if (!(dx == 0 && dy == 0 && dz == 0)) {
            Matrix33 orient = new Matrix33();
            orient.setForwardUpGuide(
                new javax.vecmath.Vector3d(dx, dy, dz), new javax.vecmath.Vector3d(0, 1, 0));
            // System.out.println(m_asSeenBy);
            subject.setOrientationRightNow(orient, m_asSeenBy);
            // subject.s
          } else {
            // System.out.println("deriv 0");
          }

          if (timePerStep == -1) {
            if (!Double.isNaN(duration.doubleValue())) {
              timePerStep = duration.doubleValue() / numberOfSteps;
            } else {
              timePerStep = 1.0 / stepSpeed.doubleValue();
            }
          }

          // int stepNumber = (int)java.lang.Math.ceil(
          // getTimeElapsed(t) * stepSpeed.doubleValue()) - 1;
          int stepNumber = (int) java.lang.Math.ceil(getTimeElapsed(t) * (1.0 / timePerStep)) - 1;
          if (stepNumber == -1) {
            stepNumber = 0;
          }
          if (stepNumber == numberOfSteps) {
            stepNumber -= 1;
          }
          double portionOfStep = (getTimeElapsed(t) - stepNumber * timePerStep) / timePerStep;

          if (portionOfStep > 1.0) {
            portionOfStep = 1.0;
          }

          boolean lastStep = false;
          if (stepNumber == numberOfSteps - 1) {
            lastStep = true;
          }

          if (stepNumber % 2 == 0) {
            stepRight(portionOfStep, lastStep);
          } else {
            stepLeft(portionOfStep, lastStep);
          }

          super.update(t);
        }
        ((edu.cmu.cs.stage3.alice.core.Transformable) m_asSeenBy)
            .setTransformationRightNow(asSeenByTrans, subject.getWorld());
      }
    }
Beispiel #17
0
  private Object interpretFunction(Functions function, Sprite sprite) {
    Object left = null;
    Object right = null;

    Double doubleValueOfLeftChild = null;
    Double doubleValueOfRightChild = null;

    if (leftChild != null) {
      left = leftChild.interpretRecursive(sprite);
      if (left instanceof String) {
        try {
          doubleValueOfLeftChild = Double.valueOf((String) left);
        } catch (NumberFormatException numberFormatException) {
          Log.d(getClass().getSimpleName(), "Couldn't parse String", numberFormatException);
        }
      } else {
        doubleValueOfLeftChild = (Double) left;
      }
    }

    if (rightChild != null) {
      right = rightChild.interpretRecursive(sprite);
      if (right instanceof String) {
        try {
          doubleValueOfRightChild = Double.valueOf((String) right);
        } catch (NumberFormatException numberFormatException) {
          Log.d(getClass().getSimpleName(), "Couldn't parse String", numberFormatException);
        }
      } else {
        doubleValueOfRightChild = (Double) right;
      }
    }

    switch (function) {
      case SIN:
        return doubleValueOfLeftChild == null
            ? 0d
            : java.lang.Math.sin(Math.toRadians(doubleValueOfLeftChild));
      case COS:
        return doubleValueOfLeftChild == null
            ? 0d
            : java.lang.Math.cos(Math.toRadians(doubleValueOfLeftChild));
      case TAN:
        return doubleValueOfLeftChild == null
            ? 0d
            : java.lang.Math.tan(Math.toRadians(doubleValueOfLeftChild));
      case LN:
        return doubleValueOfLeftChild == null ? 0d : java.lang.Math.log(doubleValueOfLeftChild);
      case LOG:
        return doubleValueOfLeftChild == null ? 0d : java.lang.Math.log10(doubleValueOfLeftChild);
      case SQRT:
        return doubleValueOfLeftChild == null ? 0d : java.lang.Math.sqrt(doubleValueOfLeftChild);
      case RAND:
        return (doubleValueOfLeftChild == null || doubleValueOfRightChild == null)
            ? 0d
            : interpretFunctionRand(doubleValueOfLeftChild, doubleValueOfRightChild);
      case ABS:
        return doubleValueOfLeftChild == null ? 0d : java.lang.Math.abs(doubleValueOfLeftChild);
      case ROUND:
        return doubleValueOfLeftChild == null
            ? 0d
            : (double) java.lang.Math.round(doubleValueOfLeftChild);
      case PI:
        return java.lang.Math.PI;
      case MOD:
        return (doubleValueOfLeftChild == null || doubleValueOfRightChild == null)
            ? 0d
            : interpretFunctionMod(doubleValueOfLeftChild, doubleValueOfRightChild);
      case ARCSIN:
        return doubleValueOfLeftChild == null
            ? 0d
            : java.lang.Math.toDegrees(Math.asin(doubleValueOfLeftChild));
      case ARCCOS:
        return doubleValueOfLeftChild == null
            ? 0d
            : java.lang.Math.toDegrees(Math.acos(doubleValueOfLeftChild));
      case ARCTAN:
        return doubleValueOfLeftChild == null
            ? 0d
            : java.lang.Math.toDegrees(Math.atan(doubleValueOfLeftChild));
      case EXP:
        return doubleValueOfLeftChild == null ? 0d : java.lang.Math.exp(doubleValueOfLeftChild);
      case POWER:
        return (doubleValueOfLeftChild == null || doubleValueOfRightChild == null)
            ? 0d
            : java.lang.Math.pow(doubleValueOfLeftChild, doubleValueOfRightChild);
      case FLOOR:
        return doubleValueOfLeftChild == null ? 0d : java.lang.Math.floor(doubleValueOfLeftChild);
      case CEIL:
        return doubleValueOfLeftChild == null ? 0d : java.lang.Math.ceil(doubleValueOfLeftChild);
      case MAX:
        return (doubleValueOfLeftChild == null || doubleValueOfRightChild == null)
            ? 0d
            : java.lang.Math.max(doubleValueOfLeftChild, doubleValueOfRightChild);
      case MIN:
        return (doubleValueOfLeftChild == null || doubleValueOfRightChild == null)
            ? 0d
            : java.lang.Math.min(doubleValueOfLeftChild, doubleValueOfRightChild);
      case TRUE:
        return 1d;
      case FALSE:
        return 0d;
      case LETTER:
        return interpretFunctionLetter(right, left);
      case LENGTH:
        return interpretFunctionLength(left, sprite);
      case JOIN:
        return interpretFunctionJoin(sprite);
      case ARDUINODIGITAL:
        Arduino arduinoDigital =
            ServiceProvider.getService(CatroidService.BLUETOOTH_DEVICE_SERVICE)
                .getDevice(BluetoothDevice.ARDUINO);
        if (arduinoDigital != null && left != null) {
          if (doubleValueOfLeftChild < 0 || doubleValueOfLeftChild > 13) {
            return 0d;
          }
          return arduinoDigital.getDigitalArduinoPin(doubleValueOfLeftChild.intValue());
        }
        break;
      case ARDUINOANALOG:
        Arduino arduinoAnalog =
            ServiceProvider.getService(CatroidService.BLUETOOTH_DEVICE_SERVICE)
                .getDevice(BluetoothDevice.ARDUINO);
        if (arduinoAnalog != null && left != null) {
          if (doubleValueOfLeftChild < 0 || doubleValueOfLeftChild > 5) {
            return 0d;
          }
          return arduinoAnalog.getAnalogArduinoPin(doubleValueOfLeftChild.intValue());
        }
        break;
      case RASPIDIGITAL:
        RPiSocketConnection connection = RaspberryPiService.getInstance().connection;
        int pin = doubleValueOfLeftChild.intValue();
        try {
          return connection.getPin(pin) ? 1d : 0d;
        } catch (Exception e) {
          Log.e(getClass().getSimpleName(), "RPi: exception during getPin: " + e);
        }
        break;
      case MULTI_FINGER_TOUCHED:
        return TouchUtil.isFingerTouching(doubleValueOfLeftChild.intValue()) ? 1d : 0d;
      case MULTI_FINGER_X:
        return Double.valueOf(TouchUtil.getX(doubleValueOfLeftChild.intValue()));
      case MULTI_FINGER_Y:
        return Double.valueOf(TouchUtil.getY(doubleValueOfLeftChild.intValue()));
      case LIST_ITEM:
        return interpretFunctionListItem(left, sprite);
      case CONTAINS:
        return interpretFunctionContains(right, sprite);
      case NUMBER_OF_ITEMS:
        return interpretFunctionNumberOfItems(left, sprite);
    }
    return 0d;
  }
Beispiel #18
0
  /*
   * This method creates and fills three arrays, Y, Cb, and Cr using the
   * input image.
   */
  private void getYCCArray() {
    int[] values = new int[imageWidth * imageHeight];
    int r;
    int g;
    int b;
    int y;
    int x;

    // In order to minimize the chance that grabPixels will throw an exception
    // it may be necessary to grab some pixels every few scanlines and process
    // those before going for more.  The time expense may be prohibitive.
    // However, for a situation where memory overhead is a concern, this may be
    // the only choice.
    PixelGrabber grabber =
        new PixelGrabber(
            imageobj.getSource(), 0, 0, imageWidth, imageHeight, values, 0, imageWidth);
    MaxHsampFactor = 1;
    MaxVsampFactor = 1;

    for (y = 0; y < NumberOfComponents; y++) {
      MaxHsampFactor = Math.max(MaxHsampFactor, HsampFactor[y]);
      MaxVsampFactor = Math.max(MaxVsampFactor, VsampFactor[y]);
    }

    for (y = 0; y < NumberOfComponents; y++) {
      compWidth[y] =
          ((((imageWidth % 8) != 0)
                      ? (((int) Math.ceil((double) imageWidth / 8.0)) * 8)
                      : imageWidth)
                  / MaxHsampFactor)
              * HsampFactor[y];

      if (compWidth[y] != ((imageWidth / MaxHsampFactor) * HsampFactor[y])) {
        lastColumnIsDummy[y] = true;
      }

      // results in a multiple of 8 for compWidth
      // this will make the rest of the program fail for the unlikely
      // event that someone tries to compress an 16 x 16 pixel image
      // which would of course be worse than pointless
      BlockWidth[y] = (int) Math.ceil((double) compWidth[y] / 8.0);
      compHeight[y] =
          ((((imageHeight % 8) != 0)
                      ? (((int) Math.ceil((double) imageHeight / 8.0)) * 8)
                      : imageHeight)
                  / MaxVsampFactor)
              * VsampFactor[y];

      if (compHeight[y] != ((imageHeight / MaxVsampFactor) * VsampFactor[y])) {
        lastRowIsDummy[y] = true;
      }

      BlockHeight[y] = (int) Math.ceil((double) compHeight[y] / 8.0);
    }

    try {
      if (grabber.grabPixels() != true) {
        try {
          throw new AWTException("Grabber returned false: " + grabber.status());
        } catch (Exception e) {
          String2.log(MustBe.throwableToString(e));
        }
      }
    } catch (InterruptedException e) {
    }

    ;
    float[][] Y = new float[compHeight[0]][compWidth[0]];
    float[][] Cr1 = new float[compHeight[0]][compWidth[0]];
    float[][] Cb1 = new float[compHeight[0]][compWidth[0]];
    float[][] Cb2 = new float[compHeight[1]][compWidth[1]];
    float[][] Cr2 = new float[compHeight[2]][compWidth[2]];
    int index = 0;

    for (y = 0; y < imageHeight; ++y) {
      for (x = 0; x < imageWidth; ++x) {
        r = ((values[index] >> 16) & 0xff);
        g = ((values[index] >> 8) & 0xff);
        b = (values[index] & 0xff);

        // The following three lines are a more correct color conversion but
        // the current conversion technique is sufficient and results in a higher
        // compression rate.
        //                Y[y][x] = 16 + (float)(0.8588*(0.299 * (float)r + 0.587 * (float)g + 0.114
        // * (float)b ));
        //                Cb1[y][x] = 128 + (float)(0.8784*(-0.16874 * (float)r - 0.33126 * (float)g
        // + 0.5 * (float)b));
        //                Cr1[y][x] = 128 + (float)(0.8784*(0.5 * (float)r - 0.41869 * (float)g -
        // 0.08131 * (float)b));
        Y[y][x] = (float) (((0.299 * (float) r) + (0.587 * (float) g) + (0.114 * (float) b)));
        Cb1[y][x] =
            128 + (float) (((-0.16874 * (float) r) - (0.33126 * (float) g) + (0.5 * (float) b)));
        Cr1[y][x] =
            128 + (float) (((0.5 * (float) r) - (0.41869 * (float) g) - (0.08131 * (float) b)));
        index++;
      }
    }

    // Need a way to set the H and V sample factors before allowing downsampling.
    // For now (04/04/98) downsampling must be hard coded.
    // Until a better downsampler is implemented, this will not be done.
    // Downsampling is currently supported.  The downsampling method here
    // is a simple box filter.
    Components[0] = Y;

    //        Cb2 = DownSample(Cb1, 1);
    Components[1] = Cb1;

    //        Cr2 = DownSample(Cr1, 2);
    Components[2] = Cr1;
  }
Beispiel #19
0
 /**
  * First get rid of any rounding errors before passing the value to {@link Math#ceil(double)};
  *
  * @param val to be ceiled
  * @return the {@link Math#ceil(double)} of the cleaned value.
  */
 private final double ceil(double val) {
   val = removeImprecisions(val);
   return Math.ceil(val);
 }