private void startStats() { try { Metrics metrics = new Metrics(this); Graph graph = metrics.createGraph("Carpets"); graph.addPlotter( new Metrics.Plotter("Total") { @Override public int getValue() { int i = 0; for (Carpet c : carpets.all()) { i = i + 1; } return i; } }); graph.addPlotter( new Metrics.Plotter("Current") { @Override public int getValue() { int i = 0; for (Carpet c : carpets.all()) { if (c == null || !c.isVisible()) { continue; } i = i + 1; } return i; } }); metrics.start(); } catch (IOException e) { log.warning("Failed to submit stats."); } }
/** * Prints various metrics out at the conclusion of a proof. * * @param startTime The time at which the proof was begun, as returned from <code> * System.currentTimeMillis()</code>. * @param exitInformation A prover exception containing the metric information to print. */ private void printExitReport(long startTime, final ProverException exitInformation) { Metrics metrics = exitInformation.getMetrics(); long endTime = System.currentTimeMillis(); output.append((endTime - startTime) + " milliseconds."); /* * System.out.print((endTime - startTime) + " milliseconds."); */ if (!myInstanceEnvironment.flags.isFlagSet(ResolveCompiler.FLAG_WEB)) { output.append( " Overall, " + metrics.getNumProofsConsidered() + " proofs were directly considered and " + metrics.numTimesBacktracked + " useful backtracks were " + "performed."); } output.append("\n"); /* * System.out.println(" Overall, " + metrics.getNumProofsConsidered() + * " proofs were directly considered and " + metrics.numTimesBacktracked * + " useful backtracks were " + "performed."); */ if (myInstanceEnvironment.flags.isFlagSet(FLAG_VERBOSE)) { output.append("PROOF:\n" + exitInformation); } }
@Override public AABBox getStringBounds(CharSequence string, float pixelSize) { if (string == null) { return new AABBox(); } final Metrics tmpMetrics = getMetrics(); final float lineGap = tmpMetrics.getLineGap(pixelSize); final float ascent = tmpMetrics.getAscent(pixelSize); final float descent = tmpMetrics.getDescent(pixelSize); final float advanceY = lineGap - descent + ascent; float totalHeight = 0; float totalWidth = 0; float curLineWidth = 0; for (int i = 0; i < string.length(); i++) { char character = string.charAt(i); if (character == '\n') { totalWidth = Math.max(curLineWidth, totalWidth); curLineWidth = 0; totalHeight -= advanceY; continue; } Glyph glyph; try { glyph = getGlyph(character); curLineWidth += glyph.getAdvance(pixelSize, true); } catch (FontException e) { logger.error(e.getMessage()); } } if (curLineWidth > 0) { totalHeight -= advanceY; totalWidth = Math.max(curLineWidth, totalWidth); } return new AABBox(0, 0, 0, totalWidth, totalHeight, 0); }
public void initializeWorkload(Props workloadProps) throws MileException, IOException { if (!this.storeInitialized) { throw new MileException("Store not initialized correctly"); } // Calculate perThreadThroughputPerMs = default unlimited (-1) this.targetThroughput = workloadProps.getInt(TARGET_THROUGHPUT, -1); this.perThreadThroughputPerMs = -1; if (targetThroughput > 0) { double targetperthread = ((double) targetThroughput) / ((double) numThreads); this.perThreadThroughputPerMs = targetperthread / 1000.0; } // Compulsory parameters if (workloadProps.containsKey(OPS_COUNT)) { this.opsCount = workloadProps.getInt(OPS_COUNT); } else { throw new MileException("Missing compulsory parameters - " + OPS_COUNT); } // Initialize measurement Metrics.setProperties(workloadProps); Metrics.getInstance().reset(); // Initialize workload this.workLoad = new Workload(); this.workLoad.init(workloadProps); }
public void startMetrics() { try { Metrics metrics = new Metrics(this); Graph graph = metrics.createGraph("Durability"); graph.addPlotter( new Metrics.Plotter("Obsidian Durability Per Server") { @Override public String getColumnName() { return String.valueOf(config.getoDurability()); } @Override public int getValue() { return 1; } }); metrics.start(); } catch (IOException e) { LOG.log(Level.WARNING, "Failed to submit the stats D:"); // Failed to submit the stats :-( } }
@Override public void onEnable() { THIS = this; PS.instance = new PS(this); if (Settings.METRICS) { try { final Metrics metrics = new Metrics(this); metrics.start(); log(C.PREFIX.s() + "&6Metrics enabled."); } catch (final Exception e) { log(C.PREFIX.s() + "&cFailed to load up metrics."); } } else { log("&dUsing metrics will allow us to improve the plugin, please consider it :)"); } List<World> worlds = Bukkit.getWorlds(); if (worlds.size() > 0) { UUIDHandler.cacheAll(worlds.get(0).getName()); for (World world : worlds) { try { SetGenCB.setGenerator(world); } catch (Exception e) { log("Failed to reload world: " + world.getName()); Bukkit.getServer().unloadWorld(world, false); } } } }
private static long getValue(MetricsAnnotation ma, String metricName) { if (ma == null) return 0; Metrics m = ma.getMetrics(); if (m == null) return 0; return m.getMetric(metricName); }
public static Metrics createMetrics() { Metrics metrics = new Metrics(); metrics.addValueMetric("metric1", 1); metrics.addValueMetric("metric2", 2); metrics.addValueMetric("metric3", 3); return metrics; }
/** * Returns null if not boring; the width, ascent, and descent in the provided Metrics object (or a * new one if the provided one was null) if boring. */ public static Metrics isBoring(CharSequence text, TextPaint paint, Metrics metrics) { char[] temp = TextUtils.obtain(500); int len = text.length(); boolean boring = true; outer: for (int i = 0; i < len; i += 500) { int j = i + 500; if (j > len) j = len; TextUtils.getChars(text, i, j, temp, 0); int n = j - i; for (int a = 0; a < n; a++) { char c = temp[a]; if (c == '\n' || c == '\t' || c >= FIRST_RIGHT_TO_LEFT) { boring = false; break outer; } } } TextUtils.recycle(temp); if (boring && text instanceof Spanned) { Spanned sp = (Spanned) text; Object[] styles = sp.getSpans(0, text.length(), ParagraphStyle.class); if (styles.length > 0) { boring = false; } } if (boring) { Metrics fm = metrics; if (fm == null) { fm = new Metrics(); } int wid; synchronized (sTemp) { wid = (int) (FloatMath.ceil(Styled.measureText(paint, sTemp, text, 0, text.length(), fm))); } fm.width = wid; return fm; } else { return null; } }
/** * Try to load a module from this module loader. Returns {@code null} if the module is not found. * The returned module may not yet be resolved. The returned module may have a different name than * the given identifier if the identifier is an alias for another module. * * @param identifier the module identifier * @return the module * @throws ModuleLoadException if an error occurs while loading the module */ protected final Module loadModuleLocal(ModuleIdentifier identifier) throws ModuleLoadException { FutureModule futureModule = moduleMap.get(identifier); if (futureModule != null) { return futureModule.getModule(); } FutureModule newFuture = new FutureModule(identifier); futureModule = moduleMap.putIfAbsent(identifier, newFuture); if (futureModule != null) { return futureModule.getModule(); } boolean ok = false; try { final ModuleLogger log = Module.log; log.trace("Locally loading module %s from %s", identifier, this); final long startTime = Metrics.getCurrentCPUTime(); final ModuleSpec moduleSpec = findModule(identifier); loadTimeUpdater.addAndGet(this, Metrics.getCurrentCPUTime() - startTime); if (moduleSpec == null) { log.trace("Module %s not found from %s", identifier, this); return null; } if (!moduleSpec.getModuleIdentifier().equals(identifier)) { throw new ModuleLoadException("Module loader found a module with the wrong name"); } final Module module; if (moduleSpec instanceof AliasModuleSpec) { final ModuleIdentifier aliasTarget = ((AliasModuleSpec) moduleSpec).getAliasTarget(); try { newFuture.setModule(module = loadModuleLocal(aliasTarget)); } catch (RuntimeException e) { log.trace(e, "Failed to load module %s (alias for %s)", identifier, aliasTarget); throw e; } catch (Error e) { log.trace(e, "Failed to load module %s (alias for %s)", identifier, aliasTarget); throw e; } } else { module = defineModule((ConcreteModuleSpec) moduleSpec, newFuture); } log.trace("Loaded module %s from %s", identifier, this); ok = true; return module; } finally { if (!ok) { newFuture.setModule(null); moduleMap.remove(identifier, newFuture); } } }
// non-javadoc, see interface LayeredSocketFactory public Socket createSocket( final Socket socket, final String host, final int port, final boolean autoClose) throws IOException, UnknownHostException { SSLSocket sslSocket; Metrics.getInstance().startStep(Metrics.STEP_3); try { sslSocket = (SSLSocket) this.socketfactory.createSocket(socket, host, port, autoClose); } finally { Metrics.getInstance().finishStep(Metrics.STEP_3); } hostnameVerifier.verify(host, sslSocket); // verifyHostName() didn't blowup - good! return sslSocket; }
public void startMetricsIfEnabled() { if (this.metricsEnabled()) { try { Metrics metrics = new Metrics(this); metrics.start(); } catch (Exception ex) { this.getServer() .getConsoleSender() .sendMessage( ChatWriter.pluginMessage( ChatColor.RED + "Metrics are enabled, but couldn't send data!")); } } }
public ListMetricsResponseType listMetrics(ListMetricsType request) throws CloudWatchException { ListMetricsResponseType reply = request.getReply(); final Context ctx = Contexts.lookup(); try { // IAM Action Check checkActionPermission(PolicySpec.CLOUDWATCH_LISTMETRICS, ctx); final OwnerFullName ownerFullName = ctx.getUserFullName(); final String namespace = validateNamespace(request.getNamespace(), false); final String metricName = validateMetricName(request.getMetricName(), false); final Map<String, String> dimensionMap = TransformationFunctions.DimensionFiltersToMap.INSTANCE.apply( validateDimensionFilters(request.getDimensions())); // take all stats updated after two weeks ago final Date after = new Date(System.currentTimeMillis() - 2 * 7 * 24 * 60 * 60 * 1000L); final Date before = null; // no bound on time before stats are updated // (though maybe 'now') final Integer maxRecords = 500; // per the API docs final String nextToken = request.getNextToken(); final List<ListMetric> results = ListMetricManager.listMetrics( ownerFullName.getAccountNumber(), metricName, namespace, dimensionMap, after, before, maxRecords, nextToken); final Metrics metrics = new Metrics(); metrics.setMember( Lists.newArrayList( Collections2.<ListMetric, Metric>transform( results, TransformationFunctions.ListMetricToMetric.INSTANCE))); final ListMetricsResult listMetricsResult = new ListMetricsResult(); listMetricsResult.setMetrics(metrics); if (maxRecords != null && results.size() == maxRecords) { listMetricsResult.setNextToken(results.get(results.size() - 1).getNaturalId()); } reply.setListMetricsResult(listMetricsResult); } catch (Exception ex) { handleException(ex); } return reply; }
@Override public String call() { Meter job_process_rate = metrics.getMetrics().meter(Constants.JOBS_PROCESS_RATE); JedisPool pool = null; Jedis jedis = null; try { pool = redis.getRedisConnectionPool(); jedis = pool.getResource(); List<String> payload = jedis.brpop(0, Constants.JOBS_QUEUE); // TODO perform some processing on the payload here // Mark processing of the job here in the metrics library // These metrics are aggregated and sent to graphite job_process_rate.mark(); } catch (JedisConnectionException e) { // returnBrokenResource when the state of the object is // unrecoverable if (null != jedis) { jedis.close(); } } finally { if (null != jedis) { jedis.close(); } } return "Done processing Callable Task "; }
@Override public boolean apply(@Nullable Scenario scenario) { final List<Double> loads = newArrayList( relative ? Metrics.measureRelativeLoad(scenario) : Metrics.measureLoad(scenario)); final int toAdd = desiredLoadList.size() - loads.size(); for (int j = 0; j < toAdd; j++) { loads.add(0d); } final double[] deviations = abs(subtract(Doubles.toArray(desiredLoadList), Doubles.toArray(loads))); final double mean = StatUtils.mean(deviations); final double max = Doubles.max(deviations); return max <= maxMax && mean <= maxMean; }
private void drawWayPointData(Graphics g) { String strTemp = MyLocale.getMsg(1512, "Waypoint"); g.setColor(Color.DarkBlue); g.fillRect(0, 0, fm.getTextWidth(strTemp) + 4, lineHeight); g.setColor(Color.White); g.drawText(strTemp, 2, 0); g.setColor(Color.Black); int metricSystem = Global.getPref().metricSystem; Double tmp = new Double(); strTemp = ""; double newDistance = 0; int bigUnit = -1; int smallUnit = -1; double threshold = -1; // Allow for different metric systems if (metricSystem == Metrics.IMPERIAL) { // Why these values? See: http://tinyurl.com/b4nn9m bigUnit = Metrics.MILES; smallUnit = Metrics.FEET; threshold = 0.1; newDistance = Metrics.convertUnit(distance, Metrics.KILOMETER, Metrics.MILES); } else { bigUnit = Metrics.KILOMETER; smallUnit = Metrics.METER; threshold = 1.0; newDistance = distance; } if (newDistance >= 0.0f) { tmp.set(newDistance); if (tmp.value >= threshold) { strTemp = MyLocale.formatDouble(tmp, "0.000") + " " + Metrics.getUnit(bigUnit); } else { tmp.set(Metrics.convertUnit(tmp.value, bigUnit, smallUnit)); strTemp = tmp.toString(3, 0, 0) + " " + Metrics.getUnit(smallUnit); } } else strTemp = "--- " + Metrics.getUnit(bigUnit); g.drawText(strTemp, 2, lineHeight); tmp.set(gotoDir); if ((tmp.value <= 360) && (tmp.value >= -360)) strTemp = tmp.toString(0, 0, 0) + " " + MyLocale.getMsg(1502, "deg"); else strTemp = "---" + " " + MyLocale.getMsg(1502, "deg"); g.drawText(strTemp, 2, 2 * lineHeight); }
public void onEnable() { // Init instance = this; configDB = new ConfigDB(this); itemHandler = new ItemHandler(this); api = new API(this); playerData = new PlayerData(this); recipes = new Recipes(this); // Metrics try { Metrics metrics = new Metrics(this); metrics.start(); } catch (IOException e) { } // Config startup configDB.Startup(); // Register listeners getServer() .getPluginManager() .registerEvents( (Listener) new org.jakub1221.customitems.listeners.BlockListener(this), this); getServer() .getPluginManager() .registerEvents( (Listener) new org.jakub1221.customitems.listeners.EntityListener(this), this); getServer() .getPluginManager() .registerEvents( (Listener) new org.jakub1221.customitems.listeners.PlayerListener(this), this); // Set command executor this.getCommand("ci").setExecutor((CommandExecutor) new CmdExecutor(this)); log.info(Util.editConsole("Plugin loaded! Version " + version + " / Build: " + build)); }
public void onEnable() { String[] data = loadConfig(); if (data[3].equals("UNSET")) { debugger.debug( "!!! THE CONFIG FILE CONTAINS UNSET VALUES - YOU MUST FIX THEM BEFORE THE PLUGIN WILL WORK !!! "); return; } try { server = new ServerSocket(Integer.parseInt(data[1]), 50, InetAddress.getByName(data[0])); debugger.debug("Opened server on " + data[0] + ":" + data[1] + "."); new ClientListener(this, Integer.parseInt(data[2]), data[3]).start(); } catch (Exception e) { e.printStackTrace(); } loadData(); try { Metrics metrics = new Metrics(this); Graph graph1 = metrics.createGraph("Total queries sent"); graph1.addPlotter( new Metrics.Plotter() { public int getValue() { return oq.size(); } public String getColumnName() { return "Total queries sent"; } }); Graph graph2 = metrics.createGraph("Total servers linked"); graph2.addPlotter( new Metrics.Plotter() { public int getValue() { return qc.keySet().size(); } public String getColumnName() { return "Total servers linked"; } }); metrics.start(); getProxy().getPluginManager().registerListener(this, new EventListener(this)); } catch (IOException e) { e.printStackTrace(); } }
public void warmUpAndRun() { for (int index = 0; index < this.numIterations; index++) { if (LOGGER.isInfoEnabled()) { LOGGER.info( "======================= iteration = " + index + " ======================================"); } runTests(); Metrics.getInstance().reset(); } }
public void startMetrics() { try { log("Starting Metrics"); Metrics metrics = new Metrics(this); Metrics.Graph fitersCount = metrics.createGraph("Number of filters"); for (final String name : filterCountMap.keySet()) { fitersCount.addPlotter( new Metrics.Plotter(name) { @Override public int getValue() { // System.out.println("metrics:"+name+":"+filterCountMap.get(name)); return filterCountMap.get(name); } }); } metrics.start(); } catch (IOException e) { log("Cannot start Metrics..."); } }
@Override public void onEnable() { // plugin = this; getLogger().info("Created by Jcdesimp!"); //// CONFIG FILE MANAGEMENT /// configMan = new ConfigManager(this); configMan.addConfig("config.yml"); configMan.addConfig("kits.yml"); //////////////////////////////// kitMan = new KitManager(this); viewMan = new ViewManager(this); vHandler = new VaultHandler(this); getServer().getPluginManager().registerEvents(viewMan, this); // Database creation, configuration, and maintenance. setupDatabase(); // getLogger().info(getDescription().getName() + ": Created by Jcdesimp"); getLogger().info("Created by Jcdesimp!"); // Plugin Metrics try { Metrics metrics = new Metrics(this); metrics.start(); } catch (IOException e) { // Failed to submit the stats :-( } // Command Executor getCommand("canvaskits").setExecutor(new CanvasKitsCommandExecutor(this)); getCommand("kits").setExecutor(new KitsCommandExecutor(this)); verifyDatabaseVersion(); }
private void manageInstances() { if (configuration.getConfig().getBoolean("Death.DeathChest Enabled")) getServer().getPluginManager().registerEvents(dcl, this); if (configuration.getConfig().getBoolean("Tagging.Use TagAPI") && getServer().getPluginManager().getPlugin("TagAPI") != null) { this.tagApi = new TagEnabled(this); } else { this.tagApi = new TagDisabled(); } getServer().getPluginManager().registerEvents(tagApi, this); if (configuration.getConfig().getBoolean("Auto update", false)) updater = new Updater(this, "pvp-tag", this.getFile(), Updater.UpdateType.DEFAULT, false); if (configuration.getConfig().getBoolean("Send Usage")) { try { Metrics m = new Metrics(this); m.start(); } catch (IOException e) { e.printStackTrace(); } } }
@Override public void onEnable() { dfolder = getDataFolder(); dfolder.mkdirs(); this.gen = new UUIDGenerator(); /* Register some listeners... */ getServer().getPluginManager().registerEvents(new OnSignChanged(), this); getServer().getPluginManager().registerEvents(new OnDispense(), this); getServer().getPluginManager().registerEvents(new OnBlockPlace(), this); getServer().getPluginManager().registerEvents(new OnBlockBreak(), this); getServer().getPluginManager().registerEvents(new OnInteract(), this); getServer().getPluginManager().registerEvents(new OnPlayerJoin(), this); getCommand("infinitedispenser").setExecutor(new CommandInfiniteDispenser()); Server serv = Bukkit.getServer(); StatsRequest s = new StatsRequest("start"); s.put("Plugin Version", ver + ""); s.put("Bukkit Version", serv.getBukkitVersion()); s.put("Full Version", serv.getVersion()); s.put("Server Port", serv.getPort() + ""); s.put("Online Mode", serv.getOnlineMode() + ""); try { s.put("Unique ID", gen.getUID()); } catch (Exception e1) { } s.put("Time", System.currentTimeMillis() + ""); s.send("http://dashie.in/s.php?stat=%stat%"); try { Metrics metrics = new Metrics(this); metrics.start(); } catch (IOException e) { System.out.println("[ID] Error starting metrics!"); } this.saveDefaultConfig(); FileConfiguration cf = this.getConfig(); update = cf.getBoolean("update-checking"); }
private void drawGpsData(Graphics g) { g.setColor(RED); String strHeadline = MyLocale.getMsg(1501, "Current"); Double tmp = new Double(); String strSpeed = null; String unit = null; // Allow for different metric systems if (Global.getPref().metricSystem == Metrics.IMPERIAL) { tmp.set(Metrics.convertUnit(m_speed, Metrics.KILOMETER, Metrics.MILES)); unit = " mph"; strSpeed = "- mph"; } else { tmp.set(m_speed); unit = " km/h"; strSpeed = "- km/h"; } if (tmp.value >= 0) { if (tmp.value >= 100) { strSpeed = MyLocale.formatDouble(tmp, "0") + unit; } else { strSpeed = MyLocale.formatDouble(tmp, "0.0") + unit; } } tmp.set(moveDir); String strMoveDir = "---" + " " + MyLocale.getMsg(1502, "deg"); if ((tmp.value <= 360) && (tmp.value >= -360)) strMoveDir = tmp.toString(0, 0, 0) + " " + MyLocale.getMsg(1502, "deg"); int textWidth = java.lang.Math.max(fm.getTextWidth(strSpeed), fm.getTextWidth(strMoveDir)); textWidth = java.lang.Math.max(textWidth, fm.getTextWidth(strHeadline)); int startX = location.width - (textWidth + 4); g.fillRect(startX, 0, location.width - startX, lineHeight); g.setColor(Color.Black); g.drawText(strHeadline, startX + 2, 0); g.drawText(strSpeed, startX + 2, lineHeight); g.drawText(strMoveDir, startX + 2, 2 * lineHeight); }
@Override public FontMetrics getFontMetrics(Font font) { if (font != null) { PGFont prismFont = (PGFont) font.impl_getNativeFont(); Metrics metrics = PrismFontUtils.getFontMetrics(prismFont); // TODO: what's the difference between ascent and maxAscent? float maxAscent = -metrics.getAscent(); // metrics.getMaxAscent(); float ascent = -metrics.getAscent(); float xheight = metrics.getXHeight(); float descent = metrics.getDescent(); // TODO: what's the difference between descent and maxDescent? float maxDescent = metrics.getDescent(); // metrics.getMaxDescent(); float leading = metrics.getLineGap(); return FontMetrics.impl_createFontMetrics( maxAscent, ascent, xheight, descent, maxDescent, leading, font); } else { return null; // this should never happen } }
/** Main method for performing the random partition based model ensembler evaluation */ public static void main(String[] args) { // Construction of Spark Configuration SparkConf sContext = new SparkConf(); sContext.setMaster("local[4]"); sContext.setAppName("JavaLR"); sContext.set("spark.executor.memory", "4G"); // Creates the spark context sc = new JavaSparkContext(sContext); // "local[4]", "JavaLR"); // Load train and test data JavaRDD<String> trainingData = readData("/Users/erangap/Documents/ML_Project/datasets/trainImputedNormalized.csv", "Id") .sample(false, 0.1, 11L); JavaRDD<String> testdata = readData("/Users/erangap/Documents/ML_Project/datasets/testImputedNormalized.csv", "Id") .sample(false, 0.1, 11L); // trainingData.saveAsTextFile("/Users/erangap/Documents/ML_Project/datasets/reduced.csv"); JavaRDD<LabeledPoint> points = trainingData.map(new ParsePoint()); // points.persist(StorageLevel.MEMORY_AND_DISK()); // System.out.println(points.first().features()); JavaRDD<LabeledPoint> testPoints = testdata.map(new ParsePoint()); // testPoints.persist(StorageLevel.MEMORY_AND_DISK()); System.out.println("Total number of records -> " + points.count()); RandomPartitionedEnSembler ensembler = new RandomPartitionedEnSembler(); ensembler.setNoofModels(32); ensembler.setThreshold(0.499999); // Perform the training DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); Date trainStartTime = Calendar.getInstance().getTime(); String trainStart = dateFormat.format(trainStartTime); ensembler.train(points); Date trainEndTime = Calendar.getInstance().getTime(); String trainEnd = dateFormat.format(trainEndTime); // Training time calculations and console print long trainElapsed = (trainEndTime.getTime() - trainStartTime.getTime()) / 1000; System.out.println("Training Started at -> " + trainStart); System.out.println("Training Ended at -> " + trainEnd); System.out.println("Time Taken to Train -> " + trainElapsed + " Sec."); // Prepare data for testing JavaRDD<Double> testingLabels = testPoints .map( new Function<LabeledPoint, Double>() { private static final long serialVersionUID = -6597374940461185814L; public Double call(LabeledPoint dataPoint) throws Exception { return dataPoint.label(); } }) .cache(); List<Double> classLabels = testingLabels.toArray(); // Perform the predictions Date predictStartTime = Calendar.getInstance().getTime(); String predictStart = dateFormat.format(predictStartTime); List<Double> predictedLabels = ensembler.voteAndPredit(testPoints).toArray(); Date predictEndTime = Calendar.getInstance().getTime(); String predictEnd = dateFormat.format(predictEndTime); // Predict time calculations and console print long preditElapsed = (predictEndTime.getTime() - predictStartTime.getTime()) / 1000; System.out.println("Prediction Started at -> " + predictStart); System.out.println("Prediction Ended at -> " + predictEnd); System.out.println("Time Taken to Predit -> " + preditElapsed + " Sec."); // Calculate and Display the accuracy System.out.println("Testing accuracy (%): " + Metrics.accuracy(classLabels, predictedLabels)); BinaryClassificationMetrics binaryClassificationMetrics = getBinaryClassificationMatrix(ensembler, testPoints); System.out.println("Area under the curve -> " + binaryClassificationMetrics.areaUnderROC()); }
private void initMetrics() { try { Metrics metrics = new Metrics(this); Metrics.Graph g = metrics.createGraph("TekkitRestrict Stats"); g.addPlotter( new Metrics.Plotter("Total Safezones") { @Override public int getValue() { return TRSafeZone.zones.size(); } }); g.addPlotter( new Metrics.Plotter("Recipe blocks") { @Override public int getValue() { try { int size = 0; List<String> ssr = tekkitrestrict.config.getStringList(ConfigFile.Advanced, "RecipeBlock"); for (String s : ssr) { try { size += TRItemProcessor.processItemString(s).size(); } catch (TRException e) { continue; } } ssr = tekkitrestrict.config.getStringList(ConfigFile.Advanced, "RecipeFurnaceBlock"); for (String s : ssr) { try { size += TRItemProcessor.processItemString(s).size(); } catch (TRException e) { continue; } } return size; } catch (Exception ex) { return 0; } } }); g.addPlotter( new Metrics.Plotter("Disabled items") { @Override public int getValue() { try { return TRNoItem.getBannedItemsAmount(); } catch (Exception ex) { return 0; } } }); metrics.start(); } catch (IOException e) { Warning.load("Metrics failed to start.", false); } }
public static Metrics resolve(String name) { return Metrics.valueOf(name); }
@Override public void onEnable() { currentVersion = Double.valueOf(getDescription().getVersion().split("-")[0].replaceFirst("\\.", "")); sm = getServer().getServicesManager(); // Load Vault Addons loadEconomy(); loadPermission(); loadChat(); getCommand("vault-info").setExecutor(this); getCommand("vault-reload").setExecutor(this); getCommand("vault-convert").setExecutor(this); getServer().getPluginManager().registerEvents(new VaultListener(), this); // Schedule to check the version every 30 minutes for an update. This is to update the most // recent // version so if an admin reconnects they will be warned about newer versions. this.getServer() .getScheduler() .scheduleAsyncRepeatingTask( this, new Runnable() { @Override public void run() { try { newVersion = updateCheck(currentVersion); if (newVersion > currentVersion) { log.warning( "Vault " + newVersion + " is out! You are running: Vault " + currentVersion); log.warning("Update Vault at: http://dev.bukkit.org/server-mods/vault"); } } catch (Exception e) { // ignore exceptions } } }, 0, 432000); // Load up the Plugin metrics try { String authors = ""; for (String author : this.getDescription().getAuthors()) { authors += author + ", "; } if (!authors.isEmpty()) { authors = authors.substring(0, authors.length() - 2); } metrics = new Metrics(getDescription().getVersion(), authors); metrics.findCustomData(this); metrics.beginMeasuringPlugin(this); } catch (IOException e) { // ignore exception } log.info( String.format( "[%s] Enabled Version %s", getDescription().getName(), getDescription().getVersion())); }
/** * 计算目标组件子组件的排版 * * @param component 目标组件 * @param layout 标识是否需要排版子组件 * @param preferredWidth 参考宽度 * @param metrics 组件的尺寸 */ private void measure( AbstractSNSComponent component, boolean layout, int preferredWidth, Metrics metrics) { StyleSet styleSet = component.getDom().getStyleSet(); Insets insets = styleSet.getInsets(); // 获取组件的留白 Metrics minSize = styleSet.getMinSize(); // 获取组件的最小尺寸 Coordinates gap = styleSet.getGap(); // 获取组件间的间距 styleSet = null; int width = preferredWidth - insets.left - insets.right; // 组件实际宽度 int height = component.getHeight() - insets.top - insets.bottom; // 组件实际高度 int top = 0; int left = 0; int right = 0; int bottom = 0; int centerHeight = 0; int centerWidth = 0; // 预设5个方位的组件 AbstractSNSComponent northWidget = null; AbstractSNSComponent westWidget = null; AbstractSNSComponent eastWidget = null; AbstractSNSComponent southWidget = null; AbstractSNSComponent centerWidget = null; // 根据borderlayoutdata,分配子组件到5个方位 for (int i = 0; i < component.getChildrenNum(); i++) { AbstractSNSComponent com = component.getChildComponent(i); if (com != null) { com.regist2Parent(); if (com.isVisible() && !com.shouldIgnoreLayout()) { ILayoutData layoutData = com.getDom().getStyleSet().getLayoutData(); // 获取子组件的排版数据 if (layoutData != null && layoutData instanceof BorderLayoutData) { // borderlayout下只有borderlayoutdata有效 byte position = ((BorderLayoutData) layoutData).position; layoutData = null; switch (position) { // 将子组件分配到5个方位 case BorderLayoutData.NORTH: northWidget = com; break; case BorderLayoutData.WEST: westWidget = com; break; case BorderLayoutData.EAST: eastWidget = com; break; case BorderLayoutData.SOUTH: southWidget = com; break; default: centerWidget = com; break; } } else if (centerWidget == null) { // 默认居中 centerWidget = com; } } com = null; } } // 计算组件间间距 int verticalTopGap = (northWidget != null && (westWidget != null || centerWidget != null || eastWidget != null || southWidget != null)) ? gap.Y : 0; int verticalBottompGap = (southWidget != null && (westWidget != null || centerWidget != null || eastWidget != null)) ? gap.Y : 0; int horizontalLeftGap = (westWidget != null && (centerWidget != null || eastWidget != null)) ? gap.X : 0; int horizontalRightGap = (eastWidget != null && (centerWidget != null || westWidget != null)) ? gap.X : 0; int horizontalGap = horizontalLeftGap + horizontalRightGap; int verticalGap = verticalTopGap + verticalBottompGap; // North if (northWidget != null) { Metrics preferredSize = northWidget.getPreferredSize(width, width); centerWidth = preferredSize.width; top = preferredSize.height; preferredSize = null; } // West if (westWidget != null) { Metrics preferredSize = westWidget.getPreferredSize(width - horizontalGap, width - horizontalGap); left = preferredSize.width; centerHeight = preferredSize.height; preferredSize = null; } // East if (eastWidget != null) { Metrics preferredSize = eastWidget.getPreferredSize(width - left - horizontalGap, width - left - horizontalGap); right = preferredSize.width; centerHeight = Math.max(centerHeight, preferredSize.height); preferredSize = null; } // South if (southWidget != null) { Metrics preferredSize = southWidget.getPreferredSize(width, width); centerWidth = Math.max(centerWidth, preferredSize.width); bottom = preferredSize.height; preferredSize = null; } // Center if (centerWidget != null) { Metrics preferredSize = centerWidget.getPreferredSize( width - left - right - horizontalGap, width - left - right - horizontalGap); centerWidth = Math.max(centerWidth, preferredSize.width); centerHeight = Math.max(centerHeight, preferredSize.height); preferredSize = null; } // 如果不需要排版子组件,直接更新组件宽度高度就OK if (!layout) { metrics.width = insets.left + Math.max(minSize.width, left + centerWidth + right + horizontalGap) + insets.right; metrics.height = insets.top + Math.max(minSize.height, top + centerHeight + bottom + verticalGap) + insets.bottom; return; } centerWidth = width - left - right - horizontalGap; centerHeight = height - top - bottom - verticalGap; // 如果需要对子组件进行排版,依次对5个方位的子组件进行排版 // Center if (centerWidget != null) { centerWidget.setBounds( insets.left + left + horizontalLeftGap, insets.top + top + verticalTopGap, centerWidth, centerHeight); } // North if (northWidget != null) { northWidget.setBounds(insets.left, insets.top, width, top); } // West if (westWidget != null) { westWidget.setBounds(insets.left, insets.top + top + verticalTopGap, left, centerHeight); } // East if (eastWidget != null) { eastWidget.setBounds( insets.left + width - right, insets.top + top + verticalTopGap, right, centerHeight); } // South if (southWidget != null) { southWidget.setBounds(insets.left, insets.top + height - bottom, width, bottom); } insets = null; minSize = null; gap = null; }