auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected SimpleResult compareMetricValues(final Object value1, final Object value2, final String metricName) { boolean equal = true; String description = ""; if (value1 == null || value2 == null) { if (value1 != null || value2 != null) { equal = false; description = "One of the values is null"; } } else { if (value1 instanceof Number) { double numValue1 = ((Number) value1).doubleValue(); double numValue2 = ((Number) value2).doubleValue(); double relativeChange = 0; if ((!Double.isNaN(numValue1)) || (!Double.isNaN(numValue2))) { relativeChange = (numValue1 == 0 && numValue2 == 0) ? 0 : (numValue1 == 0) ? Double.MAX_VALUE : (numValue1 - numValue2) / numValue2; } if (relativeChange != 0) { if (MetricToAllowableRelativeChange.containsKey(metricName)) { double allowableRelativeChange = MetricToAllowableRelativeChange.get(metricName); if (Math.abs(relativeChange) >= allowableRelativeChange) { equal = false; description = "Changed by " + relativeChange + " which is outside of the allowable tolerance of " + allowableRelativeChange; } else { equal = true; description = "Changed by " + relativeChange + " which is within the allowable tolerance of " + allowableRelativeChange; } } else { equal = false; description = "Changed by " + relativeChange; } } } else { if (!value1.equals(value2)) { equal = false; description = ""; } } } return new SimpleResult(equal, description); }

Target:
protected SimpleResult compareMetricValues(final Object value1, final Object value2, final String metricName) { boolean equal = true; String description = ""; if (value1 == null || value2 == null) { if (value1 != null || value2 != null) { equal = false; description = "One of the values is null"; } } else { if (value1 instanceof Number) { double numValue1 = ((Number) value1).doubleValue(); double numValue2 = ((Number) value2).doubleValue(); double absoluteChange = 0; if (!Double.isNaN(numValue1) || !Double.isNaN(numValue2)) { absoluteChange = numValue2 - numValue1; } if (absoluteChange != 0) { double relativeChange = numValue1 == 0 ? Double.MAX_VALUE : absoluteChange / numValue1; if (MetricToAllowableRelativeChange.containsKey(metricName)) { double allowableRelativeChange = MetricToAllowableRelativeChange.get(metricName); if (Math.abs(relativeChange) >= allowableRelativeChange) { equal = false; description = "Changed by " + absoluteChange + " (relative change of " + relativeChange + ") which is outside of the allowable relative change tolerance of " + allowableRelativeChange; } else { equal = true; description = "Changed by " + absoluteChange + " (relative change of " + relativeChange + ") which is within the allowable relative change tolerance of " + allowableRelativeChange; } } else { equal = false; description = "Changed by " + absoluteChange + " (relative change of " + relativeChange + ")"; } } } else { if (!value1.equals(value2)) { equal = false; description = ""; } } } return new SimpleResult(equal, description); }
Source:
public boolean matches(RelOptRuleCall call) { TableConfig config = call.getPlanner().getContext().unwrap(FlinkContext.class).getTableConfig(); if (!config.getConfiguration().getBoolean( OptimizerConfigOptions.TABLE_OPTIMIZER_SOURCE_PREDICATE_PUSHDOWN_ENABLED)) { return false; } Filter filter = call.rel(0); if (filter.getCondition() == null) { return false; } LogicalTableScan scan = call.rel(1); TableSourceTable tableSourceTable = scan.getTable().unwrap(TableSourceTable.class); return tableSourceTable != null && tableSourceTable.tableSource() instanceof SupportsFilterPushDown && !Arrays.stream(tableSourceTable.extraDigests()).anyMatch(str -> str.contains("filter")); }

Target:
public boolean matches(RelOptRuleCall call) { TableConfig config = call.getPlanner().getContext().unwrap(FlinkContext.class).getTableConfig(); if (!config.getConfiguration().getBoolean( OptimizerConfigOptions.TABLE_OPTIMIZER_SOURCE_PREDICATE_PUSHDOWN_ENABLED)) { return false; } Filter filter = call.rel(0); if (filter.getCondition() == null) { return false; } LogicalTableScan scan = call.rel(1); TableSourceTable tableSourceTable = scan.getTable().unwrap(TableSourceTable.class); return tableSourceTable != null && tableSourceTable.tableSource() instanceof SupportsFilterPushDown && !Arrays.stream(tableSourceTable.extraDigests()).anyMatch(str -> str.startsWith("filter=[")); }
Source:
public void handleEvent(Event event) { Object element = event.getProperty(IEventBroker.DATA); if (!(element instanceof MApplication)) { return; } for (MWindow window : ((MApplication) element).getChildren()) { CSSEngine engine = getEngine(window); if (engine != null) { invalidateResourcesInRegistry(engine.getResourcesRegistry()); engine.reapply(); } } }

Target:
public void handleEvent(Event event) { Object element = event.getProperty(IEventBroker.DATA); if (!(element instanceof MApplication)) { return; } List<Object> unusedResources = new ArrayList<Object>(); Set<IResourcesRegistry> processedRegistries = new HashSet<IResourcesRegistry>(); for (MWindow window : ((MApplication) element).getChildren()) { CSSEngine engine = getEngine(window); if (engine != null) { IResourcesRegistry registry = engine.getResourcesRegistry(); if (!processedRegistries.contains(registry)) { unusedResources.addAll(removeResources(registry)); processedRegistries.add(registry); } engine.reapply(); } } for (Object resource : unusedResources) { disposeResource(resource); } }
Source:
public void removeDroneConfiguration(InjectionPoint<?> injectionPoint) { DronePair<?, ?> pair = dronePairMap.get(injectionPoint); if (pair == null) { LOGGER.warning("Injection point doesn't exist!"); return; } if (pair.getDroneCallable() != null) { LOGGER.warning("Drone is still set, but you won't be able to access it anymore!"); } if (pair.getConfiguration() == null) { LOGGER.warning("Couldn't remove configuration, because it wasn't set!"); } pair.setConfiguration(null); dronePairMap.remove(injectionPoint); }

Target:
public void removeDroneConfiguration(InjectionPoint<?> injectionPoint) { DronePair<?, ?> pair = dronePairMap.get(injectionPoint); if (pair == null) { LOGGER.log(Level.WARNING, "Couldn''t remove configuration, because the injection point wasn''t prepared. " + "Injection point: {0}", injectionPoint); return; } if (pair.getDroneCallable() != null) { LOGGER.log(Level.WARNING, "Drone is still set, but you won''t be able to access it anymore! Injection " + "point: {0}", injectionPoint); } if (pair.getConfiguration() == null) { LOGGER.log(Level.WARNING, "Couldn''t remove configuration, because it wasn''t set! Injection point: {0}", injectionPoint); } pair.setConfiguration(null); dronePairMap.remove(injectionPoint); }
Source:
public NakadiCursor convert(final String eventTypeStr, final Cursor cursor) throws InternalNakadiException, NoSuchEventTypeException, InvalidCursorException { final String orderStr = cursor.getOffset().substring( NakadiCursor.VERSION_LENGTH, NakadiCursor.VERSION_LENGTH + TIMELINE_ORDER_LENGTH); final int order = Integer.parseInt(orderStr, TIMELINE_ORDER_BASE); final List<Timeline> timelines = eventTypeCache.getTimelines(eventTypeStr); final EventType eventType = eventTypeCache.getEventType(eventTypeStr); final String realOffset = cursor.getOffset().substring(NakadiCursor.VERSION_LENGTH + TIMELINE_ORDER_LENGTH); if (timelines.isEmpty()) { Preconditions.checkArgument( order == (Timeline.STARTING_ORDER + 1), "Fallback supported only for order next after initial"); return new NakadiCursor( timelineService.getFakeTimeline(eventType), cursor.getPartition(), StringUtils.leftPad(realOffset, VersionZeroConverter.VERSION_ZERO_MIN_OFFSET_LENGTH, '0') ); } final Timeline timeline = timelines.stream() .filter(t -> t.getOrder().equals(order)) .findAny() .orElseThrow(() -> new InvalidCursorException(CursorError.UNAVAILABLE)); return new NakadiCursor( timeline, cursor.getPartition(), realOffset); }

Target:
public NakadiCursor convert(final String eventTypeStr, final Cursor cursor) throws InternalNakadiException, NoSuchEventTypeException, InvalidCursorException { final String[] parts = cursor.getOffset().split("-", 3); if (parts.length != 3) { throw new InvalidCursorException(CursorError.INVALID_OFFSET); } final String versionStr = parts[0]; if (versionStr.length() != NakadiCursor.VERSION_LENGTH) { throw new InvalidCursorException(CursorError.INVALID_OFFSET); } final String orderStr = parts[1]; if (orderStr.length() != TIMELINE_ORDER_LENGTH) { throw new InvalidCursorException(CursorError.INVALID_OFFSET); } final String offsetStr = parts[2]; if (offsetStr.isEmpty()) { throw new InvalidCursorException(CursorError.INVALID_OFFSET); } final int order; try { order = Integer.parseInt(orderStr, TIMELINE_ORDER_BASE); } catch (final NumberFormatException ex) { throw new InvalidCursorException(CursorError.INVALID_OFFSET); } final List<Timeline> timelines = eventTypeCache.getTimelinesOrdered(eventTypeStr); final EventType eventType = eventTypeCache.getEventType(eventTypeStr); if (timelines.isEmpty()) { Preconditions.checkArgument( order == (Timeline.STARTING_ORDER + 1), "Fallback supported only for order next after initial"); return new NakadiCursor( timelineService.getFakeTimeline(eventType), cursor.getPartition(), StringUtils.leftPad(offsetStr, VersionZeroConverter.VERSION_ZERO_MIN_OFFSET_LENGTH, '0') ); } final Timeline timeline = timelines.stream() .filter(t -> t.getOrder().equals(order)) .findAny() .orElseThrow(() -> new InvalidCursorException(CursorError.UNAVAILABLE)); return new NakadiCursor( timeline, cursor.getPartition(), offsetStr); }
Source:
static Command createCustomer() { final LocalDate localDate = LocalDates.now(); final CustomerId customerId = CustomerId.newBuilder() .setRegistrationDate(localDate) .setNumber(customerNumber) .build(); customerNumber++; final Message msg = CreateCustomer.newBuilder() .setCustomerId(customerId) .setCustomer(Customer.newBuilder() .setId(customerId) .setName(PersonName.newBuilder() .setGivenName("Kreat") .setFamilyName( "C'Ustomer") .setHonorificSuffix( "Cmd"))) .build(); final UserId userId = newUserId(Identifiers.newUuid()); final Command result = create(msg, userId, getCurrentTime()); return result; }

Target:
static Command createCustomer() { final LocalDate localDate = LocalDates.now(); final CustomerId customerId = CustomerId.newBuilder() .setRegistrationDate(localDate) .setNumber(customerNumber.get()) .build(); customerNumber.incrementAndGet(); final PersonName personName = PersonName.newBuilder() .setGivenName("Kreat") .setFamilyName("C'Ustomer") .setHonorificSuffix("Cmd") .build(); final Customer customer = Customer.newBuilder() .setId(customerId) .setName(personName) .build(); final Message msg = CreateCustomer.newBuilder() .setCustomerId(customerId) .setCustomer(customer) .build(); final UserId userId = newUserId(Identifiers.newUuid()); final Command result = create(msg, userId, getCurrentTime()); return result; }
Source:
public ToggleDebugKeyValueCommand(IServerWorkingCopy server, Button useImageDebugPortKeyButton, SelectionListener toggleListener, Text debugPortKeyText, ModifyListener keyModifier, Text debugPortText, ModifyListener valModifier) { super(server, "Enable Debugging"); this.wc = server; this.useImageDebugPortKeyButton = useImageDebugPortKeyButton; this.toggleListener = toggleListener; this.debugPortKeyText = debugPortKeyText; this.debugPortText = debugPortText; this.keyModifier = keyModifier; this.valModifier = valModifier; preSelected = !useImageDebugPortKeyButton.getSelection(); preKey = debugPortKeyText.getText(); preVal = debugPortText.getText(); }

Target:
public ToggleDebugKeyValueCommand(IServerWorkingCopy server, Button useImageDebugPortKeyButton, SelectionListener toggleListener, Text debugPortKeyText, ModifyListener keyModifier, Text debugPortText, ModifyListener valModifier) { super(server, "Enable Debugging"); this.wc = server; this.useImageDebugPortKeyButton = useImageDebugPortKeyButton; this.toggleListener = toggleListener; this.debugPortKeyText = debugPortKeyText; this.debugPortText = debugPortText; this.keyModifier = keyModifier; this.valModifier = valModifier; this.preSelected = !useImageDebugPortKeyButton.getSelection(); this.preKey = debugPortKeyText.getText(); this.preVal = debugPortText.getText(); }
Source:
private boolean checkAndDisableCLIScheduler() { GlusterVolumeEntity metaVolume = getGlusterVolumeDao().getByName(getVdsGroupId(), Config.<String> getValue(ConfigValues.GlusterMetaVolumeName)); VDSGroup cluster = getVdsGroup(); if (metaVolume != null && cluster.isGlusterCliBasedSchedulingOn()) { VdcReturnValueBase returnValue = runInternalAction(VdcActionType.DisableGlusterCliSnapshotScheduleInternal, new DisableGlusterCliSnapshotScheduleParameters(getGlusterVolumeId(), true)); return returnValue.getSucceeded(); } return true; }

Target:
private boolean checkAndDisableCLIScheduler() { VDSGroup cluster = getVdsGroup(); if (getMetaVolume() != null && cluster.isGlusterCliBasedSchedulingOn()) { VdcReturnValueBase returnValue = runInternalAction(VdcActionType.DisableGlusterCliSnapshotScheduleInternal, new DisableGlusterCliSnapshotScheduleParameters(getGlusterVolumeId(), true)); return returnValue.getSucceeded(); } return true; }
Source:
private static boolean isBasicValue(ExpressionTree expression) { if (expression.is(Kind.BOOLEAN_LITERAL, Kind.NUMERIC_LITERAL, Kind.STRING_LITERAL, Kind.NULL_LITERAL)) { return BASIC_VALUES.contains(((LiteralTree) expression).value()); } else if (expression.is(Kind.UNARY_MINUS)) { ExpressionTree operand = ((UnaryExpressionTree) expression).expression(); return operand.is(Kind.NUMERIC_LITERAL) && "1".equals(((LiteralTree) operand).value()); } ExpressionTree withoutParenthesis = CheckUtils.removeParenthesis(expression); if (withoutParenthesis.is(Kind.VOID)) { ExpressionTree operand = ((UnaryExpressionTree) withoutParenthesis).expression(); return operand.is(Kind.NUMERIC_LITERAL) && "0".equals(((LiteralTree) operand).value()); } return false; }

Target:
private static boolean isBasicValue(ExpressionTree expression) { if (expression.is(Kind.BOOLEAN_LITERAL, Kind.NUMERIC_LITERAL, Kind.STRING_LITERAL, Kind.NULL_LITERAL)) { return BASIC_VALUES.contains(((LiteralTree) expression).value()); } else if (expression.is(Kind.UNARY_MINUS)) { ExpressionTree operand = ((UnaryExpressionTree) expression).expression(); return BASIC_VALUES.contains("-" + ((LiteralTree) operand).value()); } ExpressionTree withoutParenthesis = CheckUtils.removeParenthesis(expression); if (withoutParenthesis.is(Kind.VOID)) { ExpressionTree operand = ((UnaryExpressionTree) withoutParenthesis).expression(); return operand.is(Kind.NUMERIC_LITERAL) && "0".equals(((LiteralTree) operand).value()); } return false; }
Source:
protected boolean canDoAction() { clusterId = getParameters().getClusterId(); serverId = getParameters().getServerId(); serviceType = getParameters().getServiceType(); actionType = getParameters().getActionType(); if (!actionType.equalsIgnoreCase(ManageGlusterServiceCommand.MANAGE_GLUSTER_SERVICE_ACTION_TYPE_START) || !actionType.equalsIgnoreCase(ManageGlusterServiceCommand.MANAGE_GLUSTER_SERVICE_ACTION_TYPE_STOP)) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_INVALID_ACTION_TYPE); } if (Guid.isNullOrEmpty(clusterId) && Guid.isNullOrEmpty(serverId)) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_CLUSTERID_AND_SERVERID_BOTH_NULL); } return true; }

Target:
protected boolean canDoAction() { clusterId = getParameters().getClusterId(); serverId = getParameters().getServerId(); serviceType = getParameters().getServiceType(); actionType = getParameters().getActionType(); if (!manageActionDetailsMap.keySet().contains(actionType)) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_INVALID_ACTION_TYPE); } if (Guid.isNullOrEmpty(clusterId) && Guid.isNullOrEmpty(serverId)) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_CLUSTERID_AND_SERVERID_BOTH_NULL); } if (!(Guid.isNullOrEmpty(clusterId)) && getClusterUtils().getAllUpServers(clusterId).size() == 0) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_NO_SERVERS_FOR_CLUSTER); } return true; }
Source:
public void testQueryWithMultipleColumnsInExpression() { Query query1 = new Query().from(table1).select("contributor_id,name"); DataSet set = getDataContext().executeQuery(query1); assertEquals(set.next(), true); assertEquals(set.getRow().toString(), "Row[values=[1, kasper]]"); Query query2 = new Query().from(table1).select("Greatest(1,2,3),max(contributer_id)"); assertEquals(query2.toString(), "SELECT Greatest(1,2,3), MAX(contributer_id) FROM MetaModelSchema.contributor"); Query query3 = new Query().from(table1).select("*,count(*)"); assertEquals(query3.toString(), "SELECT contributor.contributor_id, contributor.name, contributor.country, COUNT(*)" + " FROM MetaModelSchema.contributor"); }

Target:
public void testQueryWithMultipleColumnsInExpression() { Query query1 = new Query().from(table1).select("contributor_id,name"); DataSet set = getDataContext().executeQuery(query1); assertEquals(true,set.next()); assertEquals("Row[values=[1, kasper]]",set.getRow().toString()); Query query2 = new Query().from(table1).select("Greatest(1,2,3),max(contributer_id)"); assertEquals("SELECT Greatest(1,2,3), MAX(contributer_id) FROM MetaModelSchema.contributor",query2.toString()); Query query3 = new Query().from(table1).select("*,count(*)"); assertEquals("SELECT contributor.contributor_id, contributor.name, contributor.country, COUNT(*)" + " FROM MetaModelSchema.contributor",query3.toString()); }
Source:
Project.Id getValueKey() { return new Project.Id(Integer.parseInt(getValue())); }

Target:
Project.Id getValueKey() { return projectId; }
Source:
public SipMessage.Builder<T> withViaHeaders(final List<ViaHeader> vias) { if (vias != null) { this.viaHeaders = ensureList(this.viaHeaders); this.viaHeaders.clear(); for (final ViaHeader via : vias) { this.viaHeaders.add(via); viaHeader = via; } } return this; }

Target:
public SipMessage.Builder<T> withViaHeaders(final List<ViaHeader> vias) { if (vias != null && !vias.isEmpty()) { this.viaHeaders = ensureList(this.viaHeaders); this.viaHeaders.clear(); viaHeader = vias.get(0); this.viaHeaders.addAll(vias); } return this; }
Source:
public void initStorageUsage(Map<String, Map<String, Long>> usage) { logger.info("Initializing storage usage for " + usage.size() + " accounts"); storageUsage = new ConcurrentHashMap<>(); initMap(usage, storageUsage, true); }

Target:
public void initStorageUsage(Map<String, Map<String, Long>> usage) { logger.info("Initializing storage usage for accounts", usage.size()); storageUsage = new ConcurrentHashMap<>(); initMap(usage, storageUsage, true); }
Source:
protected void setSeries(String seriesName, double[] seriesValues) { Objects.requireNonNull(seriesName); Objects.requireNonNull(seriesValues); String seriesType = getSeriesType(seriesName); fModelBuilder.addYSeries( new YSeries( seriesType, getSeriesColor(seriesName), getWidth(seriesName), getSeriesStyle(seriesType), seriesName, seriesValues)); }

Target:
protected void setSeries(String seriesName, double[] seriesValues) { Objects.requireNonNull(seriesName, "Series name cannot be null"); Objects.requireNonNull(seriesValues, "Series values cannot be null"); String seriesType = getSeriesType(seriesName); fModelBuilder.addYSeries( new YSeries( seriesType, getSeriesColor(seriesName), getWidth(seriesName), getSeriesStyle(seriesType), seriesName, seriesValues)); }
Source:
public void openGroup(int notificationNumber) { WebElement notifications = getDriver().findElementsByCssSelector(NOTIFICATION_EVENT_SELECTOR).get(notificationNumber); WebElement group = notifications.findElement(cssSelector(GROUP_SELECTOR)); group.click(); }

Target:
public void openGroup(int notificationNumber) { WebElement notifications = findNotifications().get(notificationNumber); WebElement group = notifications.findElement(cssSelector(GROUP_SELECTOR)); group.click(); }
Source:
public void checkAttributeValue(PerunSessionImpl sess, User user, Facility facility, Attribute attribute) throws WrongAttributeValueException, WrongReferenceAttributeValueException, InternalErrorException, WrongAttributeAssignmentException { try { Attribute uidNamespaceAttribute = sess.getPerunBl().getAttributesManagerBl().getAttribute(sess, facility, AttributesManager.NS_FACILITY_ATTR_DEF + ":uid-namespace"); Attribute uidAttribute; if (uidNamespaceAttribute.getValue() != null) { uidAttribute = sess.getPerunBl().getAttributesManagerBl().getAttribute(sess, user, AttributesManager.NS_USER_ATTR_DEF + ":uid-namespace:" + uidNamespaceAttribute.getValue()); uidAttribute.setValue(attribute.getValue()); sess.getPerunBl().getAttributesManagerBl().checkAttributeValue(sess, user, uidAttribute); } else { throw new WrongReferenceAttributeValueException(attribute); } } catch (AttributeNotExistsException e) { throw new ConsistencyErrorException(e); } }

Target:
public void checkAttributeValue(PerunSessionImpl sess, User user, Facility facility, Attribute attribute) throws WrongAttributeValueException, WrongReferenceAttributeValueException, InternalErrorException, WrongAttributeAssignmentException { try { Attribute uidNamespaceAttribute = sess.getPerunBl().getAttributesManagerBl().getAttribute(sess, facility, AttributesManager.NS_FACILITY_ATTR_DEF + ":uid-namespace"); Attribute uidAttribute; if (uidNamespaceAttribute.getValue() != null) { uidAttribute = sess.getPerunBl().getAttributesManagerBl().getAttribute(sess, user, AttributesManager.NS_USER_ATTR_DEF + ":uid-namespace:" + uidNamespaceAttribute.getValue()); uidAttribute.setValue(attribute.getValue()); sess.getPerunBl().getAttributesManagerBl().checkAttributeValue(sess, user, uidAttribute); } else { throw new WrongReferenceAttributeValueException(attribute, (Attribute) null); } } catch (AttributeNotExistsException e) { throw new ConsistencyErrorException(e); } }
Source:
public void setExpiryQueueSize(int expiryQueueSize) { testImmutability("expiryQueueSize"); setProperty(location, "location", properties); this.expiryQueueSize = expiryQueueSize; }

Target:
public void setExpiryQueueSize(int expiryQueueSize) { testImmutability("expiryQueueSize"); setProperty(String.valueOf(expiryQueueSize), "expiryQueueSize", properties); this.expiryQueueSize = expiryQueueSize; }
Source:
public void verifyDeleteViaVideoNotPresent() { addVideoViaAjax(); deleteVideo(); verifyNotificationMessage(); Assertion.assertNotEquals(VideoContent.youtubeVideoURL2name, getNewestVideoTitle()); PageObjectLogging.log("verifyDeleteVideoNotPresent", "verify that video with following title was deleted: " + VideoContent.youtubeVideoURL2name, true); }

Target:
public void verifyDeleteViaVideoNotPresent() { addVideoViaAjax(VideoContent.youtubeVideoURL2); refreshPage(); deleteVideo(); verifyNotificationMessage(); Assertion.assertNotEquals(VideoContent.youtubeVideoURL2name, getNewestVideoTitle()); PageObjectLogging.log("verifyDeleteVideoNotPresent", "verify video " + VideoContent.youtubeVideoURL2name + " was deleted", true); }
Source:
public void activate(final PatchSet.Id patchSetId) { if (indexOf(patchSetId) != -1) { if (!patchSetId.equals(activePatchSetId)) { deactivate(); PatchSetComplexDisclosurePanel patchSetPanel = patchSetPanels.get(patchSetId); patchSetPanel.setOpen(true); patchSetPanel.setActive(true); activePatchSetId = patchSetId; } } else { Gerrit.display("change," + patchSetId.getParentKey().get()); } }

Target:
public void activate(final PatchSet.Id patchSetId) { if (indexOf(patchSetId) != -1) { if (!patchSetId.equals(activePatchSetId)) { deactivate(); PatchSetComplexDisclosurePanel patchSetPanel = patchSetPanels.get(patchSetId); patchSetPanel.setOpen(true); patchSetPanel.setActive(true); activePatchSetId = patchSetId; } } else { Gerrit.display(PageLinks.toChange(patchSetId.getParentKey())); } }
Source:
public DataStoreTransaction beginTransaction() { EntityManager entityManager = entityManagerSupplier.get(); return new AggregationDataStoreTransaction(entityManager, queryEngine, aggregationDataStoreTransactionCancel); }

Target:
public DataStoreTransaction beginTransaction() { return new AggregationDataStoreTransaction(queryEngine, cache); }
Source:
public void process(Message<?> message) { if (message != null) { double value = convertToDouble(message.getPayload()); String metricName = computeMetricName(message); RichGauge gauge = this.richGaugeRepository.findOne(metricName); if (gauge == null) { gauge = new RichGauge(metricName, 0.0D, this.alpha, 0.0D, 0.0D, 0.0D, 0L); } gauge.set(value); this.richGaugeRepository.save(gauge); } }

Target:
public void process(Message<?> message) { if (message != null) { double value = convertToDouble(message.getPayload()); this.richGaugeRepository.setValue(computeMetricName(message), value, alpha); } }
Source:
private void processWrite(Request request) throws RequestProcessorException { if (request.commitProcQueueStartTime != -1 && request.commitRecvTime != -1) { long currentTime = Time.currentElapsedTime(); ServerMetrics.getMetrics().WRITE_COMMITPROC_TIME.add(currentTime - request.commitProcQueueStartTime); ServerMetrics.getMetrics().LOCAL_WRITE_COMMITTED_TIME.add(currentTime - request.commitRecvTime); } else if (request.commitRecvTime != -1) { ServerMetrics.getMetrics().SERVER_WRITE_COMMITTED_TIME.add( Time.currentElapsedTime() - request.commitRecvTime); } long timeBeforeFinalProc = Time.currentElapsedTime(); nextProcessor.processRequest(request); ServerMetrics.getMetrics().WRITE_FINAL_PROC_TIME.add( Time.currentElapsedTime() - timeBeforeFinalProc); }

Target:
private void processWrite(Request request) throws RequestProcessorException { processCommitMetrics(request, true); long timeBeforeFinalProc = Time.currentElapsedTime(); nextProcessor.processRequest(request); ServerMetrics.getMetrics().WRITE_FINAL_PROC_TIME.add( Time.currentElapsedTime() - timeBeforeFinalProc); }
Source:
private Metacard createMetacardForFeature(SimpleFeature feature) throws FeatureIndexingException { Validate.notEmpty(metacardType, GEO_ENTRY_METACARD_TYPE_MISSING_ERROR_MSG); Metacard metacard = new MetacardImpl(metacardType.get(0)); String countryCode = feature.getID(); Object nameObject = feature.getAttribute(NAME_KEY); if (nameObject instanceof String) { metacard.setAttribute(new AttributeImpl(Core.TITLE, (String) nameObject)); metacard.setAttribute(new AttributeImpl(Location.COUNTRY_CODE, countryCode)); String wkt = WKT_WRITER_THREAD_LOCAL.get().write((Geometry) feature.getDefaultGeometry()); metacard.setAttribute(new AttributeImpl(Core.LOCATION, wkt)); List<Serializable> tags = Arrays.asList(GAZETTEER_METACARD_TAG, GeoCodingConstants.COUNTRY_TAG); metacard.setAttribute(new AttributeImpl(Core.METACARD_TAGS, tags)); metacard.setAttribute( new AttributeImpl( GeoEntryAttributes.GAZETTEER_SORT_VALUE, GeoCodingConstants.COUNTRY_GAZETTEER_SORT_VALUE)); if (isCountry(feature)) { metacard.setAttribute( new AttributeImpl( GeoEntryAttributes.FEATURE_CODE_ATTRIBUTE_NAME, GeoCodingConstants.POLITICAL_ENTITY)); } return metacard; } throw new FeatureIndexingException("Malformed feature"); }

Target:
private Metacard createMetacardForFeature(SimpleFeature feature) throws FeatureIndexingException { Metacard metacard = new MetacardImpl( metacardTypes .stream() .findFirst() .orElseThrow( () -> new FeatureIndexingException(GEO_ENTRY_METACARD_TYPE_MISSING_ERROR_MSG))); String countryCode = feature.getID(); Object nameObject = feature.getAttribute(NAME_KEY); if (nameObject instanceof String) { metacard.setAttribute(new AttributeImpl(Core.TITLE, (String) nameObject)); metacard.setAttribute(new AttributeImpl(Location.COUNTRY_CODE, countryCode)); String wkt = WKT_WRITER_THREAD_LOCAL.get().write((Geometry) feature.getDefaultGeometry()); metacard.setAttribute(new AttributeImpl(Core.LOCATION, wkt)); List<Serializable> tags = Arrays.asList(GAZETTEER_METACARD_TAG, GeoCodingConstants.COUNTRY_TAG); metacard.setAttribute(new AttributeImpl(Core.METACARD_TAGS, tags)); metacard.setAttribute( new AttributeImpl( GeoEntryAttributes.GAZETTEER_SORT_VALUE, GeoCodingConstants.COUNTRY_GAZETTEER_SORT_VALUE)); if (isCountry(feature)) { metacard.setAttribute( new AttributeImpl( GeoEntryAttributes.FEATURE_CODE_ATTRIBUTE_NAME, GeoCodingConstants.POLITICAL_ENTITY)); } return metacard; } throw new FeatureIndexingException("Malformed feature"); }
Source:
public boolean isSpawnIfNoHome() { return config.getBoolean("spawn-if-no-home", false); }

Target:
public boolean isSpawnIfNoHome() { return config.getBoolean("spawn-if-no-home", true); }
Source:
private void orphan() { if (slot == null) { return; } if (!slot.isRemovable()) { throw new IllegalArgumentException("Cannont remove a child from a permanent slot"); } if (parent != null) { internalHide(); parent.children.remove(this); parent = null; } slot = null; }

Target:
private void orphan() { if (slot == null) { return; } if (!slot.isRemovable()) { throw new IllegalArgumentException("Cannot remove a child from a permanent slot"); } if (parent != null) { internalHide(); parent.children.remove(this); parent = null; } slot = null; }
Source:
public Response add(Event event) { validateParameters(event, "origin", "severity", "customId", "description"); validateEnums(Event.class, event); AddExternalEventParameters parameters; boolean isHostExternalStateDefined = event.isSetHost() && event.getHost().isSetExternalStatus() && event.getHost().getExternalStatus().isSetState(); boolean isStorageDomainExternalStateDefined = event.isSetStorageDomain() && event.getStorageDomain().isSetExternalStatus() && event.getStorageDomain().getExternalStatus().isSetState(); if (isHostExternalStateDefined) { parameters = new AddExternalEventParameters(map(event), ExternalStatusMapper.map(EntityExternalStatus.fromValue( event.getHost().getExternalStatus().getState()), null)); } else if (isStorageDomainExternalStateDefined) { parameters = new AddExternalEventParameters(map(event), ExternalStatusMapper.map(EntityExternalStatus.fromValue( event.getStorageDomain().getExternalStatus().getState()), null)); } else{ parameters = new AddExternalEventParameters(map(event), null); } return performCreate(VdcActionType.AddExternalEvent, parameters, new QueryIdResolver<Long>(VdcQueryType.GetAuditLogById, GetAuditLogByIdParameters.class)); }

Target:
public Response add(Event event) { validateParameters(event, "origin", "severity", "customId", "description"); validateEnums(Event.class, event); return performCreate(VdcActionType.AddExternalEvent, getParameters(event), new QueryIdResolver<Long>(VdcQueryType.GetAuditLogById, GetAuditLogByIdParameters.class)); }
Source:
private void writeOutUsersDotAttributesFile(File userAttributesFile) { Map<String, Object> json = null; try (InputStream stream = Files.newInputStream(Paths.get(userAttributesFile.toURI()))) { if ((json = MAPPER.parser().parseMap(stream)) == null) { return; } addGuestClaimsProfileAttributes(json); if (json.containsKey(oldHostName)) { json.put(System.getProperty(SystemBaseUrl.HOST), json.remove(oldHostName)); } for (Map.Entry<String, Object> entry : json.entrySet()) { json.put(entry.getKey(), replaceLocalhost(entry.getValue())); } } catch (IOException e) { LOGGER.warn("Unable to read system user attribute file for hostname update.", e); } if (json != null) { try { FileUtils.writeStringToFile(userAttributesFile, Boon.toPrettyJson(json)); } catch (IOException e) { LOGGER.warn("Unable to write user attribute file for system update.", e); } } }

Target:
private void writeOutUsersDotAttributesFile(File userAttributesFile) { Map<String, Object> json = null; try (InputStream stream = Files.newInputStream(Paths.get(userAttributesFile.toURI()))) { if ((json = MAPPER.parser().parseMap(stream)) == null) { LOGGER.debug("Json not found"); return; } addGuestClaimsProfileAttributes(json); if (json.containsKey(oldHostName)) { json.put(System.getProperty(SystemBaseUrl.HOST), json.remove(oldHostName)); } for (Map.Entry<String, Object> entry : json.entrySet()) { json.put(entry.getKey(), replaceLocalhost(entry.getValue())); } } catch (IOException e) { LOGGER.warn("Unable to read system user attribute file for hostname update.", e); } if (json != null) { try { FileUtils.writeStringToFile(userAttributesFile, Boon.toPrettyJson(json)); } catch (IOException e) { LOGGER.warn("Unable to write user attribute file for system update.", e); } } }
Source:
private void waitForStatus(final long jobId, final Status status) throws InterruptedException, TimeoutException { CommonUtils.waitFor("Waiting for job status", () -> { try { return mJobMaster.getStatus(jobId).getStatus() == status; } catch (Exception e) { Throwables.propagate(e); } return null; }, WaitForOptions.defaults().setInterval(10).setTimeoutMs(10 * Constants.SECOND_MS)); }

Target:
private void waitForStatus(final long jobId, final Status status) throws InterruptedException, TimeoutException { CommonUtils.waitFor("Waiting for job status", () -> { try { return mJobMaster.getStatus(jobId).getStatus() == status; } catch (Exception e) { Throwables.propagate(e); } return null; }, WaitForOptions.defaults().setTimeoutMs(10 * Constants.SECOND_MS)); }
Source:
private static CharSequence parseBody(String strippedRawBody) { Spanned body = Html.fromHtml(strippedRawBody); int i = body.length()-1; for (; i >= 0 && Character.isWhitespace(body.charAt(i)); --i); return body.subSequence(0, i+1); }

Target:
static CharSequence parseBody(String strippedRawBody) { CharSequence body = Html.fromHtml(strippedRawBody); final int len = body.length(); if (body.charAt(len-1) == '\n' && body.charAt(len-2) == '\n') { body = body.subSequence(0, len-2); } return body; }
Source:
public void checkWhitespaceAroundOperator(OperatorDeclarationContext ctx) { for (int i = 0; i < ctx.getChild(0).getChildCount(); i++) { if (ctx.getChild(0).getChild(i) instanceof OperatorContext) { OperatorContext op = (OperatorContext) ctx.getChild(0).getChild(i); Token before = ((TerminalNodeImpl) ctx.getChild(0).getChild(i - 1)).getSymbol(); Token after = ((TerminalNodeImpl) ctx.getChild(0).getChild(i + 1)).getSymbol(); int leftMargin = op.getStart().getCharPositionInLine() - ListenerUtil.getLastCharPositionInLine(before); if (op.getStart().getLine() == before.getLine() && leftMargin != 2) { printer.error(Messages.OPERATOR + Messages.SPACE_BEFORE, ListenerUtil.getContextStopLocation(op)); } int rightMargin = after.getCharPositionInLine() - ListenerUtil.getLastCharPositionInLine(op.getStart()); if (after.getLine() == op.getStart().getLine() && rightMargin != 2) { printer.error(Messages.OPERATOR + Messages.SPACE_AFTER, ListenerUtil.getContextStopLocation(op)); } } } }

Target:
void checkWhitespaceAroundOperator(OperatorDeclarationContext ctx) { for (int i = 0; i < ctx.getChild(0).getChildCount(); i++) { if (ctx.getChild(0).getChild(i) instanceof OperatorContext) { OperatorContext op = (OperatorContext) ctx.getChild(0).getChild(i); Token before = ((TerminalNodeImpl) ctx.getChild(0).getChild(i - 1)).getSymbol(); Token after = ((TerminalNodeImpl) ctx.getChild(0).getChild(i + 1)).getSymbol(); int leftMargin = op.getStart().getCharPositionInLine() - ListenerUtil.getLastCharPositionInLine(before); if (op.getStart().getLine() == before.getLine() && leftMargin != 2) { printer.error(Messages.OPERATOR + Messages.SPACE_BEFORE, ListenerUtil.getContextStopLocation(op)); } int rightMargin = after.getCharPositionInLine() - ListenerUtil.getLastCharPositionInLine(op.getStart()); if (after.getLine() == op.getStart().getLine() && rightMargin != 2) { printer.error(Messages.OPERATOR + Messages.SPACE_AFTER, ListenerUtil.getContextStopLocation(op)); } } } }
Source:
private void hideElementRecursive(MUIElement element) { if (element == null || element.getWidget() == null) return; if (element instanceof MPlaceholder) { MPlaceholder ph = (MPlaceholder) element; element = ph.getRef(); element.setCurSharedRef(null); } if (element instanceof MWindow && element.getWidget() != null) { element.setVisible(false); } if (element instanceof MGenericStack<?>) { MGenericStack<?> container = (MGenericStack<?>) element; MUIElement curSel = container.getSelectedElement(); hideElementRecursive(curSel); } else if (element instanceof MElementContainer<?>) { MElementContainer<?> container = (MElementContainer<?>) element; for (MUIElement childElement : container.getChildren()) { hideElementRecursive(childElement); } if (element instanceof MWindow) { for (MWindow w : ((MWindow) element).getWindows()) { hideElementRecursive(w); } } else if (element instanceof MPerspective) { for (MWindow w : ((MPerspective) element).getWindows()) { hideElementRecursive(w); } } } }

Target:
private void hideElementRecursive(MUIElement element) { if (element == null || element.getWidget() == null) return; if (element instanceof MPlaceholder) { MPlaceholder ph = (MPlaceholder) element; element = ph.getRef(); if (element.getCurSharedRef() == ph) { element.setCurSharedRef(null); } } if (element instanceof MWindow && element.getWidget() != null) { element.setVisible(false); } if (element instanceof MGenericStack<?>) { MGenericStack<?> container = (MGenericStack<?>) element; MUIElement curSel = container.getSelectedElement(); hideElementRecursive(curSel); } else if (element instanceof MElementContainer<?>) { MElementContainer<?> container = (MElementContainer<?>) element; for (MUIElement childElement : container.getChildren()) { hideElementRecursive(childElement); } if (element instanceof MWindow) { for (MWindow w : ((MWindow) element).getWindows()) { hideElementRecursive(w); } } else if (element instanceof MPerspective) { for (MWindow w : ((MPerspective) element).getWindows()) { hideElementRecursive(w); } } } }
Source:
private void startShutdown() { if (stop == false) { stop = true; logger.info("Shutting down workflow executor loop"); workflowExecutor.noticeRunWhileConditionChange(); } }

Target:
private void startShutdown() { if (!stop) { stop = true; logger.info("Shutting down workflow executor loop"); workflowExecutor.noticeRunWhileConditionChange(); } }
Source:
public int openTaskDeactivationDialog(List<IEditorReference> dirtyRefs) { Iterable<String> iter = Iterables.transform(dirtyRefs, new Function<IEditorReference, String>() { @Override public String apply(IEditorReference ref) { return ref.getTitle(); } }); Joiner joiner = Joiner.on('\n'); return new MessageDialog(WorkbenchUtil.getShell(), "Task Deactivation", null, "The following editors have unsaved changes. Do you still want to deactivate the task?\n\n" + joiner.join(iter), MessageDialog.QUESTION, new String[] { "Deactivate Task and Save All", "Deactivate and Save Some...", IDialogConstants.CANCEL_LABEL }, 1).open(); }

Target:
public int openTaskDeactivationDialog(List<IEditorReference> dirtyRefs) { String editors = Joiner.on('\n').join( Iterables.transform(dirtyRefs, new Function<IEditorReference, String>() { @Override public String apply(IEditorReference ref) { return ref.getTitle(); } })); return new MessageDialog(WorkbenchUtil.getShell(), "Task Deactivation", null, "The following editors have unsaved changes. Do you still want to deactivate the task?\n\n" + editors, MessageDialog.QUESTION, new String[] { "Deactivate Task and Save All", "Deactivate and Save Some...", IDialogConstants.CANCEL_LABEL }, 1).open(); }
Source:
protected Item createBroadcast(org.atlasapi.media.entity.simple.Item inputItem) { Item item = new Item(); HashSet<Broadcast> broadcasts = Sets.newHashSet(); for(org.atlasapi.media.entity.simple.Broadcast broadcast : inputItem.getBroadcasts()) { broadcasts.add(broadcastTransformer.transform(broadcast)); } Version version = new Version().copyWithBroadcasts(broadcasts); item.setVersions(ImmutableSet.of(version)); return item; }

Target:
private Item createBroadcast(org.atlasapi.media.entity.simple.Item inputItem) { Item item = new Item(); HashSet<Broadcast> broadcasts = Sets.newHashSet(); for(org.atlasapi.media.entity.simple.Broadcast broadcast : inputItem.getBroadcasts()) { broadcasts.add(broadcastTransformer.transform(broadcast)); } Version version = new Version().copyWithBroadcasts(broadcasts); item.setVersions(ImmutableSet.of(version)); return item; }
Source:
public void init() throws DBException { Properties props = getProperties(); commitTime = Integer .parseInt(props.getProperty("solr.commit.within.time", DEFAULT_COMMIT_WITHIN_TIME)); batchMode = Boolean.parseBoolean(props.getProperty("solr.batch.mode", DEFAULT_BATCH_MODE)); Boolean cloudMode = Boolean.parseBoolean(props.getProperty("solr.cloud", DEFAULT_CLOUD_MODE)); System.out.println("Solr Cloud Mode = " + cloudMode); if (cloudMode) { System.out.println("Solr Zookeeper Remote Hosts = " + props.getProperty("zookeeper.host.list", DEFAULT_REMOTE_ZOOKEEPER_HOST)); client = new CloudSolrClient( props.getProperty("zookeeper.host.list", DEFAULT_REMOTE_ZOOKEEPER_HOST)); } else { client = new HttpSolrClient(props.getProperty("solr.base.url", DEFAULT_SOLR_BASE_URL)); } }

Target:
public void init() throws DBException { Properties props = getProperties(); commitTime = Integer .parseInt(props.getProperty("solr.commit.within.time", DEFAULT_COMMIT_WITHIN_TIME)); batchMode = Boolean.parseBoolean(props.getProperty("solr.batch.mode", DEFAULT_BATCH_MODE)); Boolean cloudMode = Boolean.parseBoolean(props.getProperty("solr.cloud", DEFAULT_CLOUD_MODE)); System.err.println("Solr Cloud Mode = " + cloudMode); if (cloudMode) { System.err.println("Solr Zookeeper Remote Hosts = " + props.getProperty("solr.zookeeper.hosts", DEFAULT_ZOOKEEPER_HOSTS)); client = new CloudSolrClient( props.getProperty("solr.zookeeper.hosts", DEFAULT_ZOOKEEPER_HOSTS)); } else { client = new HttpSolrClient(props.getProperty("solr.base.url", DEFAULT_SOLR_BASE_URL)); } }
Source:
public Agent agentByUuid(String uuid) { String key = agentCacheKey(uuid); Agent agent = (Agent) cache.get(key); if (agent == null) { synchronized (key) { agent = fetchAgentByUuid(uuid); cache.put(key, agent); } } return agent; }

Target:
public Agent agentByUuid(String uuid) { String key = agentCacheKey(uuid); Agent agent = (Agent) cache.get(key); if (agent == null) { synchronized (key) { agent = (Agent) cache.get(key); if (agent != null){ return agent; } agent = fetchAgentByUuid(uuid); cache.put(key, agent); } } return agent; }
Source:
public static void main(String[] args) { SampleCRUDQuickstartAsync p = new SampleCRUDQuickstartAsync(); try { System.out.println("Starting ASYNC main"); p.getStartedDemo(); System.out.println("Demo complete, please hold while resources are released"); } catch (Exception e) { e.printStackTrace(); System.err.println(String.format("Cosmos getStarted failed with %s", e)); } finally { System.out.println("Closing the client"); p.close(); } System.exit(0); }

Target:
public static void main(String[] args) { SampleCRUDQuickstartAsync p = new SampleCRUDQuickstartAsync(); try { logger.info("Starting ASYNC main"); System.out.println("got here.\n"); p.getStartedDemo(); logger.info("Demo complete, please hold while resources are released"); } catch (Exception e) { e.printStackTrace(); logger.error(String.format("Cosmos getStarted failed with %s", e)); } finally { logger.info("Closing the client"); p.close(); } }
Source:
public void init(HttpSecurity http) throws Exception { ApplicationContext context = http.getSharedObject(ApplicationContext.class); context.getAutowireCapableBeanFactory().autowireBean(this); if (stormpathWebEnabled) { if (loginEnabled) { http .formLogin() .loginPage(loginUri) .defaultSuccessUrl(loginNextUri) .successHandler(successHandler) .usernameParameter("login") .passwordParameter("password") .and().authorizeRequests() .antMatchers(loginUri+"*").permitAll(); } if (logoutEnabled) { http .logout() .invalidateHttpSession(true) .logoutUrl(logoutUri) .logoutSuccessUrl(logoutNextUri) .addLogoutHandler(logoutHandler) .and().authorizeRequests() .antMatchers(logoutUri).permitAll(); } if (!csrfProtectionEnabled) { http.csrf().disable(); } else { http.csrf().csrfTokenRepository(csrfTokenRepository); } if (forgotEnabled) { http.authorizeRequests().antMatchers(forgotUri).permitAll(); } if (changeEnabled) { http.authorizeRequests().antMatchers(changeUri).permitAll(); } if (registerEnabled) { http.authorizeRequests().antMatchers(registerUri).permitAll(); } if (verifyEnabled) { http.authorizeRequests().antMatchers(verifyUri).permitAll(); } if (fullyAuthenticatedEnabled) { http .authorizeRequests() .antMatchers("/assets/**").permitAll() .anyRequest().fullyAuthenticated(); } } }

Target:
public void init(HttpSecurity http) throws Exception { ApplicationContext context = http.getSharedObject(ApplicationContext.class); context.getAutowireCapableBeanFactory().autowireBean(this); if (stormpathWebEnabled) { if (loginEnabled) { String loginUriMatch = (loginUri.endsWith("*")) ? loginUri : loginUri + "*"; http .formLogin() .loginPage(loginUri) .defaultSuccessUrl(loginNextUri) .successHandler(successHandler) .usernameParameter("login") .passwordParameter("password") .and().authorizeRequests() .antMatchers(loginUriMatch).permitAll(); } if (logoutEnabled) { http .logout() .invalidateHttpSession(true) .logoutUrl(logoutUri) .logoutSuccessUrl(logoutNextUri) .addLogoutHandler(logoutHandler) .and().authorizeRequests() .antMatchers(logoutUri).permitAll(); } if (!csrfProtectionEnabled) { http.csrf().disable(); } else { http.csrf().csrfTokenRepository(csrfTokenRepository); } if (forgotEnabled) { http.authorizeRequests().antMatchers(forgotUri).permitAll(); } if (changeEnabled) { http.authorizeRequests().antMatchers(changeUri).permitAll(); } if (registerEnabled) { http.authorizeRequests().antMatchers(registerUri).permitAll(); } if (verifyEnabled) { http.authorizeRequests().antMatchers(verifyUri).permitAll(); } if (fullyAuthenticatedEnabled) { http.authorizeRequests() .antMatchers("/assets/css/stormpath.css").permitAll() .antMatchers("/assets/css/custom.stormpath.css").permitAll() .anyRequest().fullyAuthenticated(); } } }
Source:
private String toColumData(TmfStatisticsTreeNode node, long config) { if (config == TmfStatisticsTreeNode.TOTAL) { if ((node.getParent().getParent() == null) || (fTotalMasterNode == null) || (fTotalMasterNode.getValues().getTotal() == 0)) { return fFormatter.format(node.getValues().getTotal()); } return String.format("%s (%s %s)", fFormatter.format(node.getValues().getTotal()), String.format("%3.1f", (float) (100 * node.getValues().getTotal()) / fTotalMasterNode.getValues().getTotal()), "%"); } else if (config == TmfStatisticsTreeNode.PARTIAL) { if ((node.getParent().getParent() == null) || (fTotalMasterNode == null) || (fTotalMasterNode.getValues().getPartial() == 0)) { return fFormatter.format(node.getValues().getPartial()); } return String.format("%s (%s %s)", fFormatter.format(node.getValues().getPartial()), String.format("%3.1f", (float) (100 * node.getValues().getPartial()) / fTotalMasterNode.getValues().getPartial()), "%"); } return ""; }

Target:
private String toColumData(TmfStatisticsTreeNode node, long config) { long eventValue = 0; long eventTotal = 0; if (node != null && fTotalMasterNode != null) { if (config == TmfStatisticsTreeNode.TOTAL) { eventValue = node.getValues().getTotal(); eventTotal = fTotalMasterNode.getValues().getTotal(); } else if (config == TmfStatisticsTreeNode.PARTIAL) { eventValue = node.getValues().getPartial(); eventTotal = fTotalMasterNode.getValues().getPartial(); } else { throw new IllegalArgumentException(); } } if ((node == null) || (node.getParent().getParent() == null) || (fTotalMasterNode == null) || (eventTotal == 0)) { return fFormatter.format(eventValue); } return String.format("%s (%s %s)", fFormatter.format(eventValue), String.format("%3.1f", (float) (100 * eventValue) / eventTotal), "%"); }
Source:
public void sequentialPredictOnBatch(PredictOnBatchParams predictParams) throws Exception { try { MultiLayerNetwork model = predictParams.getSequentialModel(); DataSetIterator dataSetIterator = new HDF5MiniBatchDataSetIterator( predictParams.getFeaturesDirectory() ); while(dataSetIterator.hasNext()) { DataSet data = dataSetIterator.next(); model.output(data.getFeatures()); } model.output(dataSetIterator); log.info("model.predict_on_batch() operation complete."); } catch (Throwable e) { log.error("Error while performing model.predict_on_batch()", e); throw e; } }

Target:
public double[][] sequentialPredictOnBatch(PredictOnBatchParams predictParams) throws Exception { try { MultiLayerNetwork model = predictParams.getSequentialModel(); INDArray input = NDArrayHelper.fromFlattened(predictParams.getData()); INDArray ret = model.output(input); log.info("model.predict_on_batch() operation complete."); return NDArrayHelper.toFlattened(ret); } catch (Throwable e) { log.error("Error while performing model.predict_on_batch()", e); throw e; } }