Example usage for java.util Scanner hasNext

List of usage examples for java.util Scanner hasNext

Introduction

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

Prototype

public boolean hasNext() 

Source Link

Document

Returns true if this scanner has another token in its input.

Usage

From source file:unalcol.termites.boxplots.SucessfulRatesHybrid.java

private static CategoryDataset createDataset(ArrayList<Double> Pf) {
    DefaultCategoryDataset defaultcategorydataset = new DefaultCategoryDataset();
    String sDirectorio = ".\\experiments\\2015-10-14-Maze\\results";
    File f = new File(sDirectorio);
    String extension;/*w  ww. j a  v  a  2  s.co m*/
    File[] files = f.listFiles();
    Hashtable<String, String> Pop = new Hashtable<>();
    PrintWriter escribir;
    Scanner sc = null;
    double sucessfulExp = 0.0;
    for (File file : files) {
        extension = "";
        int i = file.getName().lastIndexOf('.');
        int p = Math.max(file.getName().lastIndexOf('/'), file.getName().lastIndexOf('\\'));
        if (i > p) {
            extension = file.getName().substring(i + 1);
        }

        // System.out.println(file.getName() + "extension" + extension);
        if (file.isFile() && extension.equals("csv") && file.getName().startsWith("experiment")) {
            System.out.println(file.getName());
            System.out.println("get: " + file.getName());
            String[] filenamep = file.getName().split(Pattern.quote("+"));

            System.out.println("file" + filenamep[8]);

            int popsize = Integer.valueOf(filenamep[2]);
            double pf = Double.valueOf(filenamep[4]);
            String mode = filenamep[6];

            int maxIter = -1;
            //if (!filenamep[8].isEmpty()) {
            maxIter = Integer.valueOf(filenamep[8]);
            //}
            int n = 0;
            int rho = 0;
            double evapRate = 0.0;
            //14, 16, 16
            if (mode.equals("hybrid")) {
                n = Integer.valueOf(filenamep[14]);
                rho = Integer.valueOf(filenamep[16]);
                String[] tmp = filenamep[18].split(Pattern.quote("."));

                System.out.println("history size:" + n);
                System.out.println("rho:" + rho);
                String sEvap = tmp[0] + "." + tmp[1];
                evapRate = Double.valueOf(sEvap);
            }

            System.out.println("psize:" + popsize);
            System.out.println("pf:" + pf);
            System.out.println("mode:" + mode);
            System.out.println("maxIter:" + maxIter);

            //String[] aMode = {"random", "levywalk", "sandc", "sandclw"};
            //String[] aMode = {"lwphclwevap", "lwsandc2", "lwsandc", "lwphevap2", "lwphevap"};
            String[] aMode = { "hybrid", "lwphevap" };

            if (isInMode(aMode, mode)) {
                final List list = new ArrayList();
                try {
                    sc = new Scanner(file);

                } catch (FileNotFoundException ex) {
                    Logger.getLogger(DataCollectedLatexConsolidatorSASOMessagesSend1.class.getName())
                            .log(Level.SEVERE, null, ex);
                }
                int agentsCorrect = 0;
                int worldSize = 0;
                double averageExplored = 0.0;
                int bestRoundNumber = 0;
                double avgSend = 0;
                double avgRecv = 0;
                double avgdataExplInd = 0;
                ArrayList<Double> acSt = new ArrayList<>();
                ArrayList<Double> avgExp = new ArrayList<>();
                ArrayList<Double> bestR = new ArrayList<>();
                ArrayList<Double> avSnd = new ArrayList<>();
                ArrayList<Double> avRecv = new ArrayList<>();
                ArrayList<Double> avIndExpl = new ArrayList<>();

                String[] data = null;
                while (sc.hasNext()) {
                    String line = sc.nextLine();
                    //System.out.println("line:" + line);
                    data = line.split(",");
                    agentsCorrect = Integer.valueOf(data[0]);
                    //agentsIncorrect = Integer.valueOf(data[1]); // not used
                    worldSize = Integer.valueOf(data[3]);
                    averageExplored = Double.valueOf(data[4]);
                    // data[3] stdavgExplored - not used
                    bestRoundNumber = Integer.valueOf(data[6]);
                    avgSend = Double.valueOf(data[7]);
                    avgRecv = Double.valueOf(data[8]);
                    avgdataExplInd = Double.valueOf(data[11]);

                    //Add Data and generate statistics 
                    acSt.add((double) agentsCorrect);
                    avgExp.add(averageExplored);

                    avSnd.add(avgSend);
                    avRecv.add(avgRecv);
                    avIndExpl.add(avgdataExplInd);

                    sucessfulExp = 0.0;
                    for (int j = 0; j < acSt.size(); j++) {
                        if (acSt.get(j) > 0) {
                            sucessfulExp++;
                        }
                    }

                }
                if (Pf.contains(pf)) {
                    if (mode.equals("hybrid")) {
                        String nameSeries = n + "-" + rho + "-" + evapRate;
                        defaultcategorydataset.addValue(((double) sucessfulExp) / acSt.size() * 100.0,
                                "" + popsize, nameSeries);
                    } else {
                        defaultcategorydataset.addValue(((double) sucessfulExp) / acSt.size() * 100.0,
                                "" + popsize, getTechniqueName(mode) + "\nPf:" + pf);
                    }
                    /*pf == 1.0E-4 || pf == 3.0E-4*/
                }
            }
        }

    }
    return defaultcategorydataset;
}

From source file:io.minio.MinioClient.java

/**
 * Executes complete multipart upload of given bucket name, object name, upload ID and parts.
 *//* ww w.jav a 2  s.  com*/
private void completeMultipart(String bucketName, String objectName, String uploadId, Part[] parts)
        throws InvalidBucketNameException, NoSuchAlgorithmException, InsufficientDataException, IOException,
        InvalidKeyException, NoResponseException, XmlPullParserException, ErrorResponseException,
        InternalException {
    Map<String, String> queryParamMap = new HashMap<>();
    queryParamMap.put(UPLOAD_ID, uploadId);

    CompleteMultipartUpload completeManifest = new CompleteMultipartUpload(parts);

    HttpResponse response = executePost(bucketName, objectName, null, queryParamMap, completeManifest);

    // Fixing issue https://github.com/minio/minio-java/issues/391
    String bodyContent = "";
    try {
        // read enitre body stream to string.
        Scanner scanner = new java.util.Scanner(response.body().charStream()).useDelimiter("\\A");
        if (scanner.hasNext()) {
            bodyContent = scanner.next();
        }
    } catch (EOFException e) {
        // Getting EOF exception is not an error.
        // Just log it.
        LOGGER.log(Level.WARNING, "EOF exception occured: " + e);
    } finally {
        response.body().close();
    }

    bodyContent = bodyContent.trim();
    if (!bodyContent.isEmpty()) {
        ErrorResponse errorResponse = new ErrorResponse(new StringReader(bodyContent));
        if (errorResponse.code() != null) {
            throw new ErrorResponseException(errorResponse, response.response());
        }
    }
}

From source file:org.de.jmg.learn.MainActivity.java

private void processPreferences(boolean blnReStarted) {
    libLearn.gStatus = "getting preferences";
    try {// w  w w.ja va2s  .c o m
        libLearn.gStatus = "onCreate getPrefs";
        prefs = this.getPreferences(Context.MODE_PRIVATE);
        String Installer = this.getPackageManager().getInstallerPackageName(this.getPackageName());
        if (!blnReStarted) {
            if (prefs.getBoolean("play", true)
                    && (Installer == null || (!Installer.equalsIgnoreCase("com.android.vending")
                            && !Installer.contains("com.google.android")))) {
                lib.YesNoCheckResult res = lib.ShowMessageYesNoWithCheckbox(this,
                        Installer != null ? Installer : "", this.getString(R.string.msgNotGooglePlay),
                        this.getString(R.string.msgDontShowThisMessageAgain), false);
                if (res != null) {
                    prefs.edit().putBoolean("play", !res.checked).commit();
                    if (res.res == yesnoundefined.yes) {
                        String url = "https://play.google.com/store/apps/details?id=org.de.jmg.learn";//"https://play.google.com/apps/testing/org.de.jmg.learn";
                        Intent i = new Intent(Intent.ACTION_VIEW);
                        i.setData(Uri.parse(url));
                        startActivity(i);
                        finish();
                    }
                }
            } else {
                //lib.ShowMessageOKCancel(this,this.getString(R.string.msgAppStarted),"",true);
            }
        }
        vok = new Vokabel(this, (TextView) this.findViewById(R.id.txtStatus));
        if (fPA.fragMain != null)
            fPA.fragMain._vok = vok;
        vok.setSchrittweite((short) prefs.getInt("Schrittweite", 6));
        CharsetASCII = prefs.getString("CharsetASCII", "Windows-1252");
        vok.CharsetASCII = CharsetASCII;
        vok.setAbfragebereich((short) prefs.getInt("Abfragebereich", -1));
        DisplayDurationWord = prefs.getFloat("DisplayDurationWord", 1.5f);
        DisplayDurationBed = prefs.getFloat("DisplayDurationBed", 2.5f);
        PaukRepetitions = prefs.getInt("PaukRepetitions", 3);
        vok.ProbabilityFactor = prefs.getFloat("ProbabilityFactor", -1f);
        vok.setAbfrageZufaellig(prefs.getBoolean("Random", vok.getAbfrageZufaellig()));
        vok.setAskAll(prefs.getBoolean("AskAll", vok.getAskAll()));
        vok.RestartInterval = prefs.getInt("RestartInterval", 10);
        lib.sndEnabled = prefs.getBoolean("Sound", lib.sndEnabled);
        SoundDir = prefs.getString("SoundDir", Environment.getExternalStorageDirectory().getPath());
        Colors = getColorsFromPrefs();
        colSounds = getSoundsFromPrefs();
        blnTextToSpeech = prefs.getBoolean("TextToSpeech", true);
        StartTextToSpeech();

        boolean blnLicenseAccepted = prefs.getBoolean("LicenseAccepted", false);
        if (!blnLicenseAccepted) {
            InputStream is = this.getAssets().open("LICENSE");
            java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
            String strLicense = s.hasNext() ? s.next() : "";
            s.close();
            is.close();
            lib.yesnoundefined res = (lib.ShowMessageYesNo(this, strLicense, getString(R.string.license),
                    true));
            /*
            java.lang.CharSequence[] cbxs = {getString(R.string.gpl),getString(R.string.gplno)};
            boolean[] blns = {false,false};
            lib.yesnoundefined res = (lib.ShowMessageYesNoWithCheckboxes
             (this,
                   strLicense,
                   cbxs,
                   blns,
                   new DialogInterface.OnMultiChoiceClickListener() {
                    
                      @Override
                      public void onClick(DialogInterface dialog, int which, boolean isChecked) {
                    
                      }
                   })
            );
            */
            if (res == lib.yesnoundefined.yes) {
                prefs.edit().putBoolean("LicenseAccepted", true).commit();
            } else {
                finish();
            }

        }
    } catch (Exception e) {

        lib.ShowException(this, e);
    }
}

From source file:io.minio.MinioClient.java

/**
 * Executes given request parameters./*from  w  ww.  j a  v  a  2s.co  m*/
 *
 * @param method         HTTP method.
 * @param region         Amazon S3 region of the bucket.
 * @param bucketName     Bucket name.
 * @param objectName     Object name in the bucket.
 * @param headerMap      Map of HTTP headers for the request.
 * @param queryParamMap  Map of HTTP query parameters of the request.
 * @param contentType    Content type of the request body.
 * @param body           HTTP request body.
 * @param length         Length of HTTP request body.
 */
private HttpResponse execute(Method method, String region, String bucketName, String objectName,
        Map<String, String> headerMap, Map<String, String> queryParamMap, String contentType, Object body,
        int length) throws InvalidBucketNameException, NoSuchAlgorithmException, InsufficientDataException,
        IOException, InvalidKeyException, NoResponseException, XmlPullParserException, ErrorResponseException,
        InternalException {
    Request request = createRequest(method, bucketName, objectName, region, headerMap, queryParamMap,
            contentType, body, length);

    if (this.accessKey != null && this.secretKey != null) {
        request = Signer.signV4(request, region, accessKey, secretKey);
    }

    if (this.traceStream != null) {
        this.traceStream.println("---------START-HTTP---------");
        String encodedPath = request.httpUrl().encodedPath();
        String encodedQuery = request.httpUrl().encodedQuery();
        if (encodedQuery != null) {
            encodedPath += "?" + encodedQuery;
        }
        this.traceStream.println(request.method() + " " + encodedPath + " HTTP/1.1");
        String headers = request.headers().toString().replaceAll("Signature=([0-9a-f]+)",
                "Signature=*REDACTED*");
        this.traceStream.println(headers);
    }

    Response response = this.httpClient.newCall(request).execute();
    if (response == null) {
        if (this.traceStream != null) {
            this.traceStream.println("<NO RESPONSE>");
            this.traceStream.println(END_HTTP);
        }
        throw new NoResponseException();
    }

    if (this.traceStream != null) {
        this.traceStream.println(response.protocol().toString().toUpperCase() + " " + response.code());
        this.traceStream.println(response.headers());
    }

    ResponseHeader header = new ResponseHeader();
    HeaderParser.set(response.headers(), header);

    if (response.isSuccessful()) {
        if (this.traceStream != null) {
            this.traceStream.println(END_HTTP);
        }
        return new HttpResponse(header, response);
    }

    ErrorResponse errorResponse = null;

    // HEAD returns no body, and fails on parseXml
    if (!method.equals(Method.HEAD)) {
        try {
            String errorXml = "";

            // read entire body stream to string.
            Scanner scanner = new java.util.Scanner(response.body().charStream()).useDelimiter("\\A");
            if (scanner.hasNext()) {
                errorXml = scanner.next();
            }

            errorResponse = new ErrorResponse(new StringReader(errorXml));

            if (this.traceStream != null) {
                this.traceStream.println(errorXml);
            }
        } finally {
            response.body().close();
        }
    }

    if (this.traceStream != null) {
        this.traceStream.println(END_HTTP);
    }

    if (errorResponse == null) {
        ErrorCode ec;
        switch (response.code()) {
        case 400:
            ec = ErrorCode.INVALID_URI;
            break;
        case 404:
            if (objectName != null) {
                ec = ErrorCode.NO_SUCH_KEY;
            } else if (bucketName != null) {
                ec = ErrorCode.NO_SUCH_BUCKET;
            } else {
                ec = ErrorCode.RESOURCE_NOT_FOUND;
            }
            break;
        case 501:
        case 405:
            ec = ErrorCode.METHOD_NOT_ALLOWED;
            break;
        case 409:
            if (bucketName != null) {
                ec = ErrorCode.NO_SUCH_BUCKET;
            } else {
                ec = ErrorCode.RESOURCE_CONFLICT;
            }
            break;
        case 403:
            ec = ErrorCode.ACCESS_DENIED;
            break;
        default:
            throw new InternalException("unhandled HTTP code " + response.code()
                    + ".  Please report this issue at " + "https://github.com/minio/minio-java/issues");
        }

        errorResponse = new ErrorResponse(ec, bucketName, objectName, request.httpUrl().encodedPath(),
                header.xamzRequestId(), header.xamzId2());
    }

    // invalidate region cache if needed
    if (errorResponse.errorCode() == ErrorCode.NO_SUCH_BUCKET) {
        BucketRegionCache.INSTANCE.remove(bucketName);
        // TODO: handle for other cases as well
        // observation: on HEAD of a bucket with wrong region gives 400 without body
    }

    throw new ErrorResponseException(errorResponse, response);
}

From source file:unalcol.termites.boxplots.HybridGlobalInfoReport.java

private static void createSuperGraph() {
    XYSeriesCollection juegoDatos = null;
    Hashtable<String, XYSeriesCollection> dataCollected = new Hashtable();
    DefaultCategoryDataset defaultcategorydataset = new DefaultCategoryDataset();
    String sDirectorio = experimentsDir;
    File f = new File(sDirectorio);
    String extension;//from   www  .  j a  va 2s  .c  o m
    File[] files = f.listFiles();
    Hashtable<String, String> Pop = new Hashtable<>();
    PrintWriter escribir;
    Scanner sc = null;
    double sucessfulExp = 0.0;
    for (File file : files) {
        extension = "";
        int i = file.getName().lastIndexOf('.');
        int p = Math.max(file.getName().lastIndexOf('/'), file.getName().lastIndexOf('\\'));
        if (i > p) {
            extension = file.getName().substring(i + 1);
        }
        // System.out.println(file.getName() + "extension" + extension);
        if (file.isFile() && extension.equals("csv") && file.getName().startsWith("dataCollected")
                && file.getName().contains(mazeMode)) {
            System.out.println(file.getName());
            System.out.println("get: " + file.getName());
            String[] filenamep = file.getName().split(Pattern.quote("+"));
            XYSeries globalInfo;

            System.out.println("file" + filenamep[9]);

            int popsize = Integer.valueOf(filenamep[3]);
            double pf = Double.valueOf(filenamep[5]);
            String mode = filenamep[7];

            int maxIter = -1;
            //if (!filenamep[8].isEmpty()) {
            maxIter = Integer.valueOf(filenamep[9]);
            //}
            int n = 0;
            int rho = 0;
            double evapRate = 0.0;
            //14, 16, 16
            if (mode.equals("hybrid")) {
                n = Integer.valueOf(filenamep[15]);
                rho = Integer.valueOf(filenamep[17]);
                String[] tmp = filenamep[19].split(Pattern.quote("."));

                System.out.println("history size:" + n);
                System.out.println("rho:" + rho);
                String sEvap = tmp[0] + "." + tmp[1];
                evapRate = Double.valueOf(sEvap);
            }

            System.out.println("psize:" + popsize);
            System.out.println("pf:" + pf);
            System.out.println("mode:" + mode);
            System.out.println("maxIter:" + maxIter);

            //String[] aMode = {"random", "levywalk", "sandc", "sandclw"};
            //String[] aMode = {"lwphclwevap", "lwsandc2", "lwsandc", "lwphevap2", "lwphevap"};
            //String[] aMode = {"hybrid", "lwphevap", "levywalk"};
            //String[] aMode = {"levywalk", "lwphevap", "hybrid", "hybrid3", "hybrid4", "sequential"};
            String key;
            if (mode.equals("hybrid")) {
                key = getTechniqueName(mode) + "+" + pf + "+" + rho + "+" + n + "+" + popsize + "+" + evapRate;
            } else {
                key = getTechniqueName(mode) + "+" + pf + "+" + popsize + "+" + evapRate;
            }

            System.out.println("key" + key);
            if (isInMode(aMode, mode)) {
                final List list = new ArrayList();
                try {
                    sc = new Scanner(file);

                } catch (FileNotFoundException ex) {
                    Logger.getLogger(DataCollectedLatexConsolidatorSASOMessagesSend1.class.getName())
                            .log(Level.SEVERE, null, ex);
                }
                int roundNumber = 0;
                double globalInfoCollected = 0.0;

                //ArrayList<Double> acSt = new ArrayList<>();
                //ArrayList<Double> avgExp = new ArrayList<>();
                String[] data = null;
                globalInfo = new XYSeries("");
                while (sc.hasNext()) {
                    String line = sc.nextLine();
                    //System.out.println("line:" + line);
                    data = line.split(",");
                    roundNumber = Integer.valueOf(data[0]);
                    globalInfoCollected = Double.valueOf(data[4]);

                    if (globalInfoCollected > 100) {
                        System.out.println("more than 100:" + file.getName());
                    } else {
                        globalInfo.add(roundNumber, globalInfoCollected);
                    }
                    //System.out.println("r" + roundNumber + "dc:" + globalInfoCollected);
                    //Add Data and generate statistics 
                    //acSt.add((double) agentsCorrect);
                    //avgExp.add(averageExplored);
                }

                if (!dataCollected.containsKey(key)) {
                    juegoDatos = new XYSeriesCollection();
                    juegoDatos.addSeries(globalInfo);
                    dataCollected.put(key, juegoDatos);
                } else {
                    ((XYSeriesCollection) dataCollected.get(key)).addSeries(globalInfo);
                }
                //if (Pf.contains(pf)) {
                /*if (mode.equals("hybrid")) {
                String nameSeries = n + "-" + rho + "-" + evapRate;
                defaultcategorydataset.addValue(((double) sucessfulExp) / acSt.size() * 100.0, "" + popsize, nameSeries);
                } else {
                defaultcategorydataset.addValue(((double) sucessfulExp) / acSt.size() * 100.0, "" + popsize, getTechniqueName(mode) + "\nPf:" + pf);
                }*/
                /*pf == 1.0E-4 || pf == 3.0E-4*/
                //}
            }
        }
    }
    createChart(dataCollected);
}

From source file:org.de.jmg.learn.MainActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.

    try {/*from   ww w . j  ava  2 s.co  m*/
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            mPager.setCurrentItem(SettingsActivity.fragID);
        } else if (id == R.id.mnuCredits) {
            InputStream is = this.getAssets().open("CREDITS");
            java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
            String strCredits = s.hasNext() ? s.next() : "";
            s.close();
            is.close();
            String versionName = context.getPackageManager().getPackageInfo(context.getPackageName(),
                    0).versionName;
            Spannable spn = lib.getSpanableString(strCredits + "\nV" + versionName);
            lib.ShowMessage(this, spn, "Credits");
        } else if (id == R.id.mnuContact) {
            Intent intent = new Intent(Intent.ACTION_SEND,
                    Uri.fromParts("mailto", "jhmgbl2@t-online.de", null));
            intent.setType("message/rfc822");
            intent.putExtra(Intent.EXTRA_EMAIL, new String[] { "jhmgbl2@t-online.de" });
            String versionName = context.getPackageManager().getPackageInfo(context.getPackageName(),
                    0).versionName;
            intent.putExtra(Intent.EXTRA_SUBJECT, "learnforandroid " + versionName);
            intent.putExtra(Intent.EXTRA_TEXT, getString(R.string.ConvertVok));
            this.startActivity(Intent.createChooser(intent, getString(R.string.SendMail)));
        } else if (id == R.id.mnuFileOpen) {
            mPager.setCurrentItem(fragFileChooser.fragID);
            //LoadFile(true);
        } else if (id == R.id.mnuHome) {
            mPager.setCurrentItem(_MainActivity.fragID);
        } else if (id == R.id.mnuOpenQuizlet) {
            //LoginQuizlet();
            if (mPager.getCurrentItem() != fragFileChooserQuizlet.fragID) {
                mPager.setCurrentItem(fragFileChooserQuizlet.fragID);
            } else {
                if (fPA != null && fPA.fragQuizlet != null) {
                    searchQuizlet();
                }
            }
        } else if (id == R.id.mnuUploadToQuizlet) {
            uploadtoQuizlet();

        } else if (id == R.id.mnuAskReverse) {
            item.setChecked(!item.isChecked());
            vok.reverse = item.isChecked();
            setMnuReverse();
        } else if (id == R.id.mnuOpenUri) {
            if (saveVok(false)) {
                String defaultURI = prefs.getString("defaultURI", "");
                Uri def;
                if (libString.IsNullOrEmpty(defaultURI)) {
                    File F = new File(JMGDataDirectory);
                    def = Uri.fromFile(F);
                } else {
                    def = Uri.parse(defaultURI);
                }
                lib.SelectFile(this, def);
            }
        } else if (id == R.id.mnuNew) {
            newVok();

        } else if (id == R.id.mnuAddWord) {
            mPager.setCurrentItem(_MainActivity.fragID);
            if (fPA.fragMain != null && fPA.fragMain.mainView != null) {
                if (fPA.fragMain.EndEdit(false)) {
                    vok.AddVokabel();
                    fPA.fragMain.getVokabel(true, false, true);
                    fPA.fragMain.StartEdit();
                }
            }

        } else if (id == R.id.mnuFileOpenASCII) {
            LoadFile(false);
        } else if (id == R.id.mnuConvMulti) {
            if (fPA.fragMain != null && fPA.fragMain.mainView != null) {
                vok.ConvertMulti();
                fPA.fragMain.getVokabel(false, false);
            }
        } else if (id == R.id.mnuFileSave) {
            saveVok(false);
        } else if (id == R.id.mnuSaveAs) {
            SaveVokAs(true, false);
        } else if (id == R.id.mnuRestart) {
            vok.restart();
        } else if (id == R.id.mnuDelete) {
            if (fPA.fragMain != null && fPA.fragMain.mainView != null) {
                vok.DeleteVokabel();
                fPA.fragMain.EndEdit2();
            }
        } else if (id == R.id.mnuReverse) {
            if (fPA.fragMain != null && fPA.fragMain.mainView != null) {
                vok.revert();
                fPA.fragMain.getVokabel(false, false);
            }
        } else if (id == R.id.mnuReset) {
            if (lib.ShowMessageYesNo(this, this.getString(R.string.ResetVocabulary),
                    "") == yesnoundefined.yes) {
                vok.reset();
            }

        } else if (id == R.id.mnuStatistics) {
            if (vok.getGesamtzahl() > 5) {
                try {
                    /*
                    IDemoChart chart = new org.de.jmg.learn.chart.LearnBarChart();
                    int UIMode = lib.getUIMode(this);
                            
                    switch (UIMode)
                    {
                    case Configuration.UI_MODE_TYPE_TELEVISION:
                    isTV = true;
                    break;
                    case Configuration.UI_MODE_TYPE_WATCH:
                    isWatch = true;
                    break;
                    }
                    Intent intent = chart.execute(this);
                    this.startActivity(intent);
                    */
                    mPager.setCurrentItem(fragStatistics.fragID);
                } catch (Exception ex) {
                    lib.ShowException(this, ex);
                }

            }
        } else if (id == R.id.mnuEdit) {
            if (fPA.fragMain != null && fPA.fragMain.mainView != null) {
                fPA.fragMain.edit();
            }
        } else if (id == R.id.mnuLoginQuizlet) {
            LoginQuizlet(false);
        }

    } catch (Throwable ex) {
        lib.ShowException(this, ex);
    }

    return super.onOptionsItemSelected(item);
}

From source file:unalcol.termites.boxplots.RoundNumberGlobal.java

/**
 * Creates a sample dataset.//from ww w . j a  v  a  2s  .  c o  m
 *
 * @return A sample dataset.
 */
private BoxAndWhiskerCategoryDataset createSampleDataset(ArrayList<Double> Pf) {

    final int seriesCount = 5;
    final int categoryCount = 4;
    final int entityCount = 22;
    //String sDirectorio = "experiments\\2015-10-30-mazeoff";
    File f = new File(experimentsDir);
    String extension;
    File[] files = f.listFiles();
    Hashtable<String, String> Pop = new Hashtable<>();
    PrintWriter escribir;
    Scanner sc = null;
    ArrayList<Integer> aPops = new ArrayList<>();
    ArrayList<Double> aPf = new ArrayList<>();
    ArrayList<String> aTech = new ArrayList<>();

    Hashtable<String, List> info = new Hashtable();

    //String[] aMode = {"levywalk", "lwphevap", "hybrid", "hybrid3", "hybrid4"};
    for (String mode : aMode) {
        info.put(mode, new ArrayList());
    }

    final DefaultBoxAndWhiskerCategoryDataset dataset = new DefaultBoxAndWhiskerCategoryDataset();

    for (File file : files) {
        extension = "";
        int i = file.getName().lastIndexOf('.');
        int p = Math.max(file.getName().lastIndexOf('/'), file.getName().lastIndexOf('\\'));
        if (i > p) {
            extension = file.getName().substring(i + 1);
        }

        // System.out.println(file.getName() + "extension" + extension);
        if (file.isFile() && extension.equals("csv") && file.getName().startsWith("dataCollected")) {
            System.out.println(file.getName());
            System.out.println("get: " + file.getName());
            String[] filenamep = file.getName().split(Pattern.quote("+"));

            System.out.println("file" + filenamep[8]);

            int popsize = Integer.valueOf(filenamep[3]);
            double pf = Double.valueOf(filenamep[5]);
            String mode = filenamep[7];

            int maxIter = -1;
            //if (!filenamep[8].isEmpty()) {
            maxIter = Integer.valueOf(filenamep[9]);
            //}

            System.out.println("psize:" + popsize);
            System.out.println("pf:" + pf);
            System.out.println("mode:" + mode);
            System.out.println("maxIter:" + maxIter);

            //String[] aMode = {"random", "levywalk", "sandc", "sandclw"};
            //String[] aMode = {"levywalk", "lwphevap", "hybrid", "hybrid3", "hybrid4", "sequential"};
            //String[] aMode = {"levywalk", "lwphevap", "hybrid", "sequential"};

            if (/*Pf == pf && */isInMode(aMode, mode)) {
                final List list = new ArrayList();
                try {
                    sc = new Scanner(file);

                } catch (FileNotFoundException ex) {
                    Logger.getLogger(DataCollectedLatexConsolidatorSASOMessagesSend1.class.getName())
                            .log(Level.SEVERE, null, ex);
                }
                int roundNumber = 0;
                double globalInfoCollected = 0;

                String[] data = null;
                while (sc.hasNext()) {
                    String line = sc.nextLine();
                    data = line.split(",");
                    //System.out.println("data");
                    roundNumber = Integer.valueOf(data[0]);
                    globalInfoCollected = Double.valueOf(data[4]);

                    if (globalInfoCollected >= 90 && Pf.contains(pf)) {
                        info.get(mode).add(roundNumber);
                        break;
                    }

                }

                LOGGER.debug("Adding series " + i);
                LOGGER.debug(list.toString());
                if (Pf.contains(pf)) {
                    /*pf == 1.0E-4 || pf == 3.0E-4*/
                    if (Pf.size() == 1) {
                        dataset.add(list, popsize, getTechniqueName(mode));
                    } else {
                        dataset.add(list, String.valueOf(popsize) + "-" + pf, getTechniqueName(mode));
                    }
                }
            }
        }

    }

    for (String key : info.keySet()) {
        System.out.println(key + ":" + info.get(key).size() / 30 * 100.0);
        dataset.add(info.get(key), 10, getTechniqueName(key));
    }

    return dataset;
}

From source file:edu.harvard.iq.dataverse.ingest.tabulardata.impl.plugins.dta.DTA117FileReader.java

private void readSTRLs(DataReader reader) throws IOException {
    logger.fine("STRLs section; at offset " + reader.getByteOffset() + "; dta map offset: "
            + dtaMap.getOffset_strls());
    // TODO: /*from   w w w. j  a v a 2s .  c om*/
    // check that we are at the right byte offset!
    //reader.readOpeningTag(TAG_STRLS);

    if (hasSTRLs) {
        reader.readOpeningTag(TAG_STRLS);

        File intermediateTabFile = ingesteddata.getTabDelimitedFile();
        FileInputStream fileInTab = new FileInputStream(intermediateTabFile);

        Scanner scanner = new Scanner(fileInTab);
        scanner.useDelimiter("\\n");

        File finalTabFile = File.createTempFile("finalTabfile.", ".tab");
        FileOutputStream fileOutTab = new FileOutputStream(finalTabFile);
        PrintWriter pwout = new PrintWriter(new OutputStreamWriter(fileOutTab, "utf8"), true);

        logger.fine("Setting the tab-delimited file to " + finalTabFile.getName());
        ingesteddata.setTabDelimitedFile(finalTabFile);

        int nvar = dataTable.getVarQuantity().intValue();
        int nobs = dataTable.getCaseQuantity().intValue();

        String[] line;

        for (int obsindex = 0; obsindex < nobs; obsindex++) {
            if (scanner.hasNext()) {
                line = (scanner.next()).split("\t", -1);

                for (int varindex = 0; varindex < nvar; varindex++) {
                    if ("STRL".equals(variableTypes[varindex])) {
                        // this is a STRL; needs to be re-processed:

                        String voPair = line[varindex];
                        long v;
                        long o;
                        if (voPair == null) {
                            throw new IOException("Failed to read an intermediate v,o Pair for variable "
                                    + varindex + ", observation " + obsindex);
                        }

                        if ("0,0".equals(voPair)) {
                            // This is a code for an empty string - "";
                            // doesn't need to be defined or looked up.

                            line[varindex] = "\"\"";
                        } else {
                            String[] voTokens = voPair.split(",", 2);

                            try {
                                v = new Long(voTokens[0]).longValue();
                                o = new Long(voTokens[1]).longValue();
                            } catch (NumberFormatException nfex) {
                                throw new IOException("Illegal v,o value: " + voPair + " for variable "
                                        + varindex + ", observation " + obsindex);
                            }

                            if (v == varindex + 1 && o == obsindex + 1) {
                                // This v,o must be defined in the STRLs section:
                                line[varindex] = readGSO(reader, v, o);
                                if (line[varindex] == null) {
                                    throw new IOException("Failed to read GSO value for " + voPair);
                                }

                            } else {
                                // This one must have been cached already:
                                if (cachedGSOs.get(voPair) != null && !cachedGSOs.get(voPair).equals("")) {
                                    line[varindex] = cachedGSOs.get(voPair);
                                } else {
                                    throw new IOException("GSO string unavailable for v,o value " + voPair);
                                }
                            }
                        }
                    }
                }
                // Dump the row of data to the tab-delimited file:
                pwout.println(StringUtils.join(line, "\t"));
            }
        }

        scanner.close();
        pwout.close();

        reader.readClosingTag(TAG_STRLS);
    } else {
        // If this data file doesn't use STRLs, we can just skip 
        // this section, and assume that we are done with the 
        // tabular data file.
        reader.readPrimitiveSection(TAG_STRLS);
    }

    //reader.readClosingTag(TAG_STRLS);
}

From source file:Model.MultiPlatformLDA.java

public void readData() {
    Scanner sc = null;
    BufferedReader br = null;//www  .j  a  va 2 s .co m
    String line = null;
    HashMap<String, Integer> userId2Index = null;
    HashMap<Integer, String> userIndex2Id = null;

    try {
        String folderName = dataPath + "/users";
        File postFolder = new File(folderName);

        // Read number of users
        int nUser = postFolder.listFiles().length;
        users = new User[nUser];
        userId2Index = new HashMap<String, Integer>(nUser);
        userIndex2Id = new HashMap<Integer, String>(nUser);
        int u = -1;

        // Read the posts from each user file
        for (File postFile : postFolder.listFiles()) {
            u++;
            users[u] = new User();

            // Read index of the user
            String userId = FilenameUtils.removeExtension(postFile.getName());
            userId2Index.put(userId, u);
            userIndex2Id.put(u, userId);
            users[u].userID = userId;

            // Read the number of posts from user
            int nPost = 0;
            br = new BufferedReader(new FileReader(postFile.getAbsolutePath()));
            while (br.readLine() != null) {
                nPost++;
            }
            br.close();

            // Declare the number of posts from user
            users[u].posts = new Post[nPost];

            // Read each of the post
            br = new BufferedReader(new FileReader(postFile.getAbsolutePath()));
            int j = -1;
            while ((line = br.readLine()) != null) {
                j++;
                users[u].posts[j] = new Post();

                sc = new Scanner(line.toString());
                sc.useDelimiter(",");
                while (sc.hasNext()) {
                    users[u].posts[j].postID = sc.next();
                    users[u].posts[j].platform = sc.nextInt();
                    users[u].posts[j].batch = sc.nextInt();

                    // Read the words in each post
                    String[] tokens = sc.next().toString().split(" ");
                    users[u].posts[j].words = new int[tokens.length];
                    for (int i = 0; i < tokens.length; i++) {
                        users[u].posts[j].words[i] = Integer.parseInt(tokens[i]);
                    }
                }
            }
            br.close();
        }

        // Read post vocabulary
        String vocabularyFileName = dataPath + "/vocabulary.csv";

        br = new BufferedReader(new FileReader(vocabularyFileName));
        int nPostWord = 0;
        while (br.readLine() != null) {
            nPostWord++;
        }
        br.close();
        vocabulary = new String[nPostWord];

        br = new BufferedReader(new FileReader(vocabularyFileName));
        while ((line = br.readLine()) != null) {
            String[] tokens = line.split(",");
            int index = Integer.parseInt(tokens[0]);
            vocabulary[index] = tokens[1];
        }
        br.close();

    } catch (Exception e) {
        System.out.println("Error in reading post from file!");
        e.printStackTrace();
        System.exit(0);
    }
}

From source file:unalcol.termites.boxplots.ECALinfoCollected.java

/**
 * Creates a sample dataset.//from   www .  j  a  v a 2 s . c om
 *
 * @return A sample dataset.
 */
private BoxAndWhiskerCategoryDataset createSampleDataset(ArrayList<Double> Pf) {

    final int seriesCount = 5;
    final int categoryCount = 4;
    final int entityCount = 22;
    String sDirectorio = ".\\experiments\\ECAL CR";
    File f = new File(sDirectorio);
    String extension;
    File[] files = f.listFiles();
    Hashtable<String, String> Pop = new Hashtable<>();
    PrintWriter escribir;
    Scanner sc = null;
    ArrayList<Integer> aPops = new ArrayList<>();
    ArrayList<Double> aPf = new ArrayList<>();
    ArrayList<String> aTech = new ArrayList<>();

    final DefaultBoxAndWhiskerCategoryDataset dataset = new DefaultBoxAndWhiskerCategoryDataset();

    for (File file : files) {
        extension = "";
        int i = file.getName().lastIndexOf('.');
        int p = Math.max(file.getName().lastIndexOf('/'), file.getName().lastIndexOf('\\'));
        if (i > p) {
            extension = file.getName().substring(i + 1);
        }

        // System.out.println(file.getName() + "extension" + extension);
        if (file.isFile() && extension.equals("csv") && file.getName().startsWith("experiment")) {
            System.out.println(file.getName());
            System.out.println("get: " + file.getName());
            String[] filenamep = file.getName().split(Pattern.quote("+"));

            System.out.println("file" + filenamep[8]);

            int popsize = Integer.valueOf(filenamep[2]);
            double pf = Double.valueOf(filenamep[4]);
            String mode = filenamep[6];

            int maxIter = -1;
            //if (!filenamep[8].isEmpty()) {
            maxIter = Integer.valueOf(filenamep[8]);
            //}

            System.out.println("psize:" + popsize);
            System.out.println("pf:" + pf);
            System.out.println("mode:" + mode);
            System.out.println("maxIter:" + maxIter);

            String[] aMode = { "random", "levywalk", "sandc" };

            if (/*Pf == pf && */isInMode(aMode, mode)) {
                final List list = new ArrayList();
                try {
                    sc = new Scanner(file);

                } catch (FileNotFoundException ex) {
                    Logger.getLogger(DataCollectedLatexConsolidatorSASOMessagesSend1.class.getName())
                            .log(Level.SEVERE, null, ex);
                }
                int agentsCorrect = 0;
                int worldSize = 0;
                double averageExplored = 0.0;
                int bestRoundNumber = 0;
                double avgSend = 0;
                double avgRecv = 0;
                double avgdataExplInd = 0;
                ArrayList<Double> acSt = new ArrayList<>();
                ArrayList<Double> avgExp = new ArrayList<>();
                ArrayList<Double> bestR = new ArrayList<>();
                ArrayList<Double> avSnd = new ArrayList<>();
                ArrayList<Double> avRecv = new ArrayList<>();
                ArrayList<Double> avIndExpl = new ArrayList<>();

                String[] data = null;
                while (sc.hasNext()) {
                    String line = sc.nextLine();
                    //System.out.println("line:" + line);
                    data = line.split(",");
                    agentsCorrect = Integer.valueOf(data[0]);
                    //agentsIncorrect = Integer.valueOf(data[1]); // not used
                    worldSize = Integer.valueOf(data[3]);
                    averageExplored = Double.valueOf(data[4]);
                    // data[3] stdavgExplored - not used
                    bestRoundNumber = Integer.valueOf(data[6]);
                    avgSend = Double.valueOf(data[7]);
                    avgRecv = Double.valueOf(data[8]);
                    avgdataExplInd = Double.valueOf(data[11]);

                    //Add Data and generate statistics 
                    acSt.add((double) agentsCorrect);
                    avgExp.add(averageExplored);

                    avSnd.add(avgSend);
                    avRecv.add(avgRecv);
                    avIndExpl.add(avgdataExplInd);

                    list.add(new Double(averageExplored / (double) worldSize * 100));
                }
                LOGGER.debug("Adding series " + i);
                LOGGER.debug(list.toString());
                if (Pf.contains(pf)) {
                    /*pf == 1.0E-4 || pf == 3.0E-4*/
                    if (Pf.size() == 1) {
                        dataset.add(list, popsize, getTechniqueName(mode));
                    } else {
                        dataset.add(list, String.valueOf(popsize) + "-" + pf, getTechniqueName(mode));
                    }
                }
            }
        }

    }

    /*for (int i = 0; i < seriesCount; i++) {
     for (int j = 0; j < categoryCount; j++) {
     final List list = new ArrayList();
     // add some values...
     for (int k = 0; k < entityCount; k++) {
     final double value1 = 10.0 + Math.random() * 3;
     list.add(new Double(value1));
     final double value2 = 11.25 + Math.random(); // concentrate values in the middle
     list.add(new Double(value2));
     }
     LOGGER.debug("Adding series " + i);
     LOGGER.debug(list.toString());
     dataset.add(list, "Series " + i, " Type " + j);
     }
            
     }*/
    return dataset;
}