Example usage for java.util List remove

List of usage examples for java.util List remove

Introduction

In this page you can find the example usage for java.util List remove.

Prototype

E remove(int index);

Source Link

Document

Removes the element at the specified position in this list (optional operation).

Usage

From source file:de.tudarmstadt.ukp.csniper.resbuild.stuff.FilterPipe.java

public static void main(String[] args) throws IOException {
    List<String> files = new ArrayList<String>();
    int i = 0;//from   www  .ja  va 2s .c o m
    for (File file : FileUtils.listFiles(new File(base), new String[] { "csv" }, true)) {
        String text = FileUtils.readFileToString(file, "UTF-8");
        files.add(StringUtils.substringBeforeLast(file.getName(), ".") + ".xml");
        if (StringUtils.containsAny(text, "")) {
            files.remove(StringUtils.substringBeforeLast(file.getName(), ".") + ".xml");
        }
        i++;
        if (i % 100 == 0) {
            System.out.println("ok:" + i);
        }
    }

    FileUtils.writeLines(new File("D:\\hadoop\\output\\BNC_new\\exclusions.txt"), "UTF-8", files);
}

From source file:Main.java

License:asdf

public static void main(String[] args) {
    int howManyWords = 2;
    List<String> listOfWords = new ArrayList<>();
    Random random = new Random();
    listOfWords.addAll(Arrays.asList(randomMessages));
    List<String> selectedRandomMessages = new ArrayList<>();
    for (int i = 0; i < howManyWords; i++) {
        int randomNumber = random.nextInt(listOfWords.size());
        String randomItem = listOfWords.get(randomNumber);
        selectedRandomMessages.add(randomItem);
        listOfWords.remove(randomItem);
    }/*from  w  w w . j  a  va  2 s .  co  m*/
    System.out.println(selectedRandomMessages);
}

From source file:com.eviware.loadui.launcher.LoadUILauncher.java

public static void main(String[] args) {
    for (String arg : args) {
        System.out.println("LoadUILauncher arg: " + arg);
        if (arg.contains("cmd")) {
            List<String> argList = new ArrayList<>(Arrays.asList(args));
            argList.remove(arg);
            String[] newArgs = argList.toArray(new String[argList.size()]);
            Application.launch(CommandApplication.class, newArgs);
            return;
        }//from w  w  w.ja v  a2s. c o m
    }

    Application.launch(FXApplication.class, args);

    // Is the below just old legacy code from JavaFX 1?

    //      System.setSecurityManager( null );
    //
    //      LoadUILauncher launcher = new LoadUILauncher( args );
    //      launcher.init();
    //      launcher.start();
    //
    //      new Thread( new LauncherWatchdog( launcher.framework, 20000 ), "loadUI Launcher Watchdog" ).start();
}

From source file:Main.java

public static void main(String[] args) {
    List<String> list = new ArrayList<>();
    list.add("Java");
    list.add("Oracle");
    list.add("CSS");
    list.add("XML");

    System.out.println("List: " + list);

    int count = list.size();
    System.out.println("Size of  List: " + count);

    // Print each element with its index
    for (int i = 0; i < count; i++) {
        String element = list.get(i);
        System.out.println("Index=" + i + ", Element=" + element);
    }/*from ww w  .j  a  v  a 2 s . co  m*/

    List<String> subList = list.subList(1, 3);
    System.out.println(subList);

    // Remove "CSS" from the list 
    list.remove("CSS"); // Same as list.remove(2);
    System.out.println(list);
}

From source file:com.edduarte.protbox.Protbox.java

public static void main(String... args) {

    // activate debug / verbose mode
    if (args.length != 0) {
        List<String> argsList = Arrays.asList(args);
        if (argsList.contains("-v")) {
            Constants.verbose = true;/*from   w ww.  j  av  a 2 s.  co  m*/
        }
    }

    // use System's look and feel
    try {
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    } catch (Exception ex) {
        // If the System's look and feel is not obtainable, continue execution with JRE look and feel
    }

    // check this is a single instance
    try {
        new ServerSocket(1882);
    } catch (IOException ex) {
        JOptionPane.showMessageDialog(null,
                "Another instance of Protbox is already running.\n" + "Please close the other instance first.",
                "Protbox already running", JOptionPane.ERROR_MESSAGE);
        System.exit(1);
    }

    // check if System Tray is supported by this operative system
    if (!SystemTray.isSupported()) {
        JOptionPane.showMessageDialog(null,
                "Your operative system does not support system tray functionality.\n"
                        + "Please try running Protbox on another operative system.",
                "System tray not supported", JOptionPane.ERROR_MESSAGE);
        System.exit(1);
    }

    // add PKCS11 providers
    FileFilter fileFilter = new AndFileFilter(new WildcardFileFilter(Lists.newArrayList("*.config")),
            HiddenFileFilter.VISIBLE);

    File[] providersConfigFiles = new File(Constants.PROVIDERS_DIR).listFiles(fileFilter);

    if (providersConfigFiles != null) {
        for (File f : providersConfigFiles) {
            try {
                List<String> lines = FileUtils.readLines(f);
                String aliasLine = lines.stream().filter(line -> line.contains("alias")).findFirst().get();
                lines.remove(aliasLine);
                String alias = aliasLine.split("=")[1].trim();

                StringBuilder sb = new StringBuilder();
                for (String s : lines) {
                    sb.append(s);
                    sb.append("\n");
                }

                Provider p = new SunPKCS11(new ReaderInputStream(new StringReader(sb.toString())));
                Security.addProvider(p);

                pkcs11Providers.put(p.getName(), alias);

            } catch (IOException | ProviderException ex) {
                if (ex.getMessage().equals("Initialization failed")) {
                    ex.printStackTrace();

                    String s = "The following error occurred:\n" + ex.getCause().getMessage()
                            + "\n\nIn addition, make sure you have "
                            + "an available smart card reader connected before opening the application.";
                    JTextArea textArea = new JTextArea(s);
                    textArea.setColumns(60);
                    textArea.setLineWrap(true);
                    textArea.setWrapStyleWord(true);
                    textArea.setSize(textArea.getPreferredSize().width, 1);

                    JOptionPane.showMessageDialog(null, textArea, "Error loading PKCS11 provider",
                            JOptionPane.ERROR_MESSAGE);
                    System.exit(1);
                } else {
                    ex.printStackTrace();
                    JOptionPane.showMessageDialog(null,
                            "Error while setting up PKCS11 provider from configuration file " + f.getName()
                                    + ".\n" + ex.getMessage(),
                            "Error loading PKCS11 provider", JOptionPane.ERROR_MESSAGE);
                }
            }
        }
    }

    // adds a shutdown hook to save instantiated directories into files when the application is being closed
    Runtime.getRuntime().addShutdownHook(new Thread(Protbox::exit));

    // get system tray and run tray applet
    tray = SystemTray.getSystemTray();
    SwingUtilities.invokeLater(() -> {

        if (Constants.verbose) {
            logger.info("Starting application");
        }

        //Start a new TrayApplet object
        trayApplet = TrayApplet.getInstance();
    });

    // prompts the user to choose which provider to use
    ProviderListWindow.showWindow(Protbox.pkcs11Providers.keySet(), providerName -> {

        // loads eID token
        eIDTokenLoadingWindow.showPrompt(providerName, (returnedUser, returnedCertificateData) -> {
            user = returnedUser;
            certificateData = returnedCertificateData;

            // gets a password to use on the saved registry files (for loading and saving)
            final AtomicReference<Consumer<SecretKey>> consumerHolder = new AtomicReference<>(null);
            consumerHolder.set(password -> {
                registriesPasswordKey = password;
                try {
                    // if there are serialized files, load them if they can be decoded by this user's private key
                    final List<SavedRegistry> serializedDirectories = new ArrayList<>();
                    if (Constants.verbose) {
                        logger.info("Reading serialized registry files...");
                    }

                    File[] registryFileList = new File(Constants.REGISTRIES_DIR).listFiles();
                    if (registryFileList != null) {
                        for (File f : registryFileList) {
                            if (f.isFile()) {
                                byte[] data = FileUtils.readFileToByteArray(f);
                                try {
                                    Cipher cipher = Cipher.getInstance("AES");
                                    cipher.init(Cipher.DECRYPT_MODE, registriesPasswordKey);
                                    byte[] registryDecryptedData = cipher.doFinal(data);
                                    serializedDirectories.add(new SavedRegistry(f, registryDecryptedData));
                                } catch (GeneralSecurityException ex) {
                                    if (Constants.verbose) {
                                        logger.info("Inserted Password does not correspond to " + f.getName());
                                    }
                                }
                            }
                        }
                    }

                    // if there were no serialized directories, show NewDirectory window to configure the first folder
                    if (serializedDirectories.isEmpty() || registryFileList == null) {
                        if (Constants.verbose) {
                            logger.info("No registry files were found: running app as first time!");
                        }
                        NewRegistryWindow.start(true);

                    } else { // there were serialized directories
                        loadRegistry(serializedDirectories);
                        trayApplet.repaint();
                        showTrayApplet();
                    }

                } catch (AWTException | IOException | GeneralSecurityException | ReflectiveOperationException
                        | ProtboxException ex) {

                    JOptionPane.showMessageDialog(null,
                            "The inserted password was invalid! Please try another one!", "Invalid password!",
                            JOptionPane.ERROR_MESSAGE);
                    insertPassword(consumerHolder.get());
                }
            });
            insertPassword(consumerHolder.get());
        });
    });
}

From source file:test.TestJavaService.java

/**
 * Main.  The cmdline arguments either do or don't contain the flag -remote: that's the only supported flag.  If it is specified,
 *   we test code on the AWS instance.  If it is not, we test code running locally.
 * The first non-flag argument is the "verb", which (currently) should be one of the verbs set at the top of source file
 *   org.qcert.javasrc.Main.  Remaining non-flag arguments are file names.  There must be at least one.  The number of such 
 *   arguments and what they should contain depends on the verb.
 * @throws Exception/*from ww w.  jav a2  s  . c  o  m*/
 */
public static void main(String[] args) throws Exception {
    /* Parse command line */
    List<String> files = new ArrayList<>();
    String loc = "localhost", verb = null;
    for (String arg : args) {
        if (arg.equals("-remote"))
            loc = REMOTE_LOC;
        else if (arg.startsWith("-"))
            illegal();
        else if (verb == null)
            verb = arg;
        else
            files.add(arg);
    }
    /* Simple consistency checks and verb-specific parsing */
    if (files.size() == 0)
        illegal();
    String file = files.remove(0);
    String schema = null;
    switch (verb) {
    case "parseSQL":
    case "serialRule2CAMP":
    case "sqlSchema2JSON":
        if (files.size() != 0)
            illegal();
        break;
    case "techRule2CAMP":
        if (files.size() != 1)
            illegal();
        schema = files.get(0);
        break;
    case "csv2JSON":
        if (files.size() < 1)
            illegal();
        break;
    default:
        illegal();
    }

    /* Assemble information from arguments */
    String url = String.format("http://%s:9879?verb=%s", loc, verb);
    byte[] contents = Files.readAllBytes(Paths.get(file));
    String toSend;
    if ("serialRule2CAMP".equals(verb))
        toSend = Base64.getEncoder().encodeToString(contents);
    else
        toSend = new String(contents);
    if ("techRule2CAMP".equals(verb))
        toSend = makeSpecialJson(toSend, schema);
    else if ("csv2JSON".equals(verb))
        toSend = makeSpecialJson(toSend, files);
    HttpClient client = HttpClients.createDefault();
    HttpPost post = new HttpPost(url);
    StringEntity entity = new StringEntity(toSend);
    entity.setContentType("text/plain");
    post.setEntity(entity);
    HttpResponse resp = client.execute(post);
    int code = resp.getStatusLine().getStatusCode();
    if (code == HttpStatus.SC_OK) {
        HttpEntity answer = resp.getEntity();
        InputStream s = answer.getContent();
        BufferedReader rdr = new BufferedReader(new InputStreamReader(s));
        String line = rdr.readLine();
        while (line != null) {
            System.out.println(line);
            line = rdr.readLine();
        }
        rdr.close();
        s.close();
    } else
        System.out.println(resp.getStatusLine());
}

From source file:imp.lstm.main.Driver.java

public static void main(String[] args)
        throws FileNotFoundException, IOException, ConfigurationException, InvalidParametersException {
    FileBasedConfigurationBuilder<PropertiesConfiguration> builder = new FileBasedConfigurationBuilder<>(
            PropertiesConfiguration.class).configure(
                    new Parameters().properties().setFileName(args[0]).setThrowExceptionOnMissing(true)
                            .setListDelimiterHandler(new DefaultListDelimiterHandler(';'))
                            .setIncludesAllowed(false));
    Configuration config = builder.getConfiguration();

    String inputSongPath = config.getString("input_song");
    String outputFolderPath = config.getString("output_folder");
    String autoEncoderParamsPath = config.getString("auto_encoder_params");
    String nameGeneratorParamsPath = config.getString("name_generator_params");
    String queueFolderPath = config.getString("queue_folder");
    String referenceQueuePath = config.getString("reference_queue", "nil");
    String inputCorpusFolder = config.getString("input_corpus_folder");
    boolean shouldWriteQueue = config.getBoolean("should_write_generated_queue");
    boolean frankensteinTest = config.getBoolean("queue_tests_frankenstein");
    boolean interpolateTest = config.getBoolean("queue_tests_interpolation");
    boolean iterateOverCorpus = config.getBoolean("iterate_over_corpus", false);
    boolean shouldGenerateSongTitle = config.getBoolean("generate_song_title");
    boolean shouldGenerateSong = config.getBoolean("generate_leadsheet");

    LogTimer.initStartTime(); //start our logging timer to keep track of our execution time
    LogTimer.log("Creating name generator...");

    //here is just silly code for generating name based on an LSTM lol $wag
    LSTM lstm = new LSTM();
    FullyConnectedLayer fullLayer = new FullyConnectedLayer(Operations.None);
    Loadable titleNetLoader = new Loadable() {
        @Override/* www . jav  a 2s.  com*/
        public boolean load(INDArray array, String path) {
            String car = pathCar(path);
            String cdr = pathCdr(path);
            switch (car) {
            case "full":
                return fullLayer.load(array, cdr);
            case "lstm":
                return lstm.load(array, cdr);
            default:
                return false;
            }
        }
    };

    LogTimer.log("Packing name generator from files...");
    (new NetworkConnectomeLoader()).load(nameGeneratorParamsPath, titleNetLoader);

    String characterString = " !\"'[],-.01245679:?ABCDEFGHIJKLMNOPQRSTUVWYZabcdefghijklmnopqrstuvwxyz";

    //Initialization
    LogTimer.log("Creating autoencoder...");
    int inputSize = 34;
    int outputSize = EncodingParameters.noteEncoder.getNoteLength();
    int featureVectorSize = 100;
    ProductCompressingAutoencoder autoencoder = new ProductCompressingAutoencoder(24, 48, 84 + 1, false); //create our network

    int numInterpolationDivisions = 5;

    //"pack" the network from weights and biases file directory
    LogTimer.log("Packing autoencoder from files");
    (new NetworkConnectomeLoader()).load(autoEncoderParamsPath, autoencoder);

    File[] songFiles;
    if (iterateOverCorpus) {
        songFiles = new File(inputCorpusFolder).listFiles();
    } else {
        songFiles = new File[] { new File(inputSongPath) };
    }
    for (File inputFile : songFiles) {
        (new NetworkConnectomeLoader()).refresh(autoEncoderParamsPath, autoencoder, "initialstate");
        String songTitle;
        if (shouldGenerateSong) {
            Random rand = new Random();
            AVector charOut = Vector.createLength(characterString.length());
            GroupedSoftMaxSampler sampler = new GroupedSoftMaxSampler(
                    new Group[] { new Group(0, characterString.length(), true) });
            songTitle = "";
            for (int i = 0; i < 50; i++) {
                charOut = fullLayer.forward(lstm.step(charOut));
                charOut = sampler.filter(charOut);
                int charIndex = 0;
                for (; charIndex < charOut.length(); charIndex++) {
                    if (charOut.get(charIndex) == 1.0) {
                        break;
                    }
                }
                songTitle += characterString.substring(charIndex, charIndex + 1);
            }
            songTitle = songTitle.trim();

            LogTimer.log("Generated song name: " + songTitle);
        } else {
            songTitle = "The Song We Never Name";
        }
        LogTimer.log("Reading file...");
        LeadSheetDataSequence inputSequence = LeadSheetIO.readLeadSheet(inputFile); //read our leadsheet to get a data vessel as retrieved in rbm-provisor
        LeadSheetDataSequence outputSequence = inputSequence.copy();

        outputSequence.clearMelody();
        if (interpolateTest) {
            LeadSheetDataSequence additionalOutput = outputSequence.copy();
            for (int i = 0; i < numInterpolationDivisions; i++) {
                outputSequence.concat(additionalOutput.copy());
            }
        }
        LeadSheetDataSequence decoderInputSequence = outputSequence.copy();

        LogTimer.startLog("Encoding data...");
        //TradingTimer.initStart(); //start our trading timer to keep track our our generation versus realtime play
        while (inputSequence.hasNext()) { //iterate through time steps in input data
            //TradingTimer.waitForNextTimedInput();
            autoencoder.encodeStep(inputSequence.retrieve()); //feed the resultant input vector into the network
            if (advanceDecoding) { //if we are using advance decoding (we start decoding as soon as we can)
                if (autoencoder.canDecode()) { //if queue has enough data to decode from
                    outputSequence.pushStep(null, null,
                            autoencoder.decodeStep(decoderInputSequence.retrieve())); //take sampled data for a timestep from autoencoder
                    //TradingTimer.logTimestep(); //log our time to TradingTimer so we can know how far ahead of realtime we are
                }
            }
        }
        LogTimer.endLog();

        if (shouldWriteQueue) {
            String queueFilePath = queueFolderPath + java.io.File.separator
                    + inputFile.getName().replace(".ls", ".q");
            FragmentedNeuralQueue currQueue = autoencoder.getQueue();
            currQueue.writeToFile(queueFilePath);
            LogTimer.log("Wrote queue " + inputFile.getName().replace(".ls", ".q") + " to file...");
        }
        if (shouldGenerateSong) {
            if (interpolateTest) {

                FragmentedNeuralQueue refQueue = new FragmentedNeuralQueue();
                refQueue.initFromFile(referenceQueuePath);

                FragmentedNeuralQueue currQueue = autoencoder.getQueue();
                //currQueue.writeToFile(queueFilePath);

                autoencoder.setQueue(currQueue.copy());
                while (autoencoder.hasDataStepsLeft()) { //we are done encoding all time steps, so just finish decoding!{
                    outputSequence.pushStep(null, null,
                            autoencoder.decodeStep(decoderInputSequence.retrieve())); //take sampled data for a timestep from autoencoder
                    //TradingTimer.logTimestep(); //log our time to TradingTimer so we can know how far ahead of realtime we are       
                }

                for (int i = 1; i <= numInterpolationDivisions; i++) {
                    System.out.println("Starting interpolation " + ((1.0 / numInterpolationDivisions) * (i)));
                    (new NetworkConnectomeLoader()).refresh(autoEncoderParamsPath, autoencoder, "initialstate");
                    FragmentedNeuralQueue currCopy = currQueue.copy();
                    currCopy.basicInterpolate(refQueue, (1.0 / numInterpolationDivisions) * (i));
                    autoencoder.setQueue(currCopy);
                    int timeStep = 0;
                    while (autoencoder.hasDataStepsLeft()) { //we are done encoding all time steps, so just finish decoding!{
                        System.out.println("interpolation " + i + " step " + ++timeStep);
                        outputSequence.pushStep(null, null,
                                autoencoder.decodeStep(decoderInputSequence.retrieve())); //take sampled data for a timestep from autoencoder
                        //TradingTimer.logTimestep(); //log our time to TradingTimer so we can know how far ahead of realtime we are       
                    }
                }

            }
            if (frankensteinTest) {
                LogTimer.startLog("Loading queues");
                File queueFolder = new File(queueFolderPath);
                int numComponents = config.getInt("frankenstein_num_components", 5);
                int numCombinations = config.getInt("frankenstein_num_combinations", 6);
                double interpolationMagnitude = config.getDouble("frankenstein_magnitude", 2.0);
                if (queueFolder.isDirectory()) {
                    File[] queueFiles = queueFolder.listFiles(new FilenameFilter() {
                        @Override
                        public boolean accept(File dir, String name) {
                            return name.contains(".q");
                        }
                    });

                    List<File> fileList = new ArrayList<>();
                    for (File file : queueFiles) {
                        fileList.add(file);
                    }
                    Collections.shuffle(fileList);
                    int numSelectedFiles = (numComponents > queueFiles.length) ? queueFiles.length
                            : numComponents;

                    for (int i = 0; i < queueFiles.length - numSelectedFiles; i++) {
                        fileList.remove(fileList.size() - 1);
                    }
                    List<FragmentedNeuralQueue> queuePopulation = new ArrayList<>(fileList.size());
                    songTitle += " - a mix of ";
                    for (File file : fileList) {
                        FragmentedNeuralQueue newQueue = new FragmentedNeuralQueue();
                        newQueue.initFromFile(file.getPath());
                        queuePopulation.add(newQueue);
                        songTitle += file.getName().replaceAll(".ls", "") + ", ";
                    }
                    LogTimer.endLog();

                    LeadSheetDataSequence additionalOutput = outputSequence.copy();
                    for (int i = 1; i < numCombinations; i++) {
                        outputSequence.concat(additionalOutput.copy());
                    }
                    decoderInputSequence = outputSequence.copy();

                    FragmentedNeuralQueue origQueue = autoencoder.getQueue();

                    for (int i = 0; i < numCombinations; i++) {

                        LogTimer.startLog("Performing queue interpolation...");
                        AVector combinationStrengths = Vector.createLength(queuePopulation.size());
                        Random vectorRand = new Random(i);
                        for (int j = 0; j < combinationStrengths.length(); j++) {
                            combinationStrengths.set(j, vectorRand.nextDouble());
                        }
                        combinationStrengths.divide(combinationStrengths.elementSum());
                        FragmentedNeuralQueue currQueue = origQueue.copy();
                        for (int k = 0; k < combinationStrengths.length(); k++) {
                            currQueue.basicInterpolate(queuePopulation.get(k),
                                    combinationStrengths.get(k) * interpolationMagnitude);
                        }
                        LogTimer.endLog();
                        autoencoder.setQueue(currQueue);
                        LogTimer.startLog("Refreshing autoencoder state...");
                        (new NetworkConnectomeLoader()).refresh(autoEncoderParamsPath, autoencoder,
                                "initialstate");
                        LogTimer.endLog();
                        LogTimer.startLog("Decoding segment...");
                        while (autoencoder.hasDataStepsLeft()) { //we are done encoding all time steps, so just finish decoding!{
                            outputSequence.pushStep(null, null,
                                    autoencoder.decodeStep(decoderInputSequence.retrieve())); //take sampled data for a timestep from autoencoder
                            //TradingTimer.logTimestep(); //log our time to TradingTimer so we can know how far ahead of realtime we are       
                        }
                        LogTimer.endLog();
                    }

                }
            }

            while (autoencoder.hasDataStepsLeft()) { //we are done encoding all time steps, so just finish decoding!{
                outputSequence.pushStep(null, null, autoencoder.decodeStep(decoderInputSequence.retrieve())); //take sampled data for a timestep from autoencoder
                //TradingTimer.logTimestep(); //log our time to TradingTimer so we can know how far ahead of realtime we are       
            }
            LogTimer.log("Writing file...");

            String outputFilename = outputFolderPath + java.io.File.separator
                    + inputFile.getName().replace(".ls", "_Output"); //we'll write our generated file with the same name plus "_Output"
            LeadSheetIO.writeLeadSheet(outputSequence, outputFilename, songTitle);
            System.out.println(outputFilename);
        } else {
            autoencoder.setQueue(new FragmentedNeuralQueue());
        }
    }
    LogTimer.log("Process finished"); //Done!

}

From source file:com.urbancode.terraform.main.Main.java

/**
 * This method initializes Terraform from the command line.
 * The static main method verifies the command line arguments and terminates if they are incorrect.
 * @param args//w  ww  .  j  a  v  a  2  s.  c o  m
 * @throws IOException
 * @throws XmlParsingException
 * @throws CredentialsException
 * @throws RestorationException
 * @throws DestructionException
 * @throws CreationException
 */
static public void main(String[] args) throws IOException, XmlParsingException, CredentialsException,
        CreationException, DestructionException, RestorationException {
    File inputXmlFile = null;
    File creds = null;
    List<String> unparsedArgs = new ArrayList<String>();
    String command = null;

    if (args != null && args.length >= 3) {
        if (!AllowedCommands.contains(args[0])) {
            String msg = "Invalid first argument: " + args[0];
            log.fatal(msg);
            throw new IOException(msg);
        } else {
            command = args[0].toLowerCase();
        }

        inputXmlFile = createFile(args[1]);
        creds = createFile(args[2]);

        Collections.addAll(unparsedArgs, args);
        // make args just the unparsed properties
        unparsedArgs.remove(0); // remove inputxmlpath
        unparsedArgs.remove(0); // remove create/destroy
        unparsedArgs.remove(0); // remove creds
    } else {
        log.fatal("Invalid number of arguments!\n" + "Found " + args.length + "\n" + "Expected at least 3");
        throw new IOException("improper args");
    }

    // check to make sure we have legit args
    if (inputXmlFile == null) {
        String msg = "No input xml file specified!";
        throw new IOException(msg);
    }
    if (creds == null) {
        String msg = "No credentials file specified!";
        throw new IOException(msg);
    }

    Main myMain = new Main(command, inputXmlFile, creds, unparsedArgs);
    myMain.execute();
}

From source file:TweetAttributes.java

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

    int k = Integer.parseInt(args[0]);
    String inputFile = args[1];// ww w  .  j a v a2  s.c  o m
    String initialSeedsFile = args[2];
    String outputFile = args[3];

    KMeansJaccard kmj = new KMeansJaccard(k);
    kmj.makeTweetObjects(inputFile);
    List<TweetAttributes> centroidPoints = kmj.getInitialCentroids(initialSeedsFile);

    Map<Long, List<Double>> distanceMap = new LinkedHashMap<>();
    List<TweetAttributes> tweets = kmj.getTweetList();

    buildDistanceMap(centroidPoints, tweets, kmj, distanceMap);

    for (Long i : distanceMap.keySet()) {
        kmj.assignClusterToTweet(i, distanceMap.get(i));
    }

    List<TweetAttributes> tweetCopy = tweets;
    List<TweetAttributes> centroidCopy = centroidPoints;

    double cost = calculateCost(tweets, centroidPoints, kmj);

    Map<Integer, List<TweetAttributes>> tweetClusterMapping = getTweetCLusterMapping(tweets);

    for (Integer i : tweetClusterMapping.keySet()) {
        List<TweetAttributes> ta = tweetClusterMapping.get(i);
        for (TweetAttributes tweet : ta) {
            centroidPoints.remove(i - 1);
            centroidPoints.add(i - 1, tweet);

            distanceMap.clear();
            buildDistanceMap(centroidPoints, tweets, kmj, distanceMap);

            for (Long id : distanceMap.keySet()) {
                kmj.assignClusterToTweet(id, distanceMap.get(id));
            }

            double newCost = calculateCost(tweets, centroidPoints, kmj);

            if (newCost < cost) {
                cost = newCost;
                tweetCopy = kmj.getTweetList();
                centroidCopy = kmj.getCentroidList();
            }

        }
    }
    double sse = calculateSSE(tweetCopy, centroidCopy, kmj);
    System.out.println("COST: " + cost + " " + "SSE:" + sse);
    writeOutputToFile(tweetCopy, outputFile);

}

From source file:edu.stanford.epad.common.pixelmed.TIFFMasksToDSOConverter.java

/**
 * @param args//from w ww . j a  v a2  s. c  o m
 */
public static void main(String[] args) {
    if (args.length < 3) {
        System.out.println(
                "\n\nInvalid arguments.\n\nUsage: java -classpath epad-ws-1.1-jar-with-dependencies.jar edu.stanford.epad.common.pixelmed.TIFFMasksToDSOConverter tiffFolder dicomFolder outputDSO.dcm");
        return;
    }
    String maskFilesDirectory = args[0];
    String dicomFilesDirectory = args[1];
    String outputFileName = args[2];
    //String maskFilesDirectory = "/Stanford/rlabs/data/tiffmasks";
    //String dicomFilesDirectory = "/Stanford/rlabs/data/dicoms";
    //String outputFileName = "/Stanford/rlabs/data/output/dso.dcm";

    List<String> dicomFilePaths = listFilesInAlphabeticOrder(dicomFilesDirectory);
    for (int i = 0; i < dicomFilePaths.size(); i++) {
        if (!dicomFilePaths.get(i).toLowerCase().endsWith(".dcm")) {
            System.out.println("Removing DICOM file " + dicomFilePaths.get(i));
            dicomFilePaths.remove(i);
            i--;
        }
    }
    if (dicomFilePaths.size() == 0) {
        System.out.println("No DICOM files found");
        return;
    }

    List<String> maskFilePaths = listFilesInAlphabeticOrder(maskFilesDirectory);
    for (int i = 0; i < maskFilePaths.size(); i++) {
        if (!maskFilePaths.get(i).toLowerCase().endsWith(".tif")
                && !maskFilePaths.get(i).toLowerCase().endsWith(".tiff")) {
            System.out.println("Removing tif file " + maskFilePaths.get(i));
            maskFilePaths.remove(i);
            i--;
        }
    }
    // Flip them because the code expects that
    List<String> reverseMaskFilePaths = new ArrayList<String>();
    for (int i = maskFilePaths.size(); i > 0; i--) {
        reverseMaskFilePaths.add(maskFilePaths.get(i - 1));
    }
    if (maskFilePaths.size() == 0) {
        System.out.println("No Tif Mask files found");
        return;
    }

    if (dicomFilePaths.size() > maskFilePaths.size())
        dicomFilePaths = dicomFilePaths.subList(0, reverseMaskFilePaths.size());
    else if (reverseMaskFilePaths.size() > dicomFilePaths.size())
        reverseMaskFilePaths = reverseMaskFilePaths.subList(0, dicomFilePaths.size());

    try {
        TIFFMasksToDSOConverter converter = new TIFFMasksToDSOConverter();
        String[] uids = null;
        if (args.length > 3)
            uids = converter.generateDSO(reverseMaskFilePaths, dicomFilePaths, outputFileName, args[3]);
        else
            uids = converter.generateDSO(reverseMaskFilePaths, dicomFilePaths, outputFileName);
        System.out
                .println("DICOM Segmentation Object created. SeriesUID:" + uids[0] + " InstanceUID:" + uids[1]);
    } catch (Exception e) {
        System.err.println(e);
        e.printStackTrace(System.err);
        System.exit(0);
    }
}