Example usage for java.util Scanner nextInt

List of usage examples for java.util Scanner nextInt

Introduction

In this page you can find the example usage for java.util Scanner nextInt.

Prototype

public int nextInt() 

Source Link

Document

Scans the next token of the input as an int .

Usage

From source file:gdsc.smlm.ij.plugins.SpotAnalysis.java

private boolean resultsWithinBounds(Rectangle bounds) {
    if (resultsWindowShowing()) {
        float minx = bounds.x;
        float maxx = minx + bounds.width;
        float miny = bounds.y;
        float maxy = miny + bounds.height;

        for (int i = 0; i < resultsWindow.getTextPanel().getLineCount(); i++) {
            String line = resultsWindow.getTextPanel().getLine(i);
            Scanner s = new Scanner(line);
            s.useDelimiter("\t");
            s.nextInt();
            float cx = s.nextFloat(); // cx
            float cy = s.nextFloat(); // cy
            s.close();//from   w  w  w  . ja v  a  2s  .c  o m
            if (cx >= minx && cx <= maxx && cy >= miny && cy <= maxy) {
                return true;
            }
        }
    }
    return false;
}

From source file:mase.MaseManagerTerminal.java

public void run(File runnersFile, File jobsFile) {
    try {/*from  w w  w  .  java  2  s .c o m*/
        if (runnersFile != null) {
            mng.loadRunners(runnersFile);
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    try {
        if (jobsFile != null) {
            mng.loadJobs(jobsFile);
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }

    final Scanner lineSC = new Scanner(System.in);

    while (true) {
        System.out.print("> ");
        String option = lineSC.next();
        Scanner sc = new Scanner(lineSC.nextLine());
        try {
            switch (option) {
            case "addrunner":
                mng.addRunner(sc.nextLine());
                break;
            case "loadrunners":
                while (sc.hasNext()) {
                    mng.loadRunners(new File(sc.next()));
                }
                break;
            case "addjobs":
                mng.addJob(sc.nextLine());
                break;
            case "loadjobs":
                while (sc.hasNext()) {
                    mng.loadJobs(new File(sc.next()));
                }
                break;
            case "remove":
                while (sc.hasNext()) {
                    mng.removeFromWaiting(sc.next());
                }
                break;
            case "killrunner":
                while (sc.hasNextInt()) {
                    mng.killRunner(sc.nextInt());
                }
                break;
            case "kill":
                while (sc.hasNext()) {
                    mng.killJob(sc.next());
                }
                break;
            case "killall":
                mng.failed.addAll(mng.waitingList);
                mng.waitingList.clear();
                List<Job> running = new ArrayList<>(mng.running.values());
                for (Job j : running) {
                    mng.killJob(j.id);
                }
                break;
            case "output":
                int id = sc.nextInt();
                int l = sc.hasNextInt() ? sc.nextInt() : lines;
                System.out.println(mng.getOutput(id, l));
                break;
            case "jobs":
                while (sc.hasNext()) {
                    String jobid = sc.next();
                    List<Job> found = mng.findJobs(jobid);
                    for (Job j : found) {
                        System.out.println(j.detailedToString() + "\n-----------------");
                    }
                }
                break;
            case "status":
                int ls = sc.hasNextInt() ? sc.nextInt() : lines;
                System.out.println("Completed: " + mng.completed.size() + "\tWaiting: " + mng.waitingList.size()
                        + "\tFailed: " + mng.failed.size() + "\tRunning: " + mng.running.size() + "/"
                        + mng.runners.size() + " " + (mng.runningStatus() ? "(ACTIVE)" : "(PAUSED)"));
                for (Entry<JobRunner, Job> e : mng.running.entrySet()) {
                    System.out.println("== " + e.getValue() + " @ " + e.getKey() + " ========");
                    System.out.println(mng.getOutput(e.getKey().id, ls));
                }
                break;
            case "list":
                while (sc.hasNext()) {
                    String t = sc.next();
                    if (t.equals("failed")) {
                        for (int i = mng.failed.size() - 1; i >= 0; i--) {
                            Job j = mng.failed.get(i);
                            System.out.println(df.format(j.submitted) + " " + j);
                        }
                    } else if (t.equals("completed")) {
                        for (int i = mng.completed.size() - 1; i >= 0; i--) {
                            Job j = mng.completed.get(i);
                            System.out.println(df.format(j.submitted) + " " + j);
                        }
                    } else if (t.equals("waiting")) {
                        for (int i = mng.waitingList.size() - 1; i >= 0; i--) {
                            Job j = mng.waitingList.get(i);
                            System.out.println(df.format(j.submitted) + " " + j);
                        }
                    } else if (t.equals("runners")) {
                        for (JobRunner r : mng.runners.values()) {
                            if (mng.running.containsKey(r)) {
                                Job runningJob = mng.running.get(r);
                                System.out
                                        .println(df.format(runningJob.started) + " " + r + " @ " + runningJob);
                            } else {
                                System.out.println("Idle     " + r);
                            }
                        }
                    } else {
                        error("Unknown list: " + t);
                    }
                }
                break;
            case "retry":
                while (sc.hasNext()) {
                    mng.retryJob(sc.next());
                }
                break;
            case "retryfailed":
                mng.retryFailed();
                break;
            case "clear":
                while (sc.hasNext()) {
                    String t = sc.next();
                    if (t.equals("failed")) {
                        mng.failed.clear();
                    } else if (t.equals("completed")) {
                        mng.completed.clear();
                    } else if (t.equals("waiting")) {
                        mng.waitingList.clear();
                    } else if (t.equals("runners")) {
                        List<Integer> runners = new ArrayList<>(mng.runners.keySet());
                        for (Integer r : runners) {
                            mng.killRunner(r);
                        }
                    } else {
                        error("Unknown list: " + t);
                    }
                }
                break;
            case "priority":
                String type = sc.next();
                while (sc.hasNext()) {
                    String i = sc.next();
                    if (type.equals("top")) {
                        mng.topPriority(i);
                    } else if (type.equals("bottom")) {
                        mng.lowestPriority(i);
                    }
                }
                break;
            case "sort":
                String sort = sc.next();
                if (sort.equals("job")) {
                    mng.sortJobFirst();
                } else if (sort.equals("date")) {
                    mng.sortSubmissionDate();
                } else {
                    error("Unknown sorting method: " + sort);
                }
                break;
            case "pause":
                mng.pause(sc.hasNext() && sc.next().equals("force"));
                break;
            case "start":
                mng.resume();
                break;
            case "exit":
                System.exit(0);
                break;
            case "set":
                String par = sc.next();
                switch (par) {
                case "lines":
                    lines = sc.nextInt();
                    break;
                case "maxtries":
                    mng.setMaxTries(sc.nextInt());
                    break;
                }

                break;
            case "mute":
                this.mute = true;
                break;
            case "unmute":
                this.mute = false;
                break;
            case "help":
                System.out.println("Available commands:\n" + "-- addrunner      runner_type [config]\n"
                        + "-- loadrunners    [file]...\n" + "-- addjobs        job_params\n"
                        + "-- loadjobs       [file]...\n" + "-- killrunner     [runner_id]...\n"
                        + "-- remove         [job_id]...\n" + "-- kill           [job_id]...\n"
                        + "-- killall        \n" + "-- output         runner_id [lines]\n"
                        + "-- jobs           [job_id]...\n" + "-- status         [lines]\n"
                        + "-- list           [waiting|completed|failed|runners]...\n"
                        + "-- retry          [job_id]...\n" + "-- retryfailed    \n"
                        + "-- priority       top|bottom [job_id]...\n" + "-- sort           batch|job|date\n"
                        + "-- clear          [waiting|completed|failed|runners]...\n"
                        + "-- pause          [force]\n" + "-- start          \n" + "-- mute|unmute    \n"
                        + "-- exit           \n" + "-- set            lines|tries value");
                break;
            default:
                System.out.println("Unknown command. Try help.");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:gdsc.smlm.ij.plugins.SpotAnalysis.java

private void saveTraces() {
    if (!onFrames.isEmpty() && updated) {
        GenericDialog gd = new GenericDialog(TITLE);
        gd.enableYesNoCancel();//from  www. j  a v  a 2s  .c  om
        gd.hideCancelButton();
        gd.addMessage("The list contains unsaved selected frames.\n \nDo you want to continue?");
        gd.showDialog();
        if (!gd.wasOKed())
            return;
    }

    // For all spots in the results window, get the ID and then save the traces to memory
    if (!resultsWindowShowing())
        return;

    // Create a results set in memory
    MemoryPeakResults results = new MemoryPeakResults();
    results.setName(TITLE);
    results.begin();
    MemoryPeakResults.addResults(results);

    ArrayList<TraceResult> traceResults = new ArrayList<TraceResult>(
            resultsWindow.getTextPanel().getLineCount());
    for (int i = 0; i < resultsWindow.getTextPanel().getLineCount(); i++) {
        String line = resultsWindow.getTextPanel().getLine(i);
        Scanner s = new Scanner(line);
        s.useDelimiter("\t");
        int id = s.nextInt();
        s.nextDouble(); // cx
        s.nextDouble(); // cy
        double signal = s.nextDouble();
        s.close();

        Trace trace = traces.get(id);
        if (trace != null) {
            results.addAll(trace.getPoints());
            traceResults.add(new TraceResult(new Spot(id, signal), trace));
        }
    }

    results.end();

    saveTracesToFile(traceResults);

    IJ.showStatus("Saved traces");
}

From source file:edu.uci.ics.asterix.transaction.management.service.locking.LockManagerDeterministicUnitTest.java

public void readRequest() throws IOException, ACIDException {
    int i = 0;/*from www.java  2s. c  om*/
    LockRequest lockRequest = null;
    TransactionContext txnContext = null;
    HashMap<Integer, TransactionContext> jobMap = new HashMap<Integer, TransactionContext>();

    int threadId;
    String requestType;
    int jobId;
    int datasetId;
    int PKHashVal;
    int waitTime;
    ArrayList<Integer> list = null;
    String lockMode;

    Scanner scanner = new Scanner(new FileInputStream(requestFileName));
    while (scanner.hasNextLine()) {
        try {
            threadId = Integer.parseInt(scanner.next().substring(1));
            requestType = scanner.next();
            if (requestType.equals("CSQ") || requestType.equals("CST") || requestType.equals("END")) {
                log("LockRequest[" + i++ + "]:T" + threadId + "," + requestType);
                lockRequest = new LockRequest("Thread-" + threadId, getRequestType(requestType));
                if (requestType.equals("CSQ") || requestType.equals("CST")) {
                    list = new ArrayList<Integer>();
                    while (scanner.hasNextInt()) {
                        threadId = scanner.nextInt();
                        if (threadId < 0) {
                            break;
                        }
                        list.add(threadId);
                    }
                    expectedResultList.add(list);
                }
            } else if (requestType.equals("DW")) {
                defaultWaitTime = scanner.nextInt();
                log("LockRequest[" + i++ + "]:T" + threadId + "," + requestType + "," + defaultWaitTime);
                continue;
            } else if (requestType.equals("W")) {
                waitTime = scanner.nextInt();
                log("LockRequest[" + i++ + "]:T" + threadId + "," + requestType);
                lockRequest = new LockRequest("Thread-" + threadId, getRequestType(requestType), waitTime);
            } else {
                jobId = Integer.parseInt(scanner.next().substring(1));
                datasetId = Integer.parseInt(scanner.next().substring(1));
                PKHashVal = Integer.parseInt(scanner.next().substring(1));
                lockMode = scanner.next();
                txnContext = jobMap.get(jobId);
                if (txnContext == null) {
                    txnContext = new TransactionContext(new JobId(jobId), txnProvider);
                    jobMap.put(jobId, txnContext);
                }
                log("LockRequest[" + i++ + "]:T" + threadId + "," + requestType + ",J" + jobId + ",D"
                        + datasetId + ",E" + PKHashVal + "," + lockMode);
                lockRequest = new LockRequest("Thread-" + threadId, getRequestType(requestType),
                        new DatasetId(datasetId), PKHashVal, getLockMode(lockMode), txnContext);
            }

            requestList.add(lockRequest);
        } catch (NoSuchElementException e) {
            scanner.close();
            break;
        }
    }
}

From source file:org.orekit.files.sp3.SP3Parser.java

/** Parses a header line from the SP3 file (line number 1 - 22).
 * @param lineNumber the current line number
 * @param line the line as read from the SP3 file
 * @param pi the current {@link ParseInfo} object
 * @throws OrekitException if a non-supported construct is found
 *///  w  ww.j  a  va2  s .c o  m
private void parseHeaderLine(final int lineNumber, final String line, final ParseInfo pi)
        throws OrekitException {

    final SP3File file = pi.file;

    Scanner scanner = null;
    try {
        scanner = new Scanner(line).useDelimiter("\\s+").useLocale(Locale.US);

        // CHECKSTYLE: stop FallThrough check

        switch (lineNumber) {

        // version, epoch, data used and agency information
        case 1: {
            scanner.skip("#");
            final String v = scanner.next();

            final char version = v.substring(0, 1).toLowerCase().charAt(0);
            if (version != 'a' && version != 'b' && version != 'c') {
                throw new OrekitException(OrekitMessages.SP3_UNSUPPORTED_VERSION, version);
            }

            pi.hasVelocityEntries = "V".equals(v.substring(1, 2));

            final int year = Integer.parseInt(v.substring(2));
            final int month = scanner.nextInt();
            final int day = scanner.nextInt();
            final int hour = scanner.nextInt();
            final int minute = scanner.nextInt();
            final double second = scanner.nextDouble();

            final AbsoluteDate epoch = new AbsoluteDate(year, month, day, hour, minute, second,
                    TimeScalesFactory.getGPS());

            file.setEpoch(epoch);

            final int numEpochs = scanner.nextInt();
            file.setNumberOfEpochs(numEpochs);

            // data used indicator
            file.setDataUsed(scanner.next());

            file.setCoordinateSystem(scanner.next());
            file.setOrbitType(SP3OrbitType.valueOf(scanner.next()));
            file.setAgency(scanner.next());
            break;
        }

        // additional date/time references in gps/julian day notation
        case 2: {
            scanner.skip("##");

            // gps week
            file.setGpsWeek(scanner.nextInt());
            // seconds of week
            file.setSecondsOfWeek(scanner.nextDouble());
            // epoch interval
            file.setEpochInterval(scanner.nextDouble());
            // julian day
            file.setJulianDay(scanner.nextInt());
            // day fraction
            file.setDayFraction(scanner.nextDouble());
            break;
        }

        // line 3 contains the number of satellites
        case 3:
            pi.maxSatellites = Integer.parseInt(line.substring(4, 6).trim());
            // fall-through intended - the line contains already the first entries

            // the following 4 lines contain additional satellite ids
        case 4:
        case 5:
        case 6:
        case 7: {
            final int lineLength = line.length();
            int count = file.getSatelliteCount();
            int startIdx = 9;
            while (count++ < pi.maxSatellites && (startIdx + 3) <= lineLength) {
                final String satId = line.substring(startIdx, startIdx + 3).trim();
                file.addSatellite(satId);
                startIdx += 3;
            }
            break;
        }

        // the following 5 lines contain general accuracy information for each satellite
        case 8:
        case 9:
        case 10:
        case 11:
        case 12: {
            final int lineLength = line.length();
            int satIdx = (lineNumber - 8) * 17;
            int startIdx = 9;
            while (satIdx < pi.maxSatellites && (startIdx + 3) <= lineLength) {
                final SatelliteInformation satInfo = file.getSatellite(satIdx++);
                final int exponent = Integer.parseInt(line.substring(startIdx, startIdx + 3).trim());
                // the accuracy is calculated as 2**exp (in m) -> can be safely
                // converted to an integer as there will be no fraction
                satInfo.setAccuracy((int) Math.pow(2d, exponent));
                startIdx += 3;
            }
            break;
        }

        case 13: {
            file.setType(getFileType(line.substring(3, 5).trim()));

            // now identify the time system in use
            final String tsStr = line.substring(9, 12).trim();
            final TimeSystem ts = TimeSystem.GPS;
            if (!tsStr.equalsIgnoreCase("ccc")) {
                TimeSystem.valueOf(tsStr);
            }
            file.setTimeSystem(ts);

            switch (ts) {
            case GPS:
                pi.timeScale = TimeScalesFactory.getGPS();
                break;

            case GAL:
                pi.timeScale = TimeScalesFactory.getGST();
                break;

            case GLO:
            case QZS:
                throw new OrekitException(OrekitMessages.SP3_UNSUPPORTED_TIMESYSTEM, ts.name());

            case TAI:
                pi.timeScale = TimeScalesFactory.getTAI();
                break;

            case UTC:
                pi.timeScale = TimeScalesFactory.getUTC();
                break;

            default:
                pi.timeScale = TimeScalesFactory.getGPS();
                break;
            }
            break;
        }

        case 14:
            // ignore additional custom fields
            break;

        // load base numbers for the standard deviations of
        // position/velocity/clock components
        case 15: {
            // String base = line.substring(3, 13).trim();
            // if (!base.equals("0.0000000")) {
            //    // (mm or 10**-4 mm/sec)
            //    pi.posVelBase = Double.valueOf(base);
            // }

            // base = line.substring(14, 26).trim();
            // if (!base.equals("0.000000000")) {
            //    // (psec or 10**-4 psec/sec)
            //    pi.clockBase = Double.valueOf(base);
            // }
            break;
        }

        case 16:
        case 17:
        case 18:
            // ignore additional custom parameters
            break;

        case 19:
        case 20:
        case 21:
        case 22:
            // ignore comment lines
            break;
        default:
            // ignore -> method should only be called up to line 22
            break;
        }

        // CHECKSTYLE: resume FallThrough check

    } finally {
        if (scanner != null) {
            scanner.close();
        }
    }

}

From source file:com.axelor.studio.service.builder.FormBuilderService.java

private Iterator<ViewPanel> sortPanels(List<ViewPanel> viewPanelList) {

    Collections.sort(viewPanelList, new Comparator<ViewPanel>() {

        @Override/*from w w  w. j  a v  a 2 s . com*/
        public int compare(ViewPanel panel1, ViewPanel panel2) {
            Scanner scan1 = new Scanner(panel1.getPanelLevel());
            Scanner scan2 = new Scanner(panel2.getPanelLevel());
            scan1.useDelimiter("\\.");
            scan2.useDelimiter("\\.");
            try {
                while (scan1.hasNextInt() && scan2.hasNextInt()) {
                    int v1 = scan1.nextInt();
                    int v2 = scan2.nextInt();
                    if (v1 < v2) {
                        return -1;
                    } else if (v1 > v2) {
                        return 1;
                    }
                }

                if (scan2.hasNextInt()) {
                    return -1;
                }
                if (scan1.hasNextInt()) {
                    return 1;
                }

                return 0;
            } finally {
                scan1.close();
                scan2.close();
            }

        }
    });

    return viewPanelList.iterator();
}

From source file:com.joey.software.MoorFLSI.RepeatImageTextReader.java

public void loadTextData(File file) {
    try {//from   w w  w .j a  v  a  2 s.c  o  m
        RandomAccessFile in = new RandomAccessFile(file, "r");

        // Skip header
        in.readLine();
        in.readLine();
        in.readLine();

        // Skip Subject Information
        in.readLine();
        in.readLine();
        in.readLine();
        in.readLine();
        in.readLine();
        in.readLine();
        String startTimeInput = in.readLine();
        String commentsInput = in.readLine();

        String data = in.readLine();
        while (!data.startsWith("2) System Configuration")) {
            commentsInput += data;
            data = in.readLine();
        }
        // System configuration

        // in.readLine();
        in.readLine();
        String timeCounstantInput = in.readLine();
        String cameraGainInput = in.readLine();
        String exposureTimeInput = in.readLine();
        in.readLine();
        in.readLine();
        in.readLine();
        String resolutionInput = in.readLine();

        // Time Data
        in.readLine();
        String timeDataInput = in.readLine();
        String totalImagesInput = in.readLine();
        in.readLine();
        in.readLine();
        // in.readLine();
        // System.out.println(in.readLine());
        // in.readLine();

        // Parse important Size

        high = (new Scanner(resolutionInput.split(":")[1])).nextInt();
        wide = (new Scanner(resolutionInput.split(",")[1])).nextInt();
        int tot = 1;
        try {
            tot = (new Scanner(totalImagesInput.split(":")[1])).nextInt();
        } catch (Exception e) {

        }
        System.out.println(wide + "," + high);
        // Parse timeInformation
        SimpleDateFormat format = new SimpleDateFormat("hh:mm:ss (dd/MM/yy)");
        Date startTime = null;
        try {
            startTime = format.parse(startTimeInput.split(": ")[1]);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        String[] frameTimeData = timeDataInput.split("information:")[1].split(",");

        Date[] timeInfo = new Date[tot];
        for (int i = 0; i < frameTimeData.length - 1; i++) {
            GregorianCalendar cal = new GregorianCalendar();
            cal.setTime(startTime);
            String dat = (frameTimeData[i]);
            String[] timeVals = dat.split(":");

            int hour = Integer.parseInt(StringOperations.removeNonNumber(timeVals[0]));
            int min = Integer.parseInt(StringOperations.removeNonNumber(timeVals[1]));
            int sec = Integer.parseInt(StringOperations.removeNonNumber(timeVals[2]));
            int msec = Integer.parseInt(StringOperations.removeNonNumber(timeVals[3]));

            cal.add(Calendar.HOUR_OF_DAY, hour);
            cal.add(Calendar.MINUTE, min);
            cal.add(Calendar.SECOND, sec);
            cal.add(Calendar.MILLISECOND, msec);
            timeInfo[i] = cal.getTime();
        }

        // Parse Image Data
        /*
         * Close Random access file and switch to scanner first store pos
         * then move to correct point.
         */
        long pos = in.getFilePointer();
        in.close();

        FileInputStream fIn = new FileInputStream(file);
        fIn.skip(pos);

        BufferedInputStream bIn = new BufferedInputStream(fIn);
        Scanner sIn = new Scanner(bIn);

        short[][][] holder = new short[tot][wide][high];

        JFrame f = new JFrame();
        f.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);

        StatusBarPanel stat = new StatusBarPanel();
        stat.setMaximum(high);
        f.getContentPane().setLayout(new BorderLayout());
        f.getContentPane().add(stat, BorderLayout.CENTER);
        f.setSize(200, 60);
        f.setVisible(true);

        for (int i = 0; i < tot; i++) {
            // Skip over the heading values
            stat.setStatusMessage("Loading " + i + " of " + tot);
            sIn.useDelimiter("\n");
            sIn.next();
            sIn.next();
            sIn.next();
            if (i != 0) {
                sIn.next();
            }
            sIn.reset();
            for (int y = 0; y < high; y++) {
                stat.setValue(y);
                sIn.nextInt();
                for (int x = 0; x < wide; x++) {
                    holder[i][x][y] = sIn.nextShort();
                }

            }
            addData(timeInfo[i], holder[i]);
        }

        // FrameFactroy.getFrame(new DynamicRangeImage(data[0]));
        // Start Image Data

    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:ffnn.FFNNTubesAI.java

@Override
public void buildClassifier(Instances i) throws Exception {
    Instance temp_instance = null;/*from  w ww .java2s  .  c  o  m*/
    RealMatrix error_output;
    RealMatrix error_hidden;
    RealMatrix input_matrix;
    RealMatrix hidden_matrix;
    RealMatrix output_matrix;
    Instances temp_instances;
    int r = 0;
    Scanner scan = new Scanner(System.in);

    output_layer = i.numDistinctValues(i.classIndex()); //3
    temp_instances = filterNominalNumeric(i);

    if (output_layer == 2) {
        Add filter = new Add();
        filter.setAttributeIndex("last");
        filter.setAttributeName("dummy");
        filter.setInputFormat(temp_instances);
        temp_instances = Filter.useFilter(temp_instances, filter);
        //            System.out.println(temp_instances);
        for (int j = 0; j < temp_instances.numInstances(); j++) {
            if (temp_instances.instance(j).value(temp_instances.numAttributes() - 2) == 0) {
                temp_instances.instance(j).setValue(temp_instances.numAttributes() - 2, 1);
                temp_instances.instance(j).setValue(temp_instances.numAttributes() - 1, 0);
            } else {
                temp_instances.instance(j).setValue(temp_instances.numAttributes() - 2, 0);
                temp_instances.instance(j).setValue(temp_instances.numAttributes() - 1, 1);
            }
        }
    }

    //temp_instances.randomize(temp_instances.getRandomNumberGenerator(1));
    //System.out.println(temp_instances);
    input_layer = temp_instances.numAttributes() - output_layer; //4
    hidden_layer = 0;
    while (hidden_layer < 1) {
        System.out.print("Hidden layer : ");
        hidden_layer = scan.nextInt();
    }
    int init_hidden = hidden_layer;
    error_hidden = new BlockRealMatrix(1, hidden_layer);
    error_output = new BlockRealMatrix(1, output_layer);
    input_matrix = new BlockRealMatrix(1, input_layer + 1); //Menambahkan bias

    buildWeight(input_layer, hidden_layer, output_layer);

    long last_time = System.nanoTime();
    double last_error_rate = 1;
    double best_error_rate = 1;

    double last_update = System.nanoTime();

    // brp iterasi
    //        for( long itr = 0; last_error_rate > 0.001; ++ itr ){
    for (long itr = 0; itr < 50000; ++itr) {
        if (r == 10) {
            break;
        }
        long time = System.nanoTime();
        if (time - last_time > 2000000000) {
            Evaluation eval = new Evaluation(i);
            eval.evaluateModel(this, i);

            double accry = eval.correct() / eval.numInstances();
            if (eval.errorRate() < last_error_rate) {
                last_update = System.nanoTime();
                if (eval.errorRate() < best_error_rate)
                    SerializationHelper.write(accry + "-" + time + ".model", this);
            }

            if (accry > 0)
                last_error_rate = eval.errorRate();

            // 2 minute without improvement restart
            if (time - last_update > 30000000000L) {
                last_update = System.nanoTime();
                learning_rate = random() * 0.05;
                hidden_layer = (int) (10 + floor(random() * 15));
                hidden_layer = (int) floor((hidden_layer / 25) * init_hidden);
                if (hidden_layer == 0) {
                    hidden_layer = 1;
                }
                itr = 0;
                System.out.println("RESTART " + learning_rate + " " + hidden_layer);
                buildWeight(input_layer, hidden_layer, output_layer);
                r++;
            }

            System.out.println(accry + " " + itr);
            last_time = time;
        }

        for (int j = 0; j < temp_instances.numInstances(); j++) {
            // foward !!
            temp_instance = temp_instances.instance(j);

            for (int k = 0; k < input_layer; k++) {
                input_matrix.setEntry(0, k, temp_instance.value(k));
            }
            input_matrix.setEntry(0, input_layer, 1.0); // bias

            hidden_matrix = input_matrix.multiply(weight1);
            for (int y = 0; y < hidden_layer; ++y) {
                hidden_matrix.setEntry(0, y, sig(hidden_matrix.getEntry(0, y)));
            }

            output_matrix = hidden_matrix.multiply(weight2).add(bias2);
            for (int y = 0; y < output_layer; ++y) {
                output_matrix.setEntry(0, y, sig(output_matrix.getEntry(0, y)));
            }

            // backward <<

            // error layer 2
            double total_err = 0;
            for (int k = 0; k < output_layer; k++) {
                double o = output_matrix.getEntry(0, k);
                double t = temp_instance.value(input_layer + k);
                double err = o * (1 - o) * (t - o);
                total_err += err * err;
                error_output.setEntry(0, k, err);
            }

            // back propagation layer 2
            for (int y = 0; y < hidden_layer; y++) {
                for (int x = 0; x < output_layer; ++x) {
                    double wold = weight2.getEntry(y, x);
                    double correction = learning_rate * error_output.getEntry(0, x)
                            * hidden_matrix.getEntry(0, y);
                    weight2.setEntry(y, x, wold + correction);
                }
            }

            for (int x = 0; x < output_layer; ++x) {
                double correction = learning_rate * error_output.getEntry(0, x); // anggap 1 inputnya
                bias2.setEntry(0, x, bias2.getEntry(0, x) + correction);
            }

            // error layer 1
            for (int k = 0; k < hidden_layer; ++k) {
                double o = hidden_matrix.getEntry(0, k);
                double t = 0;
                for (int x = 0; x < output_layer; ++x) {
                    t += error_output.getEntry(0, x) * weight2.getEntry(k, x);
                }
                double err = o * (1 - o) * t;
                error_hidden.setEntry(0, k, err);
            }

            // back propagation layer 1
            for (int y = 0; y < input_layer + 1; ++y) {
                for (int x = 0; x < hidden_layer; ++x) {
                    double wold = weight1.getEntry(y, x);
                    double correction = learning_rate * error_hidden.getEntry(0, x)
                            * input_matrix.getEntry(0, y);
                    weight1.setEntry(y, x, wold + correction);
                }
            }
        }
    }
}

From source file:gdsc.smlm.ij.plugins.DriftCalculator.java

/**
 * Read the drift file storing the T,X,Y into the class level calculatedTimepoints, lastdx and lastdy
 * arrays. Ignore any records where T is outside the limits.
 * //from w w w.j  a va  2s . c o  m
 * @param limits
 * @return The number of records read
 */
private int readDriftFile(int[] limits) {
    int ok = 0;
    BufferedReader input = null;
    try {
        FileInputStream fis = new FileInputStream(driftFilename);
        input = new BufferedReader(new UnicodeReader(fis, null));

        String line;
        Pattern pattern = Pattern.compile("[\t, ]+");
        while ((line = input.readLine()) != null) {
            if (line.length() == 0)
                continue;
            if (Character.isDigit(line.charAt(0))) {
                try {
                    Scanner scanner = new Scanner(line);
                    scanner.useDelimiter(pattern);
                    scanner.useLocale(Locale.US);
                    final int t = scanner.nextInt();
                    if (t < limits[0] || t > limits[1])
                        continue;
                    final double x = scanner.nextDouble();
                    final double y = scanner.nextDouble();
                    calculatedTimepoints[t] = ++ok;
                    lastdx[t] = x;
                    lastdy[t] = y;
                    scanner.close();
                } catch (InputMismatchException e) {
                } catch (NoSuchElementException e) {
                }
            }
        }
    } catch (IOException e) {
        // ignore
    } finally {
        try {
            if (input != null)
                input.close();
        } catch (IOException e) {
            // Ignore
        }
    }
    return ok;
}

From source file:plptool.gui.ProjectDriver.java

/**
 * GUI: update the develop window to reflect the current state of the
 * project driver (open file, etc.)/* ww  w  . j  ava2 s . co m*/
 *
 * @param commitCurrentAsm Whether to commit currently open asm file
 * in the editor before refreshing.
 * @return PLP_OK
 */
public int refreshProjectView(boolean commitCurrentAsm) {
    Msg.D("Project view refresh...", 3, this);

    if (plpfile == null) {
        g_dev.disableBuildControls();
        g_dev.catchyPLP();

        g_dev.getProjectTree()
                .setModel(new DefaultTreeModel(new DefaultMutableTreeNode("No project file open.")));

        return Constants.PLP_OK;
    }

    if (commitCurrentAsm)
        updateAsm(open_asm, g_dev.getEditorText());

    updateWindowTitle();

    DefaultMutableTreeNode root = new DefaultMutableTreeNode(plpfile.getName());
    DefaultMutableTreeNode srcRoot = new DefaultMutableTreeNode("Source Files");
    DefaultMutableTreeNode metaRoot = new DefaultMutableTreeNode("Meta Information");
    root.add(srcRoot);
    root.add(metaRoot);
    for (int i = 0; i < asms.size(); i++)
        srcRoot.add(new DefaultMutableTreeNode(i + ": " + asms.get(i).getAsmFilePath()));

    Scanner metaScanner = new Scanner(meta);
    metaScanner.findWithinHorizon("DIRTY=", 0);
    int meta_dirty = metaScanner.nextInt();
    metaRoot.add(new DefaultMutableTreeNode("meta.DIRTY=" + meta_dirty));
    metaRoot.add(new DefaultMutableTreeNode("ISA=" + ArchRegistry.getStringID(arch.getID())));

    g_dev.getProjectTree().setModel(new DefaultTreeModel(root));
    for (int i = 0; i < g_dev.getProjectTree().getRowCount(); i++)
        g_dev.getProjectTree().expandRow(i);

    if (!asms.get(open_asm).getAsmString().equals(g_dev.getEditorText()))
        g_dev.setEditorText(asms.get(open_asm).getAsmString());

    g_dev.getEditor().setEnabled(true);
    g_dev.getEditor().setVisible(true);
    g_dev.getEditor().setCaretPosition(0);
    g_dev.enableBuildControls();

    String header = asms.get(open_asm).getAsmFilePath();

    if (open_asm == 0)
        header += " <main program>";

    g_dev.setCurFile(header);

    CallbackRegistry.callback(CallbackRegistry.GUI_VIEW_REFRESH, commitCurrentAsm);
    Msg.D("Done.", 3, this);
    return Constants.PLP_OK;
}