auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private List evaluateExpressionsInContext(EvaluationContext ctx, List expressions) { List results = new ArrayList(); for (Object v : expressions) { try { ctx.enterFrame(); ctx.setValue("item", v); ctx.setRootObject(v); Object r = this.filter.evaluate(ctx); if (r == null) { <START> return null; <END> } if (r instanceof Boolean && ((Boolean) r) == Boolean.TRUE) { results.add(v); } } finally { ctx.exitFrame(); } } return results; }</code><technical_language>Page 113 of spec says: "The filter expression is evaluated for item in list, a list items filter expression is true is returned." Based other similar cases in spec, for a filter returns other "true", including "null" errors, result empty list, null</technical_language>

Target:
private List evaluateExpressionsInContext(EvaluationContext ctx, List expressions) { List results = new ArrayList(); expressions.forEach(expression -> evaluateExpressionInContext( ctx, results, expression)); return results; }
Source:
<code>protected Object calculate() { StringBuilder sb = new StringBuilder(); try { <START> StringTokenizer tokenizer = new StringTokenizer(expression, "$", true); <END> if (expression.isEmpty() || tokenizer.countTokens() == 0) { throw new IllegalArgumentException("Expression must not be empty."); } boolean inExpression = false; boolean foundToken = false; while (tokenizer.hasMoreTokens()) { String token = tokenizer.nextToken(); if (token.equals("$")) { if (inExpression && !foundToken) { throw new IllegalArgumentException("Empty reference ($$) in message is not allowed."); } inExpression = !inExpression; } else if (inExpression) { IObservableValue value = expressionMap.get(token); sb.append(value.getValue()); foundToken = true; } else { sb.append(token); } } if (inExpression) { throw new IllegalArgumentException("Inconsistent model references - a $ character is missing."); } } catch (IllegalArgumentException e) { return "ERROR: " + e.getMessage(); } return sb.toString(); }</code><technical_language>expression is parsed time getter is called. tokens cached in initializeObservableMap</technical_language>

Target:
protected Object calculate() { StringBuilder sb = new StringBuilder(); try { for (int i = 0; i < expressionTokens.size(); i++) { String token = expressionTokens.get(i); if ((i % 2) == 0) { Preconditions.checkState(expressionMap.containsKey(token), "Error while parsing expression " + token); IObservableValue value = expressionMap.get(token); sb.append(value.getValue()); } else { sb.append(token); } } } catch (Exception e) { return "ERROR: " + e.getMessage(); } return sb.toString(); }
Source:
<code>private void verifyAPIAvailableInPublisher(String apiName) throws Exception { HttpResponse response = apiPublisher.getAPI(apiName, API_CREATOR_PUBLISHER_USER, API_VERSION); log.info("Check API available in publisher response code for API \'" + apiName + "\' : " + response.getResponseCode()); log.info("Check API available in publisher response data for API \'" + apiName + "\' : " + response.getData()); <START> assertTrue(response.getData().contains(apiName), <END> "API deletion successful for API : " + apiName); assertFalse(new JSONObject(response.getData()).getBoolean("error"), "API deletion successful for API : " + apiName); }</code><technical_language>If response data contains apiName, api is deleted</technical_language>

Target:
private void verifyAPIAvailableInPublisher(String apiName) throws Exception { HttpResponse response = apiPublisher.getAPI(apiName, API_CREATOR_PUBLISHER_USERNAME, API_VERSION); log.info("Check API available in publisher response code for API \'" + apiName + "\' : " + response.getResponseCode()); log.info("Check API available in publisher response data for API \'" + apiName + "\' : " + response.getData()); assertTrue(response.getData().contains(apiName), "API has been delete : " + apiName); assertFalse(new JSONObject(response.getData()).getBoolean("error"), "API has been deleted : " + apiName); }
Source:
<code>public void run() { LOG.debug("Starting lease keep-alive thread."); while (!leaseFreed) { try { Thread.sleep(LEASE_RENEWAL_PERIOD); } catch (InterruptedException e) { LOG.debug("Keep-alive thread for lease " + leaseID + " interrupted."); Thread.currentThread().interrupt(); } try { if (!leaseFreed) { store.renewLease(path, leaseID); <START> LOG.info("Renewed lease " + leaseID + " on " + path); <END> } } catch (IOException e) { if (!leaseFreed) { leaseFreed = true; LOG.warn("Attempt to renew lease " + leaseID + " on " + path + " failed, but lease not yet freed. Reason: " + e.getMessage()); } } } }</code><technical_language>tied in FileSystem instance lifecycle too: FS instance a weak ref leases created it, fs.close stop</technical_language>

Target:
public void run() { LOG.debug("Starting lease keep-alive thread."); while (!leaseFreed) { try { Thread.sleep(LEASE_RENEWAL_PERIOD); } catch (InterruptedException e) { LOG.debug("Keep-alive thread for lease interrupted", leaseID); Thread.currentThread().interrupt(); } try { if (!leaseFreed) { LOG.debug("lease path: {}, renew lease id: {}", path, leaseID); client.renewLease(getRelativePath(path), leaseID); LOG.info("Renewed lease on {}", leaseID, path); } } catch (IOException e) { if (!leaseFreed) { leaseFreed = true; LOG.warn("Attempt to renew lease on failed, stopping renewal thread: ", leaseID, path, e.getMessage()); LOG.debug("Exception renewing lease", e); } } } }
Source:
<code>public VmDevice mapRow(ResultSet rs, int rowNum) throws SQLException { VmDevice vmDevice = new VmDevice(); vmDevice.setId(new VmDeviceId(Guid.createGuidFromString(rs.getString("device_id")), Guid.createGuidFromString(rs .getString("vm_id")))); vmDevice.setDevice(rs.getString("device")); vmDevice.setType(VmDeviceGeneralType.forValue(rs.getString("type"))); vmDevice.setAddress(rs.getString("address")); vmDevice.setBootOrder(rs.getInt("boot_order")); String specParams = rs.getString("spec_params"); if (StringUtils.isEmpty(specParams)) { vmDevice.setSpecParams(new HashMap<String, Object>()); } else { vmDevice.setSpecParams(SerializationFactory .getDeserializer() .deserialize(specParams, HashMap.class)); } vmDevice.setIsManaged(rs.getBoolean("is_managed")); vmDevice.setIsPlugged(rs.getBoolean("is_plugged")); vmDevice.setIsReadOnly(rs.getBoolean("is_readonly")); vmDevice.setAlias(rs.getString("alias")); <START> vmDevice.setCustomProperties(rs.getString("custom_properties")); <END> return vmDevice; }</code><technical_language>translated Map<String, String> string. above, done in future</technical_language>

Target:
public VmDevice mapRow(ResultSet rs, int rowNum) throws SQLException { VmDevice vmDevice = new VmDevice(); vmDevice.setId(new VmDeviceId(Guid.createGuidFromString(rs.getString("device_id")), Guid.createGuidFromString(rs .getString("vm_id")))); vmDevice.setDevice(rs.getString("device")); vmDevice.setType(VmDeviceGeneralType.forValue(rs.getString("type"))); vmDevice.setAddress(rs.getString("address")); vmDevice.setBootOrder(rs.getInt("boot_order")); String specParams = rs.getString("spec_params"); if (StringUtils.isEmpty(specParams)) { vmDevice.setSpecParams(new HashMap<String, Object>()); } else { vmDevice.setSpecParams(SerializationFactory .getDeserializer() .deserialize(specParams, HashMap.class)); } vmDevice.setIsManaged(rs.getBoolean("is_managed")); vmDevice.setIsPlugged(rs.getBoolean("is_plugged")); vmDevice.setIsReadOnly(rs.getBoolean("is_readonly")); vmDevice.setAlias(rs.getString("alias")); vmDevice.setCustomProperties(DevicePropertiesUtils.getInstance() .convertProperties(rs.getString("custom_properties"))); return vmDevice; }
Source:
<code>public Object resolveArgument(MethodParameter parameter, Message<?> message) throws Exception { Object value = message.getPayload(); if (this.canProcessMessageList) { Assert.state(value instanceof Collection, <START> "This Argument Resolver support only messages with payload as Collection<Message<?>>"); <END> Collection<Message<?>> messages = (Collection<Message<?>>) value; parameter.increaseNestingLevel(); if (Message.class.isAssignableFrom(parameter.getNestedParameterType())) { value = messages; } else { value = messages.stream() .map(Message::getPayload) .collect(Collectors.toList()); } parameter.decreaseNestingLevel(); } if (Iterator.class.isAssignableFrom(parameter.getParameterType())) { if (value instanceof Iterable) { return ((Iterable) value).iterator(); } else { return Collections.singleton(value).iterator(); } } else { return getEvaluationContext() .getTypeConverter() .convertValue(value, TypeDescriptor.forObject(value), TypeDescriptor.valueOf(parameter.getParameterType())); } }</code><technical_language>s/support only/only supports/ s/with payload as/with a payload of/</technical_language>

Target:
public Object resolveArgument(MethodParameter parameter, Message<?> message) throws Exception { Object value = message.getPayload(); if (this.canProcessMessageList) { Assert.state(value instanceof Collection, "This Argument Resolver only supports messages with a payload of Collection<Message<?>>"); Collection<Message<?>> messages = (Collection<Message<?>>) value; parameter.increaseNestingLevel(); if (Message.class.isAssignableFrom(parameter.getNestedParameterType())) { value = messages; } else { value = messages.stream() .map(Message::getPayload) .collect(Collectors.toList()); } parameter.decreaseNestingLevel(); } if (Iterator.class.isAssignableFrom(parameter.getParameterType())) { if (value instanceof Iterable) { return ((Iterable) value).iterator(); } else { return Collections.singleton(value).iterator(); } } else { return getEvaluationContext() .getTypeConverter() .convertValue(value, TypeDescriptor.forObject(value), TypeDescriptor.valueOf(parameter.getParameterType())); } }
Source:
<code>public <T> T setComponent(final Class<T> type, final T value) { T removed = null; if (value == null) { <START> removed = (T) components.get(type); <END> components.remove(type); } else { removed = (T) components.put(type, value); } if (removed != null) { fireEvent(new ComponentRemoved(type, value)); } if (value != null) { fireEvent(new ComponentAdded(type, value)); } return removed; }</code><technical_language>remove() returns removed value, need for get() remove()</technical_language>

Target:
public <T> T setComponent(final Class<T> type, final T value) { final T removed = (T) components.put(type, value); if (removed != null) { fireEvent(new ComponentRemoved(type, value)); } if (value != null) { fireEvent(new ComponentAdded(type, value)); } return removed; }
Source:
<code>public void validateNodeAndNpmVersion() { try { List<String> nodeVersionCommand = new ArrayList<>(); nodeVersionCommand.add(getNodeExecutable()); nodeVersionCommand.add("--version"); FrontendVersion foundNodeVersion = FrontendUtils.getVersion("node", nodeVersionCommand); <START> if (!ignoreVersionChecks) { <END> FrontendUtils.validateToolVersion("node", foundNodeVersion, SUPPORTED_NODE_VERSION, SHOULD_WORK_NODE_VERSION); } } catch (UnknownVersionException e) { getLogger().warn("Error checking if node is new enough", e); } try { List<String> npmVersionCommand = new ArrayList<>( getNpmExecutable(false)); npmVersionCommand.add("--version"); FrontendVersion npmVersion = FrontendUtils.getVersion("npm", npmVersionCommand); if (!ignoreVersionChecks) { FrontendUtils.validateToolVersion("npm", npmVersion, SUPPORTED_NPM_VERSION, SHOULD_WORK_NPM_VERSION); } checkForFaultyNpmVersion(npmVersion); } catch (UnknownVersionException e) { getLogger().warn("Error checking if npm is new enough", e); } }</code><technical_language>I avoid version check getVersion if anyway: takes additional time throw exception catching is more expensive check a condition. blocking though. benefit current code is logging failed version check this is failed internally: node of some version able detect it. internal issue anyway. I spend significant time checking anyway</technical_language>

Target:
public void validateNodeAndNpmVersion() { if (ignoreVersionChecks) { return; } try { List<String> nodeVersionCommand = new ArrayList<>(); nodeVersionCommand.add(getNodeExecutable()); nodeVersionCommand.add("--version"); FrontendVersion foundNodeVersion = FrontendUtils.getVersion("node", nodeVersionCommand); FrontendUtils.validateToolVersion("node", foundNodeVersion, SUPPORTED_NODE_VERSION, SHOULD_WORK_NODE_VERSION); } catch (UnknownVersionException e) { getLogger().warn("Error checking if node is new enough", e); } try { List<String> npmVersionCommand = new ArrayList<>( getNpmExecutable(false)); npmVersionCommand.add("--version"); FrontendVersion npmVersion = FrontendUtils.getVersion("npm", npmVersionCommand); FrontendUtils.validateToolVersion("npm", npmVersion, SUPPORTED_NPM_VERSION, SHOULD_WORK_NPM_VERSION); checkForFaultyNpmVersion(npmVersion); } catch (UnknownVersionException e) { getLogger().warn("Error checking if npm is new enough", e); } }
Source:
<code>public void testVisibilityForAnotherUserInOtherDomainInPublisher() throws APIManagerIntegrationTestException, ApiException { <START> APIListDTO getAllApisResponse = restAPIPublisherOtherDomainUser.getAllAPIs("carbon.super"); <END> assertFalse(APIMTestCaseUtils.isAPIAvailable(apiIdentifier, getAllApisResponse), "API is visible to another user in other domain in API Publisher. When Visibility is private." + getAPIIdentifierString(apiIdentifier)); }</code><technical_language>Lets constant here</technical_language>

Target:
public void testVisibilityForAnotherUserInOtherDomainInPublisher() throws APIManagerIntegrationTestException, ApiException { APIListDTO getAllApisResponse = restAPIPublisherOtherDomainUser .getAllAPIs(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); assertFalse(APIMTestCaseUtils.isAPIAvailable(apiIdentifier, getAllApisResponse), "API is visible to another user in other domain in API Publisher. When Visibility is private." + getAPIIdentifierString(apiIdentifier)); }
Source:
<code>private boolean setupPerspectiveStack(IEclipseContext context) { IPerspectiveRegistry registry = getWorkbench().getPerspectiveRegistry(); String forcedPerspectiveId = (String) context.get(E4Workbench.FORCED_PERSPECTIVE_ID); if (forcedPerspectiveId != null) { perspective = registry.findPerspectiveWithId(forcedPerspectiveId); if (perspective != null) { return false; } } List<MPerspectiveStack> perspStackList = modelService.findElements(model, null, MPerspectiveStack.class, null); MPerspectiveStack perspStack = !perspStackList.isEmpty() ? perspStackList.get(0) : null; if (perspStack != null && perspStack.getSelectedElement() != null) { perspective = registry.findPerspectiveWithId(perspStack.getSelectedElement() .getElementId()); <START> if (perspective != null) { <END> return false; } } if (perspective == null) { perspective = registry.findPerspectiveWithId(registry.getDefaultPerspective()); } return true; }</code><technical_language>newWindow is false in this case (the perspective stack a selected element). need calculate this if forcedPerspectiveId set</technical_language>

Target:
private boolean setupPerspectiveStack(IEclipseContext context) { IPerspectiveRegistry registry = getWorkbench().getPerspectiveRegistry(); String forcedPerspectiveId = (String) context.get(E4Workbench.FORCED_PERSPECTIVE_ID); if (forcedPerspectiveId != null) { perspective = registry.findPerspectiveWithId(forcedPerspectiveId); } List<MPerspectiveStack> perspStackList = modelService.findElements(model, null, MPerspectiveStack.class, null); MPerspective selectedPersp = null; if (!perspStackList.isEmpty()) { selectedPersp = perspStackList.get(0).getSelectedElement(); } if (perspective == null && selectedPersp != null) { perspective = registry.findPerspectiveWithId(selectedPersp.getElementId()); } if (perspective == null) { perspective = registry.findPerspectiveWithId(registry.getDefaultPerspective()); } return selectedPersp == null; }
Source:
<code>protected CallStackAnalysis() { super(); fCallGraph = new CallGraphAnalysis(); ISegmentStore<CallStackEdge> links; try { <START> File segStoreFile = new File(String.valueOf(getId()) + LINKS_SUFFIX); <END> links = SegmentStoreFactory.<@NonNull CallStackEdge> createOnDiskSegmentStore(Objects.requireNonNull(segStoreFile.toPath()), CallStackEdge.READER); } catch (IOException e) { links = SegmentStoreFactory.createSegmentStore(SegmentStoreType.Fast); } fLinks = links; }</code><technical_language>1- this in supplementary files automagically, right? 2- get path directory, Paths.get, avoid a File a toPath</technical_language>

Target:
protected CallStackAnalysis() { super(); fCallGraph = new CallGraphAnalysis(); }
Source:
<code>public void testBatchTranslateTextWithGlossaryAndModel() throws InterruptedException, ExecutionException, IOException, TimeoutException { BatchTranslateTextWithGlossaryAndModel.batchTranslateTextWithGlossaryAndModel( PROJECT_ID, "en", "ja", INPUT_URI, <START> "gs://" + PROJECT_ID + "/" + PREFIX_PATH, <END> GLOSSARY_ID, MODEL_ID); String got = bout.toString(); assertThat(got).contains("Total Characters: 25"); }</code><technical_language>Ok - I this, I if String.format a bit clearer, decided longer, I wish get rid of string contraction</technical_language>

Target:
public void testBatchTranslateTextWithGlossaryAndModel() throws InterruptedException, ExecutionException, IOException, TimeoutException { BatchTranslateTextWithGlossaryAndModel.batchTranslateTextWithGlossaryAndModel( PROJECT_ID, "en", "ja", INPUT_URI, OUTPUT_URI, GLOSSARY_ID, MODEL_ID); String got = bout.toString(); assertThat(got).contains("Total Characters: 25"); }
Source:
<code><START> public Boolean checkCanSyncSolr(String studyId, String userId) throws CatalogException { <END> return true; }</code><technical_language>Change primitives: boolean checkCanSyncSolr(...)</technical_language>

Target:
public boolean checkCanSyncSolr(String studyId, String userId) throws CatalogException { if ("admin".equals(userId)) { return true; } return true; }
Source:
<code>private void listComprehension(StringBuilder sb, String fromNodeVar, Relationship relationship, Node node, int level, int depth) { String direction = relationship.direction(node); Node toNode = relationship.other(node); String relVar = relVariableName(relationship, level); String toNodeVar = variableName(toNode, level); sb.append("[ ("); sb.append(fromNodeVar); sb.append(")"); switch (direction) { case INCOMING: appendRel(sb, relVar, relationship.type(), "<-[", "]-"); break; case OUTGOING: appendRel(sb, relVar, relationship.type(), "-[", "]->"); break; default: appendRel(sb, relVar, relationship.type(), "-[", "]-"); break; } sb.append("("); sb.append(toNodeVar); <START> if (toNode.label() != null) { <END> sb.append(":`"); sb.append(toNode.label()); sb.append("`"); } sb.append(") | [ "); sb.append(relVar); sb.append(", "); sb.append(toNodeVar); if (depth > 0 && !toNode.relationships().isEmpty()) { sb.append(", [ "); expand(sb, toNodeVar, toNode, level + 1, depth - 1); sb.append(" ]"); } sb.append(" ] ]"); }</code><technical_language>Introduce hasLabel() Node</technical_language>

Target:
private void listComprehension(StringBuilder sb, String fromNodeVar, Relationship relationship, Node node, int level, int depth) { String direction = relationship.direction(node); Node toNode = relationship.other(node); String relVar = relVariableName(relationship, level); String toNodeVar = variableName(toNode, level); sb.append("[ ("); sb.append(fromNodeVar); sb.append(")"); switch (direction) { case INCOMING: appendRel(sb, relVar, relationship.type(), "<-[", "]-"); break; case OUTGOING: appendRel(sb, relVar, relationship.type(), "-[", "]->"); break; default: appendRel(sb, relVar, relationship.type(), "-[", "]-"); break; } sb.append("("); sb.append(toNodeVar); if (toNode.label().isPresent()) { sb.append(":`"); sb.append(toNode.label().get()); sb.append("`"); } sb.append(") | [ "); sb.append(relVar); sb.append(", "); sb.append(toNodeVar); if (depth > 0 && !toNode.relationships().isEmpty()) { sb.append(", [ "); expand(sb, toNodeVar, toNode, level + 1, depth - 1); sb.append(" ]"); } sb.append(" ] ]"); }
Source:
<code>public void processExpiration() { long start = 0; if (!Thread.currentThread().isInterrupted()) { try { if (trace) { log.trace("Purging data container of expired entries"); start = timeService.time(); } List<CompletableFuture> futures = new ArrayList<>(MAX_ASYNC_EXPIRATIONS); long currentTimeMillis = timeService.wallClockTime(); LocalizedCacheTopology topology = distributionManager.getCacheTopology(); IntSet segments = IntSets.from(topology.getReadConsistentHash().getPrimarySegmentsForOwner(localAddress)); <START> dataContainer.running().forEachIncludingExpired(segments, (ice, segment) -> { <END> if (ice.canExpire()) { boolean expiredMortal; boolean expiredTransient; V value; long lifespan; long maxIdle; synchronized (ice) { value = ice.getValue(); lifespan = ice.getLifespan(); maxIdle = ice.getMaxIdle(); expiredMortal = ExpiryHelper.isExpiredMortal(lifespan, ice.getCreated(), currentTimeMillis); expiredTransient = ExpiryHelper.isExpiredTransient(maxIdle, ice.getLastUsed(), currentTimeMillis); } if (expiredMortal) { addAndWaitIfFull(handleLifespanExpireEntry(ice.getKey(), value, lifespan, false), futures); } else if (expiredTransient) { addAndWaitIfFull(actualRemoveMaxIdleExpireEntry(ice.getKey(), value, maxIdle, false), futures); } } }); if (!futures.isEmpty()) { futures.forEach(CompletableFuture::join); } if (trace) { log.tracef("Purging data container completed in %s", Util.prettyPrintTime(timeService.timeDuration(start, TimeUnit.MILLISECONDS))); } } catch (Exception e) { log.exceptionPurgingDataContainer(e); } } if (!Thread.currentThread().isInterrupted()) { persistenceManager.purgeExpired(); } }</code><technical_language>Could/should stop processing expiration topology changes? Detecting change is cheap, distributionManager.getCacheTopology() != topology</technical_language>

Target:
public void processExpiration() { if (!Thread.currentThread().isInterrupted()) { LocalizedCacheTopology topology; do { topology = distributionManager.getCacheTopology(); } while (purgeInMemoryContents(topology)); } if (!Thread.currentThread().isInterrupted()) { persistenceManager.purgeExpired(); } }
Source:
<code>public void compareEqLongToInt() { assertThat(UnindexedMatcher.compareEq(1l, 1), is(true)); assertThat(UnindexedMatcher.compareEq(1, 1l), is(true)); assertThat(UnindexedMatcher.compareEq(1l, 2), is(false)); assertThat(UnindexedMatcher.compareEq(2, 1l), is(false)); <START> } <END></code><technical_language>Do need do boxing manually instead of relying autoboxing for compareEq tests? compareEq autobox inputs dictionaries boxing happened? want passing Integers Doubles in, ensuring work, passing in Floats ensuring don't. statically import compareEq if possible</technical_language>

Target:
public void compareEqLongToInt() { assertThat(compareEq(new Long(1l), new Integer(1)), is(true)); assertThat(compareEq(new Integer(1), new Long(1l)), is(true)); assertThat(compareEq(new Long(1l), new Integer(2)), is(false)); assertThat(compareEq(new Integer(2), new Long(1l)), is(false)); }
Source:
<code>public String getTimestamp() { <START> return new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()); <END> }</code><technical_language>Suggestion: extract new SimpleDateFormat("yyyyMMddHHmmss") a private static final constant</technical_language>

Target:
public String getTimestamp() { return DATE_FORMAT.format(new Date()); }
Source:
<code>public void setUp() throws Exception { super.setUp(); receivedEvents.clear(); messageQueueRegistry.clear(); messageExecutionRegistry.clear(); startCountDownLatch = new CountDownLatch(1); waitingCountDownLatchRef.set(new CountDownLatch(1)); runtimeService.addEventListener(spyMessageListener, ActivitiEventType.ACTIVITY_MESSAGE_SENT, ActivitiEventType.ACTIVITY_MESSAGE_WAITING, ActivitiEventType.ACTIVITY_MESSAGE_RECEIVED); runtimeService.addEventListener(catchMessageListener, ActivitiEventType.ACTIVITY_MESSAGE_WAITING); newEventSubscriptionQuery().eventType("message") .list() .stream() .forEach(subscription -> { Optional<String> correlationKey = Optional.of(subscription) .filter(it -> it.getProcessInstanceId() != null) .map(it -> it.getConfiguration()); SubscriptionKey key = new SubscriptionKey(subscription.getEventName(), correlationKey); BlockingQueue<ThrowMessage> messageQueue = registerSubscription(key, correlationKey); new Thread(() -> { try { ThrowMessage throwMessage = messageQueue.take(); String messageName = throwMessage.getName(); Map<String, Object> payload = throwMessage.getPayload() .orElse(null); String businessKey = throwMessage.getBusinessKey() .orElse(null); runtimeService.startProcessInstanceByMessage(messageName, businessKey, payload); startCountDownLatch.countDown(); } catch (InterruptedException e) { e.printStackTrace(); <START> } <END> }).start(); }); }</code><technical_language>logs instead</technical_language>

Target:
public void setUp() throws Exception { super.setUp(); receivedEvents.clear(); messageQueueRegistry.clear(); messageExecutionRegistry.clear(); startCountDownLatch = new CountDownLatch(1); waitingCountDownLatchRef.set(new CountDownLatch(1)); runtimeService.addEventListener(spyMessageListener, ActivitiEventType.ACTIVITY_MESSAGE_SENT, ActivitiEventType.ACTIVITY_MESSAGE_WAITING, ActivitiEventType.ACTIVITY_MESSAGE_RECEIVED); runtimeService.addEventListener(catchMessageListener, ActivitiEventType.ACTIVITY_MESSAGE_WAITING); initExistingMessageSubscriptions(); }
Source:
<code>public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; RepositoryTreeNode other = (RepositoryTreeNode) obj; if (myType == null) { if (other.myType != null) return false; } else if (!myType.equals(other.myType)) return false; if (myParent == null) { if (other.myParent != null) return false; } else if (!myParent.equals(other.myParent)) return false; if (myType == RepositoryTreeNodeType.REPOGROUP && other.myType == RepositoryTreeNodeType.REPOGROUP) { return <START> hashCode() == other.hashCode(); <END> } if (myRepository == null) { if (other.myRepository != null) { return false; } } else { if (other.myRepository == null) { return false; } if (!myRepository.getDirectory() .equals(other.myRepository.getDirectory())) { return false; } } if (myObject == null) { if (other.myObject != null) { return false; } } else { if (other.myObject == null) { return false; } if (!checkObjectsEqual(other.myObject)) { return false; } } return true; }</code><technical_language>contract of hashCode</technical_language>

Target:
public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; RepositoryTreeNode other = (RepositoryTreeNode) obj; if (myType == null) { if (other.myType != null) return false; } else if (!myType.equals(other.myType)) return false; if (considerParent(myType)) { if (myParent == null) { if (other.myParent != null) { return false; } } else if (!myParent.equals(other.myParent)) { return false; } } if (myType == RepositoryTreeNodeType.REPOGROUP && other.myType == RepositoryTreeNodeType.REPOGROUP) { RepositoryGroup myGroup = ((RepositoryGroupNode)this).getGroup(); RepositoryGroup otherGroup = ((RepositoryGroupNode)other).getGroup(); return myGroup.getGroupId().equals(otherGroup.getGroupId()) && myGroup.getName().equals(otherGroup.getName()); } if (myRepository == null) { if (other.myRepository != null) { return false; } } else { if (other.myRepository == null) { return false; } if (!myRepository.getDirectory() .equals(other.myRepository.getDirectory())) { return false; } } if (myObject == null) { if (other.myObject != null) { return false; } } else { if (other.myObject == null) { return false; } if (!checkObjectsEqual(other.myObject)) { return false; } } return true; }
Source:
<code><START> public void setFirstReference(PDOMLinkage linkage, PDOMName name) throws CoreException { <END> PDOMName head = null; Iterator iterator = new Iterator(record); while(head == null) { if (iterator.next == null) break; if (!linkage.equals(iterator.next.getLinkage())) iterator.next = iterator.advance(); else head = iterator.next; } if (head == null) add(name); else { long nextNameRec = iterator.node + Database.INT_SIZE + Database.PTR_SIZE; pdom.getDB().putRecPtr(nextNameRec, name == null ? 0 : name.getRecord()); } }</code><technical_language>Implementation of this method exceedingly complex. simplify is clear this method is achieve</technical_language>

Target:
public void setFirstReference(PDOMLinkage linkage, PDOMName name) throws CoreException { PDOMName head = null; Iterator iterator = new Iterator(record); while (head == null) { if (iterator.next == null) break; if (!linkage.equals(iterator.next.getLinkage())) { iterator.next = iterator.advance(); } else { head = iterator.next; } } if (head == null) { add(name); } else { long nextNameRec = iterator.node + Database.INT_SIZE + Database.PTR_SIZE; pdom.getDB().putRecPtr(nextNameRec, name == null ? 0 : name.getRecord()); } }
Source:
<code>public void before() throws Exception { CacheConfiguration<Integer, String> cacheConfiguration = CacheConfigurationBuilder .newCacheConfigurationBuilder(Integer.class, String.class, resources) .withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofMillis(TIME_TO_EXPIRATION))) .build(); <START> StatisticsService statisticsService = new DefaultStatisticsService(new DefaultStatisticsServiceConfiguration()); <END> cacheManager = CacheManagerBuilder.newCacheManagerBuilder() .withCache("cache", cacheConfiguration) .using(new DefaultPersistenceConfiguration(diskPath.newFolder())) .using(statisticsService) .using(new TimeSourceConfiguration(timeSource)) .build(true); cache = cacheManager.getCache("cache", Integer.class, String.class); tierStatistics = statisticsService.getCacheStatistics("cache") .getTierStatistics().get(tierName); }</code><technical_language>a default constructor for DefaultStatisticsService creating a DefaultStaticticsServiceConfiguration sense</technical_language>

Target:
public void before() throws Exception { CacheConfiguration<Integer, String> cacheConfiguration = CacheConfigurationBuilder .newCacheConfigurationBuilder(Integer.class, String.class, resources) .withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofMillis(TIME_TO_EXPIRATION))) .build(); StatisticsService statisticsService = new DefaultStatisticsService(); cacheManager = CacheManagerBuilder.newCacheManagerBuilder() .withCache("cache", cacheConfiguration) .using(new DefaultPersistenceConfiguration(diskPath.newFolder())) .using(statisticsService) .using(new TimeSourceConfiguration(timeSource)) .build(true); cache = cacheManager.getCache("cache", Integer.class, String.class); tierStatistics = statisticsService.getCacheStatistics("cache") .getTierStatistics().get(tierName); }
Source:
<code>public Session getSessionForHost(URI uri) throws IOException { if (session != null && !session.getHost().equals(uri.getHost())) { close(); } if (session == null || !session.isConnected()) { try { int port = uri.getPort() <= 0 ? 22 : uri.getPort(); session = jsch.getSession(clientProvider.getUsername(), uri.getHost(), port); session.setConfig("StrictHostKeyChecking", "no"); session.setPassword(clientProvider.getPassword()); session.connect(); } catch (JSchException ex) { <START> throw new IOException("Unable to connect to server", ex); <END> } } return session; }</code><technical_language>log this properly too, I think. Errors in this class bubble inspected easily</technical_language>

Target:
public Session getSessionForHost(URI uri) throws IOException { if (session != null && !session.getHost().equals(uri.getHost())) { close(); } if (session == null || !session.isConnected()) { try { int port = uri.getPort() <= 0 ? 22 : uri.getPort(); session = jsch.getSession(clientProvider.getUsername(), uri.getHost(), port); session.setConfig("StrictHostKeyChecking", "no"); session.setPassword(clientProvider.getPassword()); session.connect(); } catch (JSchException ex) { String msg = String.format("Unable to connect to host {}", uri.toString()); LOG.error(msg,ex); throw new IOException(msg, ex); } } return session; }
Source:
<code>public void testPinSingleTrace() { assertEquals(CALL_STACK_VIEW_TITLE, fOriginalViewBot.getTitle()); SWTBotToolbarDropDownButton toolbarDropDownButton = fOriginalViewBot.toolbarDropDownButton(PIN_VIEW_BUTTON_NAME); toolbarDropDownButton.menuItem(PIN_TO_PREFIX + fUstTestTrace.getName()).click(); <START> assertRenamed(PINNED_CALL_STACK_VIEW_TITLE); <END> fOriginalViewBot.toolbarButton(UNPIN_VIEW_BUTTON_NAME).click(); assertRenamed(CALL_STACK_VIEW_TITLE); fOriginalViewBot.toolbarButton(PIN_VIEW_BUTTON_NAME).click(); assertRenamed(PINNED_CALL_STACK_VIEW_TITLE); }</code><technical_language>this method is called check view *not* renames... assertOriginalViewTitle()</technical_language>

Target:
public void testPinSingleTrace() { assertEquals(CALL_STACK_VIEW_TITLE, fOriginalViewBot.getTitle()); SWTBotToolbarDropDownButton toolbarDropDownButton = fOriginalViewBot.toolbarDropDownButton(PIN_VIEW_BUTTON_NAME); toolbarDropDownButton.menuItem(PIN_TO_PREFIX + fUstTestTrace.getName()).click(); assertOriginalViewTitle(PINNED_TO_UST_CALL_STACK_VIEW_TITLE); fOriginalViewBot.toolbarButton(UNPIN_VIEW_BUTTON_NAME).click(); assertOriginalViewTitle(CALL_STACK_VIEW_TITLE); fOriginalViewBot.toolbarButton(PIN_VIEW_BUTTON_NAME).click(); assertOriginalViewTitle(PINNED_TO_UST_CALL_STACK_VIEW_TITLE); }
Source:
<code>private synchronized void record() { final long now = System.currentTimeMillis(); final long lastPeriodSeconds = (now - this.lastStartTime) / 1000; this.lastStartTime = now; final long seconds = (now - startTime) / 1000; final String elapsed = formatElapseTime(seconds); final String period = pad(fmt.format(lastPeriodSeconds), 4); final String processed = pad(fmt.format(this.processed), 13); final String readInfo; if (this.lastChrom == null) readInfo = "*/*"; else readInfo = this.lastChrom + ":" + fmt.format(this.lastPos); final String rnInfo; if(lastRN != null) { rnInfo = ", last read name: " + lastRN; } else { rnInfo = ""; <START> } <END> final long n = (this.processed % this.n == 0) ? this.n : this.processed % this.n; log(this.verb, " ", processed, " " + noun + ". Elapsed time: ", elapsed, "s. Time for last ", fmt.format(n), ": ", period, "s. Last read position: ", readInfo, rnInfo); }</code><technical_language>formatting consistent rest of code</technical_language>

Target:
private synchronized void record() { final long now = System.currentTimeMillis(); final long lastPeriodSeconds = (now - this.lastStartTime) / 1000; this.lastStartTime = now; final long seconds = (now - startTime) / 1000; final String elapsed = formatElapseTime(seconds); final String period = pad(fmt.format(lastPeriodSeconds), 4); final String processed = pad(fmt.format(this.processed), 13); final String readInfo; if (this.lastChrom == null) readInfo = "*/*"; else readInfo = this.lastChrom + ":" + fmt.format(this.lastPos); final String rnInfo; if(lastReadName != null) { rnInfo = ". Last read name: " + lastReadName; } else { rnInfo = ""; } final long n = (this.processed % this.n == 0) ? this.n : this.processed % this.n; log(this.verb, " ", processed, " " + noun + ". Elapsed time: ", elapsed, "s. Time for last ", fmt.format(n), ": ", period, "s. Last read position: ", readInfo, rnInfo); }
Source:
<code>public void destroyTask(@PathVariable("name") String name, @RequestParam(required = false) Boolean cleanup) { <START> if (cleanup != null && cleanup.equals(Boolean.TRUE)) { <END> Set<Long> taskExecutionIds = this.dataflowTaskExecutionDao.getTaskExecutionIdsByTaskName(name); final Set<TaskExecutionControllerDeleteAction> actionsAsSet = new HashSet<>(); actionsAsSet.add(TaskExecutionControllerDeleteAction.CLEANUP); actionsAsSet.add(TaskExecutionControllerDeleteAction.REMOVE_DATA); if (!taskExecutionIds.isEmpty()) { this.taskDeleteService.cleanupExecutions(actionsAsSet, taskExecutionIds); } } this.taskDeleteService.deleteTaskDefinition(name); }</code><technical_language>Feel free argue me. move consideration of deleting a task executions service vs. in controller</technical_language>

Target:
public void destroyTask(@PathVariable("name") String name, @RequestParam(required = false) Boolean cleanup) { boolean taskExecutionCleanup = (cleanup != null && cleanup) ? cleanup : false; this.taskDeleteService.deleteTaskDefinition(name, taskExecutionCleanup); }
Source:
<code>public synchronized void waitUntilAllOperationsAreDone() throws InterruptedException { while(!pendingOperationsWithSize.isEmpty()) { if (lastOperationChange + MAX_UNCHANGED_WAIT_MS < System.currentTimeMillis()) { long lastUpdated = (System.currentTimeMillis() - lastOperationChange) / 1000; LOG.warn("No operations completed within the last %d seconds." + "There are still %d operations in progress.", lastUpdated, pendingOperationsWithSize.size()); <START> break; <END> } wait(WAIT_MILLIS); } }</code><technical_language>change break for a sleep? do want warn MAX_UNCHANGED_WAIT_MS</technical_language>

Target:
public synchronized void waitUntilAllOperationsAreDone() throws InterruptedException { boolean performedWarning = false; while(!pendingOperationsWithSize.isEmpty()) { if (!performedWarning && lastOperationChange + INTERVAL_NO_SUCCESS_WARNING < System.currentTimeMillis()) { long lastUpdated = (System.currentTimeMillis() - lastOperationChange) / 1000; LOG.warn("No operations completed within the last %d seconds." + "There are still %d operations in progress.", lastUpdated, pendingOperationsWithSize.size()); performedWarning = true; } wait(WAIT_MILLIS); } if (performedWarning) { LOG.info("flush() completed"); } }
Source:
<code>private void putUpWebUI() throws IOException { int port = conf.getInt(HBASE_CANARY_INFO_PORT, -1); if (port < 0) { return; } <START> if (zookeeperMode) { <END> LOG.info("WebUI is not supported in Zookeeper mode"); } else if (regionServerMode) { LOG.info("WebUI is not supported in RegionServer mode"); } else { String addr = conf.get("hbase.canary.info.bindAddress", "0.0.0.0"); try { InfoServer infoServer = new InfoServer("canary", addr, port, false, conf); infoServer.addUnprivilegedServlet("canary", "/canary-status", CanaryStatusServlet.class); infoServer.setAttribute("sink", this.sink); infoServer.start(); LOG.info("Bind Canary http info server to {}:{} ", addr, port); } catch (BindException e) { LOG.warn("Failed binding Canary http info server to {}:{}", addr, port, e); } } }</code><technical_language>removing static final declaration string literal directly</technical_language>

Target:
private void putUpWebUI() throws IOException { int port = conf.getInt(HBASE_CANARY_INFO_PORT, -1); if (port < 0) { return; } if (zookeeperMode) { LOG.info("WebUI is not supported in Zookeeper mode"); } else if (regionServerMode) { LOG.info("WebUI is not supported in RegionServer mode"); } else { String addr = conf.get(HBASE_CANARY_INFO_BINDADDRESS, "0.0.0.0"); try { InfoServer infoServer = new InfoServer("canary", addr, port, false, conf); infoServer.addUnprivilegedServlet("canary", "/canary-status", CanaryStatusServlet.class); infoServer.setAttribute("sink", this.sink); infoServer.start(); LOG.info("Bind Canary http info server to {}:{} ", addr, port); } catch (BindException e) { LOG.warn("Failed binding Canary http info server to {}:{}", addr, port, e); } } }
Source:
<code>public void prepareToCloseChannels() { for ( Channel channel : allChannels ) { BoltProtocol protocol = BoltProtocol.forChannel( channel ); try { protocol.prepareToCloseChannel( channel ); } catch ( Throwable e ) { <START> log.debug( "Failed to destruct Channel %s due to error %s. " + <END> "It is safe to ignore this error as the channel will be closed despite if it is successfully destructed.", channel, e.getMessage() ); } } }</code><technical_language>reword this a bit remove "destruct"</technical_language>

Target:
public void prepareToCloseChannels() { for ( Channel channel : allChannels ) { BoltProtocol protocol = BoltProtocol.forChannel( channel ); try { protocol.prepareToCloseChannel( channel ); } catch ( Throwable e ) { log.debug( "Failed to prepare to close Channel %s due to error %s. " + "It is safe to ignore this error as the channel will be closed despite if it is successfully prepared to close or not.", channel, e.getMessage() ); } } }
Source:
<code>private static ValidationResult checkForStructuresWithoutMedia(Workpiece workpiece, Map<String, String> translations) { boolean error = false; boolean warning = false; Collection<String> messages = new HashSet<>(); Collection<String> structuresWithoutMedia = treeStream(workpiece.getRootElement(), IncludedStructuralElement::getChildren) .filter(structure -> structure.getViews().isEmpty()) .map(structure -> translations.get(MESSAGE_STRUCTURE_WITHOUT_MEDIA) + ' ' + structure) .collect(Collectors.toSet()); if (!structuresWithoutMedia.isEmpty()) { messages.addAll(structuresWithoutMedia); warning = true; } if (!treeStream(workpiece.getRootElement(), IncludedStructuralElement::getChildren) .flatMap(structure -> structure.getViews().stream()).map(View::getMediaUnit) <START> .anyMatch(workpiece.getMediaUnits()::contains)) { <END> messages.add(translations.get(MESSAGE_MEDIA_MISSING)); error = true; } return new ValidationResult(error ? State.ERROR : warning ? State.WARNING : State.SUCCESS, messages); }</code><technical_language>replace anyMatch allMatch here, is a validator error if _none_ of media in physical structure tree. However, error message if _only one_ is in physical tree</technical_language>

Target:
private static ValidationResult checkForStructuresWithoutMedia(Workpiece workpiece, Map<String, String> translations) { boolean error = false; boolean warning = false; Collection<String> messages = new HashSet<>(); Collection<String> structuresWithoutMedia = treeStream(workpiece.getRootElement(), IncludedStructuralElement::getChildren) .filter(structure -> structure.getViews().isEmpty()) .map(structure -> translations.get(MESSAGE_STRUCTURE_WITHOUT_MEDIA) + ' ' + structure) .collect(Collectors.toSet()); if (!structuresWithoutMedia.isEmpty()) { messages.addAll(structuresWithoutMedia); warning = true; } if (!treeStream(workpiece.getRootElement(), IncludedStructuralElement::getChildren) .flatMap(structure -> structure.getViews().stream()).map(View::getMediaUnit) .allMatch(workpiece.getMediaUnits()::contains)) { messages.add(translations.get(MESSAGE_MEDIA_MISSING)); error = true; } return new ValidationResult(error ? State.ERROR : warning ? State.WARNING : State.SUCCESS, messages); }
Source:
<code>private <ResponseType> ResponseType handleResponseFuture( final ListenableFuture<ResponseType> responseListenableFuture ) { final ResponseType response; try { response = responseListenableFuture.get(); } catch (final ExecutionException | InterruptedException e) { <START> throw new GenieRuntimeException("Failed to perform request"); <END> } return response; }</code><technical_language>add e trickles properly</technical_language>

Target:
private <ResponseType> ResponseType handleResponseFuture( final ListenableFuture<ResponseType> responseListenableFuture ) { final ResponseType response; try { response = responseListenableFuture.get(); } catch (final ExecutionException | InterruptedException e) { throw new GenieRuntimeException("Failed to perform request", e); } return response; }
Source:
<code>protected Statement withAfters(FrameworkMethod method, Object target, Statement statement) { List<FrameworkMethod> afters = getTestClass().getAnnotatedMethods(After.class); Statement nextStatement = statement; List<TestRule> testRules = getTestRules(target); ExpectedException expectedException = null; if (!testRules.isEmpty()) { for (TestRule rule : testRules) { if (rule instanceof BounceMemberRule) { nextStatement = ((BounceMemberRule) rule).stopBouncing(statement); } if (rule instanceof ExpectedException) { <START> expectsException = true; <END> } } } if (THREAD_DUMP_ON_FAILURE) { return new ThreadDumpAwareRunAfters(method, nextStatement, afters, target, expectedException); } if (afters.isEmpty()) { return nextStatement; } else { return new RunAfters(nextStatement, afters, target); } }</code><technical_language>this expectedException = rule</technical_language>

Target:
protected Statement withAfters(FrameworkMethod method, Object target, Statement statement) { List<FrameworkMethod> afters = getTestClass().getAnnotatedMethods(After.class); Statement nextStatement = statement; List<TestRule> testRules = getTestRules(target); ExpectedException expectedException = null; if (!testRules.isEmpty()) { for (TestRule rule : testRules) { if (rule instanceof BounceMemberRule) { nextStatement = ((BounceMemberRule) rule).stopBouncing(statement); } if (rule instanceof ExpectedException) { expectedException = (ExpectedException) rule; } } } if (THREAD_DUMP_ON_FAILURE) { return new ThreadDumpAwareRunAfters(method, nextStatement, afters, target, expectedException); } if (afters.isEmpty()) { return nextStatement; } else { return new RunAfters(nextStatement, afters, target); } }
Source:
<code>public void onStart() { super.onStart(); <START> mHandler.sendEmptyMessage(-1); <END> mHandler.sendMessageDelayed(mHandler.obtainMessage(0), 1000); }</code><technical_language>more message, please descriptive labels in place of 0 -1. E.g. private static final int ENABLE_BUTTONS = 0;... DISABLE_BUTTONS = 1</technical_language>

Target:
public void onStart() { super.onStart(); mHandler.sendEmptyMessage(DISABLE_BUTTONS); mHandler.sendMessageDelayed(mHandler.obtainMessage(ENABLE_BUTTONS), 1000); }
Source:
<code>public void processPresign( Response response, AuthnRequest authnRequest, List<String> spMetadata, Set<Binding> supportedBindings) { Subject authnRequestSubject = authnRequest.getSubject(); if (authnRequestSubject == null) { return; } NameID authnRequestNameId = authnRequestSubject.getNameID(); if (authnRequestNameId == null) { return; } String authnRequestId = authnRequestNameId.getValue(); if (StringUtils.isBlank(authnRequestNameId.getValue())) { return; } if (!authnRequestSubject.getSubjectConfirmations().isEmpty()) { throw new SAMLRuntimeException( "The AuthnRequest contained a Subject with both a NameID and " <START> + "1 or more SubjectConfirmations"); <END> } if (getIdsFromResponseAsStream(response).noneMatch(authnRequestId::equals)) { throw new SAMLRuntimeException( String.format( "The AuthnRequest's Subject (with the NameID of %s) could not be matched against any " + "identifiers in the resulting Response (with the primary NameID of %s).", authnRequestId, getIdsFromResponseAsStream(response).findFirst().orElse(null))); } }</code><technical_language>Good catch spec requirement I this message is a misleading a NameID subject confirmations. spec is explicit, I this message NameID check put of checks for NameID</technical_language>

Target:
public void processPresign( Response response, AuthnRequest authnRequest, List<String> spMetadata, Set<Binding> supportedBindings) { Subject authnRequestSubject = authnRequest.getSubject(); if (authnRequestSubject == null) { return; } if (!authnRequestSubject.getSubjectConfirmations().isEmpty()) { throw new SAMLRuntimeException( "The AuthnRequest contained a Subject with 1 or more SubjectConfirmations."); } NameID authnRequestNameId = authnRequestSubject.getNameID(); if (authnRequestNameId == null) { return; } String authnRequestId = authnRequestNameId.getValue(); if (StringUtils.isBlank(authnRequestId)) { return; } if (idsFromResponseAsStream(response).noneMatch(authnRequestId::equals)) { throw new SAMLRuntimeException( String.format( "The AuthnRequest's Subject (with the NameID of %s) could not be matched against any " + "identifiers in the resulting Response (with the primary NameID of %s).", authnRequestId, nameIdsFromResponseAsStream(response).findFirst().orElse(null))); } }