List of usage examples for java.util SortedSet size
int size();
From source file:com.mobicage.rogerthat.plugins.messaging.ServiceMessageDetailActivity.java
protected void updateMessageDetail(final boolean isUpdate) { T.UI();// w w w . j a v a2 s.c o m // Set sender avatar ImageView avatarImage = (ImageView) findViewById(R.id.avatar); String sender = mCurrentMessage.sender; setAvatar(avatarImage, sender); // Set sender name TextView senderView = (TextView) findViewById(R.id.sender); final String senderName = mFriendsPlugin.getName(sender); senderView.setText(senderName == null ? sender : senderName); // Set timestamp TextView timestampView = (TextView) findViewById(R.id.timestamp); timestampView.setText(TimeUtils.getDayTimeStr(this, mCurrentMessage.timestamp * 1000)); // Set clickable region on top to go to friends detail final RelativeLayout messageHeader = (RelativeLayout) findViewById(R.id.message_header); messageHeader.setOnClickListener(getFriendDetailOnClickListener(mCurrentMessage.sender)); messageHeader.setVisibility(View.VISIBLE); // Set message TextView messageView = (TextView) findViewById(R.id.message); WebView web = (WebView) findViewById(R.id.webview); FrameLayout flay = (FrameLayout) findViewById(R.id.message_details); Resources resources = getResources(); flay.setBackgroundColor(resources.getColor(R.color.mc_background)); boolean showBranded = false; int darkSchemeTextColor = resources.getColor(android.R.color.primary_text_dark); int lightSchemeTextColor = resources.getColor(android.R.color.primary_text_light); senderView.setTextColor(lightSchemeTextColor); timestampView.setTextColor(lightSchemeTextColor); BrandingResult br = null; if (!TextUtils.isEmptyOrWhitespace(mCurrentMessage.branding)) { boolean brandingAvailable = false; try { brandingAvailable = mMessagingPlugin.getBrandingMgr().isBrandingAvailable(mCurrentMessage.branding); } catch (BrandingFailureException e1) { L.d(e1); } try { if (brandingAvailable) { br = mMessagingPlugin.getBrandingMgr().prepareBranding(mCurrentMessage); WebSettings settings = web.getSettings(); settings.setJavaScriptEnabled(false); settings.setBlockNetworkImage(false); web.loadUrl("file://" + br.file.getAbsolutePath()); web.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY); if (br.color != null) { flay.setBackgroundColor(br.color); } if (!br.showHeader) { messageHeader.setVisibility(View.GONE); MarginLayoutParams mlp = (MarginLayoutParams) web.getLayoutParams(); mlp.setMargins(0, 0, 0, mlp.bottomMargin); } else if (br.scheme == ColorScheme.dark) { senderView.setTextColor(darkSchemeTextColor); timestampView.setTextColor(darkSchemeTextColor); } showBranded = true; } else { mMessagingPlugin.getBrandingMgr().queueGenericBranding(mCurrentMessage.branding); } } catch (BrandingFailureException e) { L.bug("Could not display message with branding: branding is available, but prepareBranding failed", e); } } if (showBranded) { web.setVisibility(View.VISIBLE); messageView.setVisibility(View.GONE); } else { web.setVisibility(View.GONE); messageView.setVisibility(View.VISIBLE); messageView.setText(mCurrentMessage.message); } // Add list of members who did not ack yet FlowLayout memberSummary = (FlowLayout) findViewById(R.id.member_summary); memberSummary.removeAllViews(); SortedSet<MemberStatusTO> memberSummarySet = new TreeSet<MemberStatusTO>(getMemberstatusComparator()); for (MemberStatusTO ms : mCurrentMessage.members) { if ((ms.status & MessagingPlugin.STATUS_ACKED) != MessagingPlugin.STATUS_ACKED && !ms.member.equals(mCurrentMessage.sender)) { memberSummarySet.add(ms); } } FlowLayout.LayoutParams flowLP = new FlowLayout.LayoutParams(2, 0); for (MemberStatusTO ms : memberSummarySet) { FrameLayout fl = new FrameLayout(this); fl.setLayoutParams(flowLP); memberSummary.addView(fl); fl.addView(createParticipantView(ms)); } memberSummary.setVisibility(memberSummarySet.size() < 2 ? View.GONE : View.VISIBLE); // Add members statuses final LinearLayout members = (LinearLayout) findViewById(R.id.members); members.removeAllViews(); final String myEmail = mService.getIdentityStore().getIdentity().getEmail(); boolean isMember = false; mSomebodyAnswered = false; for (MemberStatusTO ms : mCurrentMessage.members) { boolean showMember = true; View view = getLayoutInflater().inflate(R.layout.message_member_detail, null); // Set receiver avatar RelativeLayout rl = (RelativeLayout) view.findViewById(R.id.avatar); rl.addView(createParticipantView(ms)); // Set receiver name TextView receiverView = (TextView) view.findViewById(R.id.receiver); final String memberName = mFriendsPlugin.getName(ms.member); receiverView.setText(memberName == null ? sender : memberName); // Set received timestamp TextView receivedView = (TextView) view.findViewById(R.id.received_timestamp); if ((ms.status & MessagingPlugin.STATUS_RECEIVED) == MessagingPlugin.STATUS_RECEIVED) { final String humanTime = TimeUtils.getDayTimeStr(this, ms.received_timestamp * 1000); if (ms.member.equals(mCurrentMessage.sender)) receivedView.setText(getString(R.string.sent_at, humanTime)); else receivedView.setText(getString(R.string.received_at, humanTime)); } else { receivedView.setText(R.string.not_yet_received); } // Set replied timestamp TextView repliedView = (TextView) view.findViewById(R.id.acked_timestamp); if ((ms.status & MessagingPlugin.STATUS_ACKED) == MessagingPlugin.STATUS_ACKED) { mSomebodyAnswered = true; String acked_timestamp = TimeUtils.getDayTimeStr(this, ms.acked_timestamp * 1000); if (ms.button_id != null) { ButtonTO button = null; for (ButtonTO b : mCurrentMessage.buttons) { if (b.id.equals(ms.button_id)) { button = b; break; } } if (button == null) { repliedView.setText(getString(R.string.dismissed_at, acked_timestamp)); // Do not show sender as member if he hasn't clicked a // button showMember = !ms.member.equals(mCurrentMessage.sender); } else { repliedView.setText(getString(R.string.replied_at, button.caption, acked_timestamp)); } } else { if (ms.custom_reply == null) { // Do not show sender as member if he hasn't clicked a // button showMember = !ms.member.equals(mCurrentMessage.sender); repliedView.setText(getString(R.string.dismissed_at, acked_timestamp)); } else repliedView.setText(getString(R.string.replied_at, ms.custom_reply, acked_timestamp)); } } else { repliedView.setText(R.string.not_yet_replied); showMember = !ms.member.equals(mCurrentMessage.sender); } if (br != null && br.scheme == ColorScheme.dark) { receiverView.setTextColor(darkSchemeTextColor); receivedView.setTextColor(darkSchemeTextColor); repliedView.setTextColor(darkSchemeTextColor); } else { receiverView.setTextColor(lightSchemeTextColor); receivedView.setTextColor(lightSchemeTextColor); repliedView.setTextColor(lightSchemeTextColor); } if (showMember) members.addView(view); isMember |= ms.member.equals(myEmail); } boolean isLocked = (mCurrentMessage.flags & MessagingPlugin.FLAG_LOCKED) == MessagingPlugin.FLAG_LOCKED; boolean canEdit = isMember && !isLocked; // Add attachments LinearLayout attachmentLayout = (LinearLayout) findViewById(R.id.attachment_layout); attachmentLayout.removeAllViews(); if (mCurrentMessage.attachments.length > 0) { attachmentLayout.setVisibility(View.VISIBLE); for (final AttachmentTO attachment : mCurrentMessage.attachments) { View v = getLayoutInflater().inflate(R.layout.attachment_item, null); ImageView attachment_image = (ImageView) v.findViewById(R.id.attachment_image); if (AttachmentViewerActivity.CONTENT_TYPE_JPEG.equalsIgnoreCase(attachment.content_type) || AttachmentViewerActivity.CONTENT_TYPE_PNG.equalsIgnoreCase(attachment.content_type)) { attachment_image.setImageResource(R.drawable.attachment_img); } else if (AttachmentViewerActivity.CONTENT_TYPE_PDF.equalsIgnoreCase(attachment.content_type)) { attachment_image.setImageResource(R.drawable.attachment_pdf); } else if (AttachmentViewerActivity.CONTENT_TYPE_VIDEO_MP4 .equalsIgnoreCase(attachment.content_type)) { attachment_image.setImageResource(R.drawable.attachment_video); } else { attachment_image.setImageResource(R.drawable.attachment_unknown); L.d("attachment.content_type not known: " + attachment.content_type); } TextView attachment_text = (TextView) v.findViewById(R.id.attachment_text); attachment_text.setText(attachment.name); v.setOnClickListener(new SafeViewOnClickListener() { @Override public void safeOnClick(View v) { String downloadUrlHash = mMessagingPlugin .attachmentDownloadUrlHash(attachment.download_url); File attachmentsDir; try { attachmentsDir = mMessagingPlugin.attachmentsDir(mCurrentMessage.getThreadKey(), null); } catch (IOException e) { L.d("Unable to create attachment directory", e); UIUtils.showAlertDialog(ServiceMessageDetailActivity.this, "", R.string.unable_to_read_write_sd_card); return; } boolean attachmentAvailable = mMessagingPlugin.attachmentExists(attachmentsDir, downloadUrlHash); if (!attachmentAvailable) { try { attachmentsDir = mMessagingPlugin.attachmentsDir(mCurrentMessage.getThreadKey(), mCurrentMessage.key); } catch (IOException e) { L.d("Unable to create attachment directory", e); UIUtils.showAlertDialog(ServiceMessageDetailActivity.this, "", R.string.unable_to_read_write_sd_card); return; } attachmentAvailable = mMessagingPlugin.attachmentExists(attachmentsDir, downloadUrlHash); } if (!mService.getNetworkConnectivityManager().isConnected() && !attachmentAvailable) { AlertDialog.Builder builder = new AlertDialog.Builder( ServiceMessageDetailActivity.this); builder.setMessage(R.string.no_internet_connection_try_again); builder.setPositiveButton(R.string.rogerthat, null); AlertDialog dialog = builder.create(); dialog.show(); return; } if (IOUtils.shouldCheckExternalStorageAvailable()) { String state = Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED.equals(state)) { // Its all oke } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) { if (!attachmentAvailable) { L.d("Unable to write to sd-card"); UIUtils.showAlertDialog(ServiceMessageDetailActivity.this, "", R.string.unable_to_read_write_sd_card); return; } } else { L.d("Unable to read or write to sd-card"); UIUtils.showAlertDialog(ServiceMessageDetailActivity.this, "", R.string.unable_to_read_write_sd_card); return; } } L.d("attachment.content_type: " + attachment.content_type); L.d("attachment.download_url: " + attachment.download_url); L.d("attachment.name: " + attachment.name); L.d("attachment.size: " + attachment.size); if (AttachmentViewerActivity.supportsContentType(attachment.content_type)) { Intent i = new Intent(ServiceMessageDetailActivity.this, AttachmentViewerActivity.class); i.putExtra("thread_key", mCurrentMessage.getThreadKey()); i.putExtra("message", mCurrentMessage.key); i.putExtra("content_type", attachment.content_type); i.putExtra("download_url", attachment.download_url); i.putExtra("name", attachment.name); i.putExtra("download_url_hash", downloadUrlHash); startActivity(i); } else { AlertDialog.Builder builder = new AlertDialog.Builder( ServiceMessageDetailActivity.this); builder.setMessage(getString(R.string.attachment_can_not_be_displayed_in_your_version, getString(R.string.app_name))); builder.setPositiveButton(R.string.rogerthat, null); AlertDialog dialog = builder.create(); dialog.show(); } } }); attachmentLayout.addView(v); } } else { attachmentLayout.setVisibility(View.GONE); } LinearLayout widgetLayout = (LinearLayout) findViewById(R.id.widget_layout); if (mCurrentMessage.form == null) { widgetLayout.setVisibility(View.GONE); } else { widgetLayout.setVisibility(View.VISIBLE); widgetLayout.setEnabled(canEdit); displayWidget(widgetLayout, br); } // Add buttons TableLayout tableLayout = (TableLayout) findViewById(R.id.buttons); tableLayout.removeAllViews(); for (final ButtonTO button : mCurrentMessage.buttons) { addButton(senderName, myEmail, mSomebodyAnswered, canEdit, tableLayout, button); } if (mCurrentMessage.form == null && (mCurrentMessage.flags & MessagingPlugin.FLAG_ALLOW_DISMISS) == MessagingPlugin.FLAG_ALLOW_DISMISS) { ButtonTO button = new ButtonTO(); button.caption = "Roger that!"; addButton(senderName, myEmail, mSomebodyAnswered, canEdit, tableLayout, button); } if (mCurrentMessage.broadcast_type != null) { L.d("Show broadcast spam control"); final RelativeLayout broadcastSpamControl = (RelativeLayout) findViewById(R.id.broadcast_spam_control); View broadcastSpamControlBorder = findViewById(R.id.broadcast_spam_control_border); final View broadcastSpamControlDivider = findViewById(R.id.broadcast_spam_control_divider); final LinearLayout broadcastSpamControlTextContainer = (LinearLayout) findViewById( R.id.broadcast_spam_control_text_container); TextView broadcastSpamControlText = (TextView) findViewById(R.id.broadcast_spam_control_text); final LinearLayout broadcastSpamControlSettingsContainer = (LinearLayout) findViewById( R.id.broadcast_spam_control_settings_container); TextView broadcastSpamControlSettingsText = (TextView) findViewById( R.id.broadcast_spam_control_settings_text); TextView broadcastSpamControlIcon = (TextView) findViewById(R.id.broadcast_spam_control_icon); broadcastSpamControlIcon.setTypeface(mFontAwesomeTypeFace); broadcastSpamControlIcon.setText(R.string.fa_bell); final FriendBroadcastInfo fbi = mFriendsPlugin.getFriendBroadcastFlowForMfr(mCurrentMessage.sender); if (fbi == null) { L.bug("BroadcastData was null for: " + mCurrentMessage.sender); collapseDetails(DETAIL_SECTIONS); return; } broadcastSpamControl.setVisibility(View.VISIBLE); broadcastSpamControlSettingsContainer.setOnClickListener(new SafeViewOnClickListener() { @Override public void safeOnClick(View v) { L.d("goto broadcast settings"); PressMenuIconRequestTO request = new PressMenuIconRequestTO(); request.coords = fbi.coords; request.static_flow_hash = fbi.staticFlowHash; request.hashed_tag = fbi.hashedTag; request.generation = fbi.generation; request.service = mCurrentMessage.sender; mContext = "MENU_" + UUID.randomUUID().toString(); request.context = mContext; request.timestamp = System.currentTimeMillis() / 1000; showTransmitting(null); Map<String, Object> userInput = new HashMap<String, Object>(); userInput.put("request", request.toJSONMap()); userInput.put("func", "com.mobicage.api.services.pressMenuItem"); MessageFlowRun mfr = new MessageFlowRun(); mfr.staticFlowHash = fbi.staticFlowHash; try { JsMfr.executeMfr(mfr, userInput, mService, true); } catch (EmptyStaticFlowException ex) { completeTransmit(null); AlertDialog.Builder builder = new AlertDialog.Builder(ServiceMessageDetailActivity.this); builder.setMessage(ex.getMessage()); builder.setPositiveButton(R.string.rogerthat, null); AlertDialog dialog = builder.create(); dialog.show(); return; } } }); UIUtils.showHint(this, mService, HINT_BROADCAST, R.string.hint_broadcast, mCurrentMessage.broadcast_type, mFriendsPlugin.getName(mCurrentMessage.sender)); broadcastSpamControlText .setText(getString(R.string.broadcast_subscribed_to, mCurrentMessage.broadcast_type)); broadcastSpamControlSettingsText.setText(fbi.label); int ligthAlpha = 180; int darkAlpha = 70; int alpha = ligthAlpha; if (br != null && br.scheme == ColorScheme.dark) { broadcastSpamControlIcon.setTextColor(getResources().getColor(android.R.color.black)); broadcastSpamControlBorder.setBackgroundColor(darkSchemeTextColor); broadcastSpamControlDivider.setBackgroundColor(darkSchemeTextColor); activity.setBackgroundColor(darkSchemeTextColor); broadcastSpamControlText.setTextColor(lightSchemeTextColor); broadcastSpamControlSettingsText.setTextColor(lightSchemeTextColor); int alpacolor = Color.argb(darkAlpha, Color.red(lightSchemeTextColor), Color.green(lightSchemeTextColor), Color.blue(lightSchemeTextColor)); broadcastSpamControl.setBackgroundColor(alpacolor); alpha = darkAlpha; } else { broadcastSpamControlIcon.setTextColor(getResources().getColor(android.R.color.white)); broadcastSpamControlBorder.setBackgroundColor(lightSchemeTextColor); broadcastSpamControlDivider.setBackgroundColor(lightSchemeTextColor); activity.setBackgroundColor(lightSchemeTextColor); broadcastSpamControlText.setTextColor(darkSchemeTextColor); broadcastSpamControlSettingsText.setTextColor(darkSchemeTextColor); int alpacolor = Color.argb(darkAlpha, Color.red(darkSchemeTextColor), Color.green(darkSchemeTextColor), Color.blue(darkSchemeTextColor)); broadcastSpamControl.setBackgroundColor(alpacolor); } if (br != null && br.color != null) { int alphaColor = Color.argb(alpha, Color.red(br.color), Color.green(br.color), Color.blue(br.color)); broadcastSpamControl.setBackgroundColor(alphaColor); } mService.postOnUIHandler(new SafeRunnable() { @Override protected void safeRun() throws Exception { int maxHeight = broadcastSpamControl.getHeight(); broadcastSpamControlDivider.getLayoutParams().height = maxHeight; broadcastSpamControlDivider.requestLayout(); broadcastSpamControlSettingsContainer.getLayoutParams().height = maxHeight; broadcastSpamControlSettingsContainer.requestLayout(); broadcastSpamControlTextContainer.getLayoutParams().height = maxHeight; broadcastSpamControlTextContainer.requestLayout(); int broadcastSpamControlWidth = broadcastSpamControl.getWidth(); android.view.ViewGroup.LayoutParams lp = broadcastSpamControlSettingsContainer .getLayoutParams(); lp.width = broadcastSpamControlWidth / 4; broadcastSpamControlSettingsContainer.setLayoutParams(lp); } }); } if (!isUpdate) collapseDetails(DETAIL_SECTIONS); }
From source file:fll.scheduler.TournamentSchedule.java
/** * Figure out how many performance rounds exist in this header line. This * method also checks that the corresponding table header exists for each * round and that the round numbers are contiguous starting at 1. * // ww w . ja v a2s. co m * @throws FLLRuntimeException if there are problems with the performance * round headers found */ private static int countNumRounds(final String[] line) { final SortedSet<Integer> perfRounds = new TreeSet<Integer>(); for (int i = 0; i < line.length; ++i) { if (null != line[i] && line[i].startsWith(BASE_PERF_HEADER) && line[i].length() > BASE_PERF_HEADER.length()) { final String perfNumberStr = line[i].substring(BASE_PERF_HEADER.length()); final Integer perfNumber = Integer.valueOf(perfNumberStr); if (!perfRounds.add(perfNumber)) { throw new FLLRuntimeException("Found performance rounds num " + perfNumber + " twice in the header: " + Arrays.asList(line)); } } } /* * check that the values start at 1, are contiguous, and that the * corresponding table header exists */ int expectedValue = 1; for (Integer value : perfRounds) { if (null == value) { throw new FLLInternalException("Found null performance round in header!"); } if (expectedValue != value.intValue()) { throw new FLLRuntimeException( "Performance rounds not contiguous after " + (expectedValue - 1) + " found " + value); } final String tableHeader = String.format(TABLE_HEADER_FORMAT, expectedValue); if (!checkHeaderExists(line, tableHeader)) { throw new FLLRuntimeException("Couldn't find header for round " + expectedValue + ". Looking for header '" + tableHeader + "'"); } ++expectedValue; } return perfRounds.size(); }
From source file:com.spotify.heroic.filter.impl.AndFilterImpl.java
private static Filter optimize(SortedSet<Filter> statements) { final SortedSet<Filter> result = new TreeSet<>(); root: for (final Filter f : statements) { if (f instanceof Filter.Not) { final Filter.Not not = (Filter.Not) f; if (statements.contains(not.first())) { return FalseFilterImpl.get(); }/* w ww. ja v a2 s . c o m*/ result.add(f); continue; } /** * If there exists two MatchTag statements, but they check for different values. */ if (f instanceof Filter.MatchTag) { final Filter.MatchTag outer = (Filter.MatchTag) f; for (final Filter inner : statements) { if (inner.equals(outer)) { continue; } if (inner instanceof Filter.MatchTag) { final Filter.MatchTag matchTag = (Filter.MatchTag) inner; if (!outer.first().equals(matchTag.first())) { continue; } if (!FilterComparatorUtils.isEqual(outer.second(), matchTag.second())) { return FalseFilterImpl.get(); } } } result.add(f); continue; } if (f instanceof Filter.MatchTag) { final Filter.MatchTag outer = (Filter.MatchTag) f; for (final Filter inner : statements) { if (inner.equals(outer)) { continue; } if (inner instanceof Filter.MatchTag) { final Filter.MatchTag tag = (Filter.MatchTag) inner; if (!outer.first().equals(tag.first())) { continue; } if (!FilterComparatorUtils.isEqual(outer.second(), tag.second())) { return FalseFilterImpl.get(); } } } result.add(f); continue; } // optimize away prefixes which encompass eachother. // Example: foo ^ hello and foo ^ helloworld -> foo ^ helloworld if (f instanceof Filter.StartsWith) { final Filter.StartsWith outer = (Filter.StartsWith) f; for (final Filter inner : statements) { if (inner.equals(outer)) { continue; } if (inner instanceof Filter.StartsWith) { final Filter.StartsWith starts = (Filter.StartsWith) inner; if (!outer.first().equals(starts.first())) { continue; } if (FilterComparatorUtils.prefixedWith(starts.second(), outer.second())) { continue root; } } } result.add(f); continue; } // all ok! result.add(f); } if (result.isEmpty()) { return FalseFilterImpl.get(); } if (result.size() == 1) { return result.iterator().next(); } return new AndFilterImpl(new ArrayList<>(result)); }
From source file:org.dllearner.reasoning.SPARQLReasoner.java
private OWLClassExpression computeDomain(OWLProperty property) { String query = String.format("SELECT ?domain WHERE {" + "<%s> <%s> ?domain. FILTER(isIRI(?domain))" + "}", property.toStringID(), RDFS.domain.getURI()); try (QueryExecution qe = qef.createQueryExecution(query)) { ResultSet rs = qe.execSelect(); SortedSet<OWLClassExpression> domains = new TreeSet<>(); while (rs.hasNext()) { QuerySolution qs = rs.next(); domains.add(df.getOWLClass(IRI.create(qs.getResource("domain").getURI()))); }//from ww w. j a v a 2 s.c o m domains.remove(df.getOWLThing()); if (domains.size() == 1) { return domains.first(); } else if (domains.size() > 1) { return df.getOWLObjectIntersectionOf(domains); } return df.getOWLThing(); } catch (Exception e) { logger.error("Failed to compute the domain for " + property + ".", e); } return null; }
From source file:org.dllearner.reasoning.SPARQLReasoner.java
@Override public OWLClassExpression getRangeImpl(OWLObjectProperty property) { return objectPropertyRanges.computeIfAbsent(property, k -> { String query = String.format("SELECT ?range WHERE {" + "<%s> <%s> ?range. FILTER(isIRI(?range))" + "}", property.toStringID(), RDFS.range.getURI()); try (QueryExecution qe = qef.createQueryExecution(query)) { ResultSet rs = qe.execSelect(); SortedSet<OWLClassExpression> ranges = new TreeSet<>(); while (rs.hasNext()) { QuerySolution qs = rs.next(); ranges.add(df.getOWLClass(IRI.create(qs.getResource("range").getURI()))); }/*from ww w . j a v a2 s . co m*/ ranges.remove(df.getOWLThing()); if (ranges.size() == 1) { return ranges.first(); } else if (ranges.size() > 1) { return df.getOWLObjectIntersectionOf(ranges); } return df.getOWLThing(); } catch (Exception e) { logger.error("Failed to compute range for " + property, e); } return null; }); }
From source file:cerrla.Performance.java
/** * Outputs performance information and estimates convergence. * /* ww w .java 2 s . co m*/ * @param convergence * The convergence as given by the rule distributions. * @param numElites * The minimum number of elites. * @param elites * The current elites. * @param numSlots * The number of slots in the distribution. * @param goalCondition * The goal condition this performance is concerned with. */ public void estimateETA(double convergence, int numElites, SortedSet<PolicyValue> elites, int numSlots, GoalCondition goalCondition) { if (!ProgramArgument.SYSTEM_OUTPUT.booleanValue()) return; boolean mainGoal = goalCondition.isMainGoal(); if (mainGoal) { long currentTime = System.currentTimeMillis(); long elapsedTime = currentTime - trainingStartTime_; String elapsed = "Elapsed: " + RRLExperiment.toTimeFormat(elapsedTime); System.out.println(elapsed); } boolean noUpdates = false; if (convergence == PolicyGenerator.NO_UPDATES_CONVERGENCE) { noUpdates = true; convergence = 0; } double totalRunComplete = (1.0 * runIndex_ + convergence) / Config.getInstance().getNumRepetitions(); if (frozen_) totalRunComplete = 1.0 * (runIndex_ + 1) / Config.getInstance().getNumRepetitions(); DecimalFormat formatter = new DecimalFormat("#0.0000"); String modular = ""; if (!goalCondition.isMainGoal()) modular = "MODULAR: [" + goalCondition + "] "; // No updates yet, convergence unknown String percentStr = null; if (noUpdates) { percentStr = "Unknown convergence; No updates yet."; } else if (!frozen_) { percentStr = "~" + formatter.format(100 * convergence) + "% " + modular + "converged (" + numSlots + " slots)."; } else { if (convergence <= 1) percentStr = formatter.format(100 * convergence) + "% " + modular + "test complete."; else percentStr = "---FULLY CONVERGED---"; } System.out.println(percentStr); if (!frozen_) { // Adjust numElites if using bounded elites String best = (!elites.isEmpty()) ? "" + formatter.format(elites.first().getValue()) : "?"; String worst = (!elites.isEmpty()) ? "" + formatter.format(elites.last().getValue()) : "?"; String eliteString = "N_E: " + numElites + ", |E|: " + elites.size() + ", E_best: " + best + ", E_worst: " + worst; System.out.println(eliteString); } if (mainGoal) { String totalPercentStr = formatter.format(100 * totalRunComplete) + "% experiment complete."; System.out.println(totalPercentStr); } }
From source file:net.sf.jasperreports.engine.xml.JRXmlWriter.java
/** * Writes out the contents of a series colors block for a chart. Assumes the caller * has already written the <code><seriesColors></code> tag. * * @param seriesColors the colors to write *//* w ww . j ava 2s .co m*/ private void writeSeriesColors(SortedSet seriesColors) throws IOException { if (seriesColors == null || seriesColors.size() == 0) return; JRSeriesColor[] colors = (JRSeriesColor[]) seriesColors.toArray(new JRSeriesColor[0]); for (int i = 0; i < colors.length; i++) { writer.startElement(JRXmlConstants.ELEMENT_seriesColor); writer.addAttribute(JRXmlConstants.ATTRIBUTE_seriesOrder, colors[i].getSeriesOrder()); writer.addAttribute(JRXmlConstants.ATTRIBUTE_color, colors[i].getColor()); writer.closeElement(); } }
From source file:org.apache.hadoop.hbase.regionserver.Store.java
private Path internalFlushCache(final SortedSet<KeyValue> set, final long logCacheFlushId, TimeRangeTracker snapshotTimeRangeTracker, AtomicLong flushedSize, MonitoredTask status) throws IOException { StoreFile.Writer writer;/*w w w . j a v a 2 s . c o m*/ // Find the smallest read point across all the Scanners. long smallestReadPoint = region.getSmallestReadPoint(); long flushed = 0; Path pathName; // Don't flush if there are no entries. if (set.size() == 0) { return null; } // Use a store scanner to find which rows to flush. // Note that we need to retain deletes, hence // treat this as a minor compaction. InternalScanner scanner = null; KeyValueScanner memstoreScanner = new CollectionBackedScanner(set, this.comparator); if (getHRegion().getCoprocessorHost() != null) { scanner = getHRegion().getCoprocessorHost().preFlushScannerOpen(this, memstoreScanner); } if (scanner == null) { Scan scan = new Scan(); scan.setMaxVersions(scanInfo.getMaxVersions()); scanner = new StoreScanner(this, scanInfo, scan, Collections.singletonList(memstoreScanner), ScanType.MINOR_COMPACT, this.region.getSmallestReadPoint(), HConstants.OLDEST_TIMESTAMP); } if (getHRegion().getCoprocessorHost() != null) { InternalScanner cpScanner = getHRegion().getCoprocessorHost().preFlush(this, scanner); // NULL scanner returned from coprocessor hooks means skip normal processing if (cpScanner == null) { return null; } scanner = cpScanner; } try { int compactionKVMax = conf.getInt(HConstants.COMPACTION_KV_MAX, 10); // TODO: We can fail in the below block before we complete adding this // flush to list of store files. Add cleanup of anything put on filesystem // if we fail. synchronized (flushLock) { status.setStatus("Flushing " + this + ": creating writer"); // A. Write the map out to the disk writer = createWriterInTmp(set.size()); writer.setTimeRangeTracker(snapshotTimeRangeTracker); pathName = writer.getPath(); try { List<KeyValue> kvs = new ArrayList<KeyValue>(); boolean hasMore; do { //next?KV hasMore = scanner.next(kvs, compactionKVMax); if (!kvs.isEmpty()) { for (KeyValue kv : kvs) { // If we know that this KV is going to be included always, then let us // set its memstoreTS to 0. This will help us save space when writing to disk. if (kv.getMemstoreTS() <= smallestReadPoint) { // let us not change the original KV. It could be in the memstore // changing its memstoreTS could affect other threads/scanners. kv = kv.shallowCopy(); kv.setMemstoreTS(0); } writer.append(kv); flushed += this.memstore.heapSizeChange(kv, true); } kvs.clear(); } } while (hasMore); } finally { // Write out the log sequence number that corresponds to this output // hfile. The hfile is current up to and including logCacheFlushId. status.setStatus("Flushing " + this + ": appending metadata"); writer.appendMetadata(logCacheFlushId, false); status.setStatus("Flushing " + this + ": closing flushed file"); writer.close(); } } } finally { flushedSize.set(flushed); scanner.close(); } if (LOG.isInfoEnabled()) { LOG.info("Flushed " + ", sequenceid=" + logCacheFlushId + ", memsize=" + StringUtils.humanReadableInt(flushed) + ", into tmp file " + pathName); } return pathName; }
From source file:net.sf.jasperreports.chartthemes.spring.GenericChartTheme.java
protected void setPlotDrawingDefaults(Plot p, JRChartPlot jrPlot) { @SuppressWarnings("unchecked") List<Paint> defaultSeriesColors = (List<Paint>) getDefaultValue(defaultChartPropertiesMap, ChartThemesConstants.SERIES_COLORS); Paint[] defaultPlotOutlinePaintSequence = getDefaultValue(defaultPlotPropertiesMap, ChartThemesConstants.PLOT_OUTLINE_PAINT_SEQUENCE) != null ? (Paint[]) getDefaultValue(defaultPlotPropertiesMap, ChartThemesConstants.PLOT_OUTLINE_PAINT_SEQUENCE) : DefaultDrawingSupplier.DEFAULT_OUTLINE_PAINT_SEQUENCE; Stroke[] defaultPlotStrokeSequence = getDefaultValue(defaultPlotPropertiesMap, ChartThemesConstants.PLOT_STROKE_SEQUENCE) != null ? (Stroke[]) getDefaultValue(defaultPlotPropertiesMap, ChartThemesConstants.PLOT_STROKE_SEQUENCE) : DefaultDrawingSupplier.DEFAULT_STROKE_SEQUENCE; Stroke[] defaultPlotOutlineStrokeSequence = getDefaultValue(defaultPlotPropertiesMap, ChartThemesConstants.PLOT_OUTLINE_STROKE_SEQUENCE) != null ? (Stroke[]) getDefaultValue(defaultPlotPropertiesMap, ChartThemesConstants.PLOT_OUTLINE_STROKE_SEQUENCE) : DefaultDrawingSupplier.DEFAULT_OUTLINE_STROKE_SEQUENCE; Shape[] defaultPlotShapeSequence = getDefaultValue(defaultPlotPropertiesMap, ChartThemesConstants.PLOT_SHAPE_SEQUENCE) != null ? (Shape[]) getDefaultValue(defaultPlotPropertiesMap, ChartThemesConstants.PLOT_SHAPE_SEQUENCE) : DefaultDrawingSupplier.DEFAULT_SHAPE_SEQUENCE; // Set color series Paint[] colors = null;//from ww w . ja v a 2s. c o m SortedSet<JRSeriesColor> seriesColors = jrPlot.getSeriesColors(); Paint[] colorSequence = null; if (seriesColors != null && seriesColors.size() > 0) { int seriesColorsSize = seriesColors.size(); colors = new Paint[DefaultDrawingSupplier.DEFAULT_PAINT_SEQUENCE.length + seriesColorsSize]; JRSeriesColor[] jrColorSequence = new JRSeriesColor[seriesColorsSize]; seriesColors.toArray(jrColorSequence); colorSequence = new Paint[seriesColorsSize]; for (int i = 0; i < seriesColorsSize; i++) { colorSequence[i] = jrColorSequence[i].getColor(); } populateSeriesColors(colors, colorSequence); } else if (defaultSeriesColors != null && defaultSeriesColors.size() > 0) { colors = new Paint[DefaultDrawingSupplier.DEFAULT_PAINT_SEQUENCE.length + defaultSeriesColors.size()]; colorSequence = new Paint[defaultSeriesColors.size()]; defaultSeriesColors.toArray(colorSequence); populateSeriesColors(colors, colorSequence); } else { colors = DefaultDrawingSupplier.DEFAULT_PAINT_SEQUENCE; } p.setDrawingSupplier(new DefaultDrawingSupplier(colors, defaultPlotOutlinePaintSequence, defaultPlotStrokeSequence, defaultPlotOutlineStrokeSequence, defaultPlotShapeSequence)); }
From source file:org.apache.cassandra.db.ColumnFamilyStore.java
public List<Row> scan(IndexClause clause, AbstractBounds range, IFilter dataFilter) { // Start with the most-restrictive indexed clause, then apply remaining clauses // to each row matching that clause. // TODO: allow merge join instead of just one index + loop IndexExpression primary = highestSelectivityPredicate(clause); ColumnFamilyStore indexCFS = getIndexedColumnFamilyStore(primary.column_name); if (logger.isDebugEnabled()) logger.debug("Primary scan clause is " + getComparator().getString(primary.column_name)); assert indexCFS != null; DecoratedKey indexKey = indexCFS.partitioner.decorateKey(primary.value); // if the slicepredicate doesn't contain all the columns for which we have expressions to evaluate, // it needs to be expanded to include those too IFilter firstFilter = dataFilter;/*www.j av a2s .co m*/ NamesQueryFilter extraFilter = null; if (clause.expressions.size() > 1) { if (dataFilter instanceof SliceQueryFilter) { // if we have a high chance of getting all the columns in a single index slice, do that. // otherwise, create an extraFilter to fetch by name the columns referenced by the additional expressions. if (getMaxRowSize() < DatabaseDescriptor.getColumnIndexSize()) { logger.debug("Expanding slice filter to entire row to cover additional expressions"); firstFilter = new SliceQueryFilter(ByteBufferUtil.EMPTY_BYTE_BUFFER, ByteBufferUtil.EMPTY_BYTE_BUFFER, ((SliceQueryFilter) dataFilter).reversed, Integer.MAX_VALUE); } else { logger.debug("adding extraFilter to cover additional expressions"); SortedSet<ByteBuffer> columns = new TreeSet<ByteBuffer>(getComparator()); for (IndexExpression expr : clause.expressions) { if (expr == primary) continue; columns.add(expr.column_name); } extraFilter = new NamesQueryFilter(columns); } } else { logger.debug("adding columns to firstFilter to cover additional expressions"); // just add in columns that are not part of the resultset assert dataFilter instanceof NamesQueryFilter; SortedSet<ByteBuffer> columns = new TreeSet<ByteBuffer>(getComparator()); for (IndexExpression expr : clause.expressions) { if (expr == primary || ((NamesQueryFilter) dataFilter).columns.contains(expr.column_name)) continue; columns.add(expr.column_name); } if (columns.size() > 0) { columns.addAll(((NamesQueryFilter) dataFilter).columns); firstFilter = new NamesQueryFilter(columns); } } } List<Row> rows = new ArrayList<Row>(); ByteBuffer startKey = clause.start_key; QueryPath path = new QueryPath(columnFamily); // we need to store last data key accessed to avoid duplicate results // because in the while loop new iteration we can access the same column if start_key was not set ByteBuffer lastDataKey = null; // fetch row keys matching the primary expression, fetch the slice predicate for each // and filter by remaining expressions. repeat until finished w/ assigned range or index row is exhausted. outer: while (true) { /* we don't have a way to get the key back from the DK -- we just have a token -- * so, we need to loop after starting with start_key, until we get to keys in the given `range`. * But, if the calling StorageProxy is doing a good job estimating data from each range, the range * should be pretty close to `start_key`. */ if (logger.isDebugEnabled()) logger.debug(String.format("Scanning index %s starting with %s", expressionString(primary), indexCFS.getComparator().getString(startKey))); // We shouldn't fetch only 1 row as this provides buggy paging in case the first row doesn't satisfy all clauses int count = Math.max(clause.count, 2); QueryFilter indexFilter = QueryFilter.getSliceFilter(indexKey, new QueryPath(indexCFS.getColumnFamilyName()), startKey, ByteBufferUtil.EMPTY_BYTE_BUFFER, false, count); ColumnFamily indexRow = indexCFS.getColumnFamily(indexFilter); logger.debug("fetched {}", indexRow); if (indexRow == null) break; ByteBuffer dataKey = null; int n = 0; for (IColumn column : indexRow.getSortedColumns()) { if (column.isMarkedForDelete()) continue; dataKey = column.name(); n++; DecoratedKey dk = partitioner.decorateKey(dataKey); if (!range.right.equals(partitioner.getMinimumToken()) && range.right.compareTo(dk.token) < 0) break outer; if (!range.contains(dk.token) || dataKey.equals(lastDataKey)) continue; // get the row columns requested, and additional columns for the expressions if necessary ColumnFamily data = getColumnFamily(new QueryFilter(dk, path, firstFilter)); assert data != null : String.format( "No data found for %s in %s:%s (original filter %s) from expression %s", firstFilter, dk, path, dataFilter, expressionString(primary)); logger.debug("fetched data row {}", data); if (extraFilter != null) { // we might have gotten the expression columns in with the main data slice, but // we can't know for sure until that slice is done. So, we'll do the extra query // if we go through and any expression columns are not present. for (IndexExpression expr : clause.expressions) { if (expr != primary && data.getColumn(expr.column_name) == null) { data.addAll(getColumnFamily(new QueryFilter(dk, path, extraFilter))); break; } } } if (satisfies(data, clause, primary)) { logger.debug("row {} satisfies all clauses", data); // cut the resultset back to what was requested, if necessary if (firstFilter != dataFilter) { ColumnFamily expandedData = data; data = expandedData.cloneMeShallow(); IColumnIterator iter = dataFilter.getMemtableColumnIterator(expandedData, dk, getComparator()); new QueryFilter(dk, path, dataFilter).collectCollatedColumns(data, iter, gcBefore()); } rows.add(new Row(dk, data)); } if (rows.size() == clause.count) break outer; } if (n < clause.count || startKey.equals(dataKey)) break; lastDataKey = startKey = dataKey; } return rows; }