auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code><START> private boolean possiblyStopAndRemoveSupervisorInternal(String id, boolean writeTombstone) <END> { Pair<Supervisor, SupervisorSpec> pair = supervisors.get(id); if (pair != null) { if (writeTombstone) { metadataSupervisorManager.insert(id, new NoopSupervisorSpec()); } pair.lhs.stop(true); supervisors.remove(id); return true; } return false; }</code><technical_language>Suggest java doc expected lock state calling</technical_language>

Target:
private boolean possiblyStopAndRemoveSupervisorInternal(String id, boolean writeTombstone) { Pair<Supervisor, SupervisorSpec> pair = supervisors.get(id); if (pair == null) { return false; } if (writeTombstone) { metadataSupervisorManager.insert(id, new NoopSupervisorSpec()); } pair.lhs.stop(true); supervisors.remove(id); return true; }
Source:
<code>protected boolean validate() { if (getParameters().isImportEntity()) { return true; } List<Pair<VM, VmDevice>> vmsForDisk = vmDao.getVmsWithPlugInfo(getDiskImage().getId()); DiskValidator diskValidator = new DiskValidator(getDiskImage()); <START> if (!validate(diskValidator.isDiskPluggedToVmsThatAreNotDown(false, vmsForDisk))) { <END> StorageDomainStatic destDomain = storageDomainStaticDao.get(getParameters().getStorageDomainId()); if (destDomain.isBackup == true) { return false; } } Guid imageGroupId = Guid.isNullOrEmpty(getParameters().getImageGroupID()) ? getImageGroupId() : getParameters().getImageGroupID(); Disk disk = diskDao.get(imageGroupId); if (disk != null) { DiskValidator diskValidator = new DiskValidator(disk); return validate(diskValidator.validateUnsupportedDiskStorageType( DiskStorageType.LUN, DiskStorageType.CINDER)); } return true; }</code><technical_language>declare diskValidator in line 115</technical_language>

Target:
protected boolean validate() { if (getParameters().isImportEntity()) { return true; } List<Pair<VM, VmDevice>> vmsForDisk = vmDao.getVmsWithPlugInfo(getDiskImage().getId()); if (!validate(diskValidator.isDiskPluggedToVmsThatAreNotDown(false, vmsForDisk))) { StorageDomainStatic destDomain = storageDomainStaticDao.get(getParameters().getStorageDomainId()); if (destDomain.isBackup() == true) { return false; } } Guid imageGroupId = Guid.isNullOrEmpty(getParameters().getImageGroupID()) ? getImageGroupId() : getParameters().getImageGroupID(); Disk disk = diskDao.get(imageGroupId); if (disk != null) { DiskValidator diskValidator = new DiskValidator(disk); return validate(diskValidator.validateUnsupportedDiskStorageType( DiskStorageType.LUN, DiskStorageType.CINDER)); } return true; }
Source:
<code>public void setFormattedOriginalResponseData(String originalResponseData) throws Exception { if(originalResponseData!=null && !originalResponseData.equals("") && originalResponseContentType!= null && originalResponseContentType.toLowerCase().indexOf("application/json")!=-1){ ObjectMapper objectMapper = new ObjectMapper(); ObjectWriter writer = objectMapper.defaultPrettyPrintingWriter(); Object json = objectMapper.readValue(originalResponseData, Object.class); this.formattedOriginalResponseData = writer.withView(ViewFilters.Default.class).writeValueAsString(json); } <START> else{ <END> this.formattedOriginalResponseData = originalResponseData; } }</code><technical_language>a small thing, formatting consistent. Watch spacing of braces, keeping "else" line previous close brace consistent rest of code</technical_language>

Target:
public void setFormattedOriginalResponseData(String originalResponseData) throws Exception { this.formattedOriginalResponseData = originalResponseData; if(originalResponseData!=null && !originalResponseData.equals("") && originalResponseContentType != null && originalResponseContentType.toLowerCase().indexOf("application/json") != -1){ try { ObjectMapper objectMapper = new ObjectMapper(); ObjectWriter writer = objectMapper.defaultPrettyPrintingWriter(); Object json = objectMapper.readValue(originalResponseData, Object.class); this.formattedOriginalResponseData = writer.withView(ViewFilters.Default.class).writeValueAsString(json); } catch (JsonParseException jpe) { } } }
Source:
<code>private void loadResourcePids() { Optional<BulkExportJobEntity> jobOpt = myBulkExportJobDao.findByJobId(myJobUUID); if (!jobOpt.isPresent()) { ourLog.warn("Job appears to be deleted"); return; } BulkExportJobEntity jobEntity = jobOpt.get(); ourLog.info("Bulk export starting generation for batch export job: {}", jobEntity); IFhirResourceDao<?> dao = myDaoRegistry.getResourceDao(myResourceType); ourLog.info("Bulk export assembling export of type for job {}", myResourceType, myJobUUID); RuntimeResourceDefinition def = myContext.getResourceDefinition(myResourceType); Class<? extends IBaseResource> nextTypeClass = def.getImplementingClass(); ISearchBuilder sb = mySearchBuilderFactory.newSearchBuilder(dao, myResourceType, nextTypeClass); SearchParameterMap map = new SearchParameterMap(); Map<String, String[]> requestUrl = UrlUtil.parseQueryStrings(jobEntity.getRequest()); String[] typeFilters = requestUrl.get(JpaConstants.PARAM_EXPORT_TYPE_FILTER); if (typeFilters != null) { Optional<String> filter = Arrays.stream(typeFilters).filter(t -> t.startsWith(myResourceType + "?")).findFirst(); if (filter.isPresent()) { String matchUrl = filter.get(); map = myMatchUrlService.translateMatchUrl(matchUrl, def); } } <START> <END> if (jobEntity.getSince() != null) { map.setLastUpdated(new DateRangeParam(jobEntity.getSince(), null)); } map.setLoadSynchronous(true); IResultIterator myResultIterator = sb.createQuery(map, new SearchRuntimeDetails(null, myJobUUID), null, RequestPartitionId.allPartitions()); List<ResourcePersistentId> myReadPids = new ArrayList<>(); while (myResultIterator.hasNext()) { myReadPids.add(myResultIterator.next()); } myPidIterator = myReadPids.iterator(); }</code><technical_language>This logical block ripped out a helper function for conciseness</technical_language>

Target:
private void loadResourcePids() { Optional<BulkExportJobEntity> jobOpt = myBulkExportJobDao.findByJobId(myJobUUID); if (!jobOpt.isPresent()) { ourLog.warn("Job appears to be deleted"); return; } BulkExportJobEntity jobEntity = jobOpt.get(); ourLog.info("Bulk export starting generation for batch export job: {}", jobEntity); IFhirResourceDao<?> dao = myDaoRegistry.getResourceDao(myResourceType); ourLog.info("Bulk export assembling export of type for job {}", myResourceType, myJobUUID); RuntimeResourceDefinition def = myContext.getResourceDefinition(myResourceType); Class<? extends IBaseResource> nextTypeClass = def.getImplementingClass(); ISearchBuilder sb = mySearchBuilderFactory.newSearchBuilder(dao, myResourceType, nextTypeClass); SearchParameterMap map = createSearchParameterMapFromTypeFilter(jobEntity, def); if (jobEntity.getSince() != null) { map.setLastUpdated(new DateRangeParam(jobEntity.getSince(), null)); } map.setLoadSynchronous(true); IResultIterator myResultIterator = sb.createQuery(map, new SearchRuntimeDetails(null, myJobUUID), null, RequestPartitionId.allPartitions()); List<ResourcePersistentId> myReadPids = new ArrayList<>(); while (myResultIterator.hasNext()) { myReadPids.add(myResultIterator.next()); } myPidIterator = myReadPids.iterator(); }
Source:
<code>private void addRefSetFilesForValidating() throws IOException { for (final URL url : configuration.getRefSetUrls()) { addRefSetFile(url); } if (!Iterables.any(releaseFileValidators, Predicates.instanceOf(SnomedLanguageRefSetValidator.class))) { Collection<File> languageRefSetFiles = configuration.getLanguageRefSetFiles(); for (File langFile : languageRefSetFiles) { if (isValidReleaseFile(langFile)) { releaseFileValidators.add(new SnomedLanguageRefSetValidator(configuration, configuration.toURL(langFile), this)); } <START> <END> } } }</code><technical_language>Extra line</technical_language>

Target:
private void addRefSetFilesForValidating() throws IOException { for (final URL url : configuration.getRefSetUrls()) { addRefSetFile(url); } }
Source:
<code>private static Map<String, Object> applyEventStyleProperties(Map<String, Object> styleMap, ITimeEvent event) { Map<String, Object> updatedStyles = new HashMap<>(styleMap); if (event.isPropertyActive(IFilterProperty.DIMMED)) { Integer colorInt = (Integer) updatedStyles.getOrDefault(ITimeEventStyleStrings.fillColor(), 255); RGBAColor oldRgbaColor = new RGBAColor(colorInt); RGBAColor rgbaColor = new RGBAColor(oldRgbaColor.getRed(), oldRgbaColor.getGreen(), oldRgbaColor.getBlue(), Integer.divideUnsigned(oldRgbaColor.getAlpha(), DIMMED_ALPHA_COEFFICIENT)); updatedStyles.put(ITimeEventStyleStrings.fillColor(), rgbaColor.toInt()); updatedStyles.put(ITimeEventStyleStrings.annotated(), true); } if (event.isPropertyActive(IFilterProperty.BOUND)) { <START> updatedStyles.put(ITimeEventStyleStrings.borderColor(), 0xff3300ff); <END> updatedStyles.put(ITimeEventStyleStrings.annotated(), false); } return updatedStyles; }</code><technical_language>extract constant expect a +2</technical_language>

Target:
private static Map<String, Object> applyEventStyleProperties(Map<String, Object> styleMap, ITimeEvent event) { Map<String, Object> updatedStyles = new HashMap<>(styleMap); if (event.isPropertyActive(IFilterProperty.DIMMED)) { Integer colorInt = (Integer) updatedStyles.getOrDefault(ITimeEventStyleStrings.fillColor(), 255); RGBAColor oldRgbaColor = new RGBAColor(colorInt); RGBAColor rgbaColor = new RGBAColor(oldRgbaColor.getRed(), oldRgbaColor.getGreen(), oldRgbaColor.getBlue(), Integer.divideUnsigned(oldRgbaColor.getAlpha(), DIMMED_ALPHA_COEFFICIENT)); updatedStyles.put(ITimeEventStyleStrings.fillColor(), rgbaColor.toInt()); updatedStyles.put(ITimeEventStyleStrings.annotated(), true); } if (event.isPropertyActive(IFilterProperty.BOUND)) { updatedStyles.put(ITimeEventStyleStrings.borderColor(), HIGHLIGHTED_BOUND_COLOR); updatedStyles.put(ITimeEventStyleStrings.annotated(), false); } return updatedStyles; }
Source:
<code><START> public <T> T getField(final String name, final TypeReference<T> typeReference) { <END> return Optional.ofNullable(fields.get(name)) .map(jsonNode -> SphereJsonUtils.readObject(jsonNode, typeReference)) .orElse(null); }</code><technical_language>add some helpers here, like: public String getFieldAsString(final String name) { return getField(name, TypeReferences.stringTypeReference()) } public Money getFieldAsMoney(final String name) ..</technical_language>

Target:
public <T> T getField(final String name, final TypeReference<T> typeReference) { return Optional.ofNullable(getField(name)) .map(jsonNode -> SphereJsonUtils.readObject(jsonNode, typeReference)) .orElse(null); }
Source:
<code>public void addUmiObservationN() { <START> <END> observedUmiWithN++; }</code><technical_language>remove whitespace</technical_language>

Target:
public void addUmiObservationN() { observedUmiWithNs++; }
Source:
<code>public boolean test(Object receiver, String property, Object[] args, Object expectedValue) { final IServerModule appModule = retrieveServerModuleFromSelectedElement(receiver); if(appModule == null) { return false; } final IServer appServer = appModule.getServer(); IModule[] modules = appModule.getModule(); return appServer != null <START> && appServer.getModuleState(appModule.getModule()) == IServer.STATE_STARTED <END> && WSTUtils.isServerStarted(appServer) && WSTUtils.getModuleURL(appServer, modules[modules.length - 1]) != null; }</code><technical_language>a web module is deployed EAR (try wildfly-javaee7-webapp-ear-archetype), WF10, state is IServer.STATE_UNKNOWN, tester returns false impossible open livereload ![](<LINK_0></technical_language>

Target:
public boolean test(Object receiver, String property, Object[] args, Object expectedValue) { final IServerModule appModule = retrieveServerModuleFromSelectedElement(receiver); if(appModule == null) { return false; } final IServer appServer = appModule.getServer(); IModule[] modules = appModule.getModule(); return appServer != null && isModuleStartedOrUnknown(appServer, modules) && WSTUtils.isServerStarted(appServer) && WSTUtils.getModuleURL(appServer, modules[modules.length - 1]) != null; }
Source:
<code>public void process() { PerformanceMonitor.startActivity("rendering/finalpostprocessing"); ocUndistorted = frameBuffersManager.getFBO("ocUndistorted"); sceneFinal = frameBuffersManager.getFBO("sceneFinal"); sceneOpaque = frameBuffersManager.getFBO("sceneOpaque"); <START> fullScale = sceneOpaque.dimensions(); <END> if (!renderingDebugConfig.isEnabled()) { finalPost.enable(); } else { debug.enable(); } if (!renderingConfig.isOculusVrSupport()) { renderFinalMonoImage(); } else { renderFinalStereoImage(worldRenderer.getCurrentRenderStage()); } PerformanceMonitor.endActivity(); }</code><technical_language>I concerned variables reset close used. ok leaving are, handle buffers dimensions differently, eventually</technical_language>

Target:
public void process() { PerformanceMonitor.startActivity("rendering/finalPostProcessing"); ocUndistorted = frameBuffersManager.getFBO("ocUndistorted"); sceneFinal = frameBuffersManager.getFBO("sceneFinal"); sceneOpaque = frameBuffersManager.getFBO("sceneOpaque"); fullScale = sceneOpaque.dimensions(); if (!renderingDebugConfig.isEnabled()) { finalPost.enable(); } else { debug.enable(); } if (!renderingConfig.isOculusVrSupport()) { renderFinalMonoImage(); } else { renderFinalStereoImage(worldRenderer.getCurrentRenderStage()); } PerformanceMonitor.endActivity(); }
Source:
<code>public MicrometerMetricsReporterProvider() { micrometerMetricsReporter = MicrometerMetricsReporter.newMetricsReporter() .withName(TRACING_METRIC_NAME) .withTagLabel(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_SERVER) <START> .withTagLabel(Tags.HTTP_STATUS.getKey(), "null") <END> .build(); }</code><technical_language>"undefined" a choice here? a long time understand passing "null" instead of null</technical_language>

Target:
public MicrometerMetricsReporterProvider() { micrometerMetricsReporter = MicrometerMetricsReporter.newMetricsReporter() .withName(TRACING_METRIC_NAME) .withTagLabel(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_SERVER) .withTagLabel(Tags.HTTP_STATUS.getKey(), "undefined") .build(); }
Source:
<code>public boolean executeWithAgent(final JobRequest jobRequest, final HttpServletRequest httpServletRequest) { for (final Pair<String, CheckRequestFunction> nameFunctionCheckPair : this.checks) { final String checkName = nameFunctionCheckPair.getKey(); final CheckRequestFunction checkFunction = nameFunctionCheckPair.getValue(); <START> final Optional<Boolean> checkOptionalOutcome = checkFunction.check(jobRequest, httpServletRequest); if (checkOptionalOutcome.isPresent()) { final boolean executeWithAgent = checkOptionalOutcome.get(); this.publishMetric(executeWithAgent, checkName); return executeWithAgent; } } <END> final boolean executeWithAgent = this.environment.getProperty( DEFAULT_EXECUTION_PROPERTY, Boolean.class, DEFAULT_EXECUTE_WITH_AGENT ); this.publishMetric(executeWithAgent, "default"); return executeWithAgent; }</code><technical_language>cleaner do this in a ifPresent block assigning a variable isPresent check</technical_language>

Target:
public boolean executeWithAgent(final JobRequest jobRequest, final HttpServletRequest httpServletRequest) { for (final Pair<String, CheckRequestFunction> nameFunctionCheckPair : this.checks) { final String checkName = nameFunctionCheckPair.getKey(); final CheckRequestFunction checkFunction = nameFunctionCheckPair.getValue(); final Optional<Boolean> checkOptionalOutcome = checkFunction.check(jobRequest, httpServletRequest); if (checkOptionalOutcome.isPresent()) { final boolean executeWithAgent = checkOptionalOutcome.get(); this.publishMetric(executeWithAgent, checkName); return executeWithAgent; } } final boolean executeWithAgent = this.environment.getProperty( DEFAULT_EXECUTE_WITH_AGENT_PROPERTY, Boolean.class, DEFAULT_EXECUTE_WITH_AGENT ); this.publishMetric(executeWithAgent, DEFAULT); return executeWithAgent; }
Source:
<code><START> public void error() { <END> if (callback != null) { callback.onError(); } }</code><technical_language>This package scoped, public</technical_language>

Target:
@Override void error() { if (callback != null) { callback.onError(); } }
Source:
<code>private void syntaxCheck(String data) { <START> if (!(data.contains("${") && data.contains(":") && data.contains("#") && data.contains("}"))) { <END> throw new IllegalArgumentException("Invalid syntax for lang lookup"); } }</code><technical_language>regex please</technical_language>

Target:
private void syntaxCheck(String data) { Matcher matcher = pattern.matcher(data); if (!matcher.matches()) { throw new IllegalArgumentException("Invalid syntax for lang lookup"); } }
Source:
<code>public void setVersion(String version) { mVersion = version; <START> System.out.println("Version is now "+version); <END> }</code><technical_language>I suggest Logy.d instead, [here](<LINK_0></technical_language>

Target:
public void setVersion(String version) { mVersion = version; }
Source:
<code>private Integer parseIoThreadId(XmlNode node) { XmlNode <START> addressNode = <END> node.selectSingleNode("driver"); if (addressNode == null) { return null; } XmlAttribute val = addressNode.attributes.get("iothread"); return val != null ? Integer.valueOf(val.getValue()) : null; }</code><technical_language>driverNode</technical_language>

Target:
private Integer parseIoThreadId(XmlNode node) { XmlNode driverNode = node.selectSingleNode("driver"); if (driverNode == null) { return null; } XmlAttribute val = driverNode.attributes.get("iothread"); return val != null ? Integer.valueOf(val.getValue()) : null; }
Source:
<code>public int getChildCount( Name name ) { int appendedChildren = appended != null ? appended.getChildCount(name) : 0; int persistedChildrenCount = persisted.getChildCount(name); int removedChildren = 0; int renamedChildren = 0; int appendedThenReorderedChildren = 0; if (changedChildren != null) { appendedThenReorderedChildren = changedChildren.insertionCount(name); for (int i = 0; i < persisted.getChildCount(name); i++) { ChildReference persistedChild = persisted.getChild(name, i + 1); if (changedChildren.isRemoved(persistedChild)) { <START> removedChildren--; <END> break; } if (changedChildren.isRenamed(persistedChild)) { renamedChildren--; } } if (changedChildren.isRenamed(name)) { renamedChildren++; } } return persistedChildrenCount + appendedChildren + appendedThenReorderedChildren + removedChildren + renamedChildren; }</code><technical_language>prefix operator is more efficient</technical_language>

Target:
public int getChildCount( Name name ) { int appendedChildren = appended != null ? appended.getChildCount(name) : 0; int persistedChildrenCount = persisted.getChildCount(name); int removedChildren = 0; int renamedChildren = 0; int appendedThenReorderedChildren = 0; if (changedChildren != null) { appendedThenReorderedChildren = changedChildren.insertionCount(name); for (Iterator<ChildReference> childReferenceIterator = persisted.iterator(name); childReferenceIterator.hasNext(); ) { ChildReference persistedChild = childReferenceIterator.next(); if (changedChildren.isRemoved(persistedChild)) { --removedChildren; continue; } if (changedChildren.isRenamed(persistedChild)) { --renamedChildren; } } if (changedChildren.isRenamed(name)) { ++renamedChildren; } } return persistedChildrenCount + appendedChildren + appendedThenReorderedChildren + removedChildren + renamedChildren; }
Source:
<code>public static AnnotationSpec get(AnnotationMirror annotation) { AnnotationSpec.Builder builder = AnnotationSpec.builder( ClassName.get((TypeElement) annotation.getAnnotationType().asElement())); for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry : annotation.getElementValues().entrySet()) { String name = entry.getKey().getSimpleName().toString(); <START> builder.addMember(name, CodeBlock.builder().add(entry.getValue().toString()).build()); <END> } return builder.build(); }</code><technical_language>this work for annotation types? useful Compile-Testing exercise this</technical_language>

Target:
public static AnnotationSpec get(AnnotationMirror annotation) { TypeElement element = (TypeElement) annotation.getAnnotationType().asElement(); AnnotationSpec.Builder builder = AnnotationSpec.builder(ClassName.get(element)); Visitor visitor = new Visitor(builder); for (ExecutableElement executableElement : annotation.getElementValues().keySet()) { String name = executableElement.getSimpleName().toString(); AnnotationValue value = annotation.getElementValues().get(executableElement); value.accept(visitor, new Entry(name, value)); } return builder.build(); }
Source:
<code>public void savePerson() { try { PersonInterface per = UghImplementation.INSTANCE .createPerson(this.myPrefs.getMetadataTypeByName(this.tempPersonRolle)); per.setFirstName(this.tempPersonVorname); per.setLastName(this.tempPersonNachname); per.setRole(this.tempPersonRolle); String[] authorityFile = parseAuthorityFileArgs(tempPersonRecord); per.setAutorityFile(authorityFile[0], authorityFile[1], authorityFile[2]); this.docStruct.addPerson(per); this.modeAddPerson = false; saveMetadataAsBean(this.docStruct); } catch (IncompletePersonObjectException e) { <START> logger.error(e.getMessage(), e); <END> Helper.setFehlerMeldung("Incomplete data for person", ""); } catch (MetadataTypeNotAllowedException e) { logger.error(e.getMessage(), e); Helper.setFehlerMeldung("Person is for this structure not allowed", ""); } }</code><technical_language>setErrorMessage</technical_language>

Target:
public void savePerson() { try { PersonInterface per = UghImplementation.INSTANCE .createPerson(this.myPrefs.getMetadataTypeByName(this.tempPersonRolle)); per.setFirstName(this.tempPersonVorname); per.setLastName(this.tempPersonNachname); per.setRole(this.tempPersonRolle); String[] authorityFile = parseAuthorityFileArgs(tempPersonRecord); per.setAutorityFile(authorityFile[0], authorityFile[1], authorityFile[2]); this.docStruct.addPerson(per); this.modeAddPerson = false; saveMetadataAsBean(this.docStruct); } catch (IncompletePersonObjectException e) { Helper.setErrorMessage("Incomplete data for person", logger, e); } catch (MetadataTypeNotAllowedException e) { Helper.setErrorMessage("Person is for this structure not allowed", logger, e); } }
Source:
<code>public synchronized void reset() { <START> this.min = 0; <END> this.max = 0; this.count = 0; this.times.clear(); t0 = System.nanoTime() / this.factor; }</code><technical_language>is Double.MAX_VALUE. I missed</technical_language>

Target:
public synchronized void reset() { this.min = Double.MAX_VALUE; this.max = 0; this.count = 0; this.times.clear(); t0 = System.nanoTime() / this.factor; }
Source:
<code>public void testCompareToCornerCases3() { final ITmfTimestamp ts0a = TmfTimestamp.create(Long.MIN_VALUE, Integer.MAX_VALUE - 1); final ITmfTimestamp ts0b = TmfTimestamp.create(0, Integer.MAX_VALUE); final ITmfTimestamp ts0c = TmfTimestamp.create(Long.MIN_VALUE, Integer.MAX_VALUE); assertTrue("compareTo", ts0a.compareTo(ts0b) < 0); assertTrue("compareTo", ts0a.compareTo(ts0c) > 0); <START> assertEquals("compareTo", 1, ts0b.compareTo(ts0a)); <END> assertEquals("compareTo", 1, ts0b.compareTo(ts0c)); assertEquals("compareTo", -1, ts0c.compareTo(ts0a)); assertEquals("compareTo", -1, ts0c.compareTo(ts0b)); }</code><technical_language>change >0 <0 also</technical_language>

Target:
public void testCompareToCornerCases3() { final ITmfTimestamp ts0a = TmfTimestamp.create(Long.MIN_VALUE, Integer.MAX_VALUE - 1); final ITmfTimestamp ts0b = TmfTimestamp.create(0, Integer.MAX_VALUE); final ITmfTimestamp ts0c = TmfTimestamp.create(Long.MIN_VALUE, Integer.MAX_VALUE); assertTrue("compareTo", ts0a.compareTo(ts0b) < 0); assertTrue("compareTo", ts0a.compareTo(ts0c) > 0); assertTrue("compareTo", ts0b.compareTo(ts0a) > 0); assertTrue("compareTo", ts0b.compareTo(ts0c) > 0); assertTrue("compareTo", ts0c.compareTo(ts0a) < 0); assertTrue("compareTo", ts0c.compareTo(ts0b) < 0); }
Source:
<code>public boolean hasNext() { if (saveNext != null) { return true; } try { saveNext = internalNext(); return true; } catch (NoSuchElementException e) { <START> return false; <END> } }</code><technical_language>This is a good convention. changing internalNext() able return null more elements</technical_language>

Target:
public boolean hasNext() { if (saveNext != null) { return true; } saveNext = internalNext(); return (saveNext != null); }
Source:
<code>public void handleNewSession() throws Exception { LOG.info("Got new session created event for processor=" + processorId); zkUtils.incGeneration(); if (coordinatorListener != null) { coordinatorListener.onJobModelExpired(); } zkUtils.unregister(); <START> if (zkController != null) { <END> LOG.info("register zk controller for the new session"); zkController.register(); } }</code><technical_language>This check unnecessary zkController is final initialized in constructor</technical_language>

Target:
public void handleNewSession() throws Exception { LOG.info("Got new session created event for processor=" + processorId); LOG.info("register zk controller for the new session"); zkController.register(); }
Source:
<code><START> public void setStatusCode(int code) { <END> this.code = code; }</code><technical_language>this need public</technical_language>

Target:
void setStatusCode(int code) { this.code = code; }
Source:
<code>public String toJSON() throws IOException { JsonGenerator g = jsonGeneratorThreadLocal.get(); g.writeStartObject(); g.writeStringField("database", this.database); g.writeStringField("table", this.table); g.writeStringField("type", this.rowType); g.writeNumberField("ts", this.timestamp); if ( this.xid != null ) g.writeNumberField("xid", this.xid); if ( this.txCommit ) g.writeBooleanField("commit", true); if ( this.excludeColumns != null ) { Set<String> keys = new HashSet<String>(); keys.addAll(this.data.keySet()); keys.addAll(this.oldData.keySet()); for ( Pattern p : this.excludeColumns ) { for ( String key : keys ) { if ( p.matcher(key).matches() ) { this.data.remove(key); this.oldData.remove(key); } } } } writeMapToJSON("data", this.data, !this.omitNulls); if ( !this.oldData.isEmpty() ) { <START> writeMapToJSON("old", this.oldData, true); <END> } g.writeEndObject(); g.flush(); return jsonFromStream(); }</code><technical_language>missed passing flag</technical_language>

Target:
public String toJSON() throws IOException { return toJSON(new MaxwellOutputConfig()); }
Source:
<code>public synchronized void startRecovery(final Map<String, GroupStats> failedGroups) { if (!isRecoveryOngoing.compareAndSet(false, true)) { throw new IllegalStateException("Internal Error : startRecovery() is called while other recovery process is " + "already running!"); } if (failedGroups.isEmpty()) { lock.lock(); <START> isRecoveryOngoing.set(true); <END> recoveryFinished.signalAll(); lock.unlock(); return; } LOG.log(Level.INFO, "Start distributed recovery on failed groups: {0}", failedGroups.keySet()); recoveryGroups.putAll(failedGroups); final List<MasterToTaskMessage> proxyToRecoveryTaskList = new ArrayList<>(); try { for (final Map.Entry<String, TaskStats> entry: taskStatsMap.entrySet()) { if (entry.getValue().getTaskLoad() < overloadedTaskThreshold) { proxyToRecoveryTaskList.add(proxyToTaskMap.get(entry.getKey())); } } for (final MasterToTaskMessage proxyToTask : proxyToRecoveryTaskList) { proxyToTask.startTaskSideRecovery(); } } catch (final AvroRemoteException e) { LOG.log(Level.SEVERE, "Start recovery through avro server has failed! " + e.toString()); } }</code><technical_language>is true</technical_language>

Target:
public synchronized void startRecovery(final Map<String, GroupStats> failedGroups) { if (failedGroups.isEmpty()) { LOG.log(Level.INFO, "No groups to recover..."); return; } if (!isRecoveryOngoing.compareAndSet(false, true)) { throw new IllegalStateException("Internal Error : startRecovery() is called while other recovery process is " + "already running!"); } LOG.log(Level.INFO, "Start distributed recovery on failed groups: {0}", failedGroups.keySet()); recoveryGroups.putAll(failedGroups); final List<MasterToTaskMessage> proxyToRecoveryTaskList = new ArrayList<>(); try { for (final Map.Entry<String, TaskStats> entry: taskStatsMap.entrySet()) { if (entry.getValue().getTaskLoad() < overloadedTaskThreshold) { proxyToRecoveryTaskList.add(proxyToTaskMap.get(entry.getKey())); } } for (final MasterToTaskMessage proxyToTask : proxyToRecoveryTaskList) { proxyToTask.startTaskSideRecovery(); } } catch (final AvroRemoteException e) { LOG.log(Level.SEVERE, "Start recovery through avro server has failed! " + e.toString()); } }
Source:
<code>public void testReduceWindowStateReader() throws Exception { String savepointPath = takeSavepoint(numbers, source -> { StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime); env.setStateBackend(getStateBackend()); env.setParallelism(4); env .addSource(source) .rebalance() .assignTimestampsAndWatermarks(WatermarkStrategy .<Integer>noWatermarks() .withTimestampAssigner((event, timestamp) -> 0)) .keyBy(id -> id) .timeWindow(Time.milliseconds(10)) .reduce(new ReduceSum()) .uid(uid) .addSink(new DiscardingSink<>()); return env; }); ExecutionEnvironment batchEnv = ExecutionEnvironment.getExecutionEnvironment(); ExistingSavepoint savepoint = Savepoint.load(batchEnv, savepointPath, getStateBackend()); List<Integer> results = savepoint .timeWindow() .reduce(uid, new ReduceSum(), Types.INT, Types.INT) .collect(); <START> Assert.assertThat("Unexpected results from keyed state", results, Matchers.containsInAnyOrder(numbers)); <END> }</code><technical_language>this test example, if I understand on. savepoint of numbers? I expect point savepoint is taken, window pane result of reducing numbers processed far. assuming 3 numbers/keys distributed a parallel instance, of in state</technical_language>

Target:
public void testReduceWindowStateReader() throws Exception { String savepointPath = takeSavepoint(numbers, source -> { StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime); env.setStateBackend(getStateBackend()); env.setParallelism(4); env .addSource(source) .rebalance() .assignTimestampsAndWatermarks(WatermarkStrategy .<Integer>noWatermarks() .withTimestampAssigner((event, timestamp) -> 0)) .keyBy(id -> id) .window(TumblingEventTimeWindows.of(Time.milliseconds(10))) .reduce(new ReduceSum()) .uid(uid) .addSink(new DiscardingSink<>()); return env; }); ExecutionEnvironment batchEnv = ExecutionEnvironment.getExecutionEnvironment(); ExistingSavepoint savepoint = Savepoint.load(batchEnv, savepointPath, getStateBackend()); List<Integer> results = savepoint .window(TumblingEventTimeWindows.of(Time.milliseconds(10))) .reduce(uid, new ReduceSum(), Types.INT, Types.INT) .collect(); Assert.assertThat("Unexpected results from keyed state", results, Matchers.containsInAnyOrder(numbers)); }
Source:
<code>public Short getShortProperty(final String key) throws ActiveMQPropertyConversionException { <START> return checkProperties().getShortProperty(SimpleString.toSimpleString(key, getPropertyKeysPool())); <END> }</code><technical_language>delegate public Short getShortProperty(final SimpleString key) throws ActiveMQPropertyConversionException {</technical_language>

Target:
public Short getShortProperty(final String key) throws ActiveMQPropertyConversionException { return getShortProperty(key(key)); }
Source:
<code>public int getJuteMaxBufferSize() { <START> return Integer.getInteger("jute.maxbuffer", 0xfffff); <END> }</code><technical_language>I magic number 0xfffff is defined in code, great in place</technical_language>

Target:
public int getJuteMaxBufferSize() { return BinaryInputArchive.maxBuffer; }
Source:
<code>protected void translateAndSendBatch(ConsumerRecords<?, ?> records, Instant readTime) { for (TopicPartition topicPartition : records.partitions()) { for (ConsumerRecord<?, ?> record : records.records(topicPartition)) { try { if (_autoPausedSourcePartitions.containsKey(topicPartition)) { _logger.warn("Abort sending as is auto-paused, rewind offset", topicPartition); seekToLastCheckpoint(Collections.singleton(topicPartition)); break; } else { DatastreamProducerRecord datastreamProducerRecord = translate(record, readTime); int numBytes = record.serializedKeySize() + record.serializedValueSize(); sendDatastreamProducerRecord(datastreamProducerRecord, topicPartition, numBytes, null); } } catch (Exception e) { <START> _logger.warn("Got exception while sending record {}, exception: ", record, e); <END> rewindAndPausePartitionOnException(topicPartition, e); break; } } } }</code><technical_language>Agreed @somandal format record _logger.warn(String, Throwable) this file</technical_language>

Target:
protected void translateAndSendBatch(ConsumerRecords<?, ?> records, Instant readTime) { for (TopicPartition topicPartition : records.partitions()) { for (ConsumerRecord<?, ?> record : records.records(topicPartition)) { try { if (_autoPausedSourcePartitions.containsKey(topicPartition)) { _logger.warn("Abort sending as is auto-paused, rewind offset", topicPartition); seekToLastCheckpoint(Collections.singleton(topicPartition)); break; } else { DatastreamProducerRecord datastreamProducerRecord = translate(record, readTime); int numBytes = record.serializedKeySize() + record.serializedValueSize(); sendDatastreamProducerRecord(datastreamProducerRecord, topicPartition, numBytes, null); } } catch (Exception e) { _logger.warn(String.format("Got exception while sending record %s, exception: ", record), e); rewindAndPausePartitionOnException(topicPartition, e); break; } } } }
Source:
<code>public static BiConsumer<ItemStack.Builder, Random> quantity(VariableAmount amount) { checkNotNull(amount, "VariableAmount cannot be null!"); <START> return ((builder, random) -> builder.quantity(amount.getFlooredAmount(random))); <END> }</code><technical_language>I extra layer of parens</technical_language>

Target:
public static BiConsumer<ItemStack.Builder, Random> quantity(VariableAmount amount) { checkNotNull(amount, "VariableAmount cannot be null!"); return (builder, random) -> builder.quantity(amount.getFlooredAmount(random)); }
Source:
<code>public void testValidateAttachementsForVlans(){ NetworkAttachment attachement1 = new NetworkAttachment(); attachement1.setNetworkName("network1"); attachement1.setNicName("eth0"); NetworkAttachment attachement2 = new NetworkAttachment(); attachement2.setNetworkName("any2"); attachement2.setNicName("eth1"); List<NetworkAttachment> attachementList = Arrays.asList(attachement1, attachement2); <START> Nic nic = new Nic(); <END> nic.setName("eth0"); VdsNetworkInterface vlanNic = createVlanNic(nic, "eth.100", 100); ValidationResult result = validator.validateAttachements(vlanNic, attachementList); assertThat(result, failsWith(EngineMessage.ACTION_TYPE_FAILED_HOST_NETWORK_ATTACHEMENT_ON_UNMANAGED_NETWORK, ReplacementUtils.createSetVariableString(NETWORK, "network1"), ReplacementUtils.createSetVariableString(NIC, "eth0"))); vlanNic.setBaseInterface("eth7"); result = validator.validateAttachements(vlanNic, attachementList); assertTrue(result.isValid()); }</code><technical_language>'createNic(..);</technical_language>

Target:
public void testValidateAttachementsForVlans(){ String unmanagedBaseNicName = "eth0"; NetworkAttachment attachement1 = new NetworkAttachment(); attachement1.setNetworkName("network1"); attachement1.setNicName(unmanagedBaseNicName); NetworkAttachment attachement2 = new NetworkAttachment(); attachement2.setNetworkName("any2"); attachement2.setNicName("eth1"); List<NetworkAttachment> attachementList = Arrays.asList(attachement1, attachement2); Nic nic = createNic(unmanagedBaseNicName); VdsNetworkInterface vlanNic = createVlanNic(nic, "eth0.100", 100, false); List<VdsNetworkInterface> existingInterfaces = Arrays.asList(vlanNic); Set<String> nicsWithUnmanagedNetworks = validator.filterNicsWithUnmanagedNetworks(existingInterfaces, Collections.emptySet()); assertEquals(1, nicsWithUnmanagedNetworks.size()); String filteredNicName = nicsWithUnmanagedNetworks.iterator().next(); assertEquals(filteredNicName, unmanagedBaseNicName); ValidationResult result = validator.validateAttachements(filteredNicName, attachementList); assertThat(result, failsWith(EngineMessage.ACTION_TYPE_FAILED_HOST_NETWORK_ATTACHEMENT_ON_UNMANAGED_NETWORK, ReplacementUtils.createSetVariableString(NETWORK, "network1"), ReplacementUtils.createSetVariableString(NIC, "eth0"))); result = validator.validateAttachements("eth7", attachementList); assertTrue(result.isValid()); }
Source:
<code><START> public ModularCrypt() <END></code><technical_language>This class static members, constructor private IMO</technical_language>

Target:
private ModularCrypt()
Source:
<code>public String graph( @RegisteredOAuth2AuthorizedClient("graph") OAuth2AuthorizedClient oAuth2AuthorizedClient ) { logAuthorizedClient(oAuth2AuthorizedClient); <START> return "graph"; <END> }</code><technical_language>return json string of oAuth2AuthorizedClient, output json string in logAuthorizedClient</technical_language>

Target:
public String graph( @RegisteredOAuth2AuthorizedClient("graph") OAuth2AuthorizedClient oAuth2AuthorizedClient ) throws JsonProcessingException { return toJsonString(oAuth2AuthorizedClient); }
Source:
<code>public void testDuplicateSetupForTransfer() { SessionData login = login(user.getUsername(), userCleartextPassword); <START> given(). <END> filter(sessionFilter). header(login.getCsrfHeader()). when(). content(ticketReceiver.getUsername()).contentType(ContentType.TEXT). post(TRANSFER_ENDPOINT + "/" + ticket.getId()). then(). extract().response(); given() .filter(sessionFilter) .header(login.getCsrfHeader()) .when() .content(ticketReceiver.getUsername()).contentType(ContentType.TEXT) .post(TRANSFER_ENDPOINT + "/" + ticket.getId()) .then() .statusCode(HttpStatus.SC_BAD_REQUEST); }</code><technical_language>Please addTicketTransfer method. This is duplicate code</technical_language>

Target:
public void testDuplicateSetupForTransfer() { addTicketTransfer(user.getUsername(), userCleartextPassword); Response response = addTicketTransfer(user.getUsername(), userCleartextPassword); response.then() .statusCode(HttpStatus.SC_BAD_REQUEST); }
Source:
<code><START> public void addFailureDescription(final ModelNode operation, final ModelNode failureDescription) { <END> ModelNode error = new ModelNode(); ModelNode failure = new ModelNode(); failure.get(FAILED).set(operation.clone()); if (failureDescription != null) { if (failureDescription.hasDefined(ControllerLogger.ROOT_LOGGER.failedServices())) { failure.get(FAILURES).add(failureDescription.get(ControllerLogger.ROOT_LOGGER.failedServices())); } if (failureDescription.hasDefined(ControllerLogger.ROOT_LOGGER.servicesMissingDependencies())) { failure.get(MISSING_DEPS).add(failureDescription.get(ControllerLogger.ROOT_LOGGER.servicesMissingDependencies())); } if(failureDescription.getType() == ModelType.STRING) { failure.get(FAILURES).add(failureDescription.asString()); } } error.get(BOOT_ERROR).set(failure); errors.get(BOOT_ERRORS).add(error); }</code><technical_language>This package protected, ModelControllerImpl calls it</technical_language>

Target:
void addFailureDescription(final ModelNode operation, final ModelNode failureDescription) { ModelNode error = new ModelNode(); ModelNode failure = new ModelNode(); ModelNode failed = failure.get(FAILED); failed.get(OP).set(operation.get(OP)); failed.get(OP_ADDR).set(operation.get(OP_ADDR)); if (failureDescription != null) { if (failureDescription.hasDefined(ControllerLogger.ROOT_LOGGER.failedServices())) { failure.get(FAILURES).add(failureDescription.get(ControllerLogger.ROOT_LOGGER.failedServices())); } if (failureDescription.hasDefined(ControllerLogger.ROOT_LOGGER.servicesMissingDependencies())) { failure.get(MISSING_DEPS).add(failureDescription.get(ControllerLogger.ROOT_LOGGER.servicesMissingDependencies())); } if (failureDescription.getType() == ModelType.STRING) { failure.get(FAILURES).add(failureDescription.asString()); } } error.get(BOOT_ERROR).set(failure); errors.get(BOOT_ERRORS).add(error); }
Source:
<code>private Connection retry(Connection connection) { int retryC = 0; while ((connection == null) && ((retryCount == -1) || (retryC < retryCount))) { retryC++; <START> log.info("[" + name + "] Attempting to create connection to RabbitMQ Broker" + <END> " in " + retryInterval + " ms"); try { Thread.sleep(retryInterval); connection = RabbitMQUtils.createConnection(connectionFactory, addresses); log.info("[" + name + "] Successfully connected to RabbitMQ Broker"); } catch (InterruptedException e1) { Thread.currentThread().interrupt(); } catch (IOException e1) { log.error("[" + name + "] Error while trying to reconnect to RabbitMQ Broker", e1); } } return connection; }</code><technical_language>log retry count aswell</technical_language>

Target:
private Connection retry(Connection connection) { int retryC = 0; while ((connection == null) && ((retryCount == -1) || (retryC < retryCount))) { retryC++; log.info("[" + name + "] Attempting to create connection to RabbitMQ Broker" + " in " + retryInterval + "ms. Retry attempts: " + retryC); try { Thread.sleep(retryInterval); connection = RabbitMQUtils.createConnection(connectionFactory, addresses); log.info("[" + name + "] Successfully connected to RabbitMQ Broker"); } catch (InterruptedException e1) { Thread.currentThread().interrupt(); } catch (IOException e1) { log.error("[" + name + "] Error while trying to reconnect to RabbitMQ Broker", e1); } } return connection; }
Source:
<code>public void run() { if (logger.isTraceEnabled()) { logger.trace(this.getConnectionId() + " Nio message assembler running..."); } try { if (this.getListener() == null && !this.isSingleUse()) { logger.debug("TcpListener exiting - no listener and not single use"); return; } try { if (dataAvailable()) { Message<?> message = convert(); if (dataAvailable()) { this.executionControl.incrementAndGet(); this.taskExecutor.execute(this); } this.executionControl.decrementAndGet(); if (message != null) { sendToChannel(message); } } else { this.executionControl.decrementAndGet(); } } catch (Exception e) { if (logger.isTraceEnabled()) { logger.error("Read exception " + this.getConnectionId(), e); } else if (!this.isNoReadErrorOnClose()) { logger.error("Read exception " + this.getConnectionId() + " " + e.getClass().getSimpleName() + <START> ":" + e.getCause() + ":" + e.getMessage()); <END> } else { logger.debug("Read exception " + this.getConnectionId() + " " + e.getClass().getSimpleName() + ":" + e.getCause() + ":" + e.getMessage()); } this.closeConnection(); this.sendExceptionToListener(e); return; } } finally { if (logger.isTraceEnabled()) { logger.trace(this.getConnectionId() + " Nio message assembler exiting..."); } try { if (this.isOpen() && dataAvailable()) { checkForAssembler(); } } catch (IOException e) { logger.error("Exception when checking for assembler", e); } } }</code><technical_language>Need whitespaces colons</technical_language>

Target:
public void run() { if (logger.isTraceEnabled()) { logger.trace(this.getConnectionId() + " Nio message assembler running..."); } try { if (this.getListener() == null && !this.isSingleUse()) { logger.debug("TcpListener exiting - no listener and not single use"); return; } try { if (dataAvailable()) { Message<?> message = convert(); if (dataAvailable()) { this.executionControl.incrementAndGet(); this.taskExecutor.execute(this); } this.executionControl.decrementAndGet(); if (message != null) { sendToChannel(message); } } else { this.executionControl.decrementAndGet(); } } catch (Exception e) { if (logger.isTraceEnabled()) { logger.error("Read exception " + this.getConnectionId(), e); } else if (!this.isNoReadErrorOnClose()) { logger.error("Read exception " + this.getConnectionId() + " " + e.getClass().getSimpleName() + ":" + e.getCause() + ":" + e.getMessage()); } else { if (logger.isDebugEnabled()) { logger.debug("Read exception " + this.getConnectionId() + " " + e.getClass().getSimpleName() + ":" + e.getCause() + ":" + e.getMessage()); } } this.closeConnection(); this.sendExceptionToListener(e); return; } } finally { if (logger.isTraceEnabled()) { logger.trace(this.getConnectionId() + " Nio message assembler exiting..."); } try { if (this.isOpen() && dataAvailable()) { checkForAssembler(); } } catch (IOException e) { logger.error("Exception when checking for assembler", e); } } }
Source:
<code>public int size() { <START> return partitions.length; <END> }</code><technical_language>this</technical_language>

Target:
public int size() { return this.partitions.length; }
Source:
<code>private boolean hasMediaPlayerAudioTracks(ExoPlayer mediaPlayer) { <START> if(mediaPlayer.getAudioComponent() == null) { <END> return false; } else { return true; } }</code><technical_language>Simplify return mediaPlayer.getAudioComponent() != null</technical_language>

Target:
private boolean hasMediaPlayerAudioTracks(ExoPlayer mediaPlayer) { return mediaPlayer.getAudioComponent() != null; }
Source:
<code>private void updateRESTConfig(String clusterName, RESTConfig restConfig, boolean overwrite) { if (!ZKUtil.isClusterSetup(clusterName, _zkClient)) { throw new HelixException("fail to update REST config. cluster: " + clusterName + " is NOT setup."); } HelixConfigScope scope = new HelixConfigScopeBuilder(ConfigScopeProperty.REST).forCluster(clusterName).build(); String zkPath = scope.getZkPath(); String parentPath = HelixUtil.getZkParentPath(zkPath); if (!_zkClient.exists(HelixUtil.getZkParentPath(zkPath))) { ZKUtil.createOrMerge(_zkClient, parentPath, new ZNRecord(parentPath), true, true); } <START> <END> if (overwrite) { ZKUtil.createOrReplace(_zkClient, zkPath, restConfig.getRecord(), true); } else { ZKUtil.createOrUpdate(_zkClient, zkPath, restConfig.getRecord(), true, true); } }</code><technical_language>Actually, if is "overwrite", is need check existence. call createOrReplace(). If is "overwrite", is need check existence either, call createOrUpdate()</technical_language>

Target:
private void updateRESTConfig(String clusterName, RESTConfig restConfig, boolean overwrite) { if (!ZKUtil.isClusterSetup(clusterName, _zkClient)) { throw new HelixException("Fail to update REST config. cluster: " + clusterName + " is NOT setup."); } HelixConfigScope scope = new HelixConfigScopeBuilder(ConfigScopeProperty.REST).forCluster(clusterName).build(); String zkPath = scope.getZkPath(); String parentPath = HelixUtil.getZkParentPath(zkPath); if (!_zkClient.exists(parentPath)) { ZKUtil.createOrMerge(_zkClient, parentPath, new ZNRecord(parentPath), true, true); } if (overwrite) { ZKUtil.createOrReplace(_zkClient, zkPath, restConfig.getRecord(), true); } else { ZKUtil.createOrUpdate(_zkClient, zkPath, restConfig.getRecord(), true, true); } }