auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public Session findSession(String id) throws IOException { Session result = super.findSession(id); if (result == null) { if (id != null) { Map<String, Object> attrs = null; try { RMap map = getMap(id); <START> if (map.isExists()) { <END> attrs = map.getAll(RedissonSession.ATTRS); } } catch (Exception e) { log.error("Can't read session object by id: " + id, e); } if (attrs == null) { log.info("Session " + id + " can't be found"); return null; } RedissonSession session = (RedissonSession) createEmptySession(); session.load(attrs); session.setId(id); session.access(); session.endAccess(); return session; } return null; } result.access(); result.endAccess(); return result; }</code><technical_language>@jchobantonov do need call for isExists method? if map exists attrs object empty. need do is check if Map empty</technical_language>

Target:
public Session findSession(String id) throws IOException { Session result = super.findSession(id); if (result == null) { if (id != null) { Map<String, Object> attrs = new HashMap<String, Object>(); try { attrs = getMap(id).getAll(RedissonSession.ATTRS); } catch (Exception e) { log.error("Can't read session object by id: " + id, e); } if (attrs.isEmpty()) { log.info("Session " + id + " can't be found"); return null; } RedissonSession session = (RedissonSession) createEmptySession(); session.load(attrs); session.setId(id); session.access(); session.endAccess(); return session; } return null; } result.access(); result.endAccess(); return result; }
Source:
<code>public void testRegisterStreamConsumerThrottled() throws Exception { final CompletableFuture<DescribeStreamSummaryResponse> dssFuture = CompletableFuture .completedFuture(createDescribeStreamSummaryResponse()); final CompletableFuture<DescribeStreamConsumerResponse> dscFuture = CompletableFuture.supplyAsync(() -> { throw ResourceNotFoundException.builder().build(); }); final CompletableFuture<RegisterStreamConsumerResponse> rscFuture = CompletableFuture.supplyAsync(() -> { throw LimitExceededException.builder().build(); }); when(client.describeStreamSummary(any(DescribeStreamSummaryRequest.class))).thenReturn(dssFuture); when(client.describeStreamConsumer(any(DescribeStreamConsumerRequest.class))).thenReturn(dscFuture); when(client.registerStreamConsumer(any(RegisterStreamConsumerRequest.class))).thenReturn(rscFuture); try { consumerRegistration.getOrCreateStreamConsumerArn(); } finally { verify(client, times(RSC_RETRIES)) .registerStreamConsumer(any(RegisterStreamConsumerRequest.class)); <START> verify(client).describeStreamConsumer(any(DescribeStreamConsumerRequest.class)); <END> } }</code><technical_language>"Verify DescribeStreamConsumer called for RegisterStreamConsumer retries + 1 start." This is verifying. This verifies calling once, this is guaranteed implementation detail testing, a cursory glance if this is a worthwhile verification</technical_language>

Target:
public void testRegisterStreamConsumerThrottled() throws Exception { final CompletableFuture<DescribeStreamSummaryResponse> dssFuture = CompletableFuture .completedFuture(createDescribeStreamSummaryResponse()); final CompletableFuture<DescribeStreamConsumerResponse> dscFuture = CompletableFuture.supplyAsync(() -> { throw ResourceNotFoundException.builder().build(); }); final CompletableFuture<RegisterStreamConsumerResponse> rscFuture = CompletableFuture.supplyAsync(() -> { throw LimitExceededException.builder().build(); }); when(client.describeStreamSummary(any(DescribeStreamSummaryRequest.class))).thenReturn(dssFuture); when(client.describeStreamConsumer(any(DescribeStreamConsumerRequest.class))).thenReturn(dscFuture); when(client.registerStreamConsumer(any(RegisterStreamConsumerRequest.class))).thenReturn(rscFuture); try { consumerRegistration.getOrCreateStreamConsumerArn(); } finally { verify(client, times(RSC_RETRIES)) .registerStreamConsumer(any(RegisterStreamConsumerRequest.class)); } }
Source:
<code>private TypeInference(FunctionLike functionDef) { for (Symbol variable : functionDef.localVariables()) { Set<Usage.Kind> unsupportedKinds = variable.usages().stream() .map(Usage::kind) .filter(k -> k != Usage.Kind.ASSIGNMENT_LHS && k != Usage.Kind.OTHER) .collect(Collectors.toSet()); <START> if (unsupportedKinds.isEmpty()) { <END> trackedVars.add((SymbolImpl) variable); } } }</code><technical_language>do allMatch stream? java if (variable.usages().stream() .map(Usage::kind) .allMatch(k -> == Usage.Kind.ASSIGNMENT_LHS || == Usage.Kind.OTHER)) { trackedVars.add((SymbolImpl) variable); }</technical_language>

Target:
private TypeInference(FunctionLike functionDef) { for (Symbol variable : functionDef.localVariables()) { if (variable.usages().stream() .map(Usage::kind) .allMatch(k -> k == Usage.Kind.ASSIGNMENT_LHS || k == Usage.Kind.OTHER)) { trackedVars.add((SymbolImpl) variable); } } }
Source:
<code>private static String normalizePhone(String data) throws CorrelationAttributeNormalizationException { <START> String phoneNumber = data.replaceAll("[^0-9\\+]", ""); <END> if(phoneNumber.matches("\\+?[0-9]+")){ return phoneNumber; } else { throw new CorrelationAttributeNormalizationException(String.format("Data was expected to be a valid phone number: %s", data)); } }</code><technical_language>@briangsweeney : this line remove number + values? If so, follow match work. If reading this correctly, I this replacing space, '-', '.', '(', ')'</technical_language>

Target:
private static String normalizePhone(String data) throws CorrelationAttributeNormalizationException { if(data.matches("\\+?[0-9()\\-\\s]+")){ String phoneNumber = data.replaceAll("[^0-9\\+]", ""); return phoneNumber; } else { throw new CorrelationAttributeNormalizationException(String.format("Data was expected to be a valid phone number: %s", data)); } }
Source:
<code><T> T computeSync(K key, Function<TransactionEntry<K, V>, T> function, Function<K, MetadataValue<V>> remoteValueSupplier) { <START> ByRef<T> future = new ByRef<>(null); <END> entries.compute(wrap(key), (wKey, entry) -> { if (entry == null) { entry = createEntryFromRemote(wKey.key, remoteValueSupplier); if (trace) { log.tracef("Fetched key (%s) from remote. Entry=%s", wKey, entry); } } if (trace) { log.tracef("Compute key (%s). Before=%s", wKey, entry); } T result = function.apply(entry); future.set(result); if (trace) { log.tracef("Compute key (%s). After=%s (result=%s)", wKey, entry, result); } return entry; }); return future.get(); }</code><technical_language>a future..</technical_language>

Target:
<T> T computeSync(K key, Function<TransactionEntry<K, V>, T> function, Function<K, MetadataValue<V>> remoteValueSupplier) { ByRef<T> ref = new ByRef<>(null); entries.compute(wrap(key), (wKey, entry) -> { if (entry == null) { entry = createEntryFromRemote(wKey.key, remoteValueSupplier); if (trace) { log.tracef("Fetched key (%s) from remote. Entry=%s", wKey, entry); } } if (trace) { log.tracef("Compute key (%s). Before=%s", wKey, entry); } T result = function.apply(entry); ref.set(result); if (trace) { log.tracef("Compute key (%s). After=%s (result=%s)", wKey, entry, result); } return entry; }); return ref.get(); }
Source:
<code>protected InstantOperatorInfo getInstantOpInfo() { final InstantOperatorInfo.Builder iOpInfoBuilder = InstantOperatorInfo.newBuilder(); iOpInfoBuilder.setInstantOperatorType(InstantOperatorTypeEnum.APPLY_STATEFUL); final List<ByteBuffer> serializedObjectList = new ArrayList<>(); serializedObjectList.add(ByteBuffer.wrap(SerializationUtils.serialize(applyStatefulFunction))); <START> iOpInfoBuilder.setObjects(serializedObjectList); <END> iOpInfoBuilder.setKeyIndex(null); return iOpInfoBuilder.build(); }</code><technical_language>functions</technical_language>

Target:
protected InstantOperatorInfo getInstantOpInfo() { final InstantOperatorInfo.Builder iOpInfoBuilder = InstantOperatorInfo.newBuilder(); iOpInfoBuilder.setInstantOperatorType(InstantOperatorTypeEnum.APPLY_STATEFUL); final List<ByteBuffer> serializedFunctionList = new ArrayList<>(); serializedFunctionList.add(ByteBuffer.wrap(SerializationUtils.serialize(applyStatefulFunction))); iOpInfoBuilder.setFunctions(serializedFunctionList); iOpInfoBuilder.setKeyIndex(null); return iOpInfoBuilder.build(); }
Source:
<code>private void analyzeTypes(List<JavaClass> types) { List<JavaClass> sortedTypes = new LinkedList<>(); Iterator<JavaClass> iterator = types.iterator(); while (iterator.hasNext()) { JavaClass javaClass = iterator.next(); if (javaClass.isEnum()) { analyzeEnum(javaClass); } else { <START> addSorted(sortedTypes, javaClass); <END> } } for (JavaClass javaClass : sortedTypes) { analyzeStruct(javaClass); } }</code><technical_language>do need do this sorting? a mechanism handle types defined. If need is types completely defined starting process services, call "fixUndefinedTypeUsages" method starting analyze services. Note sorting types inheritance relationship guarantee completely defined. For example, Vm Disk inheritance relatinship, if Vm is processed Disk Vm references Disk, undefined type processing Vm</technical_language>

Target:
private void analyzeTypes(List<JavaClass> types) { for (JavaClass javaClass : types) { if (javaClass.isEnum()) { analyzeEnum(javaClass); } else { analyzeStruct(javaClass); } } redefineUndefinedTypes(); }
Source:
<code>public void fill(int index, long[] toFill) { if (totalSize - index < toFill.length) { throw new IndexOutOfBoundsException( <START> StringUtils.safeFormat( <END> "Cannot fill array of size[%,d] at index[%,d]. Max size[%,d]", toFill.length, index, totalSize ) ); } for (int i = 0; i < toFill.length; i++) { toFill[i] = get(index + i); } }</code><technical_language>do want add IOBE</technical_language>

Target:
public void fill(int index, long[] toFill) { if (totalSize - index < toFill.length) { throw new IndexOutOfBoundsException( StringUtils.format( "Cannot fill array of size[%,d] at index[%,d]. Max size[%,d]", toFill.length, index, totalSize ) ); } for (int i = 0; i < toFill.length; i++) { toFill[i] = get(index + i); } }
Source:
<code><START> public static Optional<Span> initOptionalSpan(Tracer tracer, String component, String operation) { <END> return Optional.ofNullable(tracer.activeSpan()).map(activeSpan -> { Span span = tracer.buildSpan(component + " - " + operation) .addReference(References.FOLLOWS_FROM, activeSpan.context()) .start(); span.setTag(TracingUtil.COMPONENT, component); return span; }); }</code><technical_language>if I this is initSpan, return Optional.empty() if tracer.activeSpan() is null refactor this part reflect this logic</technical_language>

Target:
public static Optional<Span> initOptionalSpan(Tracer tracer, String component, String operation) { return Optional.ofNullable(tracer.activeSpan()).map(activeSpan -> initFromActiveSpan(tracer, component, operation, activeSpan.context())); }
Source:
<code>public MavenProjectInfo(MavenProject project) throws Exception { this.project = project; File file = new File(project.getBuild() .getOutputDirectory()); if (!file.exists()) { throw new IllegalStateException("The output directory for project " + project.getName() + " does not exist"); } <START> Jar jar = new Jar(file); <END> try (Analyzer analyzer = new Analyzer(jar)) { analyzer.analyze(); exports = analyzer.getExports(); imports = analyzer.getImports(); contained = analyzer.getContained(); } }</code><technical_language>close jar object. Add this try-with-resources. java try (Jar jar = new Jar(file); Analyzer analyzer = new Analyzer(jar)) {</technical_language>

Target:
public MavenProjectInfo(MavenProject project) throws Exception { this.project = project; File file = new File(project.getBuild() .getOutputDirectory()); if (!file.exists()) { throw new IllegalStateException("The output directory for project " + project.getName() + " does not exist"); } try (Jar jar = new Jar(file); Analyzer analyzer = new Analyzer(jar)) { analyzer.analyze(); exports = analyzer.getExports(); imports = analyzer.getImports(); contained = analyzer.getContained(); } }
Source:
<code>public void readFeedException() throws Exception { ArrayList<CosmosDatabaseProperties> dbs = new ArrayList<CosmosDatabaseProperties>(); dbs.add(new CosmosDatabaseProperties("db1")); dbs.add(new CosmosDatabaseProperties("db2")); ArrayList<FeedResponse<CosmosDatabaseProperties>> frps = new ArrayList<FeedResponse<CosmosDatabaseProperties>>(); frps.add(BridgeInternal.createFeedResponse(dbs, null)); frps.add(BridgeInternal.createFeedResponse(dbs, null)); Flux<FeedResponse<CosmosDatabaseProperties>> response = Flux.merge(Flux.fromIterable(frps)) .mergeWith(Flux.error(BridgeInternal.createCosmosException(0))) .mergeWith(Flux.fromIterable(frps)); final CosmosAsyncClientWrapper mockedClientWrapper = Mockito.spy(new CosmosAsyncClientWrapper(client)); Mockito.when(mockedClientWrapper.readAllDatabases()).thenReturn(UtilBridgeInternal.createCosmosPagedFlux(pagedFluxOptions -> { pagedFluxOptions.setTracerInformation(new TracerProvider(ServiceLoader.load(Tracer.class)), "testSpan", "testEndpoint,", "testDb"); return response; <START> })); <END> TestSubscriber<FeedResponse<CosmosDatabaseProperties>> subscriber = new TestSubscriber<>(); mockedClientWrapper.readAllDatabases().byPage().subscribe(subscriber); assertThat(subscriber.valueCount()).isEqualTo(2); assertThat(subscriber.assertNotComplete()); assertThat(subscriber.assertTerminated()); assertThat(subscriber.errorCount()).isEqualTo(1); }</code><technical_language>update is this related to? validate related tracing here</technical_language>

Target:
public void readFeedException() throws Exception { ArrayList<CosmosDatabaseProperties> dbs = new ArrayList<CosmosDatabaseProperties>(); dbs.add(new CosmosDatabaseProperties("db1")); dbs.add(new CosmosDatabaseProperties("db2")); ArrayList<FeedResponse<CosmosDatabaseProperties>> frps = new ArrayList<FeedResponse<CosmosDatabaseProperties>>(); frps.add(BridgeInternal.createFeedResponse(dbs, null)); frps.add(BridgeInternal.createFeedResponse(dbs, null)); Flux<FeedResponse<CosmosDatabaseProperties>> response = Flux.merge(Flux.fromIterable(frps)) .mergeWith(Flux.error(BridgeInternal.createCosmosException(0))) .mergeWith(Flux.fromIterable(frps)); final CosmosAsyncClientWrapper mockedClientWrapper = Mockito.spy(new CosmosAsyncClientWrapper(client)); Mockito.when(mockedClientWrapper.readAllDatabases()).thenReturn(UtilBridgeInternal.createCosmosPagedFlux(pagedFluxOptions -> { pagedFluxOptions.setTracerInformation(new TracerProvider(null), "testSpan", "testEndpoint,", "testDb"); return response; })); TestSubscriber<FeedResponse<CosmosDatabaseProperties>> subscriber = new TestSubscriber<>(); mockedClientWrapper.readAllDatabases().byPage().subscribe(subscriber); assertThat(subscriber.valueCount()).isEqualTo(2); assertThat(subscriber.assertNotComplete()); assertThat(subscriber.assertTerminated()); assertThat(subscriber.errorCount()).isEqualTo(1); }
Source:
<code>public void onDetach() { <START> timer.cancel(); <END> super.onDetach(); mDelegate = null; }</code><technical_language>Similarly here. OnDetached is called close GATT Server result in a notification a GATT Server. do this in OnStop</technical_language>

Target:
public void onDetach() { super.onDetach(); mDelegate = null; }
Source:
<code>public void return_component_info_when_file_on_master() throws Exception { init(); OrganizationDto organization = dbTester.organizations().insertForKey("my-org2"); ComponentDto main = componentDbTester.insertMainBranch(organization, p -> p.setName("Sample"), p -> p.setDbKey("sample")); userSession.addProjectPermission(UserRole.USER, main); ComponentDto dirDto = newDirectory(main, "src"); <START> componentDbTester.insertComponent(dirDto); <END> ComponentDto fileDto = newFileDto(main, dirDto) .setUuid("abcd") .setName("Main.xoo") .setDbKey("sample:src/Main.xoo"); componentDbTester.insertComponent(fileDto); executeAndVerify(fileDto.getDbKey(), "return_component_info_when_file_on_master.json"); }</code><technical_language>inline dirDto</technical_language>

Target:
public void return_component_info_when_file_on_master() throws Exception { init(); OrganizationDto organization = dbTester.organizations().insertForKey("my-org2"); ComponentDto main = componentDbTester.insertMainBranch(organization, p -> p.setName("Sample"), p -> p.setDbKey("sample")); userSession.addProjectPermission(UserRole.USER, main); ComponentDto dirDto = componentDbTester.insertComponent(newDirectory(main, "src")); ComponentDto fileDto = componentDbTester.insertComponent(newFileDto(main, dirDto) .setUuid("abcd") .setName("Main.xoo") .setDbKey("sample:src/Main.xoo")); executeAndVerify(fileDto.getDbKey(), "return_component_info_when_file_on_master.json"); }
Source:
<code>public SyncPoller<CreateSearchResponse, PhoneNumberSearch> beginCreateSearch( <START> CreateSearchOptions options, Duration lroDuration) { <END> return phoneNumberAsyncClient.beginCreateSearch(options, lroDuration).getSyncPoller(); }</code><technical_language>Sync operations include Context param</technical_language>

Target:
public SyncPoller<PhoneNumberSearch, PhoneNumberSearch> beginCreateSearch( CreateSearchOptions options, Duration lroDuration) { return phoneNumberAsyncClient.beginCreateSearch(options, lroDuration).getSyncPoller(); }
Source:
<code>protected @Nullable List<@NonNull ITimeGraphRowModel> getRowModel(@NonNull ITmfStateSystem ss, @NonNull SelectionTimeQueryFilter filter, @Nullable IProgressMonitor monitor) throws StateSystemDisposedException { TreeMultimap<Integer, ITmfStateInterval> intervals = TreeMultimap.create(Comparator.naturalOrder(), Comparator.comparing(ITmfStateInterval::getStartTime)); Map<@NonNull Long, @NonNull Integer> entries = getSelectedEntries(filter); Collection<Long> times = getTimes(filter, ss.getStartTime(), ss.getCurrentEndTime()); for (ITmfStateInterval interval : ss.query2D(entries.values(), times)) { if (monitor != null && monitor.isCanceled()) { return null; } intervals.put(interval.getAttribute(), interval); } List<ITimeGraphRowModel> rows = new ArrayList<>(); for (Map.Entry<Long, Integer> entry : entries.entrySet()) { if (monitor != null && monitor.isCanceled()) { return null; } List<ITimeGraphState> eventList = new ArrayList<>(); for (ITmfStateInterval interval : intervals.get(entry.getValue())) { long startTime = interval.getStartTime(); long duration = interval.getEndTime() - startTime + 1; Object state = interval.getValue(); String value = state == null ? null : state.toString(); <START> eventList.add(new TimeGraphState(startTime, duration, entry.getKey().intValue(), value)); <END> } rows.add(new TimeGraphRowModel(entry.getKey(), eventList)); } return rows; }</code><technical_language>crazy it, least, clamp it</technical_language>

Target:
protected @Nullable List<@NonNull ITimeGraphRowModel> getRowModel(@NonNull ITmfStateSystem ss, @NonNull SelectionTimeQueryFilter filter, @Nullable IProgressMonitor monitor) throws StateSystemDisposedException { TreeMultimap<Integer, ITmfStateInterval> intervals = TreeMultimap.create(Comparator.naturalOrder(), Comparator.comparing(ITmfStateInterval::getStartTime)); Map<@NonNull Long, @NonNull Integer> entries = getSelectedEntries(filter); Collection<Long> times = getTimes(filter, ss.getStartTime(), ss.getCurrentEndTime()); for (ITmfStateInterval interval : ss.query2D(entries.values(), times)) { if (monitor != null && monitor.isCanceled()) { return null; } intervals.put(interval.getAttribute(), interval); } List<@NonNull ITimeGraphRowModel> rows = new ArrayList<>(); for (Map.Entry<Long, Integer> entry : entries.entrySet()) { if (monitor != null && monitor.isCanceled()) { return null; } List<ITimeGraphState> eventList = new ArrayList<>(); for (ITmfStateInterval interval : intervals.get(entry.getValue())) { long startTime = interval.getStartTime(); long duration = interval.getEndTime() - startTime + 1; Object state = interval.getValue(); String value = state == null ? "" : String.valueOf(state); eventList.add(new TimeGraphState(startTime, duration, Math.max(entry.getKey().intValue(), 0), value)); } rows.add(new TimeGraphRowModel(entry.getKey(), eventList)); } return rows; }
Source:
<code>public JoinUsingAnalysis(List<Integer> leftJoinFields, List<Integer> rightJoinFields, List<Integer> otherLeftFields, List<Integer> otherRightFields) { <START> this.leftJoinFields = leftJoinFields; <END> this.rightJoinFields = rightJoinFields; this.otherLeftFields = otherLeftFields; this.otherRightFields = otherRightFields; }</code><technical_language>requireNonNull Immutable.copyOf</technical_language>

Target:
JoinUsingAnalysis(List<Integer> leftJoinFields, List<Integer> rightJoinFields, List<Integer> otherLeftFields, List<Integer> otherRightFields) { this.leftJoinFields = ImmutableList.copyOf(leftJoinFields); this.rightJoinFields = ImmutableList.copyOf(rightJoinFields); this.otherLeftFields = ImmutableList.copyOf(otherLeftFields); this.otherRightFields = ImmutableList.copyOf(otherRightFields); checkArgument(leftJoinFields.size() == rightJoinFields.size(), "Expected join fields for left and right to have the same size"); }
Source:
<code>public AnnotationList getAnnotations(AnnotationRequestParameters parameters) throws MendeleyException { try { String url = getAnnotationsUrl(parameters); Procedure<AnnotationList> proc = new GetAnnotationsProcedure(url, authenticationManager); return proc.checkedRun(); } catch (UnsupportedEncodingException e) { <START> throw new MendeleyException(e.getMessage()); <END> } }</code><technical_language>prefer report Exceptions providing cause. is done now, if client code needs distinguish (ie - for showing error message another) is string matching. losing meaning class of originating exception carries, making imposible handle exception a try - catch mechanism. Also, providing message of operation failed is handy. I would: try { [...] } catch (UnsupportedEncodingException e) { throw new MendeleyException("Could encode URL for annotations", e); }</technical_language>

Target:
public AnnotationList getAnnotations(AnnotationRequestParameters parameters) throws MendeleyException { try { String url = getAnnotationsUrl(parameters); Procedure<AnnotationList> proc = new GetAnnotationsProcedure(url, authenticationManager); return proc.checkedRun(); } catch (UnsupportedEncodingException e) { throw new MendeleyException("Could not encode the URL for getting annotations", e); } }
Source:
<code>public void validate(Object object, Errors errors) { if(object == null){ throw new IllegalArgumentException("The object parameter should not be null"); } if(!(object instanceof Condition)){ throw new IllegalArgumentException("The object parameter should be of type " + Condition.class); } Condition condition = (Condition) object; <START> if(condition.getCondition() == null || (condition.getClinicalStatus().equals(ConditionClinicalStatus.INACTIVE) && condition.getOnsetDate().compareTo(condition.getEndDate()) > 0)){ <END> errors.rejectValue("condition", "Condition.conditionShouldNotBeNull", "The condition is required"); } if(condition.getClinicalStatus() == null){ errors.rejectValue("clinicalStatus", "Condition.clinicalStatusShouldNotBeNull", "The clinical status is required"); } }</code><technical_language>do a statement here, do a separate validation already</technical_language>

Target:
public void validate(Object object, Errors errors) { if(object == null){ throw new IllegalArgumentException("The object parameter should not be null"); } if(!(object instanceof Condition)){ throw new IllegalArgumentException("The object parameter should be of type " + Condition.class); } Condition condition = (Condition) object; if(condition.getCondition() == null){ errors.rejectValue("condition", "Condition.conditionShouldNotBeNull", "The condition is required"); } else if(condition.getClinicalStatus().equals(ConditionClinicalStatus.INACTIVE) && condition.getOnsetDate().compareTo(condition.getEndDate()) > 0){ errors.rejectValue("onsetDate","Condition.onsetDateShouldBeBeforeEndDate","Valid Onset Date is required"); } if(condition.getClinicalStatus() == null){ errors.rejectValue("clinicalStatus", "Condition.clinicalStatusShouldNotBeNull", "The clinical status is required"); } }
Source:
<code>public T findByOcOID(String OCOID) { if(OCOID == null) { return null; <START> } <END> getSessionFactory().getStatistics().logSummary(); String query = "from " + getDomainClassName() + " do where do.oc_oid = :oc_oid"; Query q = getCurrentSession().createQuery(query); q.setParameter("oc_oid", OCOID); return (T) q.uniqueResult(); }</code><technical_language>add this</technical_language>

Target:
public T findByOcOID(String OCOID) { getSessionFactory().getStatistics().logSummary(); String query = "from " + getDomainClassName() + " do where do.oc_oid = :oc_oid"; Query q = getCurrentSession().createQuery(query); q.setParameter("oc_oid", OCOID); return (T) q.uniqueResult(); }
Source:
<code>private void onDiscoverServicesResult(String deviceObjectPath, boolean result) { <START> String address = mBluetoothService.getAddressFromObjectPath(deviceObjectPath); <END> if (result) { mBluetoothService.updateRemoteDevicePropertiesCache(address); } if (address != null) { mBluetoothService.sendUuidIntent(address); } mBluetoothService.makeServiceChannelCallbacks(address); }</code><technical_language>if address == null return. is better</technical_language>

Target:
private void onDiscoverServicesResult(String deviceObjectPath, boolean result) { String address = mBluetoothService.getAddressFromObjectPath(deviceObjectPath); if (address == null) return; if (result) { mBluetoothService.updateRemoteDevicePropertiesCache(address); } mBluetoothService.sendUuidIntent(address); mBluetoothService.makeServiceChannelCallbacks(address); }
Source:
<code>public void updateStockPrice(String symbol, double newPrice) throws StockMarketExpection { if (getStockForSymbol(symbol) == null) { throw new StockMarketExpection("Stock not present (" + symbol + ")"); } if (newPrice < 0.0) { throw new StockMarketExpection( "Stock price cannot be set to a negative value (" + symbol + ", " + getStockForSymbol(symbol).getPrice() + ") -> " + newPrice + " X Not Allowed "); } <START> Stock s = removeStockFromStockList(symbol); s.setPrice(newPrice); addStock(s); marketHistory.updatePriceHistory(symbol, newPrice); <END> }</code><technical_language>Vague variable name s</technical_language>

Target:
public void updateStockPrice(String symbol, double newPrice) throws StockMarketExpection { if (getStockForSymbol(symbol) == null) { throw new StockMarketExpection("Stock not present (" + symbol + ")"); } if (newPrice < 0.0) { throw new StockMarketExpection( "Stock price cannot be set to a negative value (" + symbol + ", " + getStockForSymbol(symbol).getPrice() + ") -> " + newPrice + " X Not Allowed "); } Stock stock = removeStockFromStockList(symbol); stock.setPrice(newPrice); addStock(stock); marketHistory.updatePriceHistory(symbol, newPrice); }
Source:
<code>public void testSimpleDelimitedWithTabCharacter() throws Exception { FlatFileItemReader<Foo> reader = new FlatFileItemReaderBuilder<Foo>() .name("fooReader") <START> .resource(getResource("1 2 3")) <END> .delimited() .delimiter(DelimitedLineTokenizer.DELIMITER_TAB) .names(new String[] {"first", "second", "third"}) .targetType(Foo.class) .build(); reader.open(new ExecutionContext()); Foo item = reader.read(); assertEquals(1, item.getFirst()); assertEquals(2, item.getSecond()); assertEquals("3", item.getThird()); assertNull(reader.read()); }</code><technical_language>Please replace tab \t is explicit</technical_language>

Target:
public void testSimpleDelimitedWithTabCharacter() throws Exception { FlatFileItemReader<Foo> reader = new FlatFileItemReaderBuilder<Foo>() .name("fooReader") .resource(getResource("1\t2\t3")) .delimited() .delimiter(DelimitedLineTokenizer.DELIMITER_TAB) .names(new String[] {"first", "second", "third"}) .targetType(Foo.class) .build(); reader.open(new ExecutionContext()); Foo item = reader.read(); assertEquals(1, item.getFirst()); assertEquals(2, item.getSecond()); assertEquals("3", item.getThird()); assertNull(reader.read()); }
Source:
<code>private boolean isEntityBlacklisted(CreatureEntity creature) { if (isEntityTypeBlacklisted(creature.getType())) return true; <START> if (!(creature instanceof AnimalEntity)) return true; <END> if (creature instanceof IVampire) return true; return false; }</code><technical_language>Move instanceof checks top costly method a slighlty smaller chance of returning true</technical_language>

Target:
private boolean isEntityBlacklisted(CreatureEntity creature) { if (!(creature instanceof AnimalEntity)) return true; if (creature instanceof IVampire) return true; EntityType<?> type = creature.getType(); if (!(type.getClassification() == EntityClassification.MONSTER || type.getClassification() == EntityClassification.WATER_CREATURE)) return true; if (ModTags.Entities.VAMPIRE.contains(type)) return true; if (isConfigBlackListed(type.getRegistryName())) return true; return false; }
Source:
<code>private void changePassword(User user, JsonObject json) { String password = JsonUtils.getString(json, "password"); if (Strings.isNullOrEmpty(password)) { <START> throw BennuCoreDomainException.passwordIsEmpty(); <END> } String passwordCheck = JsonUtils.getString(json, "passwordCheck"); if (!Objects.equals(password, passwordCheck)) { throw BennuCoreDomainException.passwordCheckDoesNotMatch(); } if (user.matchesPassword(password)) { throw BennuCoreDomainException.passwordIsTheSame(); } user.changePassword(password); }</code><technical_language>this change prevent of User Management interface inputting password? (For information other password is edited)</technical_language>

Target:
private void changePassword(User user, JsonObject json) { String password = JsonUtils.getString(json, "password"); if (Strings.isNullOrEmpty(password)) { return; } String passwordCheck = JsonUtils.getString(json, "passwordCheck"); if (!Objects.equals(password, passwordCheck)) { throw BennuCoreDomainException.passwordCheckDoesNotMatch(); } if (user.matchesPassword(password)) { throw BennuCoreDomainException.passwordIsTheSame(); } user.changePassword(password); }
Source:
<code>public Map<String, String> getTraceProperties() { Map<String, String> properties = new HashMap<>(); properties.putAll(fTrace.getEnvironment()); <START> properties.put(Messages.CtfTmfTrace_UtcOffset, Long.toUnsignedString(fTrace.getOffset())); <END> properties.put(Messages.CtfTmfTrace_HostID, getHostId()); return properties; }</code><technical_language>I understand Keys of this Property Map localized Strings; if Properties meant for processed programmatically, I expect Strings change UI is localized</technical_language>

Target:
public Map<String, String> getTraceProperties() { Map<String, String> properties = new HashMap<>(); properties.putAll(fTrace.getEnvironment()); properties.put(CLOCK_OFFSET, Long.toUnsignedString(fTrace.getOffset())); properties.put(Messages.CtfTmfTrace_HostID, getHostId()); return properties; }
Source:
<code>public Iterable<DocumentRevsList> createTask(List<String> ids, <START> Map<String, Collection<String>> revisions) { <END> List<BulkGetRequest> requests = new ArrayList<BulkGetRequest>(); for (String id : ids) { if (id.isEmpty()) { logger.info("Found document with empty ID in change feed, skipping"); continue; } HashSet<String> possibleAncestors = new HashSet<String>(); for (String revId : revisions.get(id)) { List<String> thesePossibleAncestors = targetDb.getDbCore().getPossibleAncestorRevisionIDs(id, revId, 50); if (thesePossibleAncestors != null) { possibleAncestors.addAll(thesePossibleAncestors); } } requests.add(new BulkGetRequest( id, new ArrayList<String>(revisions.get(id)), new ArrayList<String>(possibleAncestors))); } if (bulkSupported) { return new GetRevisionTaskBulk(this.sourceDb, requests, config.pullAttachmentsInline); } else { return new GetRevisionTaskThreaded(this.sourceDb, requests, config.pullAttachmentsInline); } }</code><technical_language>part of original work in this PR method arguments line up</technical_language>

Target:
public Iterable<DocumentRevsList> createTask(List<String> ids, Map<String, Collection<String>> revisions) { List<BulkGetRequest> requests = new ArrayList<BulkGetRequest>(); for (String id : ids) { if (id.isEmpty()) { logger.info("Found document with empty ID in change feed, skipping"); continue; } HashSet<String> possibleAncestors = new HashSet<String>(); for (String revId : revisions.get(id)) { List<String> thesePossibleAncestors = targetDb.getDbCore().getPossibleAncestorRevisionIDs(id, revId, 50); if (thesePossibleAncestors != null) { possibleAncestors.addAll(thesePossibleAncestors); } } requests.add(new BulkGetRequest( id, new ArrayList<String>(revisions.get(id)), new ArrayList<String>(possibleAncestors))); } if (useBulkGet) { return new GetRevisionTaskBulk(this.sourceDb, requests, config.pullAttachmentsInline); } else { return new GetRevisionTaskThreaded(this.sourceDb, requests, config.pullAttachmentsInline); } }
Source:
<code>public boolean equals(Object o) { if (o == this) { return true; } if (!(o instanceof FormatterBuilder)) { return false; } FormatterBuilder<?> other = (FormatterBuilder<?>) o; <START> return ((m_formatterName == null && other.m_formatterName == null) || m_formatterName.equals(other.m_formatterName)) <END> && ((m_formatterProps == null && other.m_formatterProps == null) || m_formatterProps.equals(other.m_formatterProps)) && ((m_formatterFactory == null && other.m_formatterFactory == null) || m_formatterFactory.equals(other.m_formatterFactory)); }</code><technical_language>case sensitivity of name matters here</technical_language>

Target:
public boolean equals(Object o) { if (o == this) { return true; } if (!(o instanceof FormatterBuilder)) { return false; } FormatterBuilder<?> other = (FormatterBuilder<?>) o; return ((m_formatterName == null && other.m_formatterName == null) || m_formatterName.equalsIgnoreCase(other.m_formatterName)) && ((m_formatterProps == null && other.m_formatterProps == null) || m_formatterProps.equals(other.m_formatterProps)) && ((m_formatterFactory == null && other.m_formatterFactory == null) || m_formatterFactory.equals(other.m_formatterFactory)); }
Source:
<code>protected void init() { if (getVm() == null) { return; } super.init(); <START> String vmClusterCpuName = getCluster().getCpuVerb(); <END> if (getParameters().getCustomCpuName() != null && !getParameters().getCustomCpuName().equals( getVm().getCustomCpuName() != null ? getVm().getCustomCpuName() : vmClusterCpuName)) { getVm().setUseHostCpuFlags(false); getVm().setCustomCpuName(getParameters().getCustomCpuName()); } if (getParameters().getCustomEmulatedMachine() != null) { getVm().setEmulatedMachine(getParameters().getCustomEmulatedMachine()); } if (getParameters().getBootMenuEnabled() != null) { getVm().setBootMenuEnabled(getParameters().getBootMenuEnabled()); } if (getParameters().getSpiceFileTransferEnabled() != null) { getVm().setSpiceFileTransferEnabled(getParameters().getSpiceFileTransferEnabled()); } if (getParameters().getSpiceCopyPasteEnabled() != null) { getVm().setSpiceCopyPasteEnabled(getParameters().getSpiceCopyPasteEnabled()); } if (getParameters().getBootSequence() != null) { getVm().setBootSequence(getParameters().getBootSequence()); } getVm().setVolatileRun(getParameters().isVolatileRun()); getVm().setInitrdUrl(getParameters().getInitrdUrl()); getVm().setKernelUrl(getParameters().getKernelUrl()); getVm().setKernelParams(getParameters().getKernelParams()); getVm().setCustomProperties(getParameters().getCustomProperties()); getVm().setRunOnce(true); }</code><technical_language>note VM compatibility version cluster compatibility version - this assumes same, right</technical_language>

Target:
protected void init() { if (getVm() == null) { return; } super.init(); String vmClusterCpuName; if (getCluster().getCompatibilityVersion().equals(getVm().getCompatibilityVersion())) { vmClusterCpuName = getCluster().getCpuVerb(); } else { vmClusterCpuName = getCpuFlagsManagerHandler().getCpuId( getVm().getClusterCpuName(), getVm().getCompatibilityVersion()); } if (getParameters().getCustomCpuName() != null && !getParameters().getCustomCpuName().equals( getVm().getCustomCpuName() != null ? getVm().getCustomCpuName() : vmClusterCpuName)) { getVm().setUseHostCpuFlags(false); getVm().setCustomCpuName(getParameters().getCustomCpuName()); } if (getParameters().getCustomEmulatedMachine() != null) { getVm().setEmulatedMachine(getParameters().getCustomEmulatedMachine()); } if (getParameters().getBootMenuEnabled() != null) { getVm().setBootMenuEnabled(getParameters().getBootMenuEnabled()); } if (getParameters().getSpiceFileTransferEnabled() != null) { getVm().setSpiceFileTransferEnabled(getParameters().getSpiceFileTransferEnabled()); } if (getParameters().getSpiceCopyPasteEnabled() != null) { getVm().setSpiceCopyPasteEnabled(getParameters().getSpiceCopyPasteEnabled()); } if (getParameters().getBootSequence() != null) { getVm().setBootSequence(getParameters().getBootSequence()); } getVm().setVolatileRun(getParameters().isVolatileRun()); getVm().setInitrdUrl(getParameters().getInitrdUrl()); getVm().setKernelUrl(getParameters().getKernelUrl()); getVm().setKernelParams(getParameters().getKernelParams()); getVm().setCustomProperties(getParameters().getCustomProperties()); getVm().setRunOnce(true); }
Source:
<code>public Snippet054NativeControlsInViewers(Shell shell) { <START> int style = SWT.BORDER | SWT.FULL_SELECTION; <END> final TableViewer viewer = new TableViewer(shell, style); viewer.setContentProvider(ArrayContentProvider.getInstance()); viewer.getTable().setLayoutData( new GridData(SWT.FILL, SWT.FILL, true, true, 2, 1)); TableViewerColumn column = createColumnFor(viewer, "Column 1"); column.setLabelProvider(new ColumnLabelProvider() { @Override public String getText(Object element) { return element.toString(); } }); column = createColumnFor(viewer, "Column 2"); column.setLabelProvider(createCellLabelProvider()); MyModel[] model = createModel(10); viewer.setInput(model); viewer.getTable().setLinesVisible(true); viewer.getTable().setHeaderVisible(true); Button b = createButtonFor(shell, "Modify Input"); b.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { viewer.setInput(createModel((int) (Math.random() * 10))); } }); b = createButtonFor(shell, "Refresh"); b.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { viewer.refresh(); } }); }</code><technical_language>Change</technical_language>

Target:
public Snippet054NativeControlsInViewers(Shell shell) { final TableViewer viewer = new TableViewer(shell, SWT.BORDER | SWT.FULL_SELECTION); viewer.setContentProvider(ArrayContentProvider.getInstance()); viewer.getTable().setLayoutData( new GridData(SWT.FILL, SWT.FILL, true, true, 2, 1)); TableViewerColumn column = createColumnFor(viewer, "Column 1"); column.setLabelProvider(new ColumnLabelProvider() { @Override public String getText(Object element) { return element.toString(); } }); column = createColumnFor(viewer, "Column 2"); column.setLabelProvider(createCellLabelProvider()); MyModel[] model = createModel(10); viewer.setInput(model); viewer.getTable().setLinesVisible(true); viewer.getTable().setHeaderVisible(true); Button b = createButtonFor(shell, "Modify Input"); b.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { viewer.setInput(createModel((int) (Math.random() * 10))); } }); b = createButtonFor(shell, "Refresh"); b.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { viewer.refresh(); } }); }
Source:
<code>@Test public void testTimeFilter() throws SQLException { withJavaSqlDateTypes(connection -> { String sql = "select 'result'" + " from \"java_sql_date_types\""; Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery(sql + " where \"tm\" > TIME '18:29:33'"); <START> assertTrue("Time is grater than the literal", resultSet.next()); <END> statement = connection.createStatement(); resultSet = statement.executeQuery(sql + " where \"tm\" = TIME '18:29:34'"); assertTrue("Time equals to the literal", resultSet.next()); statement = connection.createStatement(); resultSet = statement.executeQuery(sql + " where \"tm\" > TIME '18:29:34'"); assertFalse("Time is not grater the literal", resultSet.next()); statement = connection.createStatement(); resultSet = statement.executeQuery(sql + " where \"tm\" between TIME '18:29:34' and TIME '18:29:35'"); assertTrue("Time is in between the literals", resultSet.next()); }); }</code><technical_language>failure of this assertion cryptic. assertTrue("sql.Time.valueOf("18:29:34") > TIME '18:29:33'", ...) better</technical_language>

Target:
@Test public void testTimeFilter() throws SQLException { withJavaSqlDateTypes(connection -> { String sql = "select 'result'" + " from \"java_sql_date_types\""; Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery(sql + " where \"tm\" > TIME '18:29:33'"); assertTrue("java.sql.Time.valueOf(\"18:29:34\") > TIME '18:29:33'", resultSet.next()); statement = connection.createStatement(); resultSet = statement.executeQuery(sql + " where \"tm\" = TIME '18:29:34'"); assertTrue("java.sql.Time.valueOf(\"18:29:34\") = TIME '18:29:34'", resultSet.next()); statement = connection.createStatement(); resultSet = statement.executeQuery(sql + " where \"tm\" > TIME '18:29:34'"); assertFalse("java.sql.Time.valueOf(\"18:29:34\") > TIME '18:29:34'", resultSet.next()); statement = connection.createStatement(); resultSet = statement.executeQuery(sql + " where \"tm\" between TIME '18:29:34' and TIME '18:29:35'"); assertTrue("java.sql.Time.valueOf(\"18:29:34\")" + " between TIME '18:29:34' and TIME '18:29:35'", resultSet.next()); }); }
Source:
<code>private void writeTextToFile(final File output, final String header, final List<String> textLines) throws IOException { try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter( <START> new FileOutputStream(output), StandardCharsets.UTF_8))) { <END> writer.write(header + "\n\n"); writer.write(StringUtils.join(textLines, "\n")); } }</code><technical_language>This of StringUtil.join() replaced a JDK builtin, String.join() suggestion throw new PicardException("Metric(s) of name: " + String.join(", ", metricsToIgnore) + " in " + metricsFile.getAbsolutePath());</technical_language>

Target:
private static void writeTextToFile(final File output, final String header, final List<String> textLines) throws IOException { try (Writer writer = Files.newBufferedWriter(output.toPath())) { writer.write(header + "\n\n"); writer.write(String.join("\n", textLines)); } }
Source:
<code><START> public void testGroupInfo() throws IOException, OrmException { <END> ReviewDb db = reviewDbProvider.open(); try { AccountGroup adminGroup = db.accountGroups().get(new AccountGroup.Id(1)); Reader r = session.get("/groups/?q=" + adminGroup.getName()); @SuppressWarnings("serial") Map<String, GroupInfo> result = (new Gson()).fromJson(r, new TypeToken<Map<String, GroupInfo>>() {}.getType()); GroupInfo adminGroupInfo = result.get(adminGroup.getName()); assertEquals(adminGroup.getGroupUUID().get(), adminGroupInfo.id); assertEquals(Integer.valueOf(adminGroup.getId().get()), adminGroupInfo.group_id); assertEquals("#/admin/groups/uuid-" + adminGroup.getGroupUUID().get(), adminGroupInfo.url); assertEquals(adminGroup.isVisibleToAll(), toBoolean(adminGroupInfo.options.visible_to_all)); assertEquals(adminGroup.getDescription(), adminGroupInfo.description); assertEquals(adminGroup.getOwnerGroupUUID().get(), adminGroupInfo.owner_id); if (adminGroupInfo.name != null) { assertEquals(adminGroup.getName(), adminGroupInfo.name); } } finally { db.close(); } }</code><technical_language>optional: test method name more test</technical_language>

Target:
public void testGroupInfo() throws IOException, OrmException { AccountGroup adminGroup = groupCache.get(new AccountGroup.NameKey("Administrators")); Reader r = session.get("/groups/?q=" + adminGroup.getName()); @SuppressWarnings("serial") Map<String, GroupInfo> result = (new Gson()).fromJson(r, new TypeToken<Map<String, GroupInfo>>() {}.getType()); GroupInfo adminGroupInfo = result.get(adminGroup.getName()); assertEquals(adminGroup.getGroupUUID().get(), adminGroupInfo.id); assertEquals(Integer.valueOf(adminGroup.getId().get()), adminGroupInfo.group_id); assertEquals("#/admin/groups/uuid-" + adminGroup.getGroupUUID().get(), adminGroupInfo.url); assertEquals(adminGroup.isVisibleToAll(), toBoolean(adminGroupInfo.options.visible_to_all)); assertEquals(adminGroup.getDescription(), adminGroupInfo.description); assertEquals(adminGroup.getOwnerGroupUUID().get(), adminGroupInfo.owner_id); if (adminGroupInfo.name != null) { assertEquals(adminGroup.getName(), adminGroupInfo.name); } }
Source:
<code>private JobProgressUpdate progressUpdateLog(boolean isProgressLogRequested, Operation operation) { if (isProgressLogRequested && canProvideProgressLog()) { if (OperationType.EXECUTE_STATEMENT.equals(operation.getType())) { SessionState sessionState = operation.getParentSession().getSessionState(); try { while (sessionState.progressMonitor() == null && !operation.isFinished()) { <START> Thread.sleep(100L); END> } } catch (InterruptedException e) { LOG.warn("Error while getting progress update", e); } if (sessionState.progressMonitor() != null) { return new JobProgressUpdate(sessionState.progressMonitor()); } } } return new JobProgressUpdate(ProgressMonitor.NULL); }</code><technical_language>I thinking if (or need to) avoid this 100 ms sleep. I thinking add another 100ms of latency queries in some cases</technical_language>

Target:
private JobProgressUpdate progressUpdateLog(boolean isProgressLogRequested, Operation operation) { if (isProgressLogRequested && canProvideProgressLog()) { if (OperationType.EXECUTE_STATEMENT.equals(operation.getType())) { SessionState sessionState = operation.getParentSession().getSessionState(); try { while (sessionState.getProgressMonitor() == null && !operation.isFinished()) { Thread.sleep(10L); } } catch (InterruptedException e) { LOG.warn("Error while getting progress update", e); } if (sessionState.getProgressMonitor() != null) { return new JobProgressUpdate(sessionState.getProgressMonitor()); } } } return new JobProgressUpdate(ProgressMonitor.NULL); }
Source:
<code>private int compressDirectBuf() throws IOException { if (uncompressedDirectBufLen == 0) { return 0; } else { uncompressedDirectBuf.limit(uncompressedDirectBufLen).position(0); int size = Snappy.compress((ByteBuffer) uncompressedDirectBuf, (ByteBuffer) compressedDirectBuf); uncompressedDirectBufLen = 0; <START> uncompressedDirectBuf.limit(uncompressedDirectBuf.capacity()).position(0); <END> return size; } }</code><technical_language>nit: this unnecessary clear is called shortly call site</technical_language>

Target:
private int compressDirectBuf() throws IOException { if (uncompressedDirectBufLen == 0) { return 0; } else { uncompressedDirectBuf.limit(uncompressedDirectBufLen).position(0); int size = Snappy.compress((ByteBuffer) uncompressedDirectBuf, (ByteBuffer) compressedDirectBuf); uncompressedDirectBufLen = 0; return size; } }