List of usage examples for java.util Locale setDefault
public static synchronized void setDefault(Locale newLocale)
From source file:edu.ku.brc.specify.tools.StrLocalizerApp.java
/** * @param args/*from w ww . ja va2s .co m*/ */ public static void main(String[] args) { setAppName("Specify"); //$NON-NLS-1$ System.setProperty(AppPreferences.factoryName, "edu.ku.brc.specify.config.AppPrefsDBIOIImpl"); // Needed by AppReferences //$NON-NLS-1$ for (String s : args) { String[] pairs = s.split("="); //$NON-NLS-1$ if (pairs.length == 2) { if (pairs[0].startsWith("-D")) //$NON-NLS-1$ { //System.err.println("["+pairs[0].substring(2, pairs[0].length())+"]["+pairs[1]+"]"); System.setProperty(pairs[0].substring(2, pairs[0].length()), pairs[1]); } } else { String symbol = pairs[0].substring(2, pairs[0].length()); //System.err.println("["+symbol+"]"); System.setProperty(symbol, symbol); } } // Now check the System Properties String appDir = System.getProperty("appdir"); if (StringUtils.isNotEmpty(appDir)) { UIRegistry.setDefaultWorkingPath(appDir); } String appdatadir = System.getProperty("appdatadir"); if (StringUtils.isNotEmpty(appdatadir)) { UIRegistry.setBaseAppDataDir(appdatadir); } // Then set this IconManager.setApplicationClass(Specify.class); IconManager.loadIcons(XMLHelper.getConfigDir("icons.xml")); //$NON-NLS-1$ //ImageIcon icon = IconManager.getIcon("AppIcon", IconManager.IconSize.Std16); try { ResourceBundle.getBundle("resources", Locale.getDefault()); //$NON-NLS-1$ } catch (MissingResourceException ex) { Locale.setDefault(Locale.ENGLISH); UIRegistry.setResourceLocale(Locale.ENGLISH); } try { if (!System.getProperty("os.name").equals("Mac OS X")) { UIManager.setLookAndFeel(new Plastic3DLookAndFeel()); PlasticLookAndFeel.setPlasticTheme(new DesertBlue()); } } catch (Exception e) { //whatever } AppPreferences localPrefs = AppPreferences.getLocalPrefs(); localPrefs.setDirPath(UIRegistry.getAppDataDir()); boolean doIt = false; if (doIt) { Charset utf8charset = Charset.forName("UTF-8"); Charset iso88591charset = Charset.forName("ISO-8859-1"); ByteBuffer inputBuffer = ByteBuffer.wrap(new byte[] { (byte) 0xC3, (byte) 0xA2 }); // decode UTF-8 CharBuffer data = utf8charset.decode(inputBuffer); // encode ISO-8559-1 ByteBuffer outputBuffer = iso88591charset.encode(data); byte[] outputData = outputBuffer.array(); System.out.println(new String(outputData)); return; } SwingUtilities.invokeLater(new Runnable() { @Override public void run() { try { UIHelper.OSTYPE osType = UIHelper.getOSType(); if (osType == UIHelper.OSTYPE.Windows) { UIManager.setLookAndFeel(new PlasticLookAndFeel()); PlasticLookAndFeel.setPlasticTheme(new ExperienceBlue()); } else if (osType == UIHelper.OSTYPE.Linux) { UIManager.setLookAndFeel(new PlasticLookAndFeel()); } } catch (Exception e) { log.error("Can't change L&F: ", e); //$NON-NLS-1$ } JFrame frame = new JFrame(getResourceString("StrLocalizerApp.AppTitle")); frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); final StrLocalizerApp sl = new StrLocalizerApp(); sl.addMenuBar(frame); frame.setContentPane(sl); frame.setSize(768, 1024); //Dimension size = frame.getPreferredSize(); //size.height = 500; //frame.setSize(size); frame.addWindowListener(sl); IconManager.setApplicationClass(Specify.class); frame.setIconImage(IconManager.getImage(IconManager.makeIconName("SpecifyWhite32")).getImage()); UIHelper.centerAndShow(frame); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { sl.startUp(); } }); } }); }
From source file:fr.univsavoie.ltp.client.MainActivity.java
public void parsi() { String languageToLoad = "fa"; Locale locale = new Locale(languageToLoad); Locale.setDefault(locale); Configuration config = new Configuration(); config.locale = locale;//ww w . j a v a 2 s. c o m getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics()); Resources standardResources = getBaseContext().getResources(); }
From source file:fr.univsavoie.ltp.client.MainActivity.java
private void english() { String languageToLoad = "en"; Locale locale = new Locale(languageToLoad); Locale.setDefault(locale); Configuration config = new Configuration(); config.locale = locale;/*from w ww . j a va 2s. com*/ getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics()); Resources standardResources = getBaseContext().getResources(); }
From source file:fr.univsavoie.ltp.client.MainActivity.java
private void french() { // TODO Auto-generated method stub String languageToLoad = "fr"; Locale locale = new Locale(languageToLoad); Locale.setDefault(locale); Configuration config = new Configuration(); config.locale = locale;//from w w w .j a v a2 s . c o m getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics()); Resources standardResources = getBaseContext().getResources(); }
From source file:com.gargoylesoftware.htmlunit.javascript.JavaScriptEngineTest.java
/** * Configure subclass of {@link JavaScriptEngine} that collects background JS expressions. * @throws Exception if the test fails/*from w w w .j a v a 2s . c o m*/ */ @Test public void catchBackgroundJSErrors() throws Exception { Locale.setDefault(Locale.US); // Rhino has localized error message... for instance for French final WebClient webClient = getWebClient(); final List<ScriptException> jsExceptions = new ArrayList<ScriptException>(); final JavaScriptEngine myEngine = new JavaScriptEngine(webClient) { @Override protected void handleJavaScriptException(final ScriptException scriptException) { jsExceptions.add(scriptException); super.handleJavaScriptException(scriptException); } }; webClient.setJavaScriptEngine(myEngine); final String html = "<html>\n" + "<head><title>Test page</title><\n" + "<script>\n" + "function myFunction() {\n" + " document.title = 'New title';\n" + " notExisting(); // will throw\n" + "}\n" + "window.setTimeout(myFunction, 5)\n" + "</script>\n" + "</head>\n" + "<body>\n" + "</body></html>"; final MockWebConnection webConnection = new MockWebConnection(); webConnection.setDefaultResponse(html); webClient.setWebConnection(webConnection); final HtmlPage page = webClient.getPage(URL_FIRST); webClient.waitForBackgroundJavaScript(10000); assertEquals("New title", page.getTitleText()); assertEquals(1, jsExceptions.size()); final ScriptException exception = jsExceptions.get(0); assertTrue("Message: " + exception.getMessage(), exception.getMessage().contains("\"notExisting\" is not defined")); }
From source file:ru.apertum.qsystem.client.forms.FAdmin.java
/** * @param args the command line arguments * @throws Exception/* w w w.j av a 2 s .co m*/ */ public static void main(String args[]) throws Exception { QLog.initial(args, 3); Locale.setDefault(Locales.getInstance().getLangCurrent()); //? ? , ? final Thread tPager = new Thread(() -> { FAbout.loadVersionSt(); String result = ""; try { final URL url = new URL(PAGER_URL + "/qskyapi/getpagerdata?qsysver=" + FAbout.VERSION_); final HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("User-Agent", "Java bot"); conn.connect(); final int code = conn.getResponseCode(); if (code == 200) { try (BufferedReader in = new BufferedReader( new InputStreamReader(conn.getInputStream(), "utf8"))) { String inputLine; while ((inputLine = in.readLine()) != null) { result += inputLine; } } } conn.disconnect(); } catch (Exception e) { System.err.println("Pager not enabled. " + e); return; } final Gson gson = GsonPool.getInstance().borrowGson(); try { final Answer answer = gson.fromJson(result, Answer.class); forPager = answer; if (answer.getData().size() > 0) { forPager.start(); } } catch (Exception e) { System.err.println("Pager not enabled but working. " + e); } finally { GsonPool.getInstance().returnGson(gson); } }); tPager.setDaemon(true); tPager.start(); Uses.startSplash(); // plugins Uses.loadPlugins("./plugins/"); // ?. FLogin.logining(QUserList.getInstance(), null, true, 3, FLogin.LEVEL_ADMIN); Uses.showSplash(); java.awt.EventQueue.invokeLater(() -> { try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager .getInstalledLookAndFeels()) { System.out.println(info.getName()); /*Metal Nimbus CDE/Motif Windows Windows Classic //GTK+*/ if ("Windows".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } if ("/".equals(File.separator)) { final FontUIResource f = new FontUIResource(new Font("Serif", Font.PLAIN, 10)); final Enumeration<Object> keys = UIManager.getDefaults().keys(); while (keys.hasMoreElements()) { final Object key = keys.nextElement(); final Object value = UIManager.get(key); if (value instanceof FontUIResource) { final FontUIResource orig = (FontUIResource) value; final Font font1 = new Font(f.getFontName(), orig.getStyle(), f.getSize()); UIManager.put(key, new FontUIResource(font1)); } } } } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { } try { form = new FAdmin(); if (forPager != null) { forPager.showData(false); } else { form.panelPager.setVisible(false); } form.setVisible(true); } catch (Exception ex) { QLog.l().logger().error(" ? ?? . ", ex); } finally { Uses.closeSplash(); } }); }
From source file:com.adito.agent.client.Agent.java
protected static AgentArgs initArgs(String[] args) throws Throwable { int shutdown = -1; int webforwardInactivity = 300000; int tunnelInactivity = 600000; AgentArgs agentArgs = new AgentArgs(); AgentConfiguration configuration = new AgentConfiguration(); String hostHeader = null;/*www . ja va 2 s. c om*/ String protocol = null; for (int i = 0; i < args.length; i++) { if (args[i].startsWith("host")) { //$NON-NLS-1$ hostHeader = getCommandLineValue(args[i]); } else if (args[i].startsWith("protocol")) { //$NON-NLS-1$ protocol = getCommandLineValue(args[i]); } else if (args[i].startsWith("username")) { //$NON-NLS-1$ agentArgs.setUsername(getCommandLineValue(args[i])); } else if (args[i].startsWith("password")) { //$NON-NLS-1$ agentArgs.setPassword(getCommandLineValue(args[i])); } else if (args[i].startsWith("localProxyURL")) { //$NON-NLS-1$ agentArgs.setLocalProxyURL(getCommandLineValue(args[i])); } else if (args[i].startsWith("reverseProxyURL")) { //$NON-NLS-1$ agentArgs.setReverseProxyURL(getCommandLineValue(args[i])); } else if (args[i].startsWith("pluginProxyURL")) { //$NON-NLS-1$ agentArgs.setPluginProxyURL(getCommandLineValue(args[i])); } else if (args[i].startsWith("ticket")) { //$NON-NLS-1$ agentArgs.setTicket(getCommandLineValue(args[i])); } else if (args[i].startsWith("browserCommand")) { //$NON-NLS-1$ agentArgs.setBrowserCommand(getCommandLineValue(args[i])); } else if (args[i].startsWith("userAgent")) { //$NON-NLS-1$ String userAgent = getCommandLineValue(args[i]); agentArgs.setUserAgent(userAgent); HttpClient.setUserAgent(userAgent); } else if (args[i].startsWith("locale")) { //$NON-NLS-1$ agentArgs.setLocaleName(getCommandLineValue(args[i])); } else if (args[i].startsWith("disableNewSSLEngine")) { //$NON-NLS-1$ agentArgs.setDisableNewSSLEngine(Boolean.valueOf(getCommandLineValue(args[i])).booleanValue()); } else if (args[i].startsWith("webforward.inactivity")) { //$NON-NLS-1$ try { webforwardInactivity = Integer.parseInt(getCommandLineValue(args[i])); } catch (NumberFormatException ex) { } } else if (args[i].startsWith("tunnel.inactivity")) { //$NON-NLS-1$ try { tunnelInactivity = Integer.parseInt(getCommandLineValue(args[i])); } catch (NumberFormatException ex) { } } else if (args[i].startsWith("shutdown")) { //$NON-NLS-1$ try { shutdown = Integer.parseInt(getCommandLineValue(args[i])); } catch (NumberFormatException ex) { } } else if (args[i].startsWith("log4j")) { //$NON-NLS-1$ agentArgs.setLogProperties(getCommandLineValue(args[i])); } else if (args[i].startsWith("extensionClasses")) { //$NON-NLS-1$ agentArgs.setExtensionClasses(getCommandLineValue(args[i])); } else if (args[i].startsWith("ignoreCertWarnings")) { System.getProperties().put("com.maverick.ssl.allowUntrustedCertificates", "true"); System.getProperties().put("com.maverick.ssl.allowInvalidCertificates", "true"); } else if (args[i].startsWith("forceBasicUI")) { configuration.setGUIClass("com.adito.agent.client.gui.BasicFrameGUI"); } else if (args[i].startsWith("displayInformationPopups")) { configuration.setDisplayInformationPopups(getCommandLineValue(args[i]).equalsIgnoreCase("true")); } else if (args[i].startsWith("remoteTunnelsRequireConfirmation")) { configuration .setRemoteTunnelsRequireConfirmation(getCommandLineValue(args[i]).equalsIgnoreCase("true")); } else if (args[i].startsWith("cleanOnExit")) { configuration.setCleanOnExit(getCommandLineValue(args[i]).equalsIgnoreCase("true")); } else if (args[i].startsWith("localhostAddress")) { configuration.setLocalhostAddress(getCommandLineValue(args[i])); } else if (args[i].startsWith("dir")) { configuration.setCacheDir(new File(Utils.getHomeDirectory(), getCommandLineValue(args[i]))); } else if (args[i].startsWith("removeFiles")) { StringTokenizer files = new StringTokenizer(getCommandLineValue(args[i]), File.pathSeparator); while (files.hasMoreTokens()) { configuration.removeFileOnExit(new File(files.nextToken())); } } else if (args[i].startsWith("keepAlivePeriod")) { configuration.setKeepAlivePeriod(Integer.parseInt(getCommandLineValue(args[i]))); } else if (args[i].startsWith("extensionId")) { agentArgs.setExtensionId(getCommandLineValue(args[i])); } } if (hostHeader == null || protocol == null) { throw new IOException(""); } else { int idx = hostHeader.indexOf(':'); if (idx > -1) { String port = hostHeader.substring(idx + 1); agentArgs.setHostname(hostHeader.substring(0, idx)); try { agentArgs.setPort(Integer.parseInt(port)); } catch (NumberFormatException ex) { } agentArgs.setSecure(protocol.equalsIgnoreCase("https")); } else { agentArgs.setHostname(hostHeader); agentArgs.setPort(protocol.equalsIgnoreCase("http") ? 80 : 443); agentArgs.setSecure(protocol.equalsIgnoreCase("https")); } } if (isWindows64()) { configuration.setGUIClass("com.adito.agent.client.gui.BasicFrameGUI"); } WinRegistry.setLocation(new File(configuration.getCacheDir(), "applications" + File.separator + agentArgs.getExtensionId())); /* * Load the message resources. */ Locale.setDefault(Utils.createLocale(agentArgs.getLocaleName())); if (agentArgs.getLogProperties() == null) { System.out.println(Messages.getString("VPNClient.main.debugModeWarning")); //$NON-NLS-1$ } if (agentArgs.getPort() == -1 || agentArgs.getHostname() == null || agentArgs.getUsername() == null || (agentArgs.getTicket() == null && agentArgs.getPassword() == null)) throw new IOException(Messages.getString("VPNClient.main.missingCommandLineArguments")); //$NON-NLS-1$ if (shutdown > -1) configuration.setShutdownPeriod(shutdown); configuration.setSystemExitOnDisconnect(true); configuration.setWebForwardInactivity(webforwardInactivity); configuration.setTunnelInactivity(tunnelInactivity); agentArgs.setAgentConfiguration(configuration); return agentArgs; }
From source file:edu.ku.brc.specify.tools.schemalocale.SchemaLocalizerXMLHelper.java
@Override public boolean exportSingleLanguageToDirectory(final File exportDirectory, final Locale locale) { boolean isOK = false; if (inputFile != null) { Locale cachedLocale = Locale.getDefault(); try {//w w w .j a va 2 s. c om Locale.setDefault(locale); Vector<DisciplineBasedContainer> tmpTables = load(null, inputFile, true); isOK = saveContainers(exportDirectory, tmpTables); } finally { Locale.setDefault(cachedLocale); } } return isOK; }
From source file:edu.ku.brc.specify.tools.ireportspecify.MainFrameSpecify.java
protected static void adjustLocaleFromPrefs() { String language = AppPreferences.getLocalPrefs().get("locale.lang", null); //$NON-NLS-1$ if (language != null) { String country = AppPreferences.getLocalPrefs().get("locale.country", null); //$NON-NLS-1$ String variant = AppPreferences.getLocalPrefs().get("locale.var", null); //$NON-NLS-1$ Locale prefLocale = new Locale(language, country, variant); Locale.setDefault(prefLocale); UIRegistry.setResourceLocale(prefLocale); }/*from ww w . ja va 2 s . c om*/ try { ResourceBundle.getBundle("resources", Locale.getDefault()); //$NON-NLS-1$ } catch (MissingResourceException ex) { edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(MainFrameSpecify.class, ex); Locale.setDefault(Locale.ENGLISH); UIRegistry.setResourceLocale(Locale.ENGLISH); } }
From source file:de.tudarmstadt.tk.statistics.report.ReportGenerator.java
public String createPlainReport() { // Set locale to English globally to make reports independent of the // machine thei're created on, e.g. use "." as decimal points on any // machine//from ww w. j a va 2 s . co m Locale.setDefault(Locale.ENGLISH); StringBuilder report = new StringBuilder(); // // Evaluation Overview // report.append("###\n"); report.append("Evaluation Overview\n"); report.append("###\n\n"); int nModels = evalResults.getSampleData().getModelMetadata().size(); ArrayList<String> measures = evalResults.getMeasures(); String ref = "tbl:models"; // Separate training/testing datasets List<String> trainingDataList = new ArrayList<String>(); List<String> testingDataList = new ArrayList<String>(); List<Pair<String, String>> datasets = evalResults.getSampleData().getDatasetNames(); Iterator<Pair<String, String>> itp = datasets.iterator(); while (itp.hasNext()) { Pair<String, String> trainTest = itp.next(); trainingDataList.add(trainTest.getKey()); if (trainTest.getValue() != null) { testingDataList.add(trainTest.getValue()); } } Set<String> trainingDataSet = new HashSet<String>(trainingDataList); Set<String> testingDataSet = new HashSet<String>(testingDataList); String pipelineDescription = null; String sampleOrigin = "per CV"; ReportTypes pipelineType = this.evalResults.getSampleData().getPipelineType(); switch (pipelineType) { // One-domain n-fold CV (ReportData=per Fold) case CV: pipelineDescription = String.format("%d-fold cross validation", evalResults.getSampleData().getnFolds()); sampleOrigin = "per fold "; break; case MULTIPLE_CV: pipelineDescription = String.format("%dx%s repeated cross validation", evalResults.getSampleData().getnRepetitions(), evalResults.getSampleData().getnFolds()); break; case CV_DATASET_LVL: pipelineDescription = String.format("%d-fold cross validation over %d datasets", evalResults.getSampleData().getnFolds(), trainingDataSet.size()); break; case MULTIPLE_CV_DATASET_LVL: pipelineDescription = String.format("%dx%s repeated cross validation over %d datasets", evalResults.getSampleData().getnRepetitions(), evalResults.getSampleData().getnFolds(), trainingDataSet.size()); sampleOrigin = "per dataset"; break; case TRAIN_TEST_DATASET_LVL: // In the train/test scenario, the number of datasets only includes // distinct ones Set<String> allDataSets = new HashSet<String>(testingDataSet); allDataSets.addAll(trainingDataSet); pipelineDescription = String.format("Train/Test over %d datasets", allDataSets.size()); sampleOrigin = "per dataset"; break; default: pipelineDescription = "!unknown pipeline type!"; sampleOrigin = "!unknown pipeline type!"; break; } boolean isBaselineEvaluation = evalResults.isBaselineEvaluation(); report.append(String.format("The system performed a %s for the following %d models. \n", pipelineDescription, nModels)); if (isBaselineEvaluation) { report.append(String.format("The models were compared against the first baseline model. \n", pipelineDescription, nModels)); } else { report.append( String.format("The models were compared against each other. \n", pipelineDescription, nModels)); } ArrayList<Pair<String, String>> modelMetadata = evalResults.getSampleData().getModelMetadata(); for (int modelIndex = 0; modelIndex < modelMetadata.size(); modelIndex++) { String[] algorithm = modelMetadata.get(modelIndex).getKey().split("\\."); String modelAlgorithm = algorithm[algorithm.length - 1]; String modelFeatureSet = modelMetadata.get(modelIndex).getValue(); report.append(String.format("M%d: %s; %s\n", modelIndex, modelAlgorithm, modelFeatureSet)); } // List test/training datasets. Consider the case when these sets are // different. if (testingDataSet.isEmpty()) { if (trainingDataSet.size() == 1) { report.append( String.format("\nThe models were evaluated on the dataset %s. ", trainingDataList.get(0))); } else { report.append(String.format("\nThe models were evaluated on the datasets %s. ", this.createEnumeration(trainingDataList))); } } else { if (trainingDataSet.size() == 1 && testingDataSet.size() == 1) { report.append( String.format("\nThe models were trained on the dataset %s and tested on the dataset %s. ", trainingDataList.get(0), testingDataList.get(0))); } else if (trainingDataSet.size() > 1 && testingDataSet.size() == 1) { report.append(String.format( "\nThe models were trained on the datasets %s and tested on the dataset %s. ", this.createEnumeration(new ArrayList<String>(trainingDataSet)), testingDataList.get(0))); } else if (trainingDataSet.size() == 1 && testingDataSet.size() > 1) { report.append(String.format( "\nThe models were trained on the dataset %s and tested on the datasets %s. ", trainingDataList.get(0), this.createEnumeration(new ArrayList<String>(testingDataSet)))); } else { report.append(String.format( "\nThe models were trained on the datasets %s and tested on the datasets %s. ", this.createEnumeration(new ArrayList<String>(trainingDataSet)), this.createEnumeration(new ArrayList<String>(testingDataSet)))); } } report.append(String.format("Their performance was assessed with the %s", createEnumeration(measures))); // // Results (for each measure separately) // report.append("\n\n###\n"); // All previous floats must be placed before // this point report.append("Results\n"); report.append("###"); for (int i = 0; i < measures.size(); i++) { // Continue for McNemar contingency matrix String measure = measures.get(i); if (!evalResults.getSampleData().getSamples().containsKey(measure)) { continue; } // Samples report.append("\n\n#\n"); report.append(String.format("Evaluation for %s. \n", measure)); report.append("#\n\n"); report.append("Samples: \n"); ArrayList<ArrayList<Double>> models = evalResults.getSampleData().getSamples().get(measure); for (int modelId = 0; i < models.size(); i++) { ArrayList<Double> samples = models.get(modelId); report.append(String.format("C%d: ", modelId)); for (int j = 0; j < samples.size(); j++) { report.append(String.format("%.3f;", samples.get(j))); } report.append("\n"); } report.append("\n"); // Test results for (String testType : new String[] { "Parametric", "Non-Parametric" }) { report.append(String.format("%s Testing\n", testType)); Pair<String, AbstractTestResult> result = null; if (testType.equals("Parametric")) { result = evalResults.getParametricTestResults().get(measure); } else { result = evalResults.getNonParametricTestResults().get(measure); } // Use pretty-print method descriptor if specified String method = result.getKey(); if (StatsConfigConstants.PRETTY_PRINT_METHODS.containsKey(method)) { method = StatsConfigConstants.PRETTY_PRINT_METHODS.get(method); } TestResult r = (TestResult) result.getValue(); report.append(String.format("The system compared the %d models using the %s. ", nModels, method)); if (r != null && !Double.isNaN(r.getpValue())) { // A priori test: assumptions boolean assumptionViolated = false; Iterator<String> it = r.getAssumptions().keySet().iterator(); while (it.hasNext()) { String assumption = it.next(); TestResult at = (TestResult) r.getAssumptions().get(assumption); if (at == null) { report.append(String.format("Testing for %s failed. ", assumption)); assumptionViolated = true; continue; } if (Double.isNaN(at.getpValue())) { report.append( String.format("Testing for %s using %s failed. ", assumption, at.getMethod())); assumptionViolated = true; continue; } double ap = at.getpValue(); if (ap <= this.significance_low) { assumptionViolated = true; } // Verbalize result according to p value Pair<String, Double> verbalizedP = verbalizeP(ap, true); report.append(String.format("%s %s violation of %s (p=%f, alpha=%f). ", at.getMethod(), verbalizedP.getKey(), assumption, ap, verbalizedP.getValue())); } if (assumptionViolated) { report.append( "Given that the assumptions are violated, the following test may be corrupted. "); } // A Priori test results Pair<String, Double> verbalizedP = verbalizeP(r.getpValue(), false); report.append(String.format( "The %s %s differences between the performances of the models (p=%f, alpha=%f).\n\n", method, verbalizedP.getKey(), r.getpValue(), verbalizedP.getValue())); // Post-hoc test for >2 models (pairwise comparisons) if (evalResults.getSampleData().getModelMetadata().size() > 2) { Pair<String, AbstractTestResult> postHocResult = null; HashMap<Integer, TreeSet<Integer>> postHocOrdering = null; if (testType.equals("Parametric")) { postHocResult = evalResults.getParametricPostHocTestResults().get(measure); postHocOrdering = evalResults.getParameticPostHocOrdering().get(measure); } else { postHocResult = evalResults.getNonParametricPostHocTestResults().get(measure); postHocOrdering = evalResults.getNonParameticPostHocOrdering().get(measure); } method = postHocResult.getKey(); if (StatsConfigConstants.PRETTY_PRINT_METHODS.containsKey(method)) { method = StatsConfigConstants.PRETTY_PRINT_METHODS.get(method); } PairwiseTestResult rPostHoc = (PairwiseTestResult) postHocResult.getValue(); report.append(String.format("The system performed the %s post-hoc. ", method)); if (rPostHoc == null) { report.append("The test failed. "); continue; } // Assumptions boolean assumptionsViolated = false; it = rPostHoc.getAssumptions().keySet().iterator(); while (it.hasNext()) { String assumption = it.next(); PairwiseTestResult at = (PairwiseTestResult) rPostHoc.getAssumptions().get(assumption); if (at == null) { report.append(String.format("Testing for %s failed. ", assumption)); assumptionsViolated = true; continue; } report.append(String.format("\nTesting for %s using %s returned p-values:\n%s", assumption, at.getMethod(), this.pairwiseResultsToString(at.getpValue()))); // Create table with pairwise p-values for // assumption testing double[][] ap = at.getpValue(); double max = getMax(ap); double min = getMin(ap); verbalizedP = verbalizeP(min, true); if ((max > significance_low && min <= significance_low) || (max > significance_medium && min <= significance_medium) || (max > significance_high && min <= significance_high)) { // partly significant to degree as specified by // verbalized p-value report.append(String.format("%s partly %s violation of %s (alpha=%.2f).\n", at.getMethod(), verbalizedP.getKey(), assumption, verbalizedP.getValue())); } else { report.append(String.format("%s %s violation of %s (alpha=%.2f).\n", at.getMethod(), verbalizedP.getKey(), assumption, verbalizedP.getValue())); } if (min <= this.significance_low) { assumptionsViolated = true; } } if (assumptionViolated) { report.append( "Given that the assumptions are violated, the following test may be corrupted. "); } // Result double[][] ap = rPostHoc.getpValue(); report.append( String.format("P-values:\n%s", this.pairwiseResultsToString(rPostHoc.getpValue()))); // Already fetch pairwise adjustments here in order to // determine choice of words double max = getMax(ap); double min = getMin(ap); verbalizedP = verbalizeP(min, false); ArrayList<StatsConfigConstants.CORRECTION_VALUES> adjustments = new ArrayList<StatsConfigConstants.CORRECTION_VALUES>( rPostHoc.getpValueCorrections().keySet()); String adjustWord = ""; if (adjustments.size() > 0) { adjustWord = " for non-adjusted p-values"; } if ((max > significance_low && min <= significance_low) || (max > significance_medium && min <= significance_medium) || (max > significance_high && min <= significance_high)) { // partly significant to degree as specified by // verbalized p-value report.append(String.format( "The %s partly %s differences between the performances of the models%s ($\\alpha=%.2f$, Tbl. \\ref{%s}). ", method, verbalizedP.getKey(), adjustWord, verbalizedP.getValue(), ref)); } else { report.append(String.format( "The %s %s differences between the performances of the models%s ($\\alpha=%.2f$, Tbl. \\ref{%s}). ", method, verbalizedP.getKey(), adjustWord, verbalizedP.getValue(), ref)); } // Determine ordering of models String ordering = getModelOrderingRepresentation(postHocOrdering); report.append(ordering); report.append("\n\n"); // Pairwise adjustments if (adjustments.size() > 0) { double[] minAdjustments = new double[adjustments.size()]; double[] maxAdjustments = new double[adjustments.size()]; for (int j = 0; j < adjustments.size(); j++) { StatsConfigConstants.CORRECTION_VALUES adjustmentMethod = adjustments.get(j); double[][] correctedP = rPostHoc.getpValueCorrections().get(adjustmentMethod); String am = adjustmentMethod.name(); if (StatsConfigConstants.PRETTY_PRINT_METHODS.containsKey(am)) { am = StatsConfigConstants.PRETTY_PRINT_METHODS.get(am); } report.append(String.format("\nAdjusted p-values according to %s:\n%s", am, this.pairwiseResultsToString(correctedP))); minAdjustments[j] = getMin(correctedP); maxAdjustments[j] = getMax(correctedP); } min = getMin(minAdjustments); max = getMax(maxAdjustments); verbalizedP = verbalizeP(min, false); if ((max > significance_low && min <= significance_low) || (max > significance_medium && min <= significance_medium) || (max > significance_high && min <= significance_high)) { // partly significant to degree as specified by // verbalized p-value report.append(String.format( "It partly %s differences for adjusted p-values (alpha=%.2f$).\n\n ", verbalizedP.getKey(), verbalizedP.getValue(), ref)); } else { report.append( String.format("It %s differences for adjusted p-values (alpha=%.2f$).\n\n ", verbalizedP.getKey(), verbalizedP.getValue(), ref)); } } } } else { report.append(String.format("The %s failed.", method)); } } } // // Contingency table and McNemar results if this test was performed // if (evalResults.getNonParametricTest().equals("McNemar")) { String measure = "Contingency Table"; String testType = "Non-Parametric"; report.append("\n\n#\n"); report.append("Evaluation for Contingency Table\n"); report.append("#\n\n"); int[][] contingencyMatrix = evalResults.getSampleData().getContingencyMatrix(); if (evalResults.getSampleData().getPipelineType() == ReportTypes.MULTIPLE_CV) { report.append(String.format( "Contingency table drawn from the %s and the %d models. The correctly and incorrectly classified instances per fold were averaged over all repetitions:\n%s\n", pipelineDescription, nModels, this.contingencyMatrixToString(contingencyMatrix))); } else { report.append(String.format("Contingency table drawn from the %s and the %d models:\n%s\n", pipelineDescription, nModels, this.contingencyMatrixToString(contingencyMatrix))); } // Test results report.append(String.format("%s Testing\n", testType)); report.append(String.format("The system compared the %d models using the McNemar test. ", nModels)); Pair<String, AbstractTestResult> result = evalResults.getNonParametricTestResults().get(measure); TestResult r = (TestResult) result.getValue(); if (r != null && !Double.isNaN(r.getpValue())) { StringBuilder parameters = new StringBuilder(); Iterator<String> it = r.getParameter().keySet().iterator(); while (it.hasNext()) { String parameter = it.next(); double value = r.getParameter().get(parameter); parameters.append(String.format("%s=%.3f, ", parameter, value)); } // Verbalize result according to p value Pair<String, Double> verbalizedP = verbalizeP(r.getpValue(), false); report.append(String.format( "The test %s differences between the performances of the models (%sp=%.3f, alpha=%.2f).\\\\ \n", verbalizedP.getKey(), parameters.toString(), r.getpValue(), verbalizedP.getValue())); } else { report.append("The test failed.\n"); } } return report.toString(); }