auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public EurekaHttpResponse<InstanceInfo> sendHeartBeat(String appName, String id, InstanceInfo info, InstanceStatus overriddenStatus) { String urlPath = "apps/" + appName + '/' + id; Response response = null; try { WebTarget webResource = jerseyClient.target(serviceUrl) .path(urlPath) .queryParam("status", info.getStatus().toString()) .queryParam("lastDirtyTimestamp", info.getLastDirtyTimestamp().toString()); if (overriddenStatus != null) { webResource = webResource.queryParam("overriddenstatus", overriddenStatus.name()); } Builder requestBuilder = webResource.request(); addExtraProperties(requestBuilder); addExtraHeaders(requestBuilder); response = requestBuilder.put(Entity.entity("{}", MediaType.APPLICATION_JSON_TYPE)); <START> requestBuilder.accept(MediaType.APPLICATION_JSON_TYPE); <END> EurekaHttpResponseBuilder<InstanceInfo> eurekaResponseBuilder = anEurekaHttpResponse(response.getStatus(), InstanceInfo.class).headers(headersOf(response)); if (response.hasEntity()) { eurekaResponseBuilder.entity(response.readEntity(InstanceInfo.class)); } return eurekaResponseBuilder.build(); } finally { if (logger.isDebugEnabled()) { logger.debug("Jersey2 HTTP PUT {}/{}; statusCode={}", serviceUrl, urlPath, response == null ? "N/A" : response.getStatus()); } if (response != null) { response.close(); } } }</code><technical_language>This call put</technical_language>

Target:
public EurekaHttpResponse<InstanceInfo> sendHeartBeat(String appName, String id, InstanceInfo info, InstanceStatus overriddenStatus) { String urlPath = "apps/" + appName + '/' + id; Response response = null; try { WebTarget webResource = jerseyClient.target(serviceUrl) .path(urlPath) .queryParam("status", info.getStatus().toString()) .queryParam("lastDirtyTimestamp", info.getLastDirtyTimestamp().toString()); if (overriddenStatus != null) { webResource = webResource.queryParam("overriddenstatus", overriddenStatus.name()); } Builder requestBuilder = webResource.request(); addExtraProperties(requestBuilder); addExtraHeaders(requestBuilder); requestBuilder.accept(MediaType.APPLICATION_JSON_TYPE); response = requestBuilder.put(Entity.entity("{}", MediaType.APPLICATION_JSON_TYPE)); EurekaHttpResponseBuilder<InstanceInfo> eurekaResponseBuilder = anEurekaHttpResponse(response.getStatus(), InstanceInfo.class).headers(headersOf(response)); if (response.hasEntity()) { eurekaResponseBuilder.entity(response.readEntity(InstanceInfo.class)); } return eurekaResponseBuilder.build(); } finally { if (logger.isDebugEnabled()) { logger.debug("Jersey2 HTTP PUT {}/{}; statusCode={}", serviceUrl, urlPath, response == null ? "N/A" : response.getStatus()); } if (response != null) { response.close(); } } }
Source:
<code>public List<Observation> searchObservationByPatientAndCode(String patientUuid, List<TokenParam> codings) { Patient patient = Context.getPatientService().getPatientByUuid(patientUuid); List<Observation> obsList = new ArrayList<>(); if (codings.isEmpty()) { return obsList; } else { for (TokenParam tokenParam : codings) { obsList.addAll(getObservations(patient, getConcept(tokenParam))); } } <START> return new ArrayList<Observation>(new HashSet<>(obsList)); <END> }</code><technical_language>return obsList</technical_language>

Target:
public List<Observation> searchObservationByPatientAndCode(String patientUuid, List<TokenParam> codings) { Patient patient = Context.getPatientService().getPatientByUuid(patientUuid); List<Observation> obsList = new ArrayList<>(); if (codings.isEmpty()) { return obsList; } else { for (TokenParam tokenParam : codings) { obsList.addAll(getObservations(patient, getConcept(tokenParam))); } } return obsList; }
Source:
<code>private void waitForInitCompleted(Duration duration) { boolean interrupted = false; long deadlineTimeout = System.nanoTime() + duration.toNanos(); try { while (true) { try { long timeRemaining = deadlineTimeout - System.nanoTime(); if (timeRemaining <= 0 || initCompleted) { return; } synchronized (initLock) { if (!initCompleted) { initLock.wait(TimeUnit.NANOSECONDS.toMillis(timeRemaining)); } } } catch (InterruptedException e) { <START> interrupted = true; <END> } } } finally { if (interrupted) { Thread.currentThread().interrupt(); } } }</code><technical_language>For me, interrupting is a smaller timeout. out of loop directly. means explicitly called interrupt this thread. If a short timeout breaks everything, another problem</technical_language>

Target:
private void waitForInitCompleted(Duration duration) { boolean interrupted = false; long deadlineTimeout = System.nanoTime() + duration.toNanos(); try { while (true) { try { long timeRemainingInMillis = TimeUnit.NANOSECONDS.toMillis(deadlineTimeout - System.nanoTime()); if (timeRemainingInMillis <= 0 || initCompleted) { return; } synchronized (initLock) { if (!initCompleted) { initLock.wait(timeRemainingInMillis); } } } catch (InterruptedException e) { interrupted = true; } } } finally { if (interrupted) { Thread.currentThread().interrupt(); } } }
Source:
<code>public List<State> queryKeyValueWithOperator(String key1, Object value1, String key2, DBSQueryOperator operator, Object value2, Set<String> ignored) { Map<String, Object> comparatorAndValue; switch (operator) { case IN: <START> comparatorAndValue = Collections.singletonMap(QueryOperators.IN, value2); <END> break; case NOT_IN: comparatorAndValue = Collections.singletonMap(QueryOperators.NIN, value2); break; default: throw new IllegalArgumentException(String.format("Unknown operator: %s", operator)); } Document filter = new Document(converter.keyToBson(key1), value1); filter.put(converter.keyToBson(key2), comparatorAndValue); addIgnoredIds(filter, ignored); return findAll(filter); }</code><technical_language>Map.of</technical_language>

Target:
public List<State> queryKeyValueWithOperator(String key1, Object value1, String key2, DBSQueryOperator operator, Object value2, Set<String> ignored) { Map<String, Object> comparatorAndValue; switch (operator) { case IN: comparatorAndValue = Map.of(QueryOperators.IN, value2); break; case NOT_IN: comparatorAndValue = Map.of(QueryOperators.NIN, value2); break; default: throw new IllegalArgumentException(String.format("Unknown operator: %s", operator)); } Document filter = new Document(converter.keyToBson(key1), value1); filter.put(converter.keyToBson(key2), comparatorAndValue); addIgnoredIds(filter, ignored); return findAll(filter); }
Source:
<code>public ChangedLines changedLines(Provider<ReviewDb> db, PatchListCache cache) throws OrmException { if (changedLines == null) { Change c = change(db); if (c == null) { return null; } PatchSet ps = currentPatchSet(db); if (ps == null) { return null; } PatchList p; try { p = cache.get(c, ps); } catch (PatchListNotAvailableException e) { return null; } changedLines = new ChangedLines(p.getInsertions(), p.getDeletions()); <START> for (PatchListEntry e : p.getPatches()) { if (Patch.COMMIT_MSG.equals(e.getNewName())) { continue; } } <END> } return changedLines; }</code><technical_language>pointless loop</technical_language>

Target:
public ChangedLines changedLines(Provider<ReviewDb> db, PatchListCache cache) throws OrmException { if (changedLines == null) { Change c = change(db); if (c == null) { return null; } PatchSet ps = currentPatchSet(db); if (ps == null) { return null; } PatchList p; try { p = cache.get(c, ps); } catch (PatchListNotAvailableException e) { return null; } changedLines = new ChangedLines(p.getInsertions(), p.getDeletions()); } return changedLines; }
Source:
<code>private static String[] sanitizeNoteProjection(String[] projection) { <START> if (projection == null) { <END> return sDefaultNoteProjectionDBAccess; } List<String> sanitized = new ArrayList<>(); for (String column : projection) { int idx = projSearch(FlashCardsContract.Note.DEFAULT_PROJECTION, column); if (idx >= 0) { sanitized.add(sDefaultNoteProjectionDBAccess[idx]); } else { throw new IllegalArgumentException("Unknown column " + column); } } return sanitized.toArray(new String[sanitized.size()]); }</code><technical_language>check for blank trim</technical_language>

Target:
private static String[] sanitizeNoteProjection(String[] projection) { if (projection == null || projection.length == 0) { return sDefaultNoteProjectionDBAccess; } List<String> sanitized = new ArrayList<>(); for (String column : projection) { int idx = projSearch(FlashCardsContract.Note.DEFAULT_PROJECTION, column); if (idx >= 0) { sanitized.add(sDefaultNoteProjectionDBAccess[idx]); } else { throw new IllegalArgumentException("Unknown column " + column); } } return sanitized.toArray(new String[sanitized.size()]); }
Source:
<code>private void fillMap(Map<String, ByteIterator> resultMap, Map<String, Object> properties, Set<String> fields) { if (fields == null || fields.size() == 0) { for (Map.Entry<String, Object> entry : properties.entrySet()) { if (entry.getValue() instanceof String) { resultMap.put(entry.getKey(), stringToByteIterator((String)(entry.getValue()))); } else { logger.error("Error! Not the format expected! Actually is {}", entry.getValue().getClass().getName()); <START> System.exit(-1); <END> } } } else { for (String field : fields) { if (properties.get(field) instanceof String) { resultMap.put(field, stringToByteIterator((String)(properties.get(field)))); } else { logger.error("Error! Not the format expected! Actually is {}", properties.get(field).getClass().getName()); System.exit(-1); } } } }</code><technical_language>call System.exit. Please find a propagate error instead</technical_language>

Target:
private boolean fillMap(Map<String, ByteIterator> resultMap, Map<String, Object> properties, Set<String> fields) { if (fields == null || fields.size() == 0) { for (Map.Entry<String, Object> entry : properties.entrySet()) { if (entry.getValue() instanceof String) { resultMap.put(entry.getKey(), stringToByteIterator((String)(entry.getValue()))); } else { logger.error("Error! Not the format expected! Actually is {}", entry.getValue().getClass().getName()); return false; } } } else { for (String field : fields) { if (properties.get(field) instanceof String) { resultMap.put(field, stringToByteIterator((String)(properties.get(field)))); } else { logger.error("Error! Not the format expected! Actually is {}", properties.get(field).getClass().getName()); return false; } } } return true; }
Source:
<code>public Map<Term, Term> getEntries() { <START> return UnmodifiableMap.decorate(entries); <END> }</code><technical_language>switch Apache commons collection 4.0, unmodifiableMap</technical_language>

Target:
public Map<Term, Term> getEntries() { return UnmodifiableMap.unmodifiableMap(entries); }
Source:
<code>public void onInfoWindowClick(Marker marker) { mCustomInfoWindowAdapter.cancelUpdates(); ObaTripStatus status = mMarkerData.getStatusFromMarker(marker); <START> String focusedStopId = mController.getFocusedStopId(); <END> if (focusedStopId != null) { TripDetailsActivity.start(mActivity, status.getActiveTripId(), focusedStopId); } else { TripDetailsActivity.start(mActivity, status.getActiveTripId()); } }</code><technical_language>check if mController is null calling mController.getFocusedStopId(), prevent potential NPEs</technical_language>

Target:
public void onInfoWindowClick(Marker marker) { mCustomInfoWindowAdapter.cancelUpdates(); ObaTripStatus status = mMarkerData.getStatusFromMarker(marker); if (mController != null && mController.getFocusedStopId() != null) { TripDetailsActivity.start(mActivity, status.getActiveTripId(), mController.getFocusedStopId()); } else { TripDetailsActivity.start(mActivity, status.getActiveTripId()); } }
Source:
<code>public void test_wrong_lines_in_file() { settings.setProperty(JavaScriptPlugin.LCOV_UT_REPORT_PATH, "wrong_line_lcov.info"); DefaultFileSystem fs = newFileSystem(); DefaultInputFile inputFile = newSourceInputFile("sensortests/main/Person.js", "org/sonar/plugins/javascript/unittest/jstestdriver/sensortests/main/Person.js"); fs.add(inputFile.setLines(13)); newSensor(fs, settings).analyse(project, context); ArgumentCaptor<Measure> measures = ArgumentCaptor.forClass(Measure.class); <START> verify(context, times(7)).saveMeasure((Resource) anyObject(), measures.capture()); <END> for (Measure measure : measures.getAllValues()) { if (measure.getMetricKey() == CoreMetrics.COVERAGE_LINE_HITS_DATA_KEY) { assertThat(measure.getData()).isEqualTo("5=1"); } else if (measure.getMetricKey() == CoreMetrics.CONDITIONS_BY_LINE_KEY) { assertThat(measure.getData()).isEqualTo("7=3"); } } }</code><technical_language>@vilchik-elena times(7)? atLeast(2) more understandable</technical_language>

Target:
public void test_wrong_lines_in_file() { settings.setProperty(JavaScriptPlugin.LCOV_UT_REPORT_PATH, "wrong_line_lcov.info"); DefaultFileSystem fs = newFileSystem(); fs.add(newSourceInputFile("fake_file.js")); newSensor(fs, settings).analyse(project, context); ArgumentCaptor<Measure> measures = ArgumentCaptor.forClass(Measure.class); verify(context, atLeast(2)).saveMeasure((Resource) anyObject(), measures.capture()); boolean lineCoverageMetric = false; boolean conditionCoverageMetric = false; for (Measure measure : measures.getAllValues()) { if (measure.getMetricKey().equals(CoreMetrics.COVERAGE_LINE_HITS_DATA_KEY)) { assertThat(measure.getData()).isEqualTo("5=1"); lineCoverageMetric = true; } else if (measure.getMetricKey().equals(CoreMetrics.CONDITIONS_BY_LINE_KEY)) { assertThat(measure.getData()).isEqualTo("7=3"); conditionCoverageMetric = true; } } assertThat(lineCoverageMetric).isTrue(); assertThat(conditionCoverageMetric).isTrue(); }
Source:
<code>protected List<String> getTabCompleteOptions(final Server server, final CommandSource sender, final String commandLabel, final String[] args) { User user = ess.getUser(sender.getPlayer()); boolean canDelOthers = (user == null || user.isAuthorized("essentials.delhome.others")); if (args.length == 1) { if (canDelOthers) { return getPlayers(server, sender); } <START> return user != null ? user.getHomes() : Collections.emptyList(); <END> } else if (args.length == 2 && canDelOthers) { try { user = getPlayer(server, args, 0, true, true); return user.getHomes(); } catch (Exception ex) { return Collections.emptyList(); } } else { return Collections.emptyList(); } }</code><technical_language>user is null - if user is null, canDelOthers is true returns 61</technical_language>

Target:
protected List<String> getTabCompleteOptions(final Server server, final CommandSource sender, final String commandLabel, final String[] args) { User user = ess.getUser(sender.getPlayer()); boolean canDelOthers = (user == null || user.isAuthorized("essentials.delhome.others")); if (args.length == 1) { return canDelOthers ? getPlayers(server, sender) : user.getHomes(); } else if (args.length == 2 && canDelOthers) { try { user = getPlayer(server, args, 0, true, true); return user.getHomes(); } catch (Exception ex) { return Collections.emptyList(); } } else { return Collections.emptyList(); } }
Source:
<code>private Collection<?> getViewerSelection() { <START> ISelection selection = viewer.getSelection(); <END> if (selection instanceof IStructuredSelection) { return ((IStructuredSelection) selection).toList(); } return Collections.emptyList(); }</code><technical_language>IStructuredViewer::getStructuredSelection</technical_language>

Target:
private Collection<?> getViewerSelection() { return fViewer.getStructuredSelection().toList(); }
Source:
<code>public void updateMissingRootDiskController(final VMInstanceVO vm, final String rootVolChainInfo) { <START> if (vm != null && vm.getType().equals(VirtualMachine.Type.User) && !Strings.isNullOrEmpty(rootVolChainInfo)) { <END> String rootDiskController = null; try { final VirtualMachineDiskInfo infoInChain = _gson.fromJson(rootVolChainInfo, VirtualMachineDiskInfo.class); if (infoInChain != null) { rootDiskController = infoInChain.getControllerFromDeviceBusName(); } final UserVmVO userVmVo = _userVmDao.findById(vm.getId()); if ((rootDiskController != null) && (!rootDiskController.isEmpty())) { _userVmDao.loadDetails(userVmVo); _userVmMgr.persistDeviceBusInfo(userVmVo, rootDiskController); } } catch (JsonParseException e) { s_logger.debug("Error parsing chain info json: " + e.getMessage()); } } }</code><technical_language>nice extraction here. short-circuit for condition line 1851? if (vm == null || !VirtualMachine.Type.User.equals(vm.getType()) || Strings.isNullOrEmpty(rootVolChainInfo)) { return; } ... rest of code (lines 1852-1865) ..</technical_language>

Target:
public void updateMissingRootDiskController(final VMInstanceVO vm, final String rootVolChainInfo) { if (vm == null || !VirtualMachine.Type.User.equals(vm.getType()) || Strings.isNullOrEmpty(rootVolChainInfo)) { return; } String rootDiskController = null; try { final VirtualMachineDiskInfo infoInChain = _gson.fromJson(rootVolChainInfo, VirtualMachineDiskInfo.class); if (infoInChain != null) { rootDiskController = infoInChain.getControllerFromDeviceBusName(); } final UserVmVO userVmVo = _userVmDao.findById(vm.getId()); if ((rootDiskController != null) && (!rootDiskController.isEmpty())) { _userVmDao.loadDetails(userVmVo); _userVmMgr.persistDeviceBusInfo(userVmVo, rootDiskController); } } catch (JsonParseException e) { s_logger.debug("Error parsing chain info json: " + e.getMessage()); } }
Source:
<code>public void prepareRun(BatchSourceContext batchSourceContext) throws Exception { <START> excelInputreaderConfig.validate(batchSourceContext.getFailureCollector()); <END> createDatasets(null, batchSourceContext); Job job = JobUtils.createInstance(); String processFiles = ""; if (!Strings.isNullOrEmpty(excelInputreaderConfig.memoryTableName)) { processFiles = GSON.toJson(getAllProcessedFiles(batchSourceContext), ARRAYLIST_PREPROCESSED_FILES); } ExcelInputFormat.setConfigurations(job, excelInputreaderConfig.filePattern, excelInputreaderConfig.sheet, excelInputreaderConfig.reprocess, excelInputreaderConfig.sheetValue, excelInputreaderConfig.columnList, excelInputreaderConfig.skipFirstRow, excelInputreaderConfig.terminateIfEmptyRow, excelInputreaderConfig.rowsLimit, excelInputreaderConfig.ifErrorRecord, processFiles); ExcelInputFormat.addInputPaths(job, excelInputreaderConfig.filePath); ExcelInputFormat.setInputPathFilter(job, ExcelReaderRegexFilter.class); SourceInputFormatProvider inputFormatProvider = new SourceInputFormatProvider(ExcelInputFormat.class, job.getConfiguration()); batchSourceContext.setInput(Input.of(excelInputreaderConfig.referenceName, inputFormatProvider)); }</code><technical_language>call getOrThrowException this method call</technical_language>

Target:
public void prepareRun(BatchSourceContext batchSourceContext) throws Exception { FailureCollector collector = batchSourceContext.getFailureCollector(); excelInputreaderConfig.validate(collector); collector.getOrThrowException(); createDatasets(batchSourceContext); collector.getOrThrowException(); Job job = JobUtils.createInstance(); String processFiles = ""; if (!Strings.isNullOrEmpty(excelInputreaderConfig.memoryTableName)) { processFiles = GSON.toJson(getAllProcessedFiles(batchSourceContext), ARRAYLIST_PREPROCESSED_FILES); } ExcelInputFormat.setConfigurations(job, excelInputreaderConfig.filePattern, excelInputreaderConfig.sheet, excelInputreaderConfig.reprocess, excelInputreaderConfig.sheetValue, excelInputreaderConfig.columnList, excelInputreaderConfig.skipFirstRow, excelInputreaderConfig.terminateIfEmptyRow, excelInputreaderConfig.rowsLimit, excelInputreaderConfig.ifErrorRecord, processFiles); ExcelInputFormat.addInputPaths(job, excelInputreaderConfig.filePath); ExcelInputFormat.setInputPathFilter(job, ExcelReaderRegexFilter.class); SourceInputFormatProvider inputFormatProvider = new SourceInputFormatProvider(ExcelInputFormat.class, job.getConfiguration()); batchSourceContext.setInput(Input.of(excelInputreaderConfig.referenceName, inputFormatProvider)); }
Source:
<code>public JSONObject getSnapshot() { <START> return new JSONObject(); <END> }</code><technical_language>curious returns new JSONObject, however, in previous test, null is returned</technical_language>

Target:
public JSONObject getSnapshot() { return null; }
Source:
<code>public void destroy() { super.destroy(); <START> producer.close(); <END> }</code><technical_language>do close in a finally block</technical_language>

Target:
public void destroy() { try { super.destroy(); } finally { if (producer != null) { producer.close(); } } }
Source:
<code><START> private static Map<CfgBlock, LiveVariables> compute(ControlFlowGraph cfg, SymbolTable symbols) { <END> Map<CfgBlock, LiveVariables> liveVariablesPerBlock = new HashMap<>(); cfg.blocks().forEach(block -> liveVariablesPerBlock.put(block, LiveVariables.init(block, symbols))); Deque<CfgBlock> workList = new ArrayDeque<>(cfg.blocks()); while (!workList.isEmpty()) { CfgBlock currentBlock = workList.pop(); LiveVariables liveVariables = liveVariablesPerBlock.get(currentBlock); boolean liveInHasChanged = liveVariables.propagateBackwards(liveVariablesPerBlock); if (liveInHasChanged) { currentBlock.predecessors().forEach(workList::push); } } return liveVariablesPerBlock; }</code><technical_language>remove static</technical_language>

Target:
private void compute(ControlFlowGraph cfg, SymbolTable symbols) { cfg.blocks().forEach(block -> liveVariablesPerBlock.put(block, LiveVariables.build(block, symbols))); Deque<CfgBlock> workList = new ArrayDeque<>(cfg.blocks()); while (!workList.isEmpty()) { CfgBlock currentBlock = workList.pop(); LiveVariables liveVariables = liveVariablesPerBlock.get(currentBlock); boolean liveInHasChanged = liveVariables.propagate(liveVariablesPerBlock); if (liveInHasChanged) { currentBlock.predecessors().forEach(workList::push); } } }
Source:
<code>public HBMessage send(HBMessage m) throws PacemakerConnectionException, InterruptedException { <START> LOG.debug("Sending pacemaker message to {}: {}", host, m.toString()); <END> int next = availableMessageSlots.take(); synchronized (m) { m.set_message_id(next); messages[next] = m; LOG.debug("Put message in slot: for {}", Integer.toString(next), host); int retry = maxRetries; while (true) { try { waitUntilReady(); Channel channel = channelRef.get(); if (channel != null) { channel.writeAndFlush(m, channel.voidPromise()); m.wait(1000); } if (messages[next] != m && messages[next] != null) { HBMessage ret = messages[next]; messages[next] = null; LOG.debug("Got Response: {}", ret); return ret; } } catch (PacemakerConnectionException e) { if (retry <= 0) { throw e; } LOG.error("error attempting to write to a channel {}.", e.getMessage()); } if (retry <= 0) { throw new PacemakerConnectionException("couldn't get response after " + maxRetries + " attempts."); } retry--; LOG.error("Not getting response or getting null response. Making more attempts for {}.", retry, host); } } }</code><technical_language>nit: drop .toString() for m? log command do for you, if is needed</technical_language>

Target:
public HBMessage send(HBMessage m) throws PacemakerConnectionException, InterruptedException { LOG.debug("Sending pacemaker message to {}: {}", host, m); int next = availableMessageSlots.take(); synchronized (m) { m.set_message_id(next); messages[next] = m; LOG.debug("Put message in slot: for {}", Integer.toString(next), host); int retry = maxRetries; while (true) { try { waitUntilReady(); Channel channel = channelRef.get(); if (channel != null) { channel.writeAndFlush(m, channel.voidPromise()); m.wait(1000); } if (messages[next] != m && messages[next] != null) { HBMessage ret = messages[next]; messages[next] = null; LOG.debug("Got Response: {}", ret); return ret; } } catch (PacemakerConnectionException e) { if (retry <= 0) { throw e; } LOG.error("error attempting to write to a channel {}.", e.getMessage()); } if (retry <= 0) { throw new PacemakerConnectionException("couldn't get response after " + maxRetries + " attempts."); } retry--; LOG.error("Not getting response or getting null response. Making more attempts for {}.", retry, host); } } }
Source:
<code>public DistributionSnapshot getSnapshot(String key, CoreSession session) { <START> if (key == null || RuntimeSnapshot.LIVE_ALIASES.contains(key)) { <END> return getRuntimeSnapshot(); } DistributionSnapshot snap = getPersistentSnapshots(session).get(key); if (snap == null && !isSiteMode()) { DistributionSnapshot rtsnap = getRuntimeSnapshot(); if (rtsnap.getKey().equals(key)) { return rtsnap; } } return snap; }</code><technical_language>remove key == null constraint? throw exception if site mode is enabled change a bit behavior of this method</technical_language>

Target:
public DistributionSnapshot getSnapshot(String key, CoreSession session) { if (RuntimeSnapshot.LIVE_ALIASES.contains(key)) { if (!canSeeRuntimeSnapshot(session)) { throw new RuntimeServiceException("Live runtime cannot be snapshotted."); } return getRuntimeSnapshot(); } DistributionSnapshot snap = getPersistentSnapshots(session).get(key); if (snap == null && canSeeRuntimeSnapshot(session)) { DistributionSnapshot rtsnap = getRuntimeSnapshot(); if (rtsnap.getKey().equals(key)) { return rtsnap; } } return snap; }
Source:
<code>public void analyzeMember(final AbstractJavaAccessNode node, final List<NameOccurrence> occurrences, final ClassScope classScope, final Object data) { if (!node.isPrivate()) { return; } for (final ASTVariableDeclarator varDecl: node.findChildrenOfType(ASTVariableDeclarator.class)) { if (varDecl.hasInitializer()) { ASTVariableInitializer varInit = varDecl.getInitializer(); List<ASTPrimaryPrefix> initPrefix = varInit.findDescendantsOfType(ASTPrimaryPrefix.class); boolean allLiterals = true; for (ASTPrimaryPrefix prefix: initPrefix) { <START> if (!prefix.getType().isPrimitive() && !TypeHelper.isA(prefix, "java.lang.String")) { <END> allLiterals = false; break; } } if (allLiterals) { return; } } } for (final NameOccurrence no : occurrences) { ClassScope usedAtScope = no.getLocation().getScope().getEnclosingScope(ClassScope.class); if (!classScope.equals(usedAtScope)) { addViolation(data, no.getLocation()); } } }</code><technical_language>checking for types means that: java private static final long NON_CONSTANT = java.util.concurrent.TimeUnit.SECONDS.toMillis(10); private static final String NON_CONSTANT_STR = NON_CONSTANT + "foo"; consider NON_CONSTANT_STR a constant string. for types, recommend checking if prefix a single ASTLiteral child (actual constants). This of course, detecting CALCULATED a compile-time constant in: java private static final int LITERAL = 0; private static final int CALCULATED = LITERAL * 2; In order get this, should, finding LITERAL in expression LITERAL * 2 symbol table get definition, analyze recursively (these results memoized for performance)</technical_language>

Target:
public void analyzeMember(final AbstractJavaAccessNode node, final List<NameOccurrence> occurrences, final ClassScope classScope, final Object data) { if (!node.isPrivate()) { return; } if (node.isFinal()) { for (final ASTVariableDeclarator varDecl: node.findChildrenOfType(ASTVariableDeclarator.class)) { if (varDecl.hasInitializer()) { ASTVariableInitializer varInit = varDecl.getInitializer(); List<ASTExpression> initExpression = varInit.findDescendantsOfType(ASTExpression.class); boolean isConstantExpression = true; constantCheck: for (ASTExpression exp: initExpression) { List<ASTPrimaryExpression> primaryExpressions = exp.findDescendantsOfType(ASTPrimaryExpression.class); for (ASTPrimaryExpression expression: primaryExpressions) { if (!isCompileTimeConstant(expression)) { isConstantExpression = false; break constantCheck; } } } if (isConstantExpression) { cache.add(varDecl.getName()); return; } } } } for (final NameOccurrence no : occurrences) { ClassScope usedAtScope = no.getLocation().getScope().getEnclosingScope(ClassScope.class); if (!classScope.equals(usedAtScope)) { addViolation(data, no.getLocation()); } } }
Source:
<code>private <Q, R> QueryResponseMessage<R> interceptAndInvoke(UnitOfWork<QueryMessage<Q, R>> uow, MessageHandler<? super QueryMessage<?, R>> handler) throws Exception { return uow.executeWithResult(() -> { ResponseType<R> responseType = uow.getMessage().getResponseType(); Object queryResponse = new DefaultInterceptorChain<>(uow, handlerInterceptors, handler).proceed(); <START> if (queryResponse instanceof Future) { <END> queryResponse = ((Future) queryResponse).get(); } return GenericQueryResponseMessage.asNullableResponseMessage( responseType.responseMessagePayloadType(), responseType.convert(queryResponse)); }); }</code><technical_language>fair you, I expected adjustment in ResponseType#convert(Object) function, adjustment in a specific QueryBus implementation. hunch is adjustments, being: 1. Adjusting default convert function in ResponeType interface perform this check. 2. Adjusting MultipleInstanceResponseType#convert(Object) function perform this check. SimpleQueryBus impl., future QueryBusy implementation, do care knowing a Future is returned not. this suggestions @m1l4n54v1c (would hear @abuijze thoughts this well)</technical_language>

Target:
private <Q, R> CompletableFuture<QueryResponseMessage<R>> interceptAndInvoke(UnitOfWork<QueryMessage<Q, R>> uow, MessageHandler<? super QueryMessage<?, R>> handler) throws Exception { return uow.executeWithResult(() -> { ResponseType<R> responseType = uow.getMessage().getResponseType(); Object queryResponse = new DefaultInterceptorChain<>(uow, handlerInterceptors, handler).proceed(); if (queryResponse instanceof CompletableFuture) { return ((CompletableFuture) queryResponse).thenCompose( result -> buildCompletableFuture(responseType, result)); } else if (queryResponse instanceof Future) { return CompletableFuture.supplyAsync(() -> { try { return ((Future) queryResponse).get(); } catch (InterruptedException | ExecutionException e) { throw new QueryExecutionException("Error happened while trying to execute query handler", e); } }); } return buildCompletableFuture(responseType, queryResponse); }); }
Source:
<code>private String parseSwing(String value) { if (value.equals("UD")) return "Ud"; <START> if (value.equals("OFF")) return "Off"; <END> return "None"; }</code><technical_language>please refactor Enumerations instead</technical_language>

Target:
private DaikinSwing parseSwing(String value) { if (value.equals("UD")) return DaikinSwing.UpDown; if (value.equals("OFF")) return DaikinSwing.Off; return DaikinSwing.None; }
Source:
<code>public List<PermissionSubject> getPermissionCheckSubjects() { List<PermissionSubject> permissionSubjects = hosts.stream() .map(host -> new PermissionSubject(host.getId(), VdcObjectType.VDS, <START> ActionGroup.CONFIGURE_HOST_NETWORK)) <END> .collect(Collectors.toList()); return permissionSubjects; }</code><technical_language>getActionType().getActionGroup() (once correct action group:))</technical_language>

Target:
public List<PermissionSubject> getPermissionCheckSubjects() { List<PermissionSubject> permissionSubjects = hosts.stream() .map(host -> new PermissionSubject(host.getId(), VdcObjectType.VDS, getActionType().getActionGroup())) .collect(Collectors.toList()); return permissionSubjects; }
Source:
<code>public void testLocateParameterizedQuery1() throws Exception { ResultSet rs = null; String sqlText = format("select id, '-' || a2 || '-', locate(?, a5) from t1 --splice-properties useSpark=%s\n order by id", useSpark); try { PreparedStatement ps = methodWatcher.prepareStatement(sqlText); ps.setBytes(1, "ac".getBytes()); rs = ps.executeQuery(); String expected = "ID | 2 | 3 |\n" + "---------------------\n" + " 1 |-abac bc- | 3 |\n" + " 2 |-abac bc- | 3 |\n" + " 3 |-abac bc- | 3 |\n" + " 4 | -ab- | 0 |\n" + " 5 | -- | 0 |\n" + " 6 | -ab- | 0 |\n" + " 7 | NULL |NULL |"; Assert.assertEquals("\n" + sqlText + "\n", expected, TestUtils.FormattedResult.ResultFactory.toString(rs)); <START> } finally { <END> if (rs != null) rs.close(); } }</code><technical_language>a try-with-resources simplify this: try (ResultSet rs = ps.executeQuery()) { } automatically close resultset for you</technical_language>

Target:
public void testLocateParameterizedQuery1() throws Exception { String sqlText = format("select id, '-' || a2 || '-', locate(?, a5) from t1 --splice-properties useSpark=%s\n order by id", useSpark); try (PreparedStatement ps = methodWatcher.prepareStatement(sqlText)) { ps.setBytes(1, "ac".getBytes()); try (ResultSet rs = ps.executeQuery()) { String expected = "ID | 2 | 3 |\n" + "---------------------\n" + " 1 |-abac bc- | 3 |\n" + " 2 |-abac bc- | 3 |\n" + " 3 |-abac bc- | 3 |\n" + " 4 | -ab- | 0 |\n" + " 5 | -- | 0 |\n" + " 6 | -ab- | 0 |\n" + " 7 | NULL |NULL |"; Assert.assertEquals("\n" + sqlText + "\n", expected, TestUtils.FormattedResult.ResultFactory.toString(rs)); } } }
Source:
<code>private static int getDefaultDataChannelCount() { int availableProcessors = Runtime.getRuntime().availableProcessors(); <START> return (int) Math.max(1, Math.ceil(availableProcessors * 2.5d)); <END> }</code><technical_language>availableProcessors() supposed return 0, I guess trust that, checking atleast 1 channel - in light do want some upper bound check well? more 250 channels</technical_language>

Target:
private static int getDefaultDataChannelCount() { int availableProcessors = Runtime.getRuntime().availableProcessors(); return (int) Math.min(250, Math.max(1, Math.ceil(availableProcessors * 2.5d))); }
Source:
<code>public void setColorspace(String colorspace) { if(!colorspace.equals(null)) { this.colorspace = colorspace; } else { <START> throw new IllegalArgumentException("Invalid colorspace value"); <END> } }</code><technical_language>This Exception message is misleading. is invalid... is simply null. message state "Colorspace null"</technical_language>

Target:
public void setColorspace(String colorspace) { if(!colorspace.equals(null)) { this.colorspace = colorspace; } else { throw new IllegalArgumentException("Colorspace value cannot be null."); } }
Source:
<code>public ValidationResult allDomainsHaveSpaceForNewDisks(final List<DiskImage> disksList) { <START> setDomainsDisksMap(disksList); <END> return validOrFirstFailure(new ValidatorPredicate() { @Override public ValidationResult evaluate(StorageDomainValidator validator) { List disksForDomain = getDomainsDisksMap().get(validator.getDomainId()); return validator.hasSpaceForNewDisks(disksForDomain); } }); }</code><technical_language>noted above, this a local variable</technical_language>

Target:
public ValidationResult allDomainsHaveSpaceForNewDisks(final List<DiskImage> disksList) { final Map<Guid, List<DiskImage>> domainsDisksMap = getDomainsDisksMap(disksList); return validOrFirstFailure(new ValidatorPredicate() { @Override public ValidationResult evaluate(Map.Entry<Guid, StorageDomainValidator> entry) { Guid sdId = entry.getKey(); List disksForDomain = domainsDisksMap.get(sdId); return getStorageDomainValidator(entry).hasSpaceForNewDisks(disksForDomain); } }); }
Source:
<code>public void testPackageWithMainlineNetworkStackPermission() throws Exception { final PackageManager packageManager = mContext.getPackageManager(); <START> assertNotNull("Network stack permission is not defined.", packageManager); <END> final PermissionInfo permissioninfo = packageManager.getPermissionInfo(PERMISSION_MAINLINE_NETWORK_STACK, 0); assertNotNull("Package defining the network stack permission is not a system package.", permissioninfo); PackageInfo packageInfo = packageManager.getPackageInfo(permissioninfo.packageName, PackageManager.MATCH_SYSTEM_ONLY | PackageManager.GET_PERMISSIONS); assertNotNull(packageInfo.permissions); for (PermissionInfo permission : packageInfo.permissions) { if (PERMISSION_MAINLINE_NETWORK_STACK.equals(permission.name)) { return; } } fail("Expect a system package defining " + PERMISSION_MAINLINE_NETWORK_STACK + " is installed."); }</code><technical_language>this next assertNotNull</technical_language>

Target:
public void testPackageWithMainlineNetworkStackPermission() throws Exception { final PackageManager packageManager = mContext.getPackageManager(); assertNotNull("Unable to find PackageManager.", packageManager); final PermissionInfo permissioninfo = packageManager.getPermissionInfo(PERMISSION_MAINLINE_NETWORK_STACK, 0); assertNotNull("Network stack permission is not defined.", permissioninfo); PackageInfo packageInfo = packageManager.getPackageInfo(permissioninfo.packageName, PackageManager.MATCH_SYSTEM_ONLY | PackageManager.GET_PERMISSIONS); assertNotNull("Package defining the network stack permission is not a system package.", packageInfo.permissions); for (PermissionInfo permission : packageInfo.permissions) { if (PERMISSION_MAINLINE_NETWORK_STACK.equals(permission.name)) { return; } } fail("Expect a system package defining " + PERMISSION_MAINLINE_NETWORK_STACK + " is installed."); }
Source:
<code>public void initializeAgentLogDir() { if (getPropertyImpl("go.agent.log.dir") == null) { String logDir = getEnvironmentVariable("LOG_DIR") == null ? "logs" : getEnvironmentVariable("LOG_DIR"); setProperty("go.agent.log.dir", logDir); } <START> } <END></code><technical_language>a similar change in AgentOutputAppender#getEffectiveLogDirectory</technical_language>

Target:
public void initializeAgentLogDir() { String logDir; logDir = getEnvironmentVariable("GO_AGENT_LOG_DIR") == null ? getEnvironmentVariable("LOG_DIR") : getEnvironmentVariable("GO_AGENT_LOG_DIR"); if (logDir == null) { logDir = "logs"; } setProperty("go.agent.log.dir", logDir); }
Source:
<code>public Rule[] blockPluginRules() { return new Rule[]{ toc(), note(), <START> cols(), <END> }; }</code><technical_language>Alphabetize these</technical_language>

Target:
public Rule[] blockPluginRules() { return new Rule[] { cols(), note(), toc(), }; }
Source:
<code>public void testPrivateBitstream() throws Exception { context.turnOffAuthorisationSystem(); parentCommunity = CommunityBuilder.createCommunity(context) .withName("Parent Community") .build(); Collection col1 = CollectionBuilder.createCollection(context, parentCommunity).withName("Collection 1").build(); Item publicItem1 = ItemBuilder.createItem(context, col1) .withTitle("Public item 1") .withIssueDate("2017-10-17") .withAuthor("Smith, Donald").withAuthor("Doe, John") .build(); Group internalGroup = GroupBuilder.createGroup(context) .withName("Internal Group") .build(); String bitstreamContent = "Private!"; try (InputStream is = IOUtils.toInputStream(bitstreamContent, CharEncoding.UTF_8)) { Bitstream bitstream = BitstreamBuilder .createBitstream(context, publicItem1, is) .withName("Test Embargoed Bitstream") .withDescription("This bitstream is embargoed") .withMimeType("text/plain") .withReaderGroup(internalGroup) .build(); getClient().perform(get("/api/core/bitstreams/" + bitstream.getID() + "/content")) <START> .andExpect(status().isForbidden()); <END> checkNumberOfStatsRecords(bitstream, 0); } }</code><technical_language>right status unauthorized 401 user is logged-in</technical_language>

Target:
public void testPrivateBitstream() throws Exception { context.turnOffAuthorisationSystem(); parentCommunity = CommunityBuilder.createCommunity(context) .withName("Parent Community") .build(); Collection col1 = CollectionBuilder.createCollection(context, parentCommunity).withName("Collection 1").build(); Item publicItem1 = ItemBuilder.createItem(context, col1) .withTitle("Public item 1") .withIssueDate("2017-10-17") .withAuthor("Smith, Donald").withAuthor("Doe, John") .build(); Group internalGroup = GroupBuilder.createGroup(context) .withName("Internal Group") .build(); String bitstreamContent = "Private!"; try (InputStream is = IOUtils.toInputStream(bitstreamContent, CharEncoding.UTF_8)) { Bitstream bitstream = BitstreamBuilder .createBitstream(context, publicItem1, is) .withName("Test Embargoed Bitstream") .withDescription("This bitstream is embargoed") .withMimeType("text/plain") .withReaderGroup(internalGroup) .build(); getClient().perform(get("/api/core/bitstreams/" + bitstream.getID() + "/content")) .andExpect(status().isUnauthorized()); checkNumberOfStatsRecords(bitstream, 0); } }
Source:
<code>protected void removeProvider(Provider<E> provider) { final Collection<E> removedElements = new LinkedList<>(); elementWriteLock.lock(); try { final Collection<E> providerElements = providerToElements.remove(provider); if (providerElements == null) { <START> logger.warn("Cannot remove provider because it is unknown."); <END> return; } for (final E element : providerElements) { try { onRemoveElement(element); } catch (final RuntimeException ex) { logger.warn( "Removal should be prevented but we need to remove the element as the provider is gone: {}", ex.getMessage(), ex); } removedElements.add(element); elements.remove(element); elementToProvider.remove(element); identifierToElement.remove(element.getUID()); } } finally { elementWriteLock.unlock(); } removedElements.forEach(this::notifyListenersAboutRemovedElement); provider.removeProviderChangeListener(this); logger.debug("Provider '{}' has been removed.", provider.getClass().getSimpleName()); }</code><technical_language>suggestion logger.warn("Cannot remove provider '{}' is unknown.", provider.getClass().getSimpleName());</technical_language>

Target:
protected void removeProvider(Provider<E> provider) { final Collection<E> removedElements = new LinkedList<>(); elementWriteLock.lock(); try { final Collection<E> providerElements = providerToElements.remove(provider); if (providerElements == null) { logger.warn("Cannot remove provider \"{}\" because it is unknown.", provider.getClass().getSimpleName()); return; } for (final E element : providerElements) { try { onRemoveElement(element); } catch (final RuntimeException ex) { logger.warn( "Removal of \"{}\" with key \"{}\" should be prevented but we need to remove the element as the provider \"{}\" is gone: {}", element.getClass().getSimpleName(), element.getUID(), provider.getClass().getSimpleName(), ex.getMessage(), ex); } removedElements.add(element); elements.remove(element); elementToProvider.remove(element); identifierToElement.remove(element.getUID()); } } finally { elementWriteLock.unlock(); } removedElements.forEach(this::notifyListenersAboutRemovedElement); provider.removeProviderChangeListener(this); logger.debug("Provider \"{}\" has been removed.", provider.getClass().getSimpleName()); }
Source:
<code>private Optional<VM> chooseNextVmToMigrateFromVMsToHostsAffinity(Cluster cluster, List<AffinityGroup> allAffinityGroups) { <START> VM vm = null; <END> List<AffinityGroup> allVMtoHostsAffinityGroups = getAllAffinityGroupsForVMsToHostsAffinity(allAffinityGroups); if (allVMtoHostsAffinityGroups.isEmpty()) { return Optional.ofNullable(vm); } Map<Guid, VM> vmsMap = getVMsMap(allVMtoHostsAffinityGroups); List<Guid> candidateVMsPositiveEnforcingAffinitiy = getCanidatesFromVMtoHostsAffinity(allVMtoHostsAffinityGroups, vmsMap, true, true); List<Guid> candidateVMsNegativeEnforcingAffinitiy = getCanidatesFromVMtoHostsAffinity(allVMtoHostsAffinityGroups, vmsMap, false, true); List<Guid> candidateVMsPositiveNonEnforcingAffinitiy = getCanidatesFromVMtoHostsAffinity(allVMtoHostsAffinityGroups, vmsMap, true, false); List<Guid> candidateVMsNegativeNonEnforcingAffinitiy = getCanidatesFromVMtoHostsAffinity(allVMtoHostsAffinityGroups, vmsMap, false, false); List<Guid> canidatesVMs = new ArrayList<>(); canidatesVMs.addAll(candidateVMsPositiveEnforcingAffinitiy); canidatesVMs.addAll(candidateVMsNegativeEnforcingAffinitiy); canidatesVMs.addAll(candidateVMsPositiveNonEnforcingAffinitiy); canidatesVMs.addAll(candidateVMsNegativeNonEnforcingAffinitiy); if (!canidatesVMs.isEmpty()) { log.info("vm to hosts affinity group violation detected"); } for (Guid id : canidatesVMs) { VM canidateVM = vmsMap.get(id); if (isVMmigrationValid(cluster, canidateVM)) { return Optional.of(canidateVM); } } return Optional.ofNullable(vm); }</code><technical_language>do need this, below</technical_language>

Target:
private Optional<VM> chooseNextVmToMigrateFromVMsToHostsAffinity(Cluster cluster, List<AffinityGroup> allAffinityGroups) { List<AffinityGroup> allVMtoHostsAffinityGroups = getAllAffinityGroupsForVMsToHostsAffinity(allAffinityGroups); if (allVMtoHostsAffinityGroups.isEmpty()) { return Optional.empty(); } Map<Guid, VM> vmsMap = getVMsMap(allVMtoHostsAffinityGroups); List<Guid> candidateVMsPositiveEnforcingAffinity = getCandidatesFromVMtoHostsAffinity(allVMtoHostsAffinityGroups, vmsMap, true, true); List<Guid> candidateVMsNegativeEnforcingAffinity = getCandidatesFromVMtoHostsAffinity(allVMtoHostsAffinityGroups, vmsMap, false, true); List<Guid> candidateVMsPositiveNonEnforcingAffinity = getCandidatesFromVMtoHostsAffinity(allVMtoHostsAffinityGroups, vmsMap, true, false); List<Guid> candidateVMsNegativeNonEnforcingAffinity = getCandidatesFromVMtoHostsAffinity(allVMtoHostsAffinityGroups, vmsMap, false, false); List<Guid> candidatesVMs = new ArrayList<>(); candidatesVMs.addAll(candidateVMsPositiveEnforcingAffinity); candidatesVMs.addAll(candidateVMsNegativeEnforcingAffinity); candidatesVMs.addAll(candidateVMsPositiveNonEnforcingAffinity); candidatesVMs.addAll(candidateVMsNegativeNonEnforcingAffinity); if (!candidatesVMs.isEmpty()) { log.info("vm to hosts affinity group violation detected"); } for (Guid id : candidatesVMs) { VM canidateVM = vmsMap.get(id); if (isVmMigrationValid(cluster, canidateVM)) { return Optional.of(canidateVM); } } return Optional.empty(); }
Source:
<code>public void test_eviction_eviction_prioritizer_not_specified() throws Exception { UserManagedCache<Number, String> cache = UserManagedCacheBuilder.newUserManagedCacheBuilder(Number.class, String.class, LoggerFactory <START> .getLogger(Ehcache.class + "-" + "StandaloneCacheEvictionTest1")) <END> .withResourcePools(newResourcePoolsBuilder().heap(1, EntryUnit.ENTRIES).build()) .build(true); assertThat(cache.getRuntimeConfiguration().getResourcePools().getPoolForResource(ResourceType.Core.HEAP).getSize(), equalTo(1L)); for (int i = 0; i < 3; i++) { cache.putIfAbsent(i, "" + i); } int nullValuesFound = 0; for (int i = 0; i < 3; i++) { String retrievedValue = cache.get(i); if (retrievedValue == null) { nullValuesFound ++; } } assertThat("The capacity of the store is 1, and we found more than 1 non empty value in it !", nullValuesFound, is(2)); }</code><technical_language>Need change name</technical_language>

Target:
public void test_eviction_eviction_prioritizer_not_specified() throws Exception { UserManagedCache<Number, String> cache = UserManagedCacheBuilder.newUserManagedCacheBuilder(Number.class, String.class, LoggerFactory .getLogger(Ehcache.class + "-" + "UserManagedCacheEvictionTest1")) .withResourcePools(newResourcePoolsBuilder().heap(1, EntryUnit.ENTRIES).build()) .build(true); assertThat(cache.getRuntimeConfiguration().getResourcePools().getPoolForResource(ResourceType.Core.HEAP).getSize(), equalTo(1L)); for (int i = 0; i < 3; i++) { cache.putIfAbsent(i, "" + i); } int nullValuesFound = 0; for (int i = 0; i < 3; i++) { String retrievedValue = cache.get(i); if (retrievedValue == null) { nullValuesFound ++; } } assertThat("The capacity of the store is 1, and we found more than 1 non empty value in it !", nullValuesFound, is(2)); }