javafx.util.Pair Java Examples

The following examples show how to use javafx.util.Pair. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: BlazeUtilities.java    From constellation with Apache License 2.0 7 votes vote down vote up
/**
 * Display a dialog box to select a color.
 *
 * @param blazeColor The initial value of the color.
 *
 * @return a pair containing 1) if the user pressed OK and 2) the selected
 * blaze color.
 */
public static Pair<Boolean, ConstellationColor> colorDialog(ConstellationColor blazeColor) {
    final PluginParameters dlgParams = new PluginParameters();
    final PluginParameter<ColorParameterType.ColorParameterValue> colorParam = ColorParameterType.build(COLOR_PARAMETER_ID);
    colorParam.setName("Color");
    colorParam.setDescription(BLAZE_COLOR_PARAMETER_ID);
    if (blazeColor != null) {
        colorParam.setColorValue(blazeColor);
    }
    dlgParams.addParameter(colorParam);

    final PluginParametersSwingDialog dialog = new PluginParametersSwingDialog(BLAZE_COLOR_PARAMETER_ID, dlgParams);
    dialog.showAndWait();
    final boolean isOk = PluginParametersDialog.OK.equals(dialog.getResult());
    if (isOk) {
        blazeColor = dlgParams.getColorValue(COLOR_PARAMETER_ID);
    }

    return new Pair<>(isOk, blazeColor);
}
 
Example #2
Source File: CEPRuleMQ.java    From WeEvent with Apache License 2.0 6 votes vote down vote up
public void run() {
    while (!flag) {
        try {
            // if the quene is null,then the thread sleep 1s
            long ideaTime = 1000L;
            Pair<WeEvent, CEPRule> item = systemMessageQueue.poll(ideaTime, TimeUnit.MILLISECONDS);

            if (null != item) {
                log.info("auto redo thread enter,system insert db:{}", item.getValue().getId());
                //  send to  the db
                if (SystemTagEnum.BUILT_IN_SYSTEM.getCode().equals(item.getValue().getSystemTag()) && item.getValue().getFromDestination().equals("#")) {
                    SaveTopicDataUtil.saveTopicData(item.getKey(), item.getValue());
                } else {
                    DataBaseUtil.sendMessageToDB(item.getKey(), item.getValue());
                }
            }
        } catch (InterruptedException e) {
            log.info("insert  fail,{}", e.toString());
            Thread.currentThread().interrupt();
            flag = true;
        }
    }
}
 
Example #3
Source File: InventoryEstimateService.java    From blue-marlin with Apache License 2.0 6 votes vote down vote up
/**
 * This service returns available inventory for a specific targeting channel in a period of time.
 * <p>
 * THIS SERVICE DOES NOT CONSIDER REGION RATIOS. Refer to ERD for details.
 *
 * @param targetingChannel
 * @param ranges
 * @param price
 * @return
 * @throws JSONException
 * @throws ESConnectionException
 * @throws IOException
 */
public InventoryResult aggregateInventory(TargetingChannel targetingChannel, List<Range> ranges, double price) throws JSONException, ESConnectionException, IOException, ExecutionException, InterruptedException
{
    InventoryResult result = new InventoryResult();
    Pair<Impression, Long> inventoryValue = aggregateInventory(targetingChannel, ranges);
    long value = inventoryValue.getKey().countImpressions(price, targetingChannel.getPm());
    long booked = inventoryValue.getValue();
    value -= booked;
    if (value < 0)
    {
        LOGGER.info("Estimate impressions < 0");
        value = 0;
    }
    result.setAvailCount(value);
    LOGGER.info("inventory estimate:{}", value);
    return result;
}
 
Example #4
Source File: InventoryEstimateService.java    From blue-marlin with Apache License 2.0 6 votes vote down vote up
/**
 * This method returns total inventory (ignoring bookings) that is associated with
 * one booking-bucket minus a targeting channel.
 *
 * @param bookingBucket
 * @param query
 * @param day
 * @param bookingsMap
 * @return
 * @throws IOException
 * @throws JSONException
 * @throws ESConnectionException
 */
public Impression getInventoryForBookingBucketMinusQuery(BookingBucket bookingBucket, TargetingChannel query, Day day, Map<String, Booking> bookingsMap) throws IOException, JSONException, ESConnectionException
{
    List<TargetingChannel> Bns = extractTargetingChannelsFromBookingsByBookingIds(bookingsMap, bookingBucket.getAndBookingsIds());
    List<TargetingChannel> Bms = extractTargetingChannelsFromBookingsByBookingIds(bookingsMap, bookingBucket.getMinusBookingsIds());
    if (CommonUtil.isEmpty(Bns))
    {
        LOGGER.info("Bookings of BB have been removed");
        return new Impression();
    }

    Pair<Double, Impression> result = getAverageTBRForBookingBucketMinusQ(day, bookingBucket, Bns, query, bookingsMap.keySet());
    double avgTbr = result.getKey();
    Impression maxImpression = result.getValue();
    Impression impression = getInventoryFor_BNs_Minus_BMs_Minus_q(day, Bns, Bms, query, avgTbr, maxImpression);
    return impression;
}
 
Example #5
Source File: InventoryEstimateService.java    From blue-marlin with Apache License 2.0 6 votes vote down vote up
/**
 * This method returns total inventory (ignoring bookings) that is associated with intersection of
 * one booking-bucket and a targeting channel.
 *
 * @param bookingBucket
 * @param query
 * @param day
 * @param bookingsMap
 * @return
 * @throws IOException
 * @throws JSONException
 * @throws ESConnectionException
 */
public Impression getInventoryForBookingBucketCrossQuery(BookingBucket bookingBucket, TargetingChannel query, Day day, Map<String, Booking> bookingsMap) throws IOException, JSONException, ESConnectionException
{
    List<TargetingChannel> Bns = extractTargetingChannelsFromBookingsByBookingIds(bookingsMap, bookingBucket.getAndBookingsIds());
    List<TargetingChannel> Bms = extractTargetingChannelsFromBookingsByBookingIds(bookingsMap, bookingBucket.getMinusBookingsIds());
    if (CommonUtil.isEmpty(Bns))
    {
        LOGGER.info("Bookings of BB have been removed");
        return new Impression();
    }

    Pair<Double, Impression> result = getAverageTBRForBookingBucketMinusQBar(day, bookingBucket, Bns, query, bookingsMap.keySet());
    double avgTbr = result.getKey();
    Impression maxImpression = result.getValue();
    Impression impression = getInventoryFor_BNs_DOT_q_Minus_BMs(day, Bns, query, Bms, avgTbr, maxImpression);
    return impression;
}
 
Example #6
Source File: InventoryEstimateService.java    From blue-marlin with Apache License 2.0 6 votes vote down vote up
/**
 * This method returns average TBR of a booking-bucket minus targeting channel with its possible maximum value (max of ims/inv).
 *
 * @param day
 * @param bb
 * @param Bns
 * @param query
 * @param validBookingIds
 * @return
 * @throws IOException
 * @throws JSONException
 */
public Pair<Double, Impression> getAverageTBRForBookingBucketMinusQ(Day day, BookingBucket bb, List<TargetingChannel> Bns, TargetingChannel query, Set<String> validBookingIds) throws IOException, JSONException
{
    BookingBucket.AvrTBRInsight avrTBRInsight = bb.getAvrTBRInsight(validBookingIds);
    double nominator = avrTBRInsight.getNominator();
    double denominator = avrTBRInsight.getDenominator();
    Impression maxImpression = avrTBRInsight.getMaxImpression();

    List<TargetingChannel> _tcs = new ArrayList<>();
    _tcs.addAll(Bns);
    _tcs.add(query);

    Impression impression = inventoryEstimateDao.getPredictions_PI_TCs(day, _tcs);
    double tbr = tbrDao.getTBRRatio_PI_TCs(_tcs);
    double impressionValue = impression.getTotal();

    if (impressionValue * tbr > maxImpression.getTotal())
    {
        maxImpression = Impression.multiply(impression, tbr);
    }

    nominator += impressionValue * tbr;
    denominator += impressionValue;

    return buildTBRResponse(nominator, denominator, maxImpression);
}
 
Example #7
Source File: ChartPlugin.java    From chart-fx with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private <T extends InputEvent> void addEventHandlers(final Node node) {
    if (node == null) {
        return;
    }
    for (final Pair<EventType<? extends InputEvent>, EventHandler<? extends InputEvent>> pair : mouseEventHandlers) {
        final EventType<T> type = (EventType<T>) pair.getKey();
        final EventHandler<T> handler = (EventHandler<T>) pair.getValue();
        node.addEventHandler(type, handler);
        node.sceneProperty().addListener((ch, o, n) -> {
            if (o == n) {
                return;
            }
            if (o != null) {
                o.removeEventHandler(type, handler);
            }

            if (n != null) {
                n.addEventHandler(type, handler);
            }
        });
    }
}
 
Example #8
Source File: InventoryEstimateService.java    From blue-marlin with Apache License 2.0 6 votes vote down vote up
/**
 * This method returns average TBR of a booking-bucket minus inverse of a targeting channel with its possible maximum value (max of ims/inv).
 *
 * @param day
 * @param bb
 * @param Bns
 * @param query
 * @param validBookingIds
 * @return
 * @throws IOException
 * @throws JSONException
 * @throws ESConnectionException
 */
public Pair<Double, Impression> getAverageTBRForBookingBucketMinusQBar(Day day, BookingBucket bb, List<TargetingChannel> Bns, TargetingChannel query, Set<String> validBookingIds) throws IOException, JSONException, ESConnectionException
{
    BookingBucket.AvrTBRInsight avrTBRInsight = bb.getAvrTBRInsight(validBookingIds);
    double nominator = avrTBRInsight.getNominator();
    double denominator = avrTBRInsight.getDenominator();
    Impression maxImpression = avrTBRInsight.getMaxImpression();

    Impression impression = inventoryEstimateDao.getPredictions_PI_TCs_DOT_qBAR(day, Bns, query);

    /**
     * Q bar does not have tbr part
     */
    double tbr = tbrDao.getTBRRatio_PI_TCs(Bns);
    double impressionValue = impression.getTotal();

    if (impressionValue * tbr > maxImpression.getTotal())
    {
        maxImpression = Impression.multiply(impression, tbr);
    }

    nominator += impressionValue * tbr;
    denominator += impressionValue;

    return buildTBRResponse(nominator, denominator, maxImpression);
}
 
Example #9
Source File: ProxyUtilities.java    From constellation with Apache License 2.0 6 votes vote down vote up
/**
 * Parse a string representing a proxy of the form "host:port".
 *
 * @param text The proxy representation to be parsed.
 * @param canBeEmpty If true, an empty string will represent "no proxy".
 *
 * @return A Pair containing the host and port.
 */
public static Pair<String, Integer> parseProxy(final String text, final boolean canBeEmpty) {
    if (canBeEmpty && text.isEmpty()) {
        return new Pair<>("", 0);
    }

    final int ix = text.indexOf(':');
    if (ix == -1) {
        return null;
    }

    final String host = text.substring(0, ix).trim();
    if (host.isEmpty()) {
        return null;
    }

    try {
        final int port = Integer.parseInt(text.substring(ix + 1).trim());
        if (port > 0 && port <= 65535) {
            return new Pair<>(host, port);
        }
    } catch (final NumberFormatException ex) {
    }

    return null;
}
 
Example #10
Source File: RestAPITabController.java    From dev-tools with Apache License 2.0 6 votes vote down vote up
@FXML
private void handleSend(ActionEvent actionEvent) {
    clear();
    if (!validateInput()) return;
    RestAPIController.instance().innerTabPane.getSelectionModel().getSelectedItem().setText(tabTitle());
    try {
        Map<String, String> headers = requestHeadersVBox.getChildren().stream().map(n -> {
            List<Node> h = ((HBox) n).getChildren();
            return new Pair<>(((TextField) h.get(0)).getText(), ((TextField) h.get(1)).getText());
        }).filter(p -> !p.getKey().isEmpty() && !p.getValue().isEmpty())
                .collect(Collectors.toMap(Pair::getKey, Pair::getValue));
        RestResponse response = RestService.request(methodComboBox.getValue(),
                uriTextField.getText(),
                headers,
                requestBodyTextArea.getText());
        responseBodyTextArea.setText(response.getBody());
        responseHeadersTextArea.setText(response.getHeaders());
        responseStatusLabel.setText("STATUS: " + response.getStatus() + ", TIME: " + response.getTime() + "ms");
    } catch (Exception e) {
        responseStatusLabel.setText(e.getClass().getName() + ": " + e.getMessage());
    }
}
 
Example #11
Source File: RegexController.java    From dev-tools with Apache License 2.0 6 votes vote down vote up
private void doMatch() {
    regexMessage.setText("");
    if (validateInput()) {
        try {
            RegexResult result = RegexService.match(regexExpression.getText(), regexTarget.getText(),
                    regexFlagsComboBox.getCheckModel().getCheckedItems());
            regexResult.setText(result.getMatchSummary());
            List<Pair<Integer, Integer>> l = result.getFullMatchIndexes();
            if (!l.isEmpty()) {
                regexTarget.deselect();
                regexTarget.moveTo(l.get(0).getKey());
                regexTarget.requestFollowCaret();
                regexTarget.selectRange(l.get(0).getKey(), l.get(0).getValue());
            }
        } catch (Exception e) {
            regexMessage.setText("Invalid regex");
        }
    }
}
 
Example #12
Source File: RegexService.java    From dev-tools with Apache License 2.0 6 votes vote down vote up
public static RegexResult match(String regex, String target, List<String> flagList) {
    Pattern pattern = Pattern.compile(regex, calculateFlags(flagList));
    Matcher matcher = pattern.matcher(target);
    StringBuilder builder = new StringBuilder();
    boolean isGlobal = flagList.contains("global");
    ArrayList<Pair<Integer, Integer>> fullMatch = new ArrayList<>();
    while (matcher.find()) {
        for (int i = 0; i <= matcher.groupCount(); i++) {
            builder.append(i)
                    .append(": ")
                    .append(target, matcher.start(i), matcher.end(i))
                    .append("\n");
        }
        builder.append("\n");
        fullMatch.add(new Pair<>(matcher.start(0), matcher.end(0)));
        if (!isGlobal) break;
    }
    return new RegexResult(builder.toString(), fullMatch);
}
 
Example #13
Source File: Solution2.java    From code with Apache License 2.0 6 votes vote down vote up
public int numSquares(int n) {

        LinkedList<Pair<Integer, Integer>> queue = new LinkedList<Pair<Integer, Integer>>();
        queue.addLast(new Pair<Integer, Integer>(n, 0));

        boolean[] visited = new boolean[n + 1];
        visited[n] = true;

        while (!queue.isEmpty()) {
            Pair<Integer, Integer> front = queue.removeFirst();
            int num = front.getKey();
            int step = front.getValue();

            if (num == 0)
                return step;

            for (int i = 1; num - i * i >= 0; i++)
                if (!visited[num - i * i]) {
                    queue.addLast(new Pair<>(num - i * i, step + 1));
                    visited[num - i * i] = true;
                }
        }

        throw new IllegalStateException("No Solution.");
    }
 
Example #14
Source File: Solution2.java    From code with Apache License 2.0 6 votes vote down vote up
/**
 * 题目地址:https://leetcode-cn.com/problems/sum-of-left-leaves/
 * -------------------------------------------------------------------
 * 思考:
 * -------------------------------------------------------------------
 * 思路:将递归改成迭代
 * -------------------------------------------------------------------
 * 时间复杂度:
 * 空间复杂度:
 */
public int sumOfLeftLeaves(TreeNode root) {
    if (root == null) {
        return 0;
    }
    LinkedList<Pair<TreeNode, Boolean>> stack = new LinkedList<>();
    stack.push(new Pair<>(root, false));

    int sum = 0;
    Boolean flag;
    while (!stack.isEmpty()) {
        Pair<TreeNode, Boolean> pair = stack.pop();
        root = pair.getKey();
        flag = pair.getValue();
        if (flag && root.left == null && root.right == null) {
            sum += root.val;
        }
        if (root.left != null) {
            stack.push(new Pair<>(root.left, true));
        }
        if (root.right != null) {
            stack.push(new Pair<>(root.right, false));
        }
    }
    return sum;
}
 
Example #15
Source File: Solution2.java    From code with Apache License 2.0 6 votes vote down vote up
/**
 * 题目地址:https://leetcode-cn.com/problems/binary-tree-paths/
 * -------------------------------------------------------------------
 * 思考:
 * -------------------------------------------------------------------
 * 思路:先序遍历-迭代
 * -------------------------------------------------------------------
 * 时间复杂度:
 * 空间复杂度:
 */
public List<String> binaryTreePaths(TreeNode root) {
    List<String> result = new ArrayList<>();
    if (root == null) {
        return result;
    }
    LinkedList<Pair<TreeNode, String>> stack = new LinkedList<>();
    stack.push(new Pair<>(root, String.valueOf(root.val)));

    while (!stack.isEmpty()) {
        Pair<TreeNode, String> pair = stack.pop();
        root = pair.getKey();
        String path = pair.getValue();
        if (root.left == null && root.right == null) {
            result.add(path);
        }
        if (root.left != null) {
            stack.push(new Pair<>(root.left, path + "->" + root.left.val));
        }
        if (root.right != null) {
            stack.push(new Pair<>(root.right, path + "->" + root.right.val));
        }
    }
    return result;
}
 
Example #16
Source File: CRUDJobs.java    From WeEvent with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private static void startCEPRule(JobExecutionContext context, String jobName, String type) {

    try {
        CEPRule rule = JsonHelper.json2Object(context.getJobDetail().getJobDataMap().get("rule").toString(), CEPRule.class);
        // ruleMap
        Pair<CEPRule, CEPRule> ruleBak = null;
        if (StringUtils.isEmpty(context.getJobDetail().getJobDataMap().get("ruleBak"))) {
            ruleBak = (Pair<CEPRule, CEPRule>) context.getJobDetail().getJobDataMap().get("ruleBak");
        }
        log.info("{}, {}, {}", rule, jobName, type);
        // check the status,when the status equal 1,then update
        if (RuleStatusEnum.RUNNING.getCode().equals(rule.getStatus()) || RuleStatusEnum.NOT_STARTED.getCode().equals(rule.getStatus()) || RuleStatusEnum.IS_DELETED.getCode().equals(rule.getStatus())) {
            CEPRuleCache.updateCEPRule(rule, ruleBak);
        }
    } catch (BrokerException | SchedulerException e) {
        log.error("BrokerException:{}", e.toString());
    }

}
 
Example #17
Source File: FabricDeployContractUtil.java    From WeEvent with Apache License 2.0 6 votes vote down vote up
private static boolean checkChaincodeIfInstalled(HFClient client, FabricConfig fabricConfig) throws InvalidArgumentException, ProposalException {
    boolean isInstalled = false;
    String topicName = fabricConfig.getTopicName();
    String topicVersion = fabricConfig.getTopicVerison();
    String topicControllerName = fabricConfig.getTopicControllerName();
    String topicControllerVersion = fabricConfig.getTopicControllerVersion();

    List<Pair<String, String>> chaincodes = FabricSDKWrapper.queryInstalledChaincodes(client, FabricSDKWrapper.getPeer(client, fabricConfig));

    for (Pair<String, String> chaincode : chaincodes) {
        if (topicName.equals(chaincode.getKey()) && topicVersion.equals(chaincode.getValue())) {
            log.info("chaincode topic={}:{} already Installed.", topicName, topicVersion);
            isInstalled = true;
            break;
        }
        if (topicControllerName.equals(chaincode.getKey()) && topicControllerVersion.equals(chaincode.getValue())) {
            log.info("chaincode topicController={}:{} already Installed.", topicControllerName, topicControllerVersion);
            isInstalled = true;
            break;
        }
    }
    return isInstalled;
}
 
Example #18
Source File: ExtendEventLister.java    From WeEvent with Apache License 2.0 6 votes vote down vote up
@Override
public void onEvent(WeEvent event) {
    try {
        String content = new String(event.getContent());
        log.info("on event:{},content:{}", event.toString(), content);
        Pair<String, String> type;
        // check the content
        if (JsonHelper.isValid(content)) {
            type = CEPRuleMQ.handleOnEvent(client, event, ruleMap);
        } else {
            type = CEPRuleMQ.handleOnEventOtherPattern(client, event, ruleMap);
        }
        CEPRuleMQ.statisticWeEvent = StatisticCEPRuleUtil.statisticOrderType(statisticWeEvent, type);

    } catch (Exception e) {
        log.error(e.toString());
    }
}
 
Example #19
Source File: CEPRuleMQ.java    From WeEvent with Apache License 2.0 6 votes vote down vote up
private static IWeEventClient getClient(CEPRule rule) {
    try {
        String baseUrl = CommonUtil.urlPage(rule.getBrokerUrl());
        // set group id
        String groupId = rule.getGroupId();
        IWeEventClient client;
        IWeEventClient.Builder builder = IWeEventClient.builder();
        builder.brokerUrl(baseUrl);
        if (null != groupId) {
            builder.groupId(groupId);
            client = builder.build();
            clientGroupMap.put(client, new Pair<>(baseUrl, groupId));
        } else {
            client = builder.build();
            clientGroupMap.put(client, new Pair<>(baseUrl, ""));
        }
        return client;
    } catch (BrokerException e) {
        log.info("BrokerException{}", e.toString());
        return null;
    }

}
 
Example #20
Source File: DataPointTooltip.java    From chart-fx with Apache License 2.0 5 votes vote down vote up
private List<DataPoint> findNeighborPoints(final XYChart chart, final double searchedX) {
    final List<DataPoint> points = new LinkedList<>();
    for (final DataSet dataSet : chart.getAllDatasets()) {
        final Pair<DataPoint, DataPoint> neighborPoints = findNeighborPoints(dataSet, searchedX);
        if (neighborPoints.getKey() != null) {
            points.add(neighborPoints.getKey());
        }
        if (neighborPoints.getValue() != null) {
            points.add(neighborPoints.getValue());
        }
    }
    return points;
}
 
Example #21
Source File: DataPointTooltip.java    From chart-fx with Apache License 2.0 5 votes vote down vote up
/**
 * Handles series that have data sorted or not sorted with respect to X coordinate.
 * 
 * @param dataSet data set
 * @param searchedX x coordinate
 * @return return neighbouring data points
 */
private Pair<DataPoint, DataPoint> findNeighborPoints(final DataSet dataSet, final double searchedX) {
    int prevIndex = -1;
    int nextIndex = -1;
    double prevX = Double.MIN_VALUE;
    double nextX = Double.MAX_VALUE;

    final int nDataCount = dataSet.getDataCount(DataSet.DIM_X);
    final int ny = dataSet.getDataCount(DataSet.DIM_Y); // ensure that the point is within data range. TODO: correctly handle 3D Data
    for (int i = 0, size = nDataCount; i < size; i++) {
        final double currentX = dataSet.get(DataSet.DIM_X, i);

        if (currentX < searchedX) {
            if (prevX < currentX && i < ny) {
                prevIndex = i;
                prevX = currentX;
            }
        } else if (nextX > currentX && i < ny) {
            nextIndex = i;
            nextX = currentX;
        }
    }
    final DataPoint prevPoint = prevIndex == -1 ? null
                                                : new DataPoint(getChart(), dataSet.get(DataSet.DIM_X, prevIndex),
                                                        dataSet.get(DataSet.DIM_Y, prevIndex), getDataLabelSafe(dataSet, prevIndex));
    final DataPoint nextPoint = nextIndex == -1 || nextIndex == prevIndex ? null
                                                                          : new DataPoint(getChart(), dataSet.get(DataSet.DIM_X, nextIndex),
                                                                                  dataSet.get(DataSet.DIM_Y, nextIndex), getDataLabelSafe(dataSet, nextIndex));

    return new Pair<>(prevPoint, nextPoint);
}
 
Example #22
Source File: TreeUtil.java    From code with Apache License 2.0 5 votes vote down vote up
/**
 * 二叉树根节点至叶子节点的最小高度
 *
 * @param root 根节点
 * @return int 高度
 */
public int minDepth(TreeNode root) {
    if (root == null) {
        return 0;
    }
    LinkedList<Pair<TreeNode, Integer>> queue = new LinkedList<>();
    queue.add(new Pair<>(root, 1));

    // 当前深度
    int currentDepth = 0;
    Pair<TreeNode, Integer> pair = null;
    while (!queue.isEmpty()) {
        pair = queue.poll();
        root = pair.getKey();
        currentDepth = pair.getValue();
        // 找到层中第一个叶子节点
        if (root.left == null && root.right == null) {
            break;
        }
        if (root.left != null) {
            queue.add(new Pair<>(root.left, currentDepth + 1));
        }
        if (root.right != null) {
            queue.add(new Pair<>(root.right, currentDepth + 1));
        }

    }
    return currentDepth;
}
 
Example #23
Source File: TreeUtils.java    From code with Apache License 2.0 5 votes vote down vote up
/**
 * 二叉树根节点至叶子节点的最小高度
 *
 * @param root 根节点
 * @return int 高度
 */
public int minDepth(TreeNode root) {
    if (root == null) {
        return 0;
    }
    LinkedList<Pair<TreeNode, Integer>> queue = new LinkedList<>();
    queue.add(new Pair<>(root, 1));

    // 当前深度
    int currentDepth = 0;
    Pair<TreeNode, Integer> pair = null;
    while (!queue.isEmpty()) {
        pair = queue.poll();
        root = pair.getKey();
        currentDepth = pair.getValue();
        // 找到层中第一个叶子节点
        if (root.left == null && root.right == null) {
            break;
        }
        if (root.left != null) {
            queue.add(new Pair<>(root.left, currentDepth + 1));
        }
        if (root.right != null) {
            queue.add(new Pair<>(root.right, currentDepth + 1));
        }

    }
    return currentDepth;
}
 
Example #24
Source File: CommonUtil.java    From WeEvent with Apache License 2.0 5 votes vote down vote up
public static boolean compareMessage(Pair<CEPRule, CEPRule> rules) {
    if (StringUtils.isEmpty(rules)) {
        return false;
    }
    // check the from destination
    return rules.getKey().getFromDestination().equals(rules.getValue().getFromDestination());
}
 
Example #25
Source File: StatisticCEPRuleUtil.java    From WeEvent with Apache License 2.0 5 votes vote down vote up
public static StatisticWeEvent statisticOrderType(StatisticWeEvent statisticWeEvent, Pair<String, String> type) {
    if (!("".equals(type.getValue()))) {
        StatisticRule statisticRule = statisticWeEvent.getStatisticRuleMap().get(type.getValue());
        switch (type.getKey()) {
            case ConstantsHelper.HIT_TIMES:
                statisticRule.setHitTimes(statisticRule.getHitTimes() + 1);
                break;

            case ConstantsHelper.NOT_HIT_TIMES:
                statisticRule.setNotHitTimes(statisticRule.getNotHitTimes() + 1);
                break;

            case ConstantsHelper.WRITE_DB_SUCCESS:
            case ConstantsHelper.PUBLISH_EVENT_SUCCESS:
                statisticRule.setDataFlowSuccess(statisticRule.getDataFlowSuccess() + 1);
                break;

            case ConstantsHelper.WRITE_DB_FAIL:
            case ConstantsHelper.PUBLISH_EVENT_FAIL:
                statisticRule.setDataFlowFail(statisticRule.getDataFlowFail() + 1);
                break;

            case ConstantsHelper.LAST_FAIL_REASON:
                statisticRule.setLastFailReason(statisticRule.getLastFailReason());
                break;

            default:
                log.info("other type:{}", type);
                break;
        }
    }
    return statisticWeEvent;
}
 
Example #26
Source File: SystemFunctionUtil.java    From WeEvent with Apache License 2.0 5 votes vote down vote up
/**
 * @param arr enhance function message
 * @param conditionField original condition details
 * @param payload payload
 * @return condition
 */
public static String replaceCondition(String[][] arr, String conditionField, Map payload) {
    StringBuilder sb = new StringBuilder(conditionField);
    int changePosition = 0;

    for (int i = 0; i < arr.length; i++) {
        Pair<StringBuilder, Integer> ret = replaceCase(sb, conditionField, payload, arr[i], changePosition);
        sb = ret.getKey();
        changePosition = ret.getValue();
    }
    log.info("sb:{}", sb);
    return sb.toString();
}
 
Example #27
Source File: SystemFunctionUtil.java    From WeEvent with Apache License 2.0 5 votes vote down vote up
public static Pair<StringBuilder, Integer> replaceCase(StringBuilder sb, String conditionField, Map
        payload, String[] arr, int changePosition) {
    String type = arr[2];

    Pair<StringBuilder, Integer> ret;
    int changePositionAfter = 0;
    StringBuilder sbTransform = null;
    switch (type) {
        case "now":
        case "currentDate":
        case "currentTime":
            ret = timeOperator(sb, conditionField, arr, changePosition);
            sbTransform = ret.getKey();
            changePositionAfter = ret.getValue();
            break;

        case "abs":
        case "ceil":
        case "floor":
        case "round":
            ret = numberOperator(sb, conditionField, arr, payload, changePosition);
            sbTransform = ret.getKey();
            changePositionAfter = ret.getValue();
            break;

        case "substring":
        case "concat":
        case "trim":
        case "lcase":
            ret = stringOperator(sb, conditionField, arr, payload, changePosition);
            sbTransform = ret.getKey();
            changePositionAfter = ret.getValue();
            break;

        default:
            log.info("conditionField:{}", conditionField);
            break;
    }
    return new Pair<>(sbTransform, changePositionAfter);
}
 
Example #28
Source File: SystemFunctionUtil.java    From WeEvent with Apache License 2.0 5 votes vote down vote up
public static Pair<StringBuilder, Integer> timeOperator(StringBuilder sb, String conditionField, String[] arr, int changePositionString) {
    Integer start = Integer.valueOf(arr[0]);
    Integer end = Integer.valueOf(arr[1]);
    String type = arr[2];
    int changePositionAfter = 0;
    switch (type) {
        case "now":
            sb.replace(start - changePositionString, end - changePositionString, String.valueOf(new Date().getTime()));
            changePositionAfter = changePosition(conditionField, sb.toString());

            break;
        case "currentDate":
            String date = new SimpleDateFormat("yyyyMMdd").format(new Date());
            sb.replace(start - changePositionString, end - changePositionString, date);
            changePositionAfter = changePosition(conditionField, sb.toString());

            break;
        case "currentTime":
            String time = new SimpleDateFormat("HHmmss").format(new Date());
            sb.replace(start - changePositionString, end - changePositionString, time);
            changePositionAfter = changePosition(conditionField, sb.toString());

            break;
        default:
            log.info("conditionField:{}", conditionField);
            break;
    }
    return new Pair<>(sb, changePositionAfter);
}
 
Example #29
Source File: InventoryEstimateService.java    From blue-marlin with Apache License 2.0 5 votes vote down vote up
private Pair<Double, Impression> buildTBRResponse(double nominator, double denominator, Impression maxImpression)
{
    if (CommonUtil.equalNumbers(nominator, denominator))
    {
        return new Pair(1.0, maxImpression);
    }

    if (nominator == 0)
    {
        return new Pair(0.0, maxImpression);
    }

    return new Pair(nominator / denominator, maxImpression);
}
 
Example #30
Source File: EditDataSet.java    From chart-fx with Apache License 2.0 5 votes vote down vote up
protected List<DataPoint> findNeighborPoints(final XYChart chart, final double searchedX) {
    final List<DataPoint> points = new LinkedList<>();
    for (final DataSet dataSet : chart.getAllDatasets()) {
        final Pair<DataPoint, DataPoint> neighborPoints = findNeighborPoints(dataSet, searchedX);
        if (neighborPoints.getKey() != null) {
            points.add(neighborPoints.getKey());
        }
        if (neighborPoints.getValue() != null) {
            points.add(neighborPoints.getValue());
        }
    }
    return points;
}