Example usage for java.lang Math max

List of usage examples for java.lang Math max

Introduction

In this page you can find the example usage for java.lang Math max.

Prototype

@HotSpotIntrinsicCandidate
public static double max(double a, double b) 

Source Link

Document

Returns the greater of two double values.

Usage

From source file:jsdp.app.inventory.univariate.CapacitatedStochasticLotSizing.java

public static void main(String args[]) {

    boolean simulate = true;

    /*******************************************************************
     * Problem parameters//w  w  w  .  j a  va2 s .c  o  m
     */
    double fixedOrderingCost = 40;
    double proportionalOrderingCost = 0;
    double holdingCost = 1;
    double penaltyCost = 2;
    double maxOrderQuantity = 50;

    double[] meanDemand = { 20, 50, 20, 10, 20, 50 };
    double coefficientOfVariation = 0.2;
    double truncationQuantile = 0.99;

    // Random variables

    Distribution[] distributions = IntStream.iterate(0, i -> i + 1).limit(meanDemand.length)
            .mapToObj(i -> new NormalDist(meanDemand[i], meanDemand[i] * coefficientOfVariation))
            //.mapToObj(i -> new PoissonDist(meanDemand[i]))
            .toArray(Distribution[]::new);
    double[] supportLB = IntStream.iterate(0, i -> i + 1).limit(meanDemand.length)
            .mapToDouble(i -> distributions[i].inverseF(1 - truncationQuantile)).toArray();
    double[] supportUB = IntStream.iterate(0, i -> i + 1).limit(meanDemand.length)
            .mapToDouble(i -> distributions[i].inverseF(truncationQuantile)).toArray();
    double initialInventory = 0;

    /*******************************************************************
     * Model definition
     */

    // State space

    double stepSize = 1; //Stepsize must be 1 for discrete distributions
    double minState = -250;
    double maxState = 250;
    StateImpl.setStateBoundaries(stepSize, minState, maxState);

    // Actions

    Function<State, ArrayList<Action>> buildActionList = s -> {
        StateImpl state = (StateImpl) s;
        ArrayList<Action> feasibleActions = new ArrayList<Action>();
        for (double i = state.getInitialState(); i <= StateImpl.getMaxState()
                && i <= state.getInitialState() + maxOrderQuantity; i += StateImpl.getStepSize()) {
            feasibleActions.add(new ActionImpl(state, i - state.getInitialState()));
        }
        return feasibleActions;
    };

    Function<State, Action> idempotentAction = s -> new ActionImpl(s, 0);

    // Immediate Value Function

    ImmediateValueFunction<State, Action, Double> immediateValueFunction = (initialState, action,
            finalState) -> {
        ActionImpl a = (ActionImpl) action;
        StateImpl fs = (StateImpl) finalState;
        double orderingCost = a.getAction() > 0 ? (fixedOrderingCost + a.getAction() * proportionalOrderingCost)
                : 0;
        double holdingAndPenaltyCost = holdingCost * Math.max(fs.getInitialState(), 0)
                + penaltyCost * Math.max(-fs.getInitialState(), 0);
        return orderingCost + holdingAndPenaltyCost;
    };

    // Random Outcome Function

    RandomOutcomeFunction<State, Action, Double> randomOutcomeFunction = (initialState, action, finalState) -> {
        double realizedDemand = ((StateImpl) initialState).getInitialState() + ((ActionImpl) action).getAction()
                - ((StateImpl) finalState).getInitialState();
        return realizedDemand;
    };

    /*******************************************************************
     * Solve
     */

    // Sampling scheme

    SamplingScheme samplingScheme = SamplingScheme.NONE;
    int maxSampleSize = 200;
    double reductionFactorPerStage = 1;

    // Value Function Processing Method: backward recursion
    double discountFactor = 1.0;
    BackwardRecursionImpl recursion = new BackwardRecursionImpl(OptimisationDirection.MIN, distributions,
            supportLB, supportUB, immediateValueFunction, randomOutcomeFunction, buildActionList,
            idempotentAction, discountFactor, samplingScheme, maxSampleSize, reductionFactorPerStage,
            HashType.HASHTABLE);

    System.out.println("--------------Backward recursion--------------");
    recursion.runBackwardRecursionMonitoring();
    System.out.println();
    double ETC = recursion.getExpectedCost(initialInventory);
    StateDescriptorImpl initialState = new StateDescriptorImpl(0, initialInventory);
    double action = recursion.getOptimalAction(initialState).getAction();
    long percent = recursion.getMonitoringInterfaceBackward().getPercentCPU();
    System.out.println(
            "Expected total cost (assuming an initial inventory level " + initialInventory + "): " + ETC);
    System.out.println("Optimal initial action: " + action);
    System.out.println("Time elapsed: " + recursion.getMonitoringInterfaceBackward().getTime());
    System.out
            .println("Cpu usage: " + percent + "% (" + Runtime.getRuntime().availableProcessors() + " cores)");
    System.out.println();

    /*******************************************************************
     * Charting
     */
    System.out.println("--------------Charting--------------");
    int targetPeriod = 0; //If targetPeriod > 0 then no sampling!
    plotOptimalPolicyAction(targetPeriod, recursion); //Plot optimal policy action
    BackwardRecursionImpl recursionPlot = new BackwardRecursionImpl(OptimisationDirection.MIN, distributions,
            supportLB, supportUB, immediateValueFunction, randomOutcomeFunction, buildActionList,
            idempotentAction, discountFactor, samplingScheme, maxSampleSize, reductionFactorPerStage,
            HashType.HASHTABLE);
    plotOptimalPolicyCost(targetPeriod, recursionPlot); //Plot optimal policy cost      
    System.out.println();

    /*******************************************************************
     * Simulation
     */
    System.out.println("--------------Simulation--------------");
    double confidence = 0.95; //Simulation confidence level 
    double errorTolerance = 0.0001; //Simulation error threshold

    if (simulate && samplingScheme == SamplingScheme.NONE)
        simulate(distributions, fixedOrderingCost, holdingCost, penaltyCost, proportionalOrderingCost,
                initialInventory, recursion, confidence, errorTolerance);
    else {
        if (!simulate)
            System.out.println("Simulation disabled.");
        if (samplingScheme != SamplingScheme.NONE)
            System.out.println(
                    "Cannot simulate a sampled solution, please disable sampling: set samplingScheme == SamplingScheme.NONE.");
    }
}

From source file:com.metamx.druid.utils.ExposeS3DataSource.java

public static void main(String[] args) throws ServiceException, IOException, NoSuchAlgorithmException {
    CLI cli = new CLI();
    cli.addOption(new RequiredOption(null, "s3Bucket", true, "s3 bucket to pull data from"));
    cli.addOption(new RequiredOption(null, "s3Path", true,
            "base input path in s3 bucket.  Everything until the date strings."));
    cli.addOption(new RequiredOption(null, "timeInterval", true, "ISO8601 interval of dates to index"));
    cli.addOption(new RequiredOption(null, "granularity", true, String.format(
            "granularity of index, supported granularities: [%s]", Arrays.asList(Granularity.values()))));
    cli.addOption(new RequiredOption(null, "zkCluster", true, "Cluster string to connect to ZK with."));
    cli.addOption(new RequiredOption(null, "zkBasePath", true, "The base path to register index changes to."));

    CommandLine commandLine = cli.parse(args);

    if (commandLine == null) {
        return;/*from  w w w.  j a  va  2 s .c om*/
    }

    String s3Bucket = commandLine.getOptionValue("s3Bucket");
    String s3Path = commandLine.getOptionValue("s3Path");
    String timeIntervalString = commandLine.getOptionValue("timeInterval");
    String granularity = commandLine.getOptionValue("granularity");
    String zkCluster = commandLine.getOptionValue("zkCluster");
    String zkBasePath = commandLine.getOptionValue("zkBasePath");

    Interval timeInterval = new Interval(timeIntervalString);
    Granularity gran = Granularity.valueOf(granularity.toUpperCase());
    final RestS3Service s3Client = new RestS3Service(new AWSCredentials(
            System.getProperty("com.metamx.aws.accessKey"), System.getProperty("com.metamx.aws.secretKey")));
    ZkClient zkClient = new ZkClient(new ZkConnection(zkCluster), Integer.MAX_VALUE, new StringZkSerializer());

    zkClient.waitUntilConnected();

    for (Interval interval : gran.getIterable(timeInterval)) {
        log.info("Processing interval[%s]", interval);
        String s3DatePath = JOINER.join(s3Path, gran.toPath(interval.getStart()));
        if (!s3DatePath.endsWith("/")) {
            s3DatePath += "/";
        }

        StorageObjectsChunk chunk = s3Client.listObjectsChunked(s3Bucket, s3DatePath, "/", 2000, null, true);
        TreeSet<String> commonPrefixes = Sets.newTreeSet();
        commonPrefixes.addAll(Arrays.asList(chunk.getCommonPrefixes()));

        if (commonPrefixes.isEmpty()) {
            log.info("Nothing at s3://%s/%s", s3Bucket, s3DatePath);
            continue;
        }

        String latestPrefix = commonPrefixes.last();

        log.info("Latest segments at [s3://%s/%s]", s3Bucket, latestPrefix);

        chunk = s3Client.listObjectsChunked(s3Bucket, latestPrefix, "/", 2000, null, true);
        Integer partitionNumber;
        if (chunk.getCommonPrefixes().length == 0) {
            partitionNumber = null;
        } else {
            partitionNumber = -1;
            for (String partitionPrefix : chunk.getCommonPrefixes()) {
                String[] splits = partitionPrefix.split("/");
                partitionNumber = Math.max(partitionNumber, Integer.parseInt(splits[splits.length - 1]));
            }
        }

        log.info("Highest segment partition[%,d]", partitionNumber);

        if (partitionNumber == null) {
            final S3Object s3Obj = new S3Object(new S3Bucket(s3Bucket),
                    String.format("%sdescriptor.json", latestPrefix));
            updateWithS3Object(zkBasePath, s3Client, zkClient, s3Obj);
        } else {
            for (int i = partitionNumber; i >= 0; --i) {
                final S3Object partitionObject = new S3Object(new S3Bucket(s3Bucket),
                        String.format("%s%s/descriptor.json", latestPrefix, i));

                updateWithS3Object(zkBasePath, s3Client, zkClient, partitionObject);
            }
        }
    }
}

From source file:edu.berkeley.sparrow.examples.ProtoFrontendAsync.java

public static void main(String[] args) {
    try {/*from w w w . ja v a 2 s  .  c o m*/
        OptionParser parser = new OptionParser();
        parser.accepts("c", "configuration file").withRequiredArg().ofType(String.class);
        parser.accepts("help", "print help statement");
        OptionSet options = parser.parse(args);

        if (options.has("help")) {
            parser.printHelpOn(System.out);
            System.exit(-1);
        }

        // Logger configuration: log to the console
        BasicConfigurator.configure();
        LOG.setLevel(Level.DEBUG);

        Configuration conf = new PropertiesConfiguration();

        if (options.has("c")) {
            String configFile = (String) options.valueOf("c");
            conf = new PropertiesConfiguration(configFile);
        }

        Random r = new Random();
        double lambda = conf.getDouble("job_arrival_rate_s", DEFAULT_JOB_ARRIVAL_RATE_S);
        int tasksPerJob = conf.getInt("tasks_per_job", DEFAULT_TASKS_PER_JOB);
        int benchmarkIterations = conf.getInt("benchmark.iterations", DEFAULT_BENCHMARK_ITERATIONS);
        int benchmarkId = conf.getInt("benchmark.id", DEFAULT_TASK_BENCHMARK);

        int schedulerPort = conf.getInt("scheduler_port", SchedulerThrift.DEFAULT_SCHEDULER_THRIFT_PORT);

        TProtocolFactory factory = new TBinaryProtocol.Factory();
        TAsyncClientManager manager = new TAsyncClientManager();

        long lastLaunch = System.currentTimeMillis();
        // Loop and generate tasks launches
        while (true) {
            // Lambda is the arrival rate in S, so we need to multiply the result here by
            // 1000 to convert to ms.
            long delay = (long) (generateInterarrivalDelay(r, lambda) * 1000);
            long curLaunch = lastLaunch + delay;
            long toWait = Math.max(0, curLaunch - System.currentTimeMillis());
            lastLaunch = curLaunch;
            if (toWait == 0) {
                LOG.warn("Generated workload not keeping up with real time.");
            }
            List<TTaskSpec> tasks = generateJob(tasksPerJob, benchmarkId, benchmarkIterations);
            TUserGroupInfo user = new TUserGroupInfo();
            user.setUser("*");
            user.setGroup("*");
            TSchedulingRequest req = new TSchedulingRequest();
            req.setApp("testApp");
            req.setTasks(tasks);
            req.setUser(user);

            TNonblockingTransport tr = new TNonblockingSocket("localhost", schedulerPort);
            SchedulerService.AsyncClient client = new SchedulerService.AsyncClient(factory, manager, tr);
            //client.registerFrontend("testApp", new RegisterCallback());
            client.submitJob(req, new SubmitCallback(req, tr));
        }
    } catch (Exception e) {
        LOG.error("Fatal exception", e);
    }
}

From source file:jsdp.app.inventory.univariate.StochasticLotSizing.java

public static void main(String args[]) {

    boolean simulate = true;

    /*******************************************************************
     * Problem parameters/* w  w w  . jav  a 2s  .  c o m*/
     */
    double fixedOrderingCost = 300;
    double proportionalOrderingCost = 0;
    double holdingCost = 1;
    double penaltyCost = 10;

    double[] meanDemand = { 10, 20, 15, 20, 15, 10 };
    double coefficientOfVariation = 0.2;
    double truncationQuantile = 0.999;

    // Random variables

    Distribution[] distributions = IntStream.iterate(0, i -> i + 1).limit(meanDemand.length)
            //.mapToObj(i -> new NormalDist(meanDemand[i],meanDemand[i]*coefficientOfVariation))
            .mapToObj(i -> new PoissonDist(meanDemand[i])).toArray(Distribution[]::new);
    double[] supportLB = IntStream.iterate(0, i -> i + 1).limit(meanDemand.length)
            .mapToDouble(i -> distributions[i].inverseF(1 - truncationQuantile)).toArray();
    double[] supportUB = IntStream.iterate(0, i -> i + 1).limit(meanDemand.length)
            .mapToDouble(i -> distributions[i].inverseF(truncationQuantile)).toArray();

    double initialInventory = 0;

    /*******************************************************************
     * Model definition
     */

    // State space

    double stepSize = 1; //Stepsize must be 1 for discrete distributions
    double minState = -50; //Inventory level lower bound in each period
    double maxState = 150; //Inventory level upper bound in each period
    StateImpl.setStateBoundaries(stepSize, minState, maxState);

    // Actions

    Function<State, ArrayList<Action>> buildActionList = s -> {
        StateImpl state = (StateImpl) s;
        ArrayList<Action> feasibleActions = new ArrayList<Action>();
        for (double i = state.getInitialState(); i <= StateImpl.getMaxState(); i += StateImpl.getStepSize()) {
            feasibleActions.add(new ActionImpl(state, i - state.getInitialState()));
        }
        return feasibleActions;
    };

    Function<State, Action> idempotentAction = s -> new ActionImpl(s, 0.0);

    // Immediate Value Function

    ImmediateValueFunction<State, Action, Double> immediateValueFunction = (initialState, action,
            finalState) -> {
        ActionImpl a = (ActionImpl) action;
        StateImpl fs = (StateImpl) finalState;
        double orderingCost = a.getAction() > 0 ? (fixedOrderingCost + a.getAction() * proportionalOrderingCost)
                : 0;
        double holdingAndPenaltyCost = holdingCost * Math.max(fs.getInitialState(), 0)
                + penaltyCost * Math.max(-fs.getInitialState(), 0);
        return orderingCost + holdingAndPenaltyCost;
    };

    // Random Outcome Function

    RandomOutcomeFunction<State, Action, Double> randomOutcomeFunction = (initialState, action, finalState) -> {
        double realizedDemand = ((StateImpl) initialState).getInitialState() + ((ActionImpl) action).getAction()
                - ((StateImpl) finalState).getInitialState();
        return realizedDemand;
    };

    /*******************************************************************
     * Solve
     */

    // Sampling scheme

    SamplingScheme samplingScheme = SamplingScheme.NONE;
    int maxSampleSize = 100;
    double reductionFactorPerStage = 1;

    // Value Function Processing Method: backward recursion
    double discountFactor = 1.0;
    int stateSpaceLowerBound = 10000000;
    float loadFactor = 0.8F;
    BackwardRecursionImpl recursion = new BackwardRecursionImpl(OptimisationDirection.MIN, distributions,
            supportLB, supportUB, immediateValueFunction, randomOutcomeFunction, buildActionList,
            idempotentAction, discountFactor, samplingScheme, maxSampleSize, reductionFactorPerStage,
            stateSpaceLowerBound, loadFactor, HashType.THASHMAP);

    System.out.println("--------------Backward recursion--------------");
    recursion.runBackwardRecursionMonitoring();
    System.out.println();
    double ETC = recursion.getExpectedCost(initialInventory);
    StateDescriptorImpl initialState = new StateDescriptorImpl(0, initialInventory);
    double action = recursion.getOptimalAction(initialState).getAction();
    long percent = recursion.getMonitoringInterfaceBackward().getPercentCPU();
    System.out.println(
            "Expected total cost (assuming an initial inventory level " + initialInventory + "): " + ETC);
    System.out.println("Optimal initial action: " + action);
    System.out.println("Time elapsed: " + recursion.getMonitoringInterfaceBackward().getTime());
    System.out
            .println("Cpu usage: " + percent + "% (" + Runtime.getRuntime().availableProcessors() + " cores)");
    System.out.println();

    /*******************************************************************
     * Charting
     */
    System.out.println("--------------Charting--------------");
    int targetPeriod = 0;
    plotOptimalPolicyAction(targetPeriod, recursion); //Plot optimal policy action
    BackwardRecursionImpl recursionPlot = new BackwardRecursionImpl(OptimisationDirection.MIN, distributions,
            supportLB, supportUB, immediateValueFunction, randomOutcomeFunction, buildActionList,
            idempotentAction, discountFactor, targetPeriod > 0 ? SamplingScheme.NONE : samplingScheme,
            maxSampleSize, reductionFactorPerStage, HashType.THASHMAP);
    plotOptimalPolicyCost(targetPeriod, recursionPlot); //Plot optimal policy cost 
    System.out.println();

    /*******************************************************************
     * Simulation
     */
    System.out.println("--------------Simulation--------------");
    double confidence = 0.95; //Simulation confidence level 
    double errorTolerance = 0.0001; //Simulation error threshold

    if (simulate && samplingScheme == SamplingScheme.NONE)
        simulate(distributions, fixedOrderingCost, holdingCost, penaltyCost, proportionalOrderingCost,
                initialInventory, recursion, confidence, errorTolerance);
    else {
        if (!simulate)
            System.out.println("Simulation disabled.");
        if (samplingScheme != SamplingScheme.NONE)
            System.out.println(
                    "Cannot simulate a sampled solution, please disable sampling: set samplingScheme == SamplingScheme.NONE.");
    }
}

From source file:org.eclipse.swt.snippets.Snippet334.java

public static void main(String[] arg) {
    display = new Display();
    shell = new Shell(display);
    shell.setText("Snippet 334");
    shell.setLayout(new GridLayout(2, false));
    Label label = new Label(shell, SWT.NONE);
    label.setText("Test:");
    canvas = new Canvas(shell, SWT.MULTI | SWT.BORDER);
    final Caret caret = new Caret(canvas, SWT.NONE);
    canvas.addPaintListener(e -> {//  w  w w  .j av a 2 s  .c  o  m
        GC gc = e.gc;
        gc.drawText(text, 10, 10);
        caret.setBounds(10, 10, 2, gc.getFontMetrics().getHeight());
        Rectangle rect = canvas.getClientArea();
        if (canvas.isFocusControl()) {
            gc.drawFocus(rect.x, rect.y, rect.width, rect.height);
        }
    });
    canvas.addTraverseListener(e -> {
        switch (e.detail) {
        case SWT.TRAVERSE_TAB_NEXT:
        case SWT.TRAVERSE_TAB_PREVIOUS:
            e.doit = true; // enable traversal
            break;
        }
    });

    // key listener enables traversal out)
    canvas.addKeyListener(keyPressedAdapter(e -> {
    }));

    canvas.addFocusListener(focusGainedAdapter(event -> canvas.redraw()));
    canvas.addFocusListener(focusLostAdapter(event -> canvas.redraw()));
    canvas.addMouseListener(mouseDownAdapter(e -> canvas.setFocus()));
    Accessible acc = canvas.getAccessible();
    acc.addRelation(ACC.RELATION_LABELLED_BY, label.getAccessible());
    acc.addAccessibleControlListener(new AccessibleControlAdapter() {
        @Override
        public void getRole(AccessibleControlEvent e) {
            e.detail = ACC.ROLE_TEXT;
        }

        @Override
        public void getLocation(AccessibleControlEvent e) {
            Rectangle rect = canvas.getBounds();
            Point pt = shell.toDisplay(rect.x, rect.y);
            e.x = pt.x;
            e.y = pt.y;
            e.width = rect.width;
            e.height = rect.height;
        }

        @Override
        public void getValue(AccessibleControlEvent e) {
            e.result = text;
        }

        @Override
        public void getFocus(AccessibleControlEvent e) {
            e.childID = ACC.CHILDID_SELF;
        }

        @Override
        public void getChildCount(AccessibleControlEvent e) {
            e.detail = 0;
        }

        @Override
        public void getState(AccessibleControlEvent e) {
            e.detail = ACC.STATE_NORMAL | ACC.STATE_FOCUSABLE;
            if (canvas.isFocusControl())
                e.detail |= ACC.STATE_FOCUSED | ACC.STATE_SELECTABLE;
        }
    });
    acc.addAccessibleTextListener(new AccessibleTextExtendedAdapter() {
        @Override
        public void getSelectionRange(AccessibleTextEvent e) {
            // select the first 4 characters for testing
            e.offset = 0;
            e.length = 4;
        }

        @Override
        public void getCaretOffset(AccessibleTextEvent e) {
            e.offset = 0;
        }

        @Override
        public void getTextBounds(AccessibleTextEvent e) {
            // for now, assume that start = 0 and end = text.length
            GC gc = new GC(canvas);
            Point extent = gc.textExtent(text);
            gc.dispose();
            Rectangle rect = display.map(canvas, null, 10, 10, extent.x, extent.y);
            e.x = rect.x;
            e.y = rect.y;
            e.width = rect.width;
            e.height = rect.height;
        }

        @Override
        public void getText(AccessibleTextEvent e) {
            int start = 0, end = text.length();
            switch (e.type) {
            case ACC.TEXT_BOUNDARY_ALL:
                start = e.start;
                end = e.end;
                break;
            case ACC.TEXT_BOUNDARY_CHAR:
                start = e.count >= 0 ? e.start + e.count : e.start - e.count;
                start = Math.max(0, Math.min(end, start));
                end = start;
                e.count = start - e.start;
                e.start = start;
                e.end = start;
                break;
            case ACC.TEXT_BOUNDARY_LINE:
                int offset = e.count <= 0 ? e.start : e.end;
                offset = Math.min(offset, text.length());
                int lineCount = 0;
                int index = 0;
                while (index != -1) {
                    lineCount++;
                    index = text.indexOf("\n", index);
                    if (index != -1)
                        index++;
                }
                e.count = e.count < 0 ? Math.max(e.count, -lineCount) : Math.min(e.count, lineCount);
                index = 0;
                int lastIndex = 0;
                String[] lines = new String[lineCount];
                for (int i = 0; i < lines.length; i++) {
                    index = text.indexOf("\n", index);
                    lines[i] = index != -1 ? text.substring(lastIndex, index) : text.substring(lastIndex);
                    lastIndex = index;
                    index++;
                }
                int len = 0;
                int lineAtOffset = 0;
                for (int i = 0; i < lines.length; i++) {
                    len += lines[i].length();
                    if (len >= e.offset) {
                        lineAtOffset = i;
                        break;
                    }
                }
                int result = Math.max(0, Math.min(lineCount - 1, lineAtOffset + e.count));
                e.count = result - lineAtOffset;
                e.result = lines[result];
                break;
            }
            e.result = text.substring(start, end);
        }

        @Override
        public void getSelectionCount(AccessibleTextEvent e) {
            e.count = 1;
        }

        @Override
        public void getSelection(AccessibleTextEvent e) {
            // there is only 1 selection, so index = 0
            getSelectionRange(e);
            e.start = e.offset;
            e.end = e.offset + e.length;
        }

        @Override
        public void getRanges(AccessibleTextEvent e) {
            // for now, ignore bounding box
            e.start = 0;
            e.end = text.length() - 1;
        }

        @Override
        public void getCharacterCount(AccessibleTextEvent e) {
            e.count = text.length();
        }

        @Override
        public void getVisibleRanges(AccessibleTextEvent e) {
            e.start = 0;
            e.end = text.length() - 1;
        }
    });
    Button button = new Button(shell, SWT.PUSH);
    button.setText("Button");
    button.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 2, 1));
    shell.pack();
    shell.open();
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch())
            display.sleep();
    }
    display.dispose();
}

From source file:fr.inria.atlanmod.instantiator.SpecimenGenerator.java

public static void main(String[] args) throws GenerationException, IOException {

    Options options = new Options();

    configureOptions(options);//from  ww w .  ja v  a2  s .  c  o m

    CommandLineParser parser = new GnuParser();

    try {
        CommandLine commandLine = parser.parse(options, args);

        String metamodel = commandLine.getOptionValue(METAMODEL);
        DefaultModelGenerator modelGen = new DefaultModelGenerator(URI.createFileURI(metamodel));

        if (commandLine.hasOption(ADDITIONAL_METAMODEL)) {
            for (String additionalMetamodel : commandLine.getOptionValues(ADDITIONAL_METAMODEL)) {
                URI additionalMetamodelUri = URI.createFileURI(additionalMetamodel);
                Resource resource = new XMIResourceImpl(additionalMetamodelUri);
                resource.load(Collections.emptyMap());
                registerPackages(resource);
            }
        }

        if (commandLine.hasOption(OUTPUT_DIR)) {
            String outDir = commandLine.getOptionValue(OUTPUT_DIR);
            modelGen.setSamplesPath(Paths.get(outDir));
        } else {
            modelGen.setSamplesPath(Paths.get("."));
        }
        if (commandLine.hasOption(N_MODELS)) {
            int models = ((Number) commandLine.getParsedOptionValue(N_MODELS)).intValue();
            modelGen.setSetSize(new int[] { models });
        } else {
            modelGen.setSetSize(new int[] { 1 });
        }
        if (commandLine.hasOption(SIZE)) {
            long size = ((Number) commandLine.getParsedOptionValue(SIZE)).longValue();
            modelGen.setModelsSize(new long[] { size });
        } else {
            modelGen.setModelsSize(new long[] { 1000 });
        }
        if (commandLine.hasOption(SEED)) {
            long seed = ((Number) commandLine.getParsedOptionValue(SEED)).longValue();
            modelGen.setSeed(seed);
        } else {
            modelGen.setSeed(System.currentTimeMillis());
        }
        modelGen.runGeneration();
    } catch (ParseException e) {
        System.err.println(e.getLocalizedMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.setOptionComparator(new OptionComarator<Option>());
        try {
            formatter.setWidth(Math.max(TerminalFactory.get().getWidth(), 80));
        } catch (Throwable t) {
            // Nothing to do...
        }
        ;
        formatter.printHelp("java -jar <this-file.jar>", options, true);
    }
}

From source file:net.sf.jsignpdf.verify.Verifier.java

/**
 * @param args/*from w w  w.j a v  a  2  s.  c  om*/
 */
public static void main(String[] args) {

    // create the Options
    Option optHelp = new Option("h", "help", false, "print this message");
    // Option optVersion = new Option("v", "version", false,
    // "print version info");
    Option optCerts = new Option("c", "cert", true, "use external semicolon separated X.509 certificate files");
    optCerts.setArgName("certificates");
    Option optPasswd = new Option("p", "password", true, "set password for opening PDF");
    optPasswd.setArgName("password");
    Option optExtract = new Option("e", "extract", true, "extract signed PDF revisions to given folder");
    optExtract.setArgName("folder");
    Option optListKs = new Option("lk", "list-keystore-types", false, "list keystore types provided by java");
    Option optListCert = new Option("lc", "list-certificates", false, "list certificate aliases in a KeyStore");
    Option optKsType = new Option("kt", "keystore-type", true, "use keystore type with given name");
    optKsType.setArgName("keystore_type");
    Option optKsFile = new Option("kf", "keystore-file", true, "use given keystore file");
    optKsFile.setArgName("file");
    Option optKsPass = new Option("kp", "keystore-password", true,
            "password for keystore file (look on -kf option)");
    optKsPass.setArgName("password");
    Option optFailFast = new Option("ff", "fail-fast", false,
            "flag which sets the Verifier to exit with error code on the first validation failure");

    final Options options = new Options();
    options.addOption(optHelp);
    // options.addOption(optVersion);
    options.addOption(optCerts);
    options.addOption(optPasswd);
    options.addOption(optExtract);
    options.addOption(optListKs);
    options.addOption(optListCert);
    options.addOption(optKsType);
    options.addOption(optKsFile);
    options.addOption(optKsPass);
    options.addOption(optFailFast);

    CommandLine line = null;
    try {
        // create the command line parser
        CommandLineParser parser = new PosixParser();
        // parse the command line arguments
        line = parser.parse(options, args);
    } catch (ParseException exp) {
        System.err.println("Illegal command used: " + exp.getMessage());
        System.exit(SignatureVerification.SIG_STAT_CODE_ERROR_UNEXPECTED_PROBLEM);
    }

    final boolean failFast = line.hasOption("ff");
    final String[] tmpArgs = line.getArgs();
    if (line.hasOption("h") || args == null || args.length == 0) {
        // automatically generate the help statement
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(70, "java -jar Verifier.jar [file1.pdf [file2.pdf ...]]",
                "JSignPdf Verifier is a command line tool for verifying signed PDF documents.", options, null,
                true);
    } else if (line.hasOption("lk")) {
        // list keystores
        for (String tmpKsType : KeyStoreUtils.getKeyStores()) {
            System.out.println(tmpKsType);
        }
    } else if (line.hasOption("lc")) {
        // list certificate aliases in the keystore
        for (String tmpCert : KeyStoreUtils.getCertAliases(line.getOptionValue("kt"), line.getOptionValue("kf"),
                line.getOptionValue("kp"))) {
            System.out.println(tmpCert);
        }
    } else {
        final VerifierLogic tmpLogic = new VerifierLogic(line.getOptionValue("kt"), line.getOptionValue("kf"),
                line.getOptionValue("kp"));
        tmpLogic.setFailFast(failFast);

        if (line.hasOption("c")) {
            String tmpCertFiles = line.getOptionValue("c");
            for (String tmpCFile : tmpCertFiles.split(";")) {
                tmpLogic.addX509CertFile(tmpCFile);
            }
        }
        byte[] tmpPasswd = null;
        if (line.hasOption("p")) {
            tmpPasswd = line.getOptionValue("p").getBytes();
        }
        String tmpExtractDir = null;
        if (line.hasOption("e")) {
            tmpExtractDir = new File(line.getOptionValue("e")).getPath();
        }

        int exitCode = 0;

        for (String tmpFilePath : tmpArgs) {
            int exitCodeForFile = 0;
            System.out.println("Verifying " + tmpFilePath);
            final File tmpFile = new File(tmpFilePath);
            if (!tmpFile.canRead()) {
                exitCodeForFile = SignatureVerification.SIG_STAT_CODE_ERROR_FILE_NOT_READABLE;
                System.err.println("Couln't read the file. Check the path and permissions.");
                if (failFast) {
                    System.exit(exitCodeForFile);
                }
                exitCode = Math.max(exitCode, exitCodeForFile);
                continue;
            }
            final VerificationResult tmpResult = tmpLogic.verify(tmpFilePath, tmpPasswd);
            if (tmpResult.getException() != null) {
                tmpResult.getException().printStackTrace();
                exitCodeForFile = SignatureVerification.SIG_STAT_CODE_ERROR_UNEXPECTED_PROBLEM;
                if (failFast) {
                    System.exit(exitCodeForFile);
                }
                exitCode = Math.max(exitCode, exitCodeForFile);
                continue;
            } else {
                System.out.println("Total revisions: " + tmpResult.getTotalRevisions());
                for (SignatureVerification tmpSigVer : tmpResult.getVerifications()) {
                    System.out.println(tmpSigVer.toString());
                    if (tmpExtractDir != null) {
                        try {
                            File tmpExFile = new File(tmpExtractDir + "/" + tmpFile.getName() + "_"
                                    + tmpSigVer.getRevision() + ".pdf");
                            System.out.println("Extracting to " + tmpExFile.getCanonicalPath());
                            FileOutputStream tmpFOS = new FileOutputStream(tmpExFile.getCanonicalPath());

                            InputStream tmpIS = tmpLogic.extractRevision(tmpFilePath, tmpPasswd,
                                    tmpSigVer.getName());
                            IOUtils.copy(tmpIS, tmpFOS);
                            tmpIS.close();
                            tmpFOS.close();
                        } catch (IOException ioe) {
                            ioe.printStackTrace();
                        }
                    }
                }
                exitCodeForFile = tmpResult.getVerificationResultCode();
                if (failFast && SignatureVerification.isError(exitCodeForFile)) {
                    System.exit(exitCodeForFile);
                }
            }
            exitCode = Math.max(exitCode, exitCodeForFile);
        }
        if (exitCode != 0 && tmpArgs.length > 1) {
            System.exit(SignatureVerification.isError(exitCode)
                    ? SignatureVerification.SIG_STAT_CODE_ERROR_ANY_ERROR
                    : SignatureVerification.SIG_STAT_CODE_WARNING_ANY_WARNING);
        } else {
            System.exit(exitCode);
        }
    }
}

From source file:com.amazonaws.services.kinesis.leases.impl.LeaseCoordinatorExerciser.java

public static void main(String[] args) throws InterruptedException, DependencyException, InvalidStateException,
        ProvisionedThroughputException, IOException {

    int numCoordinators = 9;
    int numLeases = 73;
    int leaseDurationMillis = 10000;
    int epsilonMillis = 100;

    AWSCredentialsProvider creds = new DefaultAWSCredentialsProviderChain();
    AmazonDynamoDBClient ddb = new AmazonDynamoDBClient(creds);

    ILeaseManager<KinesisClientLease> leaseManager = new KinesisClientLeaseManager("nagl_ShardProgress", ddb);

    if (leaseManager.createLeaseTableIfNotExists(10L, 50L)) {
        LOG.info("Waiting for newly created lease table");
        if (!leaseManager.waitUntilLeaseTableExists(10, 300)) {
            LOG.error("Table was not created in time");
            return;
        }/*  w  w  w.  j  av  a  2  s . c  om*/
    }

    CWMetricsFactory metricsFactory = new CWMetricsFactory(creds, "testNamespace", 30 * 1000, 1000);
    final List<LeaseCoordinator<KinesisClientLease>> coordinators = new ArrayList<LeaseCoordinator<KinesisClientLease>>();
    for (int i = 0; i < numCoordinators; i++) {
        String workerIdentifier = "worker-" + Integer.toString(i);

        LeaseCoordinator<KinesisClientLease> coord = new LeaseCoordinator<KinesisClientLease>(leaseManager,
                workerIdentifier, leaseDurationMillis, epsilonMillis, metricsFactory);

        coordinators.add(coord);
    }

    leaseManager.deleteAll();

    for (int i = 0; i < numLeases; i++) {
        KinesisClientLease lease = new KinesisClientLease();
        lease.setLeaseKey(Integer.toString(i));
        lease.setCheckpoint(new ExtendedSequenceNumber("checkpoint"));
        leaseManager.createLeaseIfNotExists(lease);
    }

    final JFrame frame = new JFrame("Test Visualizer");
    frame.setPreferredSize(new Dimension(800, 600));
    final JPanel panel = new JPanel(new GridLayout(coordinators.size() + 1, 0));
    final JLabel ticker = new JLabel("tick");
    panel.add(ticker);
    frame.getContentPane().add(panel);

    final Map<String, JLabel> labels = new HashMap<String, JLabel>();
    for (final LeaseCoordinator<KinesisClientLease> coord : coordinators) {
        JPanel coordPanel = new JPanel();
        coordPanel.setLayout(new BoxLayout(coordPanel, BoxLayout.X_AXIS));
        final Button button = new Button("Stop " + coord.getWorkerIdentifier());
        button.setMaximumSize(new Dimension(200, 50));
        button.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent arg0) {
                if (coord.isRunning()) {
                    coord.stop();
                    button.setLabel("Start " + coord.getWorkerIdentifier());
                } else {
                    try {
                        coord.start();
                    } catch (LeasingException e) {
                        LOG.error(e);
                    }
                    button.setLabel("Stop " + coord.getWorkerIdentifier());
                }
            }

        });
        coordPanel.add(button);

        JLabel label = new JLabel();
        coordPanel.add(label);
        labels.put(coord.getWorkerIdentifier(), label);
        panel.add(coordPanel);
    }

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    new Thread() {

        // Key is lease key, value is green-ness as a value from 0 to 255.
        // Great variable name, huh?
        private Map<String, Integer> greenNesses = new HashMap<String, Integer>();

        // Key is lease key, value is last owning worker
        private Map<String, String> lastOwners = new HashMap<String, String>();

        @Override
        public void run() {
            while (true) {
                for (LeaseCoordinator<KinesisClientLease> coord : coordinators) {
                    String workerIdentifier = coord.getWorkerIdentifier();

                    JLabel label = labels.get(workerIdentifier);

                    List<KinesisClientLease> asgn = new ArrayList<KinesisClientLease>(coord.getAssignments());
                    Collections.sort(asgn, new Comparator<KinesisClientLease>() {

                        @Override
                        public int compare(KinesisClientLease arg0, KinesisClientLease arg1) {
                            return arg0.getLeaseKey().compareTo(arg1.getLeaseKey());
                        }

                    });

                    StringBuilder builder = new StringBuilder();
                    builder.append("<html>");
                    builder.append(workerIdentifier).append(":").append(asgn.size()).append("          ");

                    for (KinesisClientLease lease : asgn) {
                        String leaseKey = lease.getLeaseKey();
                        String lastOwner = lastOwners.get(leaseKey);

                        // Color things green when they switch owners, decay the green-ness over time.
                        Integer greenNess = greenNesses.get(leaseKey);
                        if (greenNess == null || lastOwner == null
                                || !lastOwner.equals(lease.getLeaseOwner())) {
                            greenNess = 200;
                        } else {
                            greenNess = Math.max(0, greenNess - 20);
                        }
                        greenNesses.put(leaseKey, greenNess);
                        lastOwners.put(leaseKey, lease.getLeaseOwner());

                        builder.append(String.format("<font color=\"%s\">%03d</font>",
                                String.format("#00%02x00", greenNess), Integer.parseInt(leaseKey))).append(" ");
                    }
                    builder.append("</html>");

                    label.setText(builder.toString());
                    label.revalidate();
                    label.repaint();
                }

                if (ticker.getText().equals("tick")) {
                    ticker.setText("tock");
                } else {
                    ticker.setText("tick");
                }

                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                }
            }
        }

    }.start();

    frame.pack();
    frame.setVisible(true);

    for (LeaseCoordinator<KinesisClientLease> coord : coordinators) {
        coord.start();
    }
}

From source file:de.uni_koblenz.jgralab.utilities.tgraphbrowser.TGraphBrowserServer.java

/**
 * Runs the server. Needed args: -w --workspace the workspace
 * //from   ww  w  .  j ava 2  s .c  om
 * @param args
 */
public static void main(String[] args) {
    CommandLine comLine = processCommandLineOptions(args);
    assert comLine != null;
    try {
        starttime = System.currentTimeMillis();
        String portnumber = comLine.getOptionValue("p");
        String workspacePath;

        if (comLine.hasOption("r")) {
            TwoDVisualizer.PRINT_ROLE_NAMES = true;
        }

        if (comLine.hasOption("w")) {
            workspacePath = comLine.getOptionValue("w");
        } else {
            File workspace = new File(System.getProperty("java.io.tmpdir") + File.separator + "tgraphbrowser");
            if (!workspace.exists()) {
                if (!workspace.mkdir()) {
                    logger.info("The temp folder " + workspace.getAbsolutePath() + " could not be created.");
                }
            }
            workspace = new File(workspace.getAbsoluteFile() + File.separator + "workspace");
            if (!workspace.exists()) {
                if (!workspace.mkdir()) {
                    logger.info(
                            "The default workspace " + workspace.getAbsolutePath() + " could not be created.");
                }
            }
            workspacePath = workspace.getAbsolutePath();
        }
        new TGraphBrowserServer(portnumber == null ? DEFAULT_PORT : Integer.parseInt(portnumber), workspacePath,
                comLine.getOptionValue("m"), comLine.getOptionValue("s")).start();
        if (comLine.getOptionValue("ic") != null) {
            TabularVisualizer.NUMBER_OF_INCIDENCES_PER_PAGE = Math
                    .max(Integer.parseInt(comLine.getOptionValue("ic")), 1);
        }
        if (comLine.hasOption("d")) {
            StateRepository.dot = comLine.getOptionValue("d");
        } else {
            System.out.println("The 2D-Visualization is disabled because parameter -d is not set.");
        }
        String timeout = comLine.getOptionValue("t");
        String checkIntervall = comLine.getOptionValue("i");
        new DeleteUnusedStates(timeout == null ? 600 : Integer.parseInt(timeout),
                checkIntervall == null ? 60 : Integer.parseInt(checkIntervall)).start();
        if (comLine.hasOption("td")) {
            TwoDVisualizer.SECONDS_TO_WAIT_FOR_DOT = Integer.parseInt(comLine.getOptionValue("td"));
        }
    } catch (IOException e) {
        System.out.println(e);
    }
}

From source file:amie.keys.CSAKey.java

public static void main(String[] args) throws IOException, InterruptedException {
    final Triple<MiningAssistant, Float, String> parsedArgs = parseArguments(args);
    final Set<Rule> output = new LinkedHashSet<>();

    // Helper object that contains the implementation for the calculation
    // of confidence and support
    // The file with the non-keys, one per line
    long timea = System.currentTimeMillis();
    List<List<String>> inputNonKeys = Utilities.parseNonKeysFile(parsedArgs.third);
    System.out.println(inputNonKeys.size() + " input non-keys");
    final List<List<String>> nonKeys = pruneBySupport(inputNonKeys, parsedArgs.second,
            parsedArgs.first.getKb());//from   www.j a va  2s  .c  om
    Collections.sort(nonKeys, new Comparator<List<String>>() {

        @Override
        public int compare(List<String> o1, List<String> o2) {
            int r = Integer.compare(o2.size(), o1.size());
            if (r == 0) {
                return Integer.compare(o2.hashCode(), o1.hashCode());
            }

            return r;
        }

    });
    System.out.println(nonKeys.size() + " non-keys after pruning");
    int totalLoad = computeLoad(nonKeys);
    System.out.println(totalLoad + " is the total load");
    int nThreads = Runtime.getRuntime().availableProcessors();
    //int batchSize = Math.max(Math.min(maxBatchSize, totalLoad / nThreads), minBatchSize);
    int batchSize = Math.max(Math.min(maxLoad, totalLoad / nThreads), minLoad);

    final Queue<int[]> chunks = new PriorityQueue(50, new Comparator<int[]>() {
        @Override
        public int compare(int[] o1, int[] o2) {
            return Integer.compare(o2[2], o1[2]);
        }

    });

    final HashSet<HashSet<Integer>> nonKeysInt = new HashSet<>();
    final HashMap<String, Integer> property2Id = new HashMap<>();
    final HashMap<Integer, String> id2Property = new HashMap<>();
    final List<Integer> propertiesList = new ArrayList<>();
    int support = (int) parsedArgs.second.floatValue();
    KB kb = parsedArgs.first.getKb();
    buildDictionaries(nonKeys, nonKeysInt, property2Id, id2Property, propertiesList, support, kb);
    final List<HashSet<Integer>> nonKeysIntList = new ArrayList<>(nonKeysInt);
    int start = 0;
    int[] nextIdx = nextIndex(nonKeysIntList, 0, batchSize);
    int end = nextIdx[0];
    int load = nextIdx[1];
    while (start < nonKeysIntList.size()) {
        int[] chunk = new int[] { start, end, load };
        chunks.add(chunk);
        start = end;
        nextIdx = nextIndex(nonKeysIntList, end, batchSize);
        end = nextIdx[0];
        load = nextIdx[1];
    }

    Thread[] threads = new Thread[Math.min(Runtime.getRuntime().availableProcessors(), chunks.size())];
    for (int i = 0; i < threads.length; ++i) {
        threads[i] = new Thread(new Runnable() {

            @Override
            public void run() {
                while (true) {
                    int[] chunk = null;
                    synchronized (chunks) {
                        if (!chunks.isEmpty()) {
                            chunk = chunks.poll();
                        } else {
                            break;
                        }
                    }
                    System.out.println("Processing chunk " + Arrays.toString(chunk));
                    mine(parsedArgs, nonKeysIntList, property2Id, id2Property, propertiesList, chunk[0],
                            chunk[1], output);
                }

            }
        });
        threads[i].start();
    }

    for (int i = 0; i < threads.length; ++i) {
        threads[i].join();
    }
    long timeb = System.currentTimeMillis();
    System.out.println("==== Unique C-keys =====");
    for (Rule r : output) {
        System.out.println(Utilities.formatKey(r));
    }
    System.out.println(
            "VICKEY found " + output.size() + " unique conditional keys in " + (timeb - timea) + " ms");
}