Example usage for java.lang Double intValue

List of usage examples for java.lang Double intValue

Introduction

In this page you can find the example usage for java.lang Double intValue.

Prototype

public int intValue() 

Source Link

Document

Returns the value of this Double as an int after a narrowing primitive conversion.

Usage

From source file:org.medici.bia.service.peoplebase.PeopleBaseServiceImpl.java

/**
 * {@inheritDoc}//from   w  w  w  .j a v a2  s .c om
 */
@Override
public void cropPortraitPerson(Integer personId, Double x, Double y, Double x2, Double y2, Double width,
        Double height) throws ApplicationThrowable {
    try {
        People person = getPeopleDAO().find(personId);

        if ((person != null) && (person.getPortrait())) {
            String portraitPath = ApplicationPropertyManager.getApplicationProperty("portrait.person.path");
            File portraitFile = new File(portraitPath + "/" + person.getPortraitImageName());
            BufferedImage bufferedImage = ImageIO.read(portraitFile);
            //here code for cropping... TO BE TESTED...
            BufferedImage croppedBufferedImage = bufferedImage.getSubimage(x.intValue(), y.intValue(),
                    width.intValue(), height.intValue());
            ImageIO.write(croppedBufferedImage, "jpg", portraitFile);
        }
    } catch (Throwable th) {
        throw new ApplicationThrowable(th);
    }

}

From source file:org.sakaiproject.gradebook.gwt.sakai.hibernate.GradebookToolServiceImpl.java

public Long createCategory(final Long gradebookId, final String name, final Double weight,
        final Integer dropLowest, final Boolean equalWeightAssignments, final Boolean isUnweighted,
        final Boolean isExtraCredit, final Integer categoryOrder, final Boolean isEnforcePointWeighting)
        throws ConflictingCategoryNameException, StaleObjectModificationException {
    HibernateCallback hc = new HibernateCallback() {
        public Object doInHibernate(Session session) throws HibernateException {
            Gradebook gb = (Gradebook) session.load(Gradebook.class, gradebookId);
            List conflictList = ((List) session.createQuery(
                    "select ca from Category as ca where ca.name = ? and ca.gradebook = ? and (ca.removed=false or ca.removed is null) ")
                    .setString(0, name).setEntity(1, gb).list());
            int numNameConflicts = conflictList.size();
            if (numNameConflicts > 0) {
                throw new ConflictingCategoryNameException(
                        "You cannot save multiple categories in a gradebook with the same name");
            }/*from ww w  .  j ava  2s  . com*/
            if (weight != null) {
                if (weight.intValue() > 1 || weight.intValue() < 0) {
                    throw new IllegalArgumentException(
                            "weight for category is greater than 1 or less than 0 in createCategory of BaseHibernateManager");
                }
            }

            int dl = dropLowest == null ? 0 : dropLowest.intValue();

            Category ca = new Category();
            ca.setGradebook(gb);
            ca.setName(name);
            ca.setWeight(weight);
            ca.setDrop_lowest(dl);
            ca.setEqualWeightAssignments(equalWeightAssignments);
            ca.setUnweighted(isUnweighted);
            ca.setRemoved(false);
            ca.setExtraCredit(isExtraCredit);
            ca.setCategoryOrder(categoryOrder);
            ca.setEnforcePointWeighting(isEnforcePointWeighting);

            Long id = (Long) session.save(ca);

            return id;
        }
    };

    return (Long) getHibernateTemplate().execute(hc);
}

From source file:com.aerohive.nms.web.config.lbs.services.HmFolderServiceImpl.java

private void setFolderImageSize(HmFolder folder) throws Exception {
    String backgroundImage = folder.getBackground();
    if (StringUtils.isEmpty(backgroundImage)) {
        // no background image attached
        Double sizeX = folder.getMetricWidth();
        Double sizeY = folder.getMetricHeight();
        if (null != sizeX && null != sizeY && sizeX.doubleValue() > 0 && sizeY.doubleValue() > 0) {
            folder.setImageWidth(sizeX.intValue());
            folder.setImageHeight(sizeY.intValue());
        } else {// ww w.j  a va  2 s. c o  m
            folder.setImageWidth(0);
            folder.setImageHeight(0);
        }
    } else {
        // background image attached
        HmImageMetadata o = imageRep.findByImageNameAndOwnerId(backgroundImage, folder.getOwnerId());
        if (null != o) {
            folder.setImageWidth(o.getImageWidth());
            folder.setImageHeight(o.getImageHeight());
            logger.info("Set " + folder.getName() + " background image Height : " + o.getImageHeight()
                    + "  Width : " + o.getImageWidth());
            // calculate metric height if metric width assigned
            if (null != folder.getMetricWidth()) {
                folder.setMetricHeight(
                        folder.getMetricWidth() * folder.getImageHeight() / folder.getImageWidth());
            } else {
                folder.setMetricHeight(null);
            }
        } else {
            folder.setImageWidth(0);
            folder.setImageHeight(0);
            folder.setMetricWidth(null);
            folder.setMetricHeight(null);
            folder.setBackground(null);
            logger.error("Set " + folder.getName()
                    + " background image Height and width to 0, as no image metadata found with image: "
                    + backgroundImage);
        }
    }
}

From source file:org.sakaiproject.tool.assessment.ui.listener.evaluation.HistogramListener.java

/**
 * Calculate the detailed statistics/*from  w  w w . ja v  a  2  s.  c  om*/
 * 
 * This will populate the HistogramScoresBean with the data associated with the
 * particular versioned assessment based on the publishedId.
 *
 * Some of this code will change when we move this to Hibernate persistence.
 * @param publishedId String
 * @param histogramScores TotalScoresBean
 * @return boolean true if successful
 */
public boolean histogramScores(HistogramScoresBean histogramScores, TotalScoresBean totalScores) {
    DeliveryBean delivery = (DeliveryBean) ContextUtil.lookupBean("delivery");
    String publishedId = totalScores.getPublishedId();
    if (publishedId.equals("0")) {
        publishedId = (String) ContextUtil.lookupParam("publishedAssessmentId");
    }
    String actionString = ContextUtil.lookupParam("actionString");
    // See if this can fix SAK-16437
    if (actionString != null && !actionString.equals("reviewAssessment")) {
        // Shouldn't come to here. The action should either be null or reviewAssessment.
        // If we can confirm this is where causes SAK-16437, ask UX for a new screen with warning message.  
        log.error("SAK-16437 happens!! publishedId = " + publishedId + ", agentId = "
                + AgentFacade.getAgentString());
    }

    ResourceLoader rb = new ResourceLoader("org.sakaiproject.tool.assessment.bundle.EvaluationMessages");
    ResourceLoader rbEval = new ResourceLoader("org.sakaiproject.tool.assessment.bundle.EvaluationMessages");
    String assessmentName = "";

    histogramScores.clearLowerQuartileStudents();
    histogramScores.clearUpperQuartileStudents();

    String which = histogramScores.getAllSubmissions();
    if (which == null && totalScores.getAllSubmissions() != null) {
        // use totalscore's selection
        which = totalScores.getAllSubmissions();
        histogramScores.setAllSubmissions(which); // changed submission pulldown
    }

    histogramScores.setItemId(ContextUtil.lookupParam("itemId"));
    histogramScores.setHasNav(ContextUtil.lookupParam("hasNav"));

    GradingService delegate = new GradingService();
    PublishedAssessmentService pubService = new PublishedAssessmentService();
    List<AssessmentGradingData> allscores = delegate.getTotalScores(publishedId, which);
    //set the ItemGradingData manually here. or we cannot
    //retrieve it later.
    for (AssessmentGradingData agd : allscores) {
        agd.setItemGradingSet(delegate.getItemGradingSet(String.valueOf(agd.getAssessmentGradingId())));
    }
    if (allscores.isEmpty()) {
        // Similar case in Bug 1537, but clicking Statistics link instead of assignment title.
        // Therefore, redirect the the same page.
        delivery.setOutcome("reviewAssessmentError");
        delivery.setActionString(actionString);
        return true;
    }

    histogramScores.setPublishedId(publishedId);
    int callerName = TotalScoresBean.CALLED_FROM_HISTOGRAM_LISTENER;
    String isFromStudent = (String) ContextUtil.lookupParam("isFromStudent");
    if (isFromStudent != null && "true".equals(isFromStudent)) {
        callerName = TotalScoresBean.CALLED_FROM_HISTOGRAM_LISTENER_STUDENT;
    }

    // get the Map of all users(keyed on userid) belong to the selected sections 
    // now we only include scores of users belong to the selected sections
    Map useridMap = null;
    ArrayList scores = new ArrayList();
    // only do section filter if it's published to authenticated users
    if (totalScores.getReleaseToAnonymous()) {
        scores.addAll(allscores);
    } else {
        useridMap = totalScores.getUserIdMap(callerName);
        Iterator allscores_iter = allscores.iterator();
        while (allscores_iter.hasNext()) {
            AssessmentGradingData data = (AssessmentGradingData) allscores_iter.next();
            String agentid = data.getAgentId();
            if (useridMap.containsKey(agentid)) {
                scores.add(data);
            }
        }
    }
    Iterator iter = scores.iterator();
    //log.info("Has this many agents: " + scores.size());

    if (!iter.hasNext()) {
        log.info("Students who have submitted may have been removed from this site");
        return false;
    }

    // here scores contain AssessmentGradingData 
    Map assessmentMap = getAssessmentStatisticsMap(scores);

    /*
     * find students in upper and lower quartiles 
     * of assessment scores
     */
    ArrayList submissionsSortedForDiscrim = new ArrayList(scores);
    boolean anonymous = Boolean.valueOf(totalScores.getAnonymous()).booleanValue();
    Collections.sort(submissionsSortedForDiscrim,
            new AssessmentGradingComparatorByScoreAndUniqueIdentifier(anonymous));
    int numSubmissions = scores.size();
    //int percent27 = ((numSubmissions*10*27/100)+5)/10; // rounded
    int percent27 = numSubmissions * 27 / 100; // rounded down
    if (percent27 == 0)
        percent27 = 1;
    for (int i = 0; i < percent27; i++) {
        histogramScores.addToLowerQuartileStudents(
                ((AssessmentGradingData) submissionsSortedForDiscrim.get(i)).getAgentId());
        histogramScores.addToUpperQuartileStudents(
                ((AssessmentGradingData) submissionsSortedForDiscrim.get(numSubmissions - 1 - i)).getAgentId());
    }

    PublishedAssessmentIfc pub = (PublishedAssessmentIfc) pubService.getPublishedAssessment(publishedId, false);

    if (pub != null) {
        if (actionString != null && actionString.equals("reviewAssessment")) {
            if (AssessmentIfc.RETRACT_FOR_EDIT_STATUS.equals(pub.getStatus())) {
                // Bug 1547: If this is during review and the assessment is retracted for edit now, 
                // set the outcome to isRetractedForEdit2 error page.
                delivery.setOutcome("isRetractedForEdit2");
                delivery.setActionString(actionString);
                return true;
            } else {
                delivery.setOutcome("histogramScores");
                delivery.setSecureDeliveryHTMLFragment("");
                delivery.setBlockDelivery(false);
                SecureDeliveryServiceAPI secureDelivery = SamigoApiFactory.getInstance()
                        .getSecureDeliveryServiceAPI();
                if (secureDelivery.isSecureDeliveryAvaliable()) {

                    String moduleId = pub.getAssessmentMetaDataByLabel(SecureDeliveryServiceAPI.MODULE_KEY);
                    if (moduleId != null && !SecureDeliveryServiceAPI.NONE_ID.equals(moduleId)) {

                        HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance()
                                .getExternalContext().getRequest();
                        PhaseStatus status = secureDelivery.validatePhase(moduleId, Phase.ASSESSMENT_REVIEW,
                                pub, request);
                        delivery.setSecureDeliveryHTMLFragment(secureDelivery.getHTMLFragment(moduleId, pub,
                                request, Phase.ASSESSMENT_REVIEW, status, new ResourceLoader().getLocale()));
                        if (PhaseStatus.FAILURE == status) {
                            delivery.setOutcome("secureDeliveryError");
                            delivery.setActionString(actionString);
                            delivery.setBlockDelivery(true);
                            return true;
                        }
                    }
                }
            }
        }

        boolean showObjectivesColumn = Boolean
                .parseBoolean(pub.getAssessmentMetaDataByLabel(AssessmentBaseIfc.HASMETADATAFORQUESTIONS));
        Map<String, Double> objectivesCorrect = new HashMap<String, Double>();
        Map<String, Integer> objectivesCounter = new HashMap<String, Integer>();
        Map<String, Double> keywordsCorrect = new HashMap<String, Double>();
        Map<String, Integer> keywordsCounter = new HashMap<String, Integer>();

        assessmentName = pub.getTitle();

        List<? extends SectionDataIfc> parts = pub.getSectionArraySorted();
        histogramScores.setAssesmentParts((List<PublishedSectionData>) parts);
        ArrayList info = new ArrayList();
        Iterator partsIter = parts.iterator();
        int secseq = 1;
        double totalpossible = 0;
        boolean hasRandompart = false;
        boolean isRandompart = false;
        String poolName = null;

        HashMap itemScoresMap = delegate.getItemScores(Long.valueOf(publishedId), Long.valueOf(0), which);
        HashMap itemScores = new HashMap();

        if (totalScores.getReleaseToAnonymous()) {
            // skip section filter if it's published to anonymous users
            itemScores.putAll(itemScoresMap);
        } else {
            if (useridMap == null) {
                useridMap = totalScores.getUserIdMap(callerName);
            }

            for (Iterator it = itemScoresMap.entrySet().iterator(); it.hasNext();) {
                Map.Entry entry = (Map.Entry) it.next();
                Long itemId = (Long) entry.getKey();
                ArrayList itemScoresList = (ArrayList) entry.getValue();

                ArrayList filteredItemScoresList = new ArrayList();
                Iterator itemScoresIter = itemScoresList.iterator();
                // get the Map of all users(keyed on userid) belong to the
                // selected sections

                while (itemScoresIter.hasNext()) {
                    ItemGradingData idata = (ItemGradingData) itemScoresIter.next();
                    String agentid = idata.getAgentId();
                    if (useridMap.containsKey(agentid)) {
                        filteredItemScoresList.add(idata);
                    }
                }
                itemScores.put(itemId, filteredItemScoresList);
            }
        }

        // Iterate through the assessment parts
        while (partsIter.hasNext()) {
            SectionDataIfc section = (SectionDataIfc) partsIter.next();
            String authortype = section.getSectionMetaDataByLabel(SectionDataIfc.AUTHOR_TYPE);
            try {
                if (SectionDataIfc.RANDOM_DRAW_FROM_QUESTIONPOOL.equals(Integer.valueOf(authortype))) {
                    hasRandompart = true;
                    isRandompart = true;
                    poolName = section.getSectionMetaDataByLabel(SectionDataIfc.POOLNAME_FOR_RANDOM_DRAW);
                } else {
                    isRandompart = false;
                    poolName = null;
                }
            } catch (NumberFormatException e) {
                isRandompart = false;
                poolName = null;
            }
            if (section.getSequence() == null)
                section.setSequence(Integer.valueOf(secseq++));
            String title = rb.getString("part") + " " + section.getSequence().toString();
            title += ", " + rb.getString("question") + " ";
            List<ItemDataIfc> itemset = section.getItemArraySortedForGrading();
            int seq = 1;
            Iterator<ItemDataIfc> itemsIter = itemset.iterator();

            // Iterate through the assessment questions (items)
            while (itemsIter.hasNext()) {
                HistogramQuestionScoresBean questionScores = new HistogramQuestionScoresBean();
                questionScores.setNumberOfParts(parts.size());
                //if this part is a randompart , then set randompart = true
                questionScores.setRandomType(isRandompart);
                questionScores.setPoolName(poolName);
                ItemDataIfc item = itemsIter.next();

                if (showObjectivesColumn) {
                    String obj = item.getItemMetaDataByLabel(ItemMetaDataIfc.OBJECTIVE);
                    questionScores.setObjectives(obj);
                    String key = item.getItemMetaDataByLabel(ItemMetaDataIfc.KEYWORD);
                    questionScores.setKeywords(key);
                }

                //String type = delegate.getTextForId(item.getTypeId());
                String type = getType(item.getTypeId().intValue());
                if (item.getSequence() == null)
                    item.setSequence(Integer.valueOf(seq++));

                questionScores.setPartNumber(section.getSequence().toString());
                //set the question label depending on random pools and parts
                if (questionScores.getRandomType() && poolName != null) {
                    if (questionScores.getNumberOfParts() > 1) {
                        questionScores.setQuestionLabelFormat(rb.getString("label_question_part_pool", null));
                    } else {
                        questionScores.setQuestionLabelFormat(rb.getString("label_question_pool", null));
                    }
                } else {
                    if (questionScores.getNumberOfParts() > 1) {
                        questionScores.setQuestionLabelFormat(rb.getString("label_question_part", null));
                    } else {
                        questionScores.setQuestionLabelFormat(rb.getString("label_question", null));
                    }
                }
                questionScores.setQuestionNumber(item.getSequence().toString());
                questionScores.setItemId(item.getItemId());
                questionScores.setTitle(title + item.getSequence().toString() + " (" + type + ")");

                if (item.getTypeId().equals(TypeIfc.EXTENDED_MATCHING_ITEMS)) { // emi question
                    questionScores.setQuestionText(item.getLeadInText());
                } else {
                    questionScores.setQuestionText(item.getText());
                }

                questionScores.setQuestionType(item.getTypeId().toString());
                //totalpossible = totalpossible + item.getScore().doubleValue();
                //ArrayList responses = null;

                //for each question (item) in the published assessment's current part/section
                determineResults(pub, questionScores, (ArrayList) itemScores.get(item.getItemId()));
                questionScores.setTotalScore(item.getScore().toString());

                questionScores.setN("" + numSubmissions);
                questionScores.setItemId(item.getItemId());
                Set studentsWithAllCorrect = questionScores.getStudentsWithAllCorrect();
                Set studentsResponded = questionScores.getStudentsResponded();
                if (studentsWithAllCorrect == null || studentsResponded == null
                        || studentsWithAllCorrect.isEmpty() || studentsResponded.isEmpty()) {
                    questionScores.setPercentCorrectFromUpperQuartileStudents("0");
                    questionScores.setPercentCorrectFromLowerQuartileStudents("0");
                    questionScores.setDiscrimination("0.0");
                } else {
                    int percent27ForThisQuestion = percent27;
                    Set<String> upperQuartileStudents = histogramScores.getUpperQuartileStudents().keySet();
                    Set<String> lowerQuartileStudents = histogramScores.getLowerQuartileStudents().keySet();
                    if (isRandompart) {
                        //we need to calculate the 27% upper and lower
                        //per question for the people that actually answered
                        //this question.
                        upperQuartileStudents = new HashSet<String>();
                        lowerQuartileStudents = new HashSet<String>();
                        percent27ForThisQuestion = questionScores.getNumResponses() * 27 / 100;
                        if (percent27ForThisQuestion == 0)
                            percent27ForThisQuestion = 1;
                        if (questionScores.getNumResponses() != 0) {
                            //need to only get gradings for students that answered this question
                            List<AssessmentGradingData> filteredGradings = filterGradingData(
                                    submissionsSortedForDiscrim, questionScores.getItemId());

                            // SAM-2228: loop control issues because of unsynchronized collection access
                            int filteredGradingsSize = filteredGradings.size();
                            percent27ForThisQuestion = filteredGradingsSize * 27 / 100;

                            for (int i = 0; i < percent27ForThisQuestion; i++) {
                                lowerQuartileStudents
                                        .add(((AssessmentGradingData) filteredGradings.get(i)).getAgentId());
                                //
                                upperQuartileStudents.add(((AssessmentGradingData) filteredGradings
                                        .get(filteredGradingsSize - 1 - i)).getAgentId());
                            }
                        }
                    }
                    if (questionScores.getNumResponses() != 0) {
                        int numStudentsWithAllCorrectFromUpperQuartile = 0;
                        int numStudentsWithAllCorrectFromLowerQuartile = 0;
                        Iterator studentsIter = studentsWithAllCorrect.iterator();
                        while (studentsIter.hasNext()) {
                            String agentId = (String) studentsIter.next();
                            if (upperQuartileStudents.contains(agentId)) {
                                numStudentsWithAllCorrectFromUpperQuartile++;
                            }
                            if (lowerQuartileStudents.contains(agentId)) {
                                numStudentsWithAllCorrectFromLowerQuartile++;
                            }
                        }

                        double percentCorrectFromUpperQuartileStudents = ((double) numStudentsWithAllCorrectFromUpperQuartile
                                / (double) percent27ForThisQuestion) * 100d;

                        double percentCorrectFromLowerQuartileStudents = ((double) numStudentsWithAllCorrectFromLowerQuartile
                                / (double) percent27ForThisQuestion) * 100d;

                        questionScores.setPercentCorrectFromUpperQuartileStudents(
                                Integer.toString((int) percentCorrectFromUpperQuartileStudents));
                        questionScores.setPercentCorrectFromLowerQuartileStudents(
                                Integer.toString((int) percentCorrectFromLowerQuartileStudents));

                        double discrimination = ((double) numStudentsWithAllCorrectFromUpperQuartile
                                - (double) numStudentsWithAllCorrectFromLowerQuartile)
                                / (double) percent27ForThisQuestion;

                        // round to 2 decimals
                        if (discrimination > 999999 || discrimination < -999999) {
                            questionScores.setDiscrimination("NaN");
                        } else {
                            discrimination = ((int) (discrimination * 100.00d)) / 100.00d;
                            questionScores.setDiscrimination(Double.toString(discrimination));
                        }
                    } else {
                        questionScores.setPercentCorrectFromUpperQuartileStudents(rbEval.getString("na"));
                        questionScores.setPercentCorrectFromLowerQuartileStudents(rbEval.getString("na"));
                        questionScores.setDiscrimination(rbEval.getString("na"));
                    }
                }

                info.add(questionScores);
            } // end-while - items

            totalpossible = pub.getTotalScore().doubleValue();

        } // end-while - parts
        histogramScores.setInfo(info);
        histogramScores.setRandomType(hasRandompart);

        int maxNumOfAnswers = 0;
        List<HistogramQuestionScoresBean> detailedStatistics = new ArrayList<HistogramQuestionScoresBean>();
        Iterator infoIter = info.iterator();
        while (infoIter.hasNext()) {
            HistogramQuestionScoresBean questionScores = (HistogramQuestionScoresBean) infoIter.next();
            if (questionScores.getQuestionType().equals(TypeIfc.MULTIPLE_CHOICE.toString())
                    || questionScores.getQuestionType().equals(TypeIfc.MULTIPLE_CORRECT.toString())
                    || questionScores.getQuestionType().equals(TypeIfc.MULTIPLE_CHOICE_SURVEY.toString())
                    || questionScores.getQuestionType().equals(TypeIfc.TRUE_FALSE.toString())
                    || questionScores.getQuestionType().equals(TypeIfc.FILL_IN_BLANK.toString())
                    || questionScores.getQuestionType().equals(TypeIfc.MATCHING.toString())
                    || questionScores.getQuestionType().equals(TypeIfc.FILL_IN_NUMERIC.toString())
                    || questionScores.getQuestionType()
                            .equals(TypeIfc.MULTIPLE_CORRECT_SINGLE_SELECTION.toString())
                    || questionScores.getQuestionType().equals(TypeIfc.CALCULATED_QUESTION.toString())
                    || questionScores.getQuestionType().equals("16")) {
                questionScores.setShowIndividualAnswersInDetailedStatistics(true);
                detailedStatistics.add(questionScores);
                if (questionScores.getHistogramBars() != null) {
                    maxNumOfAnswers = questionScores.getHistogramBars().length > maxNumOfAnswers
                            ? questionScores.getHistogramBars().length
                            : maxNumOfAnswers;
                }
            }

            if (showObjectivesColumn) {
                // Get the percentage correct by objective
                String obj = questionScores.getObjectives();
                if (obj != null && !"".equals(obj)) {
                    String[] objs = obj.split(",");
                    for (int i = 0; i < objs.length; i++) {

                        // SAM-2508 set a default value to avoid the NumberFormatException issues
                        Double pctCorrect = 0.0d;
                        Double newAvg = 0.0d;
                        int divisor = 1;

                        try {
                            if (questionScores.getPercentCorrect() != null
                                    && !"N/A".equalsIgnoreCase(questionScores.getPercentCorrect())) {
                                pctCorrect = Double.parseDouble(questionScores.getPercentCorrect());
                            }
                        } catch (NumberFormatException nfe) {
                            log.error("NFE when looking at metadata and objectives", nfe);
                        }

                        if (objectivesCorrect.get(objs[i]) != null) {
                            Double objCorrect = objectivesCorrect.get(objs[i]);
                            divisor = objCorrect.intValue() + 1;

                            newAvg = objCorrect + ((pctCorrect - objCorrect) / divisor);
                            newAvg = new BigDecimal(newAvg).setScale(2, RoundingMode.HALF_UP).doubleValue();
                        } else {
                            newAvg = new BigDecimal(pctCorrect).setScale(2, RoundingMode.HALF_UP).doubleValue();
                        }

                        objectivesCounter.put(objs[i], divisor);
                        objectivesCorrect.put(objs[i], newAvg);
                    }
                }

                // Get the percentage correct by keyword
                String key = questionScores.getKeywords();
                if (key != null && !"".equals(key)) {
                    String[] keys = key.split(",");
                    for (int i = 0; i < keys.length; i++) {
                        if (keywordsCorrect.get(keys[i]) != null) {
                            int divisor = keywordsCounter.get(keys[i]) + 1;
                            Double newAvg = keywordsCorrect.get(keys[i])
                                    + ((Double.parseDouble(questionScores.getPercentCorrect())
                                            - keywordsCorrect.get(keys[i])) / divisor);

                            newAvg = new BigDecimal(newAvg).setScale(2, RoundingMode.HALF_UP).doubleValue();

                            keywordsCounter.put(keys[i], divisor);
                            keywordsCorrect.put(keys[i], newAvg);
                        } else {
                            Double newAvg = Double.parseDouble(questionScores.getPercentCorrect());
                            newAvg = new BigDecimal(newAvg).setScale(2, RoundingMode.HALF_UP).doubleValue();

                            keywordsCounter.put(keys[i], 1);
                            keywordsCorrect.put(keys[i], newAvg);
                        }
                    }
                }
            }

            //i.e. for EMI questions we add detailed stats for the whole
            //question as well as for the sub-questions
            if (questionScores.getQuestionType().equals(TypeIfc.EXTENDED_MATCHING_ITEMS.toString())) {
                questionScores.setShowIndividualAnswersInDetailedStatistics(false);
                detailedStatistics.addAll(questionScores.getInfo());

                Iterator subInfoIter = questionScores.getInfo().iterator();
                while (subInfoIter.hasNext()) {
                    HistogramQuestionScoresBean subQuestionScores = (HistogramQuestionScoresBean) subInfoIter
                            .next();
                    if (subQuestionScores.getHistogramBars() != null) {
                        subQuestionScores.setN(questionScores.getN());
                        maxNumOfAnswers = subQuestionScores.getHistogramBars().length > maxNumOfAnswers
                                ? subQuestionScores.getHistogramBars().length
                                : maxNumOfAnswers;
                    }
                }
                /*                 
                                 Object numberOfStudentsWithZeroAnswers = numberOfStudentsWithZeroAnswersForQuestion.get(questionScores.getItemId());
                                 if (numberOfStudentsWithZeroAnswers == null) {
                                    questionScores.setNumberOfStudentsWithZeroAnswers(0);
                                 }
                                 else {
                                    questionScores.setNumberOfStudentsWithZeroAnswers( ((Integer) numberOfStudentsWithZeroAnswersForQuestion.get(questionScores.getItemId())).intValue() );
                                 }
                */
            }

        }
        //VULA-1948: sort the detailedStatistics list by Question Label
        sortQuestionScoresByLabel(detailedStatistics);
        histogramScores.setDetailedStatistics(detailedStatistics);
        histogramScores.setMaxNumberOfAnswers(maxNumOfAnswers);
        histogramScores.setShowObjectivesColumn(showObjectivesColumn);

        if (showObjectivesColumn) {
            List<Entry<String, Double>> objectivesList = new ArrayList<Entry<String, Double>>(
                    objectivesCorrect.entrySet());
            Collections.sort(objectivesList, new Comparator<Entry<String, Double>>() {
                public int compare(Entry<String, Double> e1, Entry<String, Double> e2) {
                    return e1.getKey().compareTo(e2.getKey());
                }
            });
            histogramScores.setObjectives(objectivesList);

            List<Entry<String, Double>> keywordsList = new ArrayList<Entry<String, Double>>(
                    keywordsCorrect.entrySet());

            Collections.sort(keywordsList, new Comparator<Entry<String, Double>>() {
                public int compare(Entry<String, Double> e1, Entry<String, Double> e2) {
                    return e1.getKey().compareTo(e2.getKey());
                }
            });
            histogramScores.setKeywords(keywordsList);
        }

        // test to see if it gets back empty map
        if (assessmentMap.isEmpty()) {
            histogramScores.setNumResponses(0);
        }

        try {
            BeanUtils.populate(histogramScores, assessmentMap);

            // quartiles don't seem to be working, workaround
            histogramScores.setQ1((String) assessmentMap.get("q1"));
            histogramScores.setQ2((String) assessmentMap.get("q2"));
            histogramScores.setQ3((String) assessmentMap.get("q3"));
            histogramScores.setQ4((String) assessmentMap.get("q4"));
            histogramScores.setTotalScore((String) assessmentMap.get("totalScore"));
            histogramScores.setTotalPossibleScore(Double.toString(totalpossible));
            HistogramBarBean[] bars = new HistogramBarBean[histogramScores.getColumnHeight().length];
            for (int i = 0; i < histogramScores.getColumnHeight().length; i++) {
                bars[i] = new HistogramBarBean();
                bars[i].setColumnHeight(Integer.toString(histogramScores.getColumnHeight()[i]));
                bars[i].setNumStudents(histogramScores.getNumStudentCollection()[i]);
                bars[i].setRangeInfo(histogramScores.getRangeCollection()[i]);
                //log.info("Set bar " + i + ": " + bean.getColumnHeight()[i] + ", " + bean.getNumStudentCollection()[i] + ", " + bean.getRangeCollection()[i]);
            }
            histogramScores.setHistogramBars(bars);

            ///////////////////////////////////////////////////////////
            // START DEBUGGING
            /*
              log.info("TESTING ASSESSMENT MAP");
              log.info("assessmentMap: =>");
              log.info(assessmentMap);
              log.info("--------------------------------------------");
              log.info("TESTING TOTALS HISTOGRAM FORM");
              log.info(
              "HistogramScoresForm Form: =>\n" + "bean.getMean()=" +
              bean.getMean() + "\n" +
              "bean.getColumnHeight()[0] (first elem)=" +
              bean.getColumnHeight()[0] + "\n" + "bean.getInterval()=" +
              bean.getInterval() + "\n" + "bean.getLowerQuartile()=" +
              bean.getLowerQuartile() + "\n" + "bean.getMaxScore()=" +
              bean.getMaxScore() + "\n" + "bean.getMean()=" + bean.getMean() +
              "\n" + "bean.getMedian()=" + bean.getMedian() + "\n" +
              "bean.getNumResponses()=" + bean.getNumResponses() + "\n" +
              "bean.getNumStudentCollection()=" +
              bean.getNumStudentCollection() +
              "\n" + "bean.getQ1()=" + bean.getQ1() + "\n" + "bean.getQ2()=" +
              bean.getQ2() + "\n" + "bean.getQ3()=" + bean.getQ3() + "\n" +
              "bean.getQ4()=" + bean.getQ4());
              log.info("--------------------------------------------");
                    
             */
            // END DEBUGGING CODE
            ///////////////////////////////////////////////////////////
        } catch (IllegalAccessException e) {
            log.warn("IllegalAccessException:  unable to populate bean" + e);
        } catch (InvocationTargetException e) {
            log.warn("InvocationTargetException: unable to populate bean" + e);
        }

        histogramScores.setAssessmentName(assessmentName);
    } else {
        log.error("pub is null. publishedId = " + publishedId);
        return false;
    }
    return true;
}

From source file:com.aerohive.nms.web.config.lbs.services.HmFolderServiceImpl.java

private Double getActualGridSize(Double actualSize) {
    int gridCount = 8;
    Double actualGridSize = actualSize / gridCount;
    Double scale = 1.0;// w w  w  . j a v a2s. com
    while (actualGridSize >= 10) {
        actualGridSize = actualGridSize / 10;
        scale *= 10;
    }
    if (actualGridSize > 5.5) {
        actualGridSize = 10 * scale;
    } else if (actualGridSize > 3.2) {
        actualGridSize = 5 * scale;
    } else if (actualGridSize > 1.2) {
        actualGridSize = 2.5F * scale;
    } else {
        actualGridSize = scale;
    }
    if ((int) (actualSize / actualGridSize) > gridCount
            || Math.abs(actualGridSize.intValue() - actualGridSize) > 0) {
        actualGridSize *= 2;
    }

    return actualGridSize;
}

From source file:Logica.Usuario.java

/**
 *
 * @param sol//from w  w w  . j  a  v a 2  s  .c  o  m
 * @param itemsSolicitud
 * @return
 * @throws RemoteException
 *
 * Crea la solicitud
 */
@Override
public Integer crearSolicitud(solicitudPr sol, ArrayList<ItemInventario> itemsSolicitud)
        throws RemoteException {
    EntityManagerFactory emf = Persistence.createEntityManagerFactory("Biot_ServerPU");
    boolean solCreada = false;
    boolean itemsEnviados = false;
    SolicitudPr s = new SolicitudPr();
    SolicitudPrJpaController con = new SolicitudPrJpaController(emf);
    s.setIdSolicitante(sol.getIdSolicitante());
    s.setFecha(new java.util.Date(sol.getFecha().getTimeInMillis()));
    s.setObservaciones(sol.getObservaciones());
    s.setRevisado("NO");
    con.create(s);
    solCreada = true;
    Double numSol = 0.0;
    if (solCreada == true) {
        EntityManager em = emf.createEntityManager();
        Query q = em.createNamedQuery("SolicitudPr.getUltima");
        q.setParameter("id", sol.getIdSolicitante());
        numSol = new Double(q.getResultList().get(0).toString());
        ItxsolJpaController conItems = new ItxsolJpaController(emf);
        for (ItemInventario i : itemsSolicitud) {
            if (i.getCantidadSolicitada() <= 0) {
                itemsEnviados = false;
            } else {
                conItems.create(new Itxsol(new Double(Float.toString(i.getCantidadSolicitada())), numSol,
                        new Item(i.getNumero()), "NO", 0.0));
            }
        }
        itemsEnviados = true;
        TablamostrarJpaController conTabla = new TablamostrarJpaController(emf);
        Tablamostrar tablamostrar = new Tablamostrar();
        tablamostrar.setIdArchivo(numSol);
        tablamostrar.setIdUsuario(sol.getIdSolicitante());
        tablamostrar.setTipoArchivo("Solicitud");
        tablamostrar.setMostrar("SI");
        conTabla.create(tablamostrar);
        tablamostrar.setTipoArchivo("SolicitudRev");
        tablamostrar.setMostrar("SI");
        conTabla.create(tablamostrar);
        tablamostrar.setTipoArchivo("SolicitudNoRev");
        tablamostrar.setMostrar("SI");
        conTabla.create(tablamostrar);
    }
    if (itemsEnviados == false) {
        try {
            con.destroy(numSol);
        } catch (NonexistentEntityException ex) {
            Logger.getLogger(Usuario.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    emf.close();
    return (solCreada && itemsEnviados) ? numSol.intValue() : 0;
}

From source file:de.innovationgate.webgate.api.jdbc.WGDatabaseImpl.java

private int determinePatchLevel(JDBCConnectionProvider connProvider) {
    int patchLevel = 0;
    Statement stmt = null;/* w  ww  .  j  av  a 2  s  .c  om*/
    ResultSet res = null;
    try {
        stmt = connProvider.getConnection().createStatement();
        res = stmt.executeQuery(
                "SELECT datatype, numbervalue, textvalue FROM extensiondata WHERE entity_id IS NULL AND name='"
                        + DBMETA_PATCH_LEVEL.toLowerCase() + "'");
        if (res.next()) {
            int type = res.getInt(1);
            Double numberValue = res.getDouble(2);
            String textValue = res.getString(3);
            if (type == WGDocumentImpl.ITEMTYPE_NUMBER) {
                patchLevel = numberValue.intValue();
            } else if (type == WGDocumentImpl.ITEMTYPE_SERIALIZED_XSTREAM) {
                XStream xstream = new XStream(new Dom4JDriver());
                patchLevel = ((Number) xstream.fromXML(textValue)).intValue();
            }
        }
    } catch (Exception e) {
        WGFactory.getLogger().error("Exception determining CS5 patch level", e);
    } finally {
        try {
            if (res != null) {
                res.close();
            }

            if (stmt != null) {
                stmt.close();
            }
        } catch (Exception e) {
            WGFactory.getLogger().error("Exception closing resource for CS version determination", e);
        }
    }

    return patchLevel;
}

From source file:com.sr.apps.freightbit.operations.action.OperationsAction.java

public OrderBean transformToOrderFormBean(Orders entity) {

    OrderBean formBean = new OrderBean();

    formBean.setOrderNumber(entity.getOrderNumber());
    //get shipper's name
    Contacts shipperContactName = customerService.findContactById(entity.getShipperContactId());
    Customer customerName = customerService.findCustomerById(shipperContactName.getReferenceId());
    formBean.setCustomerName((customerName.getCustomerName()));
    //formBean.setCustomerName(entity.getShipperCode());
    formBean.setServiceRequirement(entity.getServiceRequirement());
    formBean.setModeOfService(entity.getServiceMode());
    //get consignee name
    Contacts consigneeName = customerService.findContactById(entity.getConsigneeContactId());
    formBean.setConsigneeName(consigneeName.getCompanyName());
    formBean.setConsigneeCode(getFullName(consigneeName.getLastName(), consigneeName.getFirstName(),
            consigneeName.getMiddleName()));
    //formBean.setConsigneeCode(entity.getConsigneeCode());
    formBean.setOrderId(entity.getOrderId());

    List<OrderItems> orderItemsVolume = orderService.findAllItemByOrderId(entity.getOrderId());

    Float orderVolume = 0.F;/* w w  w  . j a v  a 2 s  .  c o m*/

    for (OrderItems orderItemElem : orderItemsVolume) {
        if (orderItemElem.getVolume() != null) {
            orderVolume = orderVolume + orderItemElem.getVolume();
        }
    }

    formBean.setOrderVolumeInt(Math.round(orderVolume)); // For showing the total volume of order items inside booking

    Double orderWeight = 0.0;

    for (OrderItems orderItemElem : orderItemsVolume) {
        if (orderItemElem.getWeight() != null) {
            orderWeight = orderWeight + orderItemElem.getWeight();
        }
    }

    formBean.setOrderWeightInt(orderWeight.intValue()); // For showing the total volume of order items inside booking

    formBean.setOrderStatus(entity.getOrderStatus());
    formBean.setFreightType(entity.getServiceType());

    if (entity.getOriginationPort() != null) {
        formBean.setOriginationPort(entity.getOriginationPort());
    } else if (entity.getServiceMode().equals("DELIVERY")) {
        formBean.setOriginationPort("NOT APPLICABLE");
    } else {
        formBean.setOriginationPort("NONE");
    }

    /*formBean.setOriginationPort(entity.getOriginationPort());*/
    formBean.setModeOfPayment(entity.getPaymentMode());
    formBean.setNotifyBy(entity.getNotificationType());
    formBean.setOrderDate(entity.getOrderDate());
    /*formBean.setDestinationPort(entity.getDestinationPort());*/

    if (entity.getDestinationPort() != null) {
        formBean.setDestinationPort(entity.getDestinationPort());
    } else if (entity.getServiceMode().equals("PICKUP")) {
        formBean.setDestinationPort("NOT APPLICABLE");
    } else {
        formBean.setDestinationPort("NONE");
    }

    formBean.setRates(entity.getRates());
    formBean.setComments(entity.getComments());

    SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");

    if (entity.getPickupDate() != null) {
        /*formBean.setPickupDate(entity.getPickupDate());*/
        formBean.setStrPickupDate(formatter.format(entity.getPickupDate()));
    } else if (entity.getServiceMode().equals("DELIVERY")) {
        formBean.setStrPickupDate("NOT APPLICABLE");
    } else {
        formBean.setStrPickupDate("NONE");
    }

    if (entity.getDeliveryDate() != null) {
        /*formBean.setDeliveryDate(entity.getDeliveryDate());*/
        formBean.setStrDeliveryDate(formatter.format(entity.getDeliveryDate()));
    } else if (entity.getServiceMode().equals("PICKUP")) {
        formBean.setStrDeliveryDate("NOT APPLICABLE");
    } else {
        formBean.setStrDeliveryDate("NONE");
    }

    Contacts contactShipperName = customerService.findContactById(entity.getShipperContactId());

    Customer shipperName = customerService.findCustomerById(contactShipperName.getReferenceId());

    if (shipperName != null) {
        formBean.setCustomerId(shipperName.getCustomerId());
        formBean.setCustomerName(shipperName.getCustomerName());
    }

    //shipper contact info
    Contacts contacts = customerService.findContactById(entity.getShipperContactId());
    contact = new ContactBean();
    contact.setName(getFullName(contacts.getLastName(), contacts.getFirstName(), contacts.getMiddleName()));
    contact.setPhone(contacts.getPhone());
    contact.setEmail(contacts.getEmail());
    contact.setFax(contacts.getFax());
    contact.setMobile(contacts.getMobile());
    formBean.setShipperInfoContact(contact);

    //get shipper address
    if (entity.getShipperAddressId() != null) {
        Address addresses = customerService.findAddressById(entity.getShipperAddressId());
        address = new AddressBean();
        address.setAddress(getAddress(addresses));
        formBean.setShipperInfoAddress(address);
    } else if (entity.getServiceMode().equals("DELIVERY")) {
        address = new AddressBean();
        address.setAddress("NOT APPLICABLE");
        formBean.setShipperInfoAddress(address);
    } else {
        address = new AddressBean();
        address.setAddress("NONE");
        formBean.setShipperInfoAddress(address);
    }

    //consignee Info
    Contacts consigneeContact = customerService.findContactById(entity.getConsigneeContactId());

    contact = new ContactBean();
    contact.setName(getFullName(consigneeContact.getLastName(), consigneeContact.getFirstName(),
            consigneeContact.getMiddleName()));
    contact.setPhone(consigneeContact.getPhone());
    contact.setEmail(consigneeContact.getEmail());
    contact.setFax(consigneeContact.getFax());
    contact.setMobile(consigneeContact.getMobile());
    formBean.setConsigneeInfoContact(contact);

    // consignee address
    if (entity.getConsigneeAddressId() != null) {
        Address consigneeAddress = customerService.findAddressById(entity.getConsigneeAddressId());
        address = new AddressBean();
        address.setAddress(getAddress(consigneeAddress));
        formBean.setConsigneeInfoAddress(address);
    } else if (entity.getServiceMode().equals("PICKUP")) {
        address = new AddressBean();
        address.setAddress("NOT APPLICABLE");
        formBean.setConsigneeInfoAddress(address);
    } else {
        address = new AddressBean();
        address.setAddress("NONE");
        formBean.setConsigneeInfoAddress(address);
    }

    // for consignee contact person
    formBean.setConsigneeContactPersonId(entity.getConsigneeContactPersonId());
    if (entity.getConsigneeContactPersonId() != null) {
        Contacts contactElem = customerService.findContactById(entity.getConsigneeContactPersonId());
        formBean.setConsigneeContactName(contactElem.getFirstName() + " " + contactElem.getMiddleName() + " "
                + contactElem.getLastName());
    }

    List<OrderItems> orderItemEntity = operationsService.findAllOrderItemsByOrderId(entity.getOrderId());

    if (orderItemEntity.size() >= 1) {
        if (orderItemEntity.get(0).getTruckOrigin() == null
                || "".equals(orderItemEntity.get(0).getTruckOrigin())) {
            formBean.setPlateNumberOri("NONE");
        } else {
            Trucks truckEntityOri = vendorService
                    .findTrucksByTruckCode(orderItemEntity.get(0).getTruckOrigin());
            formBean.setPlateNumberOri(truckEntityOri.getPlateNumber());
        }

        if (orderItemEntity.get(0).getTruckDestination() == null
                || "".equals(orderItemEntity.get(0).getTruckDestination())) {
            formBean.setPlateNumberDes("NONE");
        } else {
            Trucks truckEntityDes = vendorService
                    .findTrucksByTruckCode(orderItemEntity.get(0).getTruckDestination());
            formBean.setPlateNumberDes(truckEntityDes.getPlateNumber());
        }
    }

    return formBean;
}

From source file:ome.formats.OMEROMetadataStoreClient.java

public void setLineStrokeWidth(Double strokeWidth, int ROIIndex, int shapeIndex) {
    Line o = getLine(ROIIndex, shapeIndex);
    o.setStrokeWidth(toRType(strokeWidth.intValue()));
}

From source file:ome.formats.OMEROMetadataStoreClient.java

public void setEllipseStrokeWidth(Double strokeWidth, int ROIIndex, int shapeIndex) {
    Ellipse o = getEllipse(ROIIndex, shapeIndex);
    o.setStrokeWidth(toRType(strokeWidth.intValue()));
}