Example usage for java.util Arrays toString

List of usage examples for java.util Arrays toString

Introduction

In this page you can find the example usage for java.util Arrays toString.

Prototype

public static String toString(Object[] a) 

Source Link

Document

Returns a string representation of the contents of the specified array.

Usage

From source file:deck36.storm.plan9.php.KittenRobbersTopology.java

public static void main(String[] args) throws Exception {

    String env = null;//from   w  ww .  j  a v  a2  s.c om

    if (args != null && args.length > 0) {
        env = args[0];
    }

    if (!"dev".equals(env))
        if (!"prod".equals(env)) {
            System.out.println("Usage: $0 (dev|prod)\n");
            System.exit(1);
        }

    // Topology config
    Config conf = new Config();

    // Load parameters and add them to the Config
    Map configMap = YamlLoader.loadYamlFromResource("config_" + env + ".yml");

    conf.putAll(configMap);

    log.info(JSONValue.toJSONString((conf)));

    // Set topology loglevel to DEBUG
    conf.put(Config.TOPOLOGY_DEBUG, JsonPath.read(conf, "$.deck36_storm.debug"));

    // Create Topology builder
    TopologyBuilder builder = new TopologyBuilder();

    // if there are not special reasons, start with parallelism hint of 1
    // and multiple tasks. By that, you can scale dynamically later on.
    int parallelism_hint = JsonPath.read(conf, "$.deck36_storm.default_parallelism_hint");
    int num_tasks = JsonPath.read(conf, "$.deck36_storm.default_num_tasks");

    String badgeName = KittenRobbersTopology.class.getSimpleName();

    // construct command to invoke the external bolt implementation
    ArrayList<String> command = new ArrayList(15);

    // Add main execution program (php, hhvm, zend, ..) and parameters
    command.add((String) JsonPath.read(conf, "$.deck36_storm.php.executor"));
    command.addAll((List<String>) JsonPath.read(conf, "$.deck36_storm.php.executor_params"));

    // Add main command to be executed (app/console, the phar file, etc.) and global context parameters (environment etc.)
    command.add((String) JsonPath.read(conf, "$.deck36_storm.php.main"));
    command.addAll((List<String>) JsonPath.read(conf, "$.deck36_storm.php.main_params"));

    // Add main route to be invoked and its parameters
    command.add((String) JsonPath.read(conf, "$.deck36_storm.KittenRobbersFromOuterSpaceBolt.main"));
    List boltParams = (List<String>) JsonPath.read(conf,
            "$.deck36_storm.KittenRobbersFromOuterSpaceBolt.params");
    if (boltParams != null)
        command.addAll(boltParams);

    // Log the final command
    log.info("Command to start bolt for KittenRobbersFromOuterSpace: " + Arrays.toString(command.toArray()));

    // Add constructed external bolt command to topology using MultilangAdapterBolt
    builder.setBolt("badge", new MultilangAdapterTickTupleBolt(command,
            (Integer) JsonPath.read(conf, "$.deck36_storm.KittenRobbersFromOuterSpaceBolt.robber_frequency"),
            "badge"), parallelism_hint).setNumTasks(num_tasks);

    builder.setBolt("rabbitmq_router",
            new Plan9RabbitMQRouterBolt(
                    (String) JsonPath.read(conf,
                            "$.deck36_storm.KittenRobbersFromOuterSpaceBolt.rabbitmq.target_exchange"),
                    "KittenRobbers" // RabbitMQ routing key
            ), parallelism_hint).setNumTasks(num_tasks).shuffleGrouping("badge");

    builder.setBolt("rabbitmq_producer", new Plan9RabbitMQPushBolt(), parallelism_hint).setNumTasks(num_tasks)
            .shuffleGrouping("rabbitmq_router");

    if ("dev".equals(env)) {
        LocalCluster cluster = new LocalCluster();
        cluster.submitTopology(badgeName + System.currentTimeMillis(), conf, builder.createTopology());
        Thread.sleep(2000000);
    }

    if ("prod".equals(env)) {
        StormSubmitter.submitTopology(badgeName + "-" + System.currentTimeMillis(), conf,
                builder.createTopology());
    }

}

From source file:ms1quant.MS1Quant.java

/**
 * @param args the command line arguments MS1Quant parameterfile
 */// w  w w .j  a v a2 s . co m
public static void main(String[] args) throws Exception {

    BufferedReader reader = null;
    try {
        System.out.println(
                "=================================================================================================");
        System.out.println("Umpire MS1 quantification and feature detection analysis (version: "
                + UmpireInfo.GetInstance().Version + ")");
        if (args.length < 3 || !args[1].startsWith("-mode")) {
            System.out
                    .println("command : java -jar -Xmx10G MS1Quant.jar ms1quant.params -mode[1 or 2] [Option]");
            System.out.println("\n-mode");
            System.out.println("\t1:Single file mode--> mzXML_file PepXML_file");
            System.out.println("\t\tEx: -mode1 file1.mzXML file1.pep.xml");
            System.out.println(
                    "\t2:Folder mode--> mzXML_Folder PepXML_Folder, all generated csv tables will be merged into a single csv file");
            System.out.println("\t\tEx: -mode2 /data/mzxml/ /data/pepxml/");
            System.out.println("\nOptions");
            System.out.println(
                    "\t-C\tNo of concurrent files to be processed (only for folder mode), Ex. -C5, default:1");
            System.out.println("\t-p\tMinimum probability, Ex. -p0.9, default:0.9");
            System.out.println("\t-ID\tDetect identified feature only");
            System.out.println("\t-O\toutput folder, Ex. -O/data/");
            return;
        }
        ConsoleLogger consoleLogger = new ConsoleLogger();
        consoleLogger.SetConsoleLogger(Level.DEBUG);
        consoleLogger.SetFileLogger(Level.DEBUG, FilenameUtils.getFullPath(args[0]) + "ms1quant_debug.log");
        Logger logger = Logger.getRootLogger();
        logger.debug("Command: " + Arrays.toString(args));
        logger.info("MS1Quant version: " + UmpireInfo.GetInstance().Version);

        String parameterfile = args[0];
        logger.info("Parameter file: " + parameterfile);
        File paramfile = new File(parameterfile);
        if (!paramfile.exists()) {
            logger.error("Parameter file " + paramfile.getAbsolutePath()
                    + " cannot be found. The program will exit.");
        }

        reader = new BufferedReader(new FileReader(paramfile.getAbsolutePath()));
        String line = "";
        InstrumentParameter param = new InstrumentParameter(InstrumentParameter.InstrumentType.TOF5600);
        int NoCPUs = 2;
        int NoFile = 1;
        param.DetermineBGByID = false;
        param.EstimateBG = true;

        //<editor-fold defaultstate="collapsed" desc="Read parameter file">
        while ((line = reader.readLine()) != null) {
            if (!"".equals(line) && !line.startsWith("#")) {
                logger.info(line);
                //System.out.println(line);
                if (line.split("=").length < 2) {
                    continue;
                }
                if (line.split("=").length < 2) {
                    continue;
                }
                String type = line.split("=")[0].trim();
                if (type.startsWith("para.")) {
                    type = type.replace("para.", "SE.");
                }
                String value = line.split("=")[1].trim();
                switch (type) {
                case "Thread": {
                    NoCPUs = Integer.parseInt(value);
                    break;
                }
                //<editor-fold defaultstate="collapsed" desc="instrument parameters">

                case "SE.MS1PPM": {
                    param.MS1PPM = Float.parseFloat(value);
                    break;
                }
                case "SE.MS2PPM": {
                    param.MS2PPM = Float.parseFloat(value);
                    break;
                }
                case "SE.SN": {
                    param.SNThreshold = Float.parseFloat(value);
                    break;
                }
                case "SE.MS2SN": {
                    param.MS2SNThreshold = Float.parseFloat(value);
                    break;
                }
                case "SE.MinMSIntensity": {
                    param.MinMSIntensity = Float.parseFloat(value);
                    break;
                }
                case "SE.MinMSMSIntensity": {
                    param.MinMSMSIntensity = Float.parseFloat(value);
                    break;
                }
                case "SE.MinRTRange": {
                    param.MinRTRange = Float.parseFloat(value);
                    break;
                }
                case "SE.MaxNoPeakCluster": {
                    param.MaxNoPeakCluster = Integer.parseInt(value);
                    param.MaxMS2NoPeakCluster = Integer.parseInt(value);
                    break;
                }
                case "SE.MinNoPeakCluster": {
                    param.MinNoPeakCluster = Integer.parseInt(value);
                    param.MinMS2NoPeakCluster = Integer.parseInt(value);
                    break;
                }
                case "SE.MinMS2NoPeakCluster": {
                    param.MinMS2NoPeakCluster = Integer.parseInt(value);
                    break;
                }
                case "SE.MaxCurveRTRange": {
                    param.MaxCurveRTRange = Float.parseFloat(value);
                    break;
                }
                case "SE.Resolution": {
                    param.Resolution = Integer.parseInt(value);
                    break;
                }
                case "SE.RTtol": {
                    param.RTtol = Float.parseFloat(value);
                    break;
                }
                case "SE.NoPeakPerMin": {
                    param.NoPeakPerMin = Integer.parseInt(value);
                    break;
                }
                case "SE.StartCharge": {
                    param.StartCharge = Integer.parseInt(value);
                    break;
                }
                case "SE.EndCharge": {
                    param.EndCharge = Integer.parseInt(value);
                    break;
                }
                case "SE.MS2StartCharge": {
                    param.MS2StartCharge = Integer.parseInt(value);
                    break;
                }
                case "SE.MS2EndCharge": {
                    param.MS2EndCharge = Integer.parseInt(value);
                    break;
                }
                case "SE.NoMissedScan": {
                    param.NoMissedScan = Integer.parseInt(value);
                    break;
                }
                case "SE.Denoise": {
                    param.Denoise = Boolean.valueOf(value);
                    break;
                }
                case "SE.EstimateBG": {
                    param.EstimateBG = Boolean.valueOf(value);
                    break;
                }
                case "SE.RemoveGroupedPeaks": {
                    param.RemoveGroupedPeaks = Boolean.valueOf(value);
                    break;
                }
                case "SE.MinFrag": {
                    param.MinFrag = Integer.parseInt(value);
                    break;
                }
                case "SE.IsoPattern": {
                    param.IsoPattern = Float.valueOf(value);
                    break;
                }
                case "SE.StartRT": {
                    param.startRT = Float.valueOf(value);
                }
                case "SE.EndRT": {
                    param.endRT = Float.valueOf(value);
                }

                //</editor-fold>
                }
            }
        }
        //</editor-fold>

        int mode = 1;
        if (args[1].equals("-mode2")) {
            mode = 2;
        } else if (args[1].equals("-mode1")) {
            mode = 1;
        } else {
            logger.error("-mode number not recongized. The program will exit.");
        }

        String mzXML = "";
        String pepXML = "";
        String mzXMLPath = "";
        String pepXMLPath = "";
        File mzXMLfile = null;
        File pepXMLfile = null;
        File mzXMLfolder = null;
        File pepXMLfolder = null;
        int idx = 0;
        if (mode == 1) {
            mzXML = args[2];
            logger.info("Mode1 mzXML file: " + mzXML);
            mzXMLfile = new File(mzXML);
            if (!mzXMLfile.exists()) {
                logger.error("Mode1 mzXML file " + mzXMLfile.getAbsolutePath()
                        + " cannot be found. The program will exit.");
                return;
            }
            pepXML = args[3];
            logger.info("Mode1 pepXML file: " + pepXML);
            pepXMLfile = new File(pepXML);
            if (!pepXMLfile.exists()) {
                logger.error("Mode1 pepXML file " + pepXMLfile.getAbsolutePath()
                        + " cannot be found. The program will exit.");
                return;
            }
            idx = 4;
        } else if (mode == 2) {
            mzXMLPath = args[2];
            logger.info("Mode2 mzXML folder: " + mzXMLPath);
            mzXMLfolder = new File(mzXMLPath);
            if (!mzXMLfolder.exists()) {
                logger.error("Mode2 mzXML folder " + mzXMLfolder.getAbsolutePath()
                        + " does not exist. The program will exit.");
                return;
            }
            pepXMLPath = args[3];
            logger.info("Mode2 pepXML folder: " + pepXMLPath);
            pepXMLfolder = new File(pepXMLPath);
            if (!pepXMLfolder.exists()) {
                logger.error("Mode2 pepXML folder " + pepXMLfolder.getAbsolutePath()
                        + " does not exist. The program will exit.");
                return;
            }
            idx = 4;
        }

        String outputfolder = "";
        float MinProb = 0f;
        for (int i = idx; i < args.length; i++) {
            if (args[i].startsWith("-")) {
                if (args[i].equals("-ID")) {
                    param.TargetIDOnly = true;
                    logger.info("Detect ID feature only: true");
                }
                if (args[i].startsWith("-O")) {
                    outputfolder = args[i].substring(2);
                    logger.info("Output folder: " + outputfolder);

                    File outputfile = new File(outputfolder);
                    if (!outputfolder.endsWith("\\") | outputfolder.endsWith("/")) {
                        outputfolder += "/";
                    }
                    if (!outputfile.exists()) {
                        outputfile.mkdir();
                    }
                }
                if (args[i].startsWith("-C")) {
                    try {
                        NoFile = Integer.parseInt(args[i].substring(2));
                        logger.info("No of concurrent files: " + NoFile);
                    } catch (Exception ex) {
                        logger.error(args[i]
                                + " is not a correct integer format, will process only one file at a time.");
                    }
                }
                if (args[i].startsWith("-p")) {
                    try {
                        MinProb = Float.parseFloat(args[i].substring(2));
                        logger.info("probability threshold: " + MinProb);
                    } catch (Exception ex) {
                        logger.error(args[i] + " is not a correct format, will use 0 as threshold instead.");
                    }
                }
            }
        }

        reader.close();
        TandemParam tandemparam = new TandemParam(DBSearchParam.SearchInstrumentType.TOF5600);
        PTMManager.GetInstance();

        if (param.TargetIDOnly) {
            param.EstimateBG = false;
            param.ApexDelta = 1.5f;
            param.NoMissedScan = 10;
            param.MiniOverlapP = 0.2f;
            param.RemoveGroupedPeaks = false;
            param.CheckMonoIsotopicApex = false;
            param.DetectByCWT = false;
            param.FillGapByBK = false;
            param.IsoCorrThreshold = -1f;
            param.SmoothFactor = 3;
        }

        if (mode == 1) {
            logger.info("Processing " + mzXMLfile.getAbsolutePath() + "....");
            long time = System.currentTimeMillis();
            LCMSPeakMS1 LCMS1 = new LCMSPeakMS1(mzXMLfile.getAbsolutePath(), NoCPUs);
            LCMS1.SetParameter(param);

            LCMS1.Resume = false;
            if (!param.TargetIDOnly) {
                LCMS1.CreatePeakFolder();
            }
            LCMS1.ExportPeakClusterTable = true;

            if (pepXMLfile.exists()) {
                tandemparam.InteractPepXMLPath = pepXMLfile.getAbsolutePath();
                LCMS1.ParsePepXML(tandemparam, MinProb);
                logger.info("No. of PSMs included: " + LCMS1.IDsummary.PSMList.size());
                logger.info("No. of Peptide ions included: " + LCMS1.IDsummary.GetPepIonList().size());
            }

            if (param.TargetIDOnly) {
                LCMS1.SaveSerializationFile = false;
            }

            if (param.TargetIDOnly || !LCMS1.ReadPeakCluster()) {
                LCMS1.PeakClusterDetection();
            }

            if (pepXMLfile.exists()) {
                LCMS1.AssignQuant(false);
                LCMS1.IDsummary.ExportPepID(outputfolder);
            }
            time = System.currentTimeMillis() - time;
            logger.info(LCMS1.ParentmzXMLName + " processed time:"
                    + String.format("%d hour, %d min, %d sec", TimeUnit.MILLISECONDS.toHours(time),
                            TimeUnit.MILLISECONDS.toMinutes(time)
                                    - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(time)),
                            TimeUnit.MILLISECONDS.toSeconds(time)
                                    - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(time))));
            LCMS1.BaseClearAllPeaks();
            LCMS1.SetSpectrumParser(null);
            LCMS1.IDsummary = null;
            LCMS1 = null;
            System.gc();
        } else if (mode == 2) {

            LCMSID IDsummary = new LCMSID("", "", "");
            logger.info("Parsing all pepXML files in " + pepXMLPath + "....");
            for (File file : pepXMLfolder.listFiles()) {
                if (file.getName().toLowerCase().endsWith("pep.xml")
                        || file.getName().toLowerCase().endsWith("pepxml")) {
                    PepXMLParser pepXMLParser = new PepXMLParser(IDsummary, file.getAbsolutePath(), MinProb);
                }
            }
            HashMap<String, LCMSID> LCMSIDMap = IDsummary.GetLCMSIDFileMap();

            ExecutorService executorPool = null;
            executorPool = Executors.newFixedThreadPool(NoFile);

            logger.info("Processing all mzXML files in " + mzXMLPath + "....");
            for (File file : mzXMLfolder.listFiles()) {
                if (file.getName().toLowerCase().endsWith("mzxml")) {
                    LCMSID id = LCMSIDMap.get(FilenameUtils.getBaseName(file.getName()));
                    if (id == null || id.PSMList == null) {
                        logger.warn("No IDs found in :" + FilenameUtils.getBaseName(file.getName())
                                + ". Quantification for this file is skipped");
                        continue;
                    }
                    if (!id.PSMList.isEmpty()) {
                        MS1TargetQuantThread thread = new MS1TargetQuantThread(file, id, NoCPUs, outputfolder,
                                param);
                        executorPool.execute(thread);
                    }
                }
            }
            LCMSIDMap.clear();
            LCMSIDMap = null;
            IDsummary = null;
            executorPool.shutdown();
            try {
                executorPool.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
            } catch (InterruptedException e) {
                logger.info("interrupted..");
            }

            if (outputfolder == null | outputfolder.equals("")) {
                outputfolder = mzXMLPath;
            }

            logger.info("Merging PSM files..");
            File output = new File(outputfolder);
            FileWriter writer = new FileWriter(output.getAbsolutePath() + "/PSM_merge.csv");
            boolean header = false;
            for (File csvfile : output.listFiles()) {
                if (csvfile.getName().toLowerCase().endsWith("_psms.csv")) {
                    BufferedReader outreader = new BufferedReader(new FileReader(csvfile));
                    String outline = outreader.readLine();
                    if (!header) {
                        writer.write(outline + "\n");
                        header = true;
                    }
                    while ((outline = outreader.readLine()) != null) {
                        writer.write(outline + "\n");
                    }
                    outreader.close();
                    csvfile.delete();
                }
            }
            writer.close();
        }
        logger.info("MS1 quant module is complete.");
    } catch (Exception e) {
        Logger.getRootLogger().error(ExceptionUtils.getStackTrace(e));
        throw e;
    }
}

From source file:com.cloudera.hts.utils.math.MyFunc2.java

public static void main(String[] args) {

    double[] x = { -5.0, -4.0, -3.0, -2.0, 0, 2, 3, 4 };
    double[] y = { 21, 13, 7, 3, 1, 7, 13, 21 };

    FunctionFitTest fitter = new FunctionFitTest();

    ArrayList<WeightedObservedPoint> points = new ArrayList<WeightedObservedPoint>();

    // Add points here; for instance,
    int i = 0;//  w w  w .j  av  a  2s  . c o  m
    for (double xc : x) {

        if (i < 1) {
            WeightedObservedPoint point = new WeightedObservedPoint(xc, y[i], 1.0);
            points.add(point);

            System.out.println(xc + " " + y[i]);
        }
        i++;
    }

    final double coeffs[] = fitter.fit(points);

    System.out.println(Arrays.toString(coeffs));

}

From source file:net.kahowell.xsd.fuzzer.XmlGenerator.java

/**
 * Drives the application, parsing command-line arguments to determine
 * options./*w  ww  . jav a  2 s  . co m*/
 * 
 * @param args command line args
 */
public static void main(String[] args) {
    try {
        setupLog4j();
        CommandLine commandLine = parser.parse(ConsoleOptions.OPTIONS, args);
        if (commandLine.hasOption("d")) {
            Logger.getLogger("net.kahowell.xsd.fuzzer").setLevel(Level.DEBUG);
        }
        for (Option option : commandLine.getOptions()) {
            if (option.getValue() != null) {
                log.debug("Using " + option.getDescription() + ": " + option.getValue());
            } else {
                log.debug("Using " + option.getDescription());
            }
        }

        Injector injector = Guice.createInjector(
                Modules.override(Modules.combine(new DefaultGeneratorsModule(), new DefaultOptionsModule()))
                        .with(new CommandLineArgumentsModule(commandLine)));

        log.debug(injector.getBindings());

        XsdParser xsdParser = injector.getInstance(XsdParser.class);
        XmlOptions xmlOptions = injector
                .getInstance(Key.get(XmlOptions.class, Names.named("xml save options")));
        XmlGenerator xmlGenerator = injector.getInstance(XmlGenerator.class);
        XmlGenerationOptions xmlGenerationOptions = injector.getInstance(XmlGenerationOptions.class);

        doPostModuleConfig(commandLine, xmlGenerationOptions, injector);

        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        XmlObject generatedXml = xsdParser.generateXml(commandLine.getOptionValue("root"));
        generatedXml.save(stream, xmlOptions);
        if (commandLine.hasOption("v")) {
            if (xsdParser.validate(stream)) {
                log.info("Valid XML file produced.");
            } else {
                log.info("Invalid XML file produced.");
                System.exit(4);
            }
        }
        xmlGenerator.showOrSave(stream);
    } catch (MissingOptionException e) {
        if (e.getMissingOptions().size() != 0) {
            System.err.println("Missing argument(s): " + Arrays.toString(e.getMissingOptions().toArray()));
        }
        helpFormatter.printHelp(XmlGenerator.class.getSimpleName(), ConsoleOptions.OPTIONS);
        System.exit(1);
    } catch (ParseException e) {
        helpFormatter.printHelp(XmlGenerator.class.getSimpleName(), ConsoleOptions.OPTIONS);
        System.exit(2);
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(3);
    }
}

From source file:at.tuwien.ifs.somtoolbox.apps.helper.VectorFileSubsetGenerator.java

public static void main(String[] args) throws IOException, SOMToolboxException {
    // register and parse all options
    JSAPResult config = OptionFactory.parseResults(args, OPTIONS);

    String inputFileName = AbstractOptionFactory.getFilePath(config, "input");
    String classInformationFileName = AbstractOptionFactory.getFilePath(config, "classInformationFile");
    String outputFileName = AbstractOptionFactory.getFilePath(config, "output");

    String[] keepClasses = config.getStringArray("classList");

    boolean skipInstanceNames = false;// config.getBoolean("skipInstanceNames");
    boolean skipInputsWithoutClass = false;// config.getBoolean("skipInputsWithoutClass");
    boolean tabSeparatedClassFile = false;// config.getBoolean("tabSeparatedClassFile");

    String inputFormat = config.getString("inputFormat");
    if (inputFormat == null) {
        inputFormat = InputDataFactory.detectInputFormatFromExtension(inputFileName, "input");
    }//ww  w  .j ava  2s .  c  o m
    String outputFormat = config.getString("outputFormat");
    if (outputFormat == null) {
        outputFormat = InputDataFactory.detectInputFormatFromExtension(outputFileName, "output");
    }

    InputData data = InputDataFactory.open(inputFormat, inputFileName);
    if (classInformationFileName != null) {
        SOMLibClassInformation classInfo = new SOMLibClassInformation(classInformationFileName);
        data.setClassInfo(classInfo);
    }
    if (data.classInformation() == null) {
        throw new SOMToolboxException("Need to provide a class information file.");
    }

    Logger.getLogger("at.tuwien.ifs.somtoolbox")
            .info("Retaining elements of classes: " + Arrays.toString(keepClasses));

    ArrayList<InputDatum> subData = new ArrayList<InputDatum>();
    for (int i = 0; i < data.numVectors(); i++) {
        InputDatum datum = data.getInputDatum(i);
        String className = data.classInformation().getClassName(datum.getLabel());
        System.out.println(datum.getLabel() + "=>" + className);
        if (ArrayUtils.contains(keepClasses, className)) {
            subData.add(datum);
        }
    }

    InputData subset = new SOMLibSparseInputData(subData.toArray(new InputDatum[subData.size()]),
            data.classInformation());
    InputDataWriter.write(outputFileName, subset, outputFormat, tabSeparatedClassFile, skipInstanceNames,
            skipInputsWithoutClass);
}

From source file:fr.inria.atlanmod.kyanos.benchmarks.XmiTraverser.java

public static void main(String[] args) {
    Options options = new Options();

    Option inputOpt = OptionBuilder.create(IN);
    inputOpt.setArgName("INPUT");
    inputOpt.setDescription("Input model");
    inputOpt.setArgs(1);//from   ww  w .jav  a 2  s  . c om
    inputOpt.setRequired(true);

    Option inClassOpt = OptionBuilder.create(EPACKAGE_CLASS);
    inClassOpt.setArgName("CLASS");
    inClassOpt.setDescription("FQN of EPackage implementation class");
    inClassOpt.setArgs(1);
    inClassOpt.setRequired(true);

    options.addOption(inputOpt);
    options.addOption(inClassOpt);

    CommandLineParser parser = new PosixParser();

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

        URI uri = URI.createFileURI(commandLine.getOptionValue(IN));

        Class<?> inClazz = XmiTraverser.class.getClassLoader()
                .loadClass(commandLine.getOptionValue(EPACKAGE_CLASS));
        inClazz.getMethod("init").invoke(null);

        ResourceSet resourceSet = new ResourceSetImpl();
        resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("xmi",
                new XMIResourceFactoryImpl());
        resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("zxmi",
                new XMIResourceFactoryImpl());

        Resource resource = resourceSet.createResource(uri);

        Map<String, Object> loadOpts = new HashMap<String, Object>();
        resource.load(loadOpts);

        LOG.log(Level.INFO, "Start counting");
        int count = 0;
        long begin = System.currentTimeMillis();
        for (Iterator<EObject> iterator = resource.getAllContents(); iterator.hasNext(); iterator
                .next(), count++)
            ;
        long end = System.currentTimeMillis();
        LOG.log(Level.INFO, "End counting");
        LOG.log(Level.INFO, MessageFormat.format("Resource {0} contains {1} elements", uri, count));
        LOG.log(Level.INFO, MessageFormat.format("Time spent: {0}", MessageUtil.formatMillis(end - begin)));

        resource.unload();

    } catch (ParseException e) {
        MessageUtil.showError(e.toString());
        MessageUtil.showError("Current arguments: " + Arrays.toString(args));
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java -jar <this-file.jar>", options, true);
    } catch (Throwable e) {
        MessageUtil.showError(e.toString());
    }
}

From source file:io.anserini.embeddings.WordEmbeddingDictionary.java

public static void main(String[] args) throws Exception {
    WordEmbeddingDictionary.Args dictionaryArgs = new WordEmbeddingDictionary.Args();
    CmdLineParser parser = new CmdLineParser(dictionaryArgs, ParserProperties.defaults().withUsageWidth(90));

    try {// www. jav a 2 s.c  om
        parser.parseArgument(args);
    } catch (CmdLineException e) {
        System.err.println(e.getMessage());
        parser.printUsage(System.err);
        System.err.println("Example: " + WordEmbeddingDictionary.class.getSimpleName()
                + parser.printExample(OptionHandlerFilter.REQUIRED));
        return;
    }

    WordEmbeddingDictionary index = new WordEmbeddingDictionary(dictionaryArgs.index);

    if (!dictionaryArgs.term.isEmpty()) {
        System.out.println(Arrays.toString(index.getEmbeddingVector(dictionaryArgs.term)));
    }
}

From source file:drpc.KMeansDrpcQuery.java

public static void main(final String[] args)
        throws IOException, TException, DRPCExecutionException, DecoderException, ClassNotFoundException {
    if (args.length < 3) {
        System.err.println("Where are the arguments? args -- DrpcServer DrpcFunctionName folder");
        return;//from w ww.  jav  a  2  s . co  m
    }

    final DRPCClient client = new DRPCClient(args[0], 3772, 1000000 /*timeout*/);
    final Queue<String> featureFiles = new ArrayDeque<String>();
    SpoutUtils.listFilesForFolder(new File(args[2]), featureFiles);

    Scanner scanner = new Scanner(featureFiles.peek());
    int i = 0;
    while (scanner.hasNextLine() && i++ < 10) {
        List<Map<String, List<Double>>> dict = SpoutUtils.pythonDictToJava(scanner.nextLine());
        for (Map<String, List<Double>> map : dict) {
            i++;

            Double[] features = map.get("chi2").toArray(new Double[0]);
            Double[] moreFeatures = map.get("chi1").toArray(new Double[0]);
            Double[] rmsd = map.get("rmsd").toArray(new Double[0]);
            Double[] both = (Double[]) ArrayUtils.addAll(features, moreFeatures);
            String parameters = serializeFeatureVector(ArrayUtils.toPrimitive(both));

            String centroidsSerialized = runQuery(args[1], parameters, client);

            Gson gson = new Gson();
            Object[] deserialized = gson.fromJson(centroidsSerialized, Object[].class);

            for (Object obj : deserialized) {
                // result we get is of the form List<result>
                List l = ((List) obj);
                centroidsSerialized = (String) l.get(0);

                String[] centroidSerializedArrays = centroidsSerialized
                        .split(MlStormClustererQuery.KmeansClustererQuery.CENTROID_DELIM);
                List<double[]> centroids = new ArrayList<double[]>();
                for (String centroid : centroidSerializedArrays) {
                    centroids.add(MlStormFeatureVectorUtils.deserializeToFeatureVector(centroid));
                }

                double[] rmsdPrimitive = ArrayUtils.toPrimitive(both);
                double[] rmsdKmeans = new double[centroids.size()];

                for (int k = 0; k < centroids.size(); k++) {
                    System.out.println("centroid        -- " + Arrays.toString(centroids.get(k)));
                    double[] centroid = centroids.get(k);
                    rmsdKmeans[k] = computeRootMeanSquare(centroid);
                }

                System.out.println("1 rmsd original -- " + Arrays.toString(rmsd));
                System.out.println("2 rmsd k- Means -- " + Arrays.toString(rmsdKmeans));
                System.out.println();
            }

        }
    }
    client.close();
}

From source file:fr.inria.atlanmod.kyanos.benchmarks.CdoTraverser.java

public static void main(String[] args) {
    Options options = new Options();

    Option inputOpt = OptionBuilder.create(IN);
    inputOpt.setArgName("INPUT");
    inputOpt.setDescription("Input CDO resource directory");
    inputOpt.setArgs(1);//from   w  w  w .  ja  v a2  s  .com
    inputOpt.setRequired(true);

    Option inClassOpt = OptionBuilder.create(EPACKAGE_CLASS);
    inClassOpt.setArgName("CLASS");
    inClassOpt.setDescription("FQN of EPackage implementation class");
    inClassOpt.setArgs(1);
    inClassOpt.setRequired(true);

    Option repoOpt = OptionBuilder.create(REPO_NAME);
    repoOpt.setArgName("REPO_NAME");
    repoOpt.setDescription("CDO Repository name");
    repoOpt.setArgs(1);
    repoOpt.setRequired(true);

    options.addOption(inputOpt);
    options.addOption(inClassOpt);
    options.addOption(repoOpt);

    CommandLineParser parser = new PosixParser();

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

        String repositoryDir = commandLine.getOptionValue(IN);
        String repositoryName = commandLine.getOptionValue(REPO_NAME);

        Class<?> inClazz = CdoTraverser.class.getClassLoader()
                .loadClass(commandLine.getOptionValue(EPACKAGE_CLASS));
        inClazz.getMethod("init").invoke(null);

        EmbeddedCDOServer server = new EmbeddedCDOServer(repositoryDir, repositoryName);
        try {
            server.run();
            CDOSession session = server.openSession();
            CDOTransaction transaction = session.openTransaction();
            Resource resource = transaction.getRootResource();

            LOG.log(Level.INFO, "Start counting");
            int count = 0;
            long begin = System.currentTimeMillis();
            for (Iterator<EObject> iterator = resource.getAllContents(); iterator.hasNext(); iterator
                    .next(), count++)
                ;
            long end = System.currentTimeMillis();
            LOG.log(Level.INFO, "End counting");
            LOG.log(Level.INFO,
                    MessageFormat.format("Resource {0} contains {1} elements", resource.getURI(), count));
            LOG.log(Level.INFO, MessageFormat.format("Time spent: {0}", MessageUtil.formatMillis(end - begin)));

            transaction.close();
            session.close();
        } finally {
            server.stop();
        }
    } catch (ParseException e) {
        MessageUtil.showError(e.toString());
        MessageUtil.showError("Current arguments: " + Arrays.toString(args));
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java -jar <this-file.jar>", options, true);
    } catch (Throwable e) {
        MessageUtil.showError(e.toString());
    }
}

From source file:org.mitre.mpf.rest.client.Main.java

public static void main(String[] args) throws RestClientException, IOException, InterruptedException {
    System.out.println("Starting rest-client!");

    //not necessary for localhost, but left if a proxy configuration is needed
    //System.setProperty("http.proxyHost","");
    //System.setProperty("http.proxyPort","");  

    String currentDirectory;/*from  w  w w.  ja  v a  2  s . com*/
    currentDirectory = System.getProperty("user.dir");
    System.out.println("Current working directory : " + currentDirectory);

    String username = "mpf";
    String password = "mpf123";
    byte[] encodedBytes = Base64.encodeBase64((username + ":" + password).getBytes());
    String base64 = new String(encodedBytes);
    System.out.println("encodedBytes " + base64);
    final String mpfAuth = "Basic " + base64;

    RequestInterceptor authorize = new RequestInterceptor() {
        @Override
        public void intercept(HttpRequestBase request) {
            request.addHeader("Authorization", mpfAuth /*credentials*/);
        }
    };

    //RestClient client = RestClient.builder().requestInterceptor(authorize).build();
    CustomRestClient client = (CustomRestClient) CustomRestClient.builder()
            .restClientClass(CustomRestClient.class).requestInterceptor(authorize).build();

    //getAvailableWorkPipelineNames
    String url = "http://localhost:8080/workflow-manager/rest/pipelines";
    Map<String, String> params = new HashMap<String, String>();
    List<String> availableWorkPipelines = client.get(url, params, new TypeReference<List<String>>() {
    });
    System.out.println("availableWorkPipelines size: " + availableWorkPipelines.size());
    System.out.println(Arrays.toString(availableWorkPipelines.toArray()));

    //processMedia        
    JobCreationRequest jobCreationRequest = new JobCreationRequest();
    URI uri = Paths.get(currentDirectory,
            "/trunk/workflow-manager/src/test/resources/samples/meds/aa/S001-01-t10_01.jpg").toUri();
    jobCreationRequest.getMedia().add(new JobCreationMediaData(uri.toString()));
    uri = Paths.get(currentDirectory,
            "/trunk/workflow-manager/src/test/resources/samples/meds/aa/S008-01-t10_01.jpg").toUri();
    jobCreationRequest.getMedia().add(new JobCreationMediaData(uri.toString()));
    jobCreationRequest.setExternalId("external id");

    //get first DLIB pipeline
    String firstDlibPipeline = availableWorkPipelines.stream()
            //.peek(pipepline -> System.out.println("will filter - " + pipepline))
            .filter(pipepline -> pipepline.startsWith("DLIB")).findFirst().get();

    System.out.println("found firstDlibPipeline: " + firstDlibPipeline);

    jobCreationRequest.setPipelineName(firstDlibPipeline); //grabbed from 'rest/pipelines' - see #1
    //two optional params
    jobCreationRequest.setBuildOutput(true);
    //jobCreationRequest.setPriority(priority); //will be set to 4 (default) if not set
    JobCreationResponse jobCreationResponse = client.customPostObject(
            "http://localhost:8080/workflow-manager/rest/jobs", jobCreationRequest, JobCreationResponse.class);
    System.out.println("jobCreationResponse job id: " + jobCreationResponse.getJobId());

    System.out.println("\n---Sleeping for 10 seconds to let the job process---\n");
    Thread.sleep(10000);

    //getJobStatus
    url = "http://localhost:8080/workflow-manager/rest/jobs"; // /status";
    params = new HashMap<String, String>();
    //OPTIONAL
    //params.put("v", "") - no versioning currently implemented         
    //id is now a path var - if not set, all job info will returned
    url = url + "/" + Long.toString(jobCreationResponse.getJobId());
    SingleJobInfo jobInfo = client.get(url, params, SingleJobInfo.class);
    System.out.println("jobInfo id: " + jobInfo.getJobId());

    //getSerializedOutput
    String jobIdToGetOutputStr = Long.toString(jobCreationResponse.getJobId());
    url = "http://localhost:8080/workflow-manager/rest/jobs/" + jobIdToGetOutputStr + "/output/detection";
    params = new HashMap<String, String>();
    //REQUIRED  - job id is now a path var and required for this endpoint
    String serializedOutput = client.getAsString(url, params);
    System.out.println("serializedOutput: " + serializedOutput);
}