auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void triggerPipeline(Pipeline pipeline) { Observable<OrcaService.TriggerResponse> orcaResponse = createTriggerObservable(pipeline) .retryWhen(new RetryWithDelay(retryCount, retryDelayMillis)) .doOnNext(this::onOrcaResponse) .doOnError(throwable -> onOrcaError(pipeline, throwable)); if (pipeline.getTrigger() != null && pipeline.getTrigger().isPropagateAuth()) { orcaResponse.subscribe(); } else { User korkUser = new User(); if (fiatStatus.isEnabled() && pipeline.getTrigger() != null) { korkUser.setEmail(pipeline.getTrigger().getRunAsUser()); } try { AuthenticatedRequest.propagate(() -> orcaResponse.subscribe(), korkUser).call(); } catch (Exception e) { <START> registry.counter("orca.error").increment(); <END> log.error("Unable to trigger pipeline {}: {}", pipeline, e); } } }</code><technical_language>consider: add class of exception a tag. bit helps understand errors rising a graph helps</technical_language>

Target:
private void triggerPipeline(Pipeline pipeline) { Observable<OrcaService.TriggerResponse> orcaResponse = createTriggerObservable(pipeline) .retryWhen(new RetryWithDelay(retryCount, retryDelayMillis)) .doOnNext(this::onOrcaResponse) .doOnError(throwable -> onOrcaError(pipeline, throwable)); if (pipeline.getTrigger() != null && pipeline.getTrigger().isPropagateAuth()) { orcaResponse.subscribe(); } else { User korkUser = new User(); if (fiatStatus.isEnabled() && pipeline.getTrigger() != null) { korkUser.setEmail(pipeline.getTrigger().getRunAsUser()); } try { AuthenticatedRequest.propagate(() -> orcaResponse.subscribe(), korkUser).call(); } catch (Exception e) { registry.counter("orca.error", "exception", e.getClass().getName()).increment(); log.error("Unable to trigger pipeline {}: {}", pipeline, e); } } }
Source:
<code><START> public javax.ws.rs.core.Response toResponse(InvalidValueException e) { <END> Fault fault = new Fault(); fault.setReason("Invalid Value"); fault.setDetail(e.getMessage()); return Response.status(Response.Status.BAD_REQUEST).entity(fault).build(); }</code><technical_language>Do need fully qualified class name here</technical_language>

Target:
public Response toResponse(InvalidValueException e) { Fault fault = new Fault(); fault.setReason("Invalid Value"); fault.setDetail(e.getMessage()); return Response.status(Response.Status.BAD_REQUEST).entity(fault).build(); }
Source:
<code>public void setup() { super.setup(); virtualGuestApi = api.getVirtualGuestApi(); datacenter = Iterables.get(api.getDatacenterApi().listDatacenters(), 0); <START> if (datacenter == null) Assert.fail(); <END> }</code><technical_language>assertNotNull a meaningful message</technical_language>

Target:
public void setup() { super.setup(); virtualGuestApi = api.getVirtualGuestApi(); datacenter = Iterables.get(api.getDatacenterApi().listDatacenters(), 0); assertNotNull(datacenter, "Datacenter must not be null"); }
Source:
<code>public Multimap<String, String> getMultimap() { <START> final ImmutableMultimap.Builder<String, String> builder = ImmutableMultimap.builder(); <END> for (final String key : headers.keySet()) { builder.putAll(key, headers.get(key)); } return builder.build(); }</code><technical_language>builder a method: <LINK_0> copy contents of a multimap, manually perform copy</technical_language>

Target:
public Multimap<String, String> getMultimap() { final ImmutableMultimap.Builder<String, String> builder = ImmutableMultimap.builder(); builder.putAll(headers); return builder.build(); }
Source:
<code>private String constructNicsWithNetworksString(Map<String, Set<String>> nicsWithNetworks) { StringBuilder nicsWithNetworksBuilder = new StringBuilder(); for (Entry<String, Set<String>> nicToNetworks : nicsWithNetworks.entrySet()) { nicsWithNetworksBuilder.append(nicToNetworks.getKey()); nicsWithNetworksBuilder.append(" ("); for (String network : nicToNetworks.getValue()) { nicsWithNetworksBuilder.append(network); nicsWithNetworksBuilder.append(", "); } nicsWithNetworksBuilder.delete(nicsWithNetworksBuilder.length() - 2, nicsWithNetworksBuilder.length()); nicsWithNetworksBuilder.append("), "); } String nicsWithNetworksString = nicsWithNetworksBuilder.toString(); return nicsWithNetworksBuilder.delete(nicsWithNetworksString.length() - 2, nicsWithNetworksString.length()) <START> .toString(); <END> }</code><technical_language>get result more readability IMO: List<String> reportedNics = new ArrayList<>(nicsWithNetworks.size()); for (Entry<String, Set<String>> nicToNetworks : nicsWithNetworks.entrySet()) { reportedNics.add(String.format("%s (%s)", nicToNetworks.getKey(), StringUtils.join(nicToNetworks.getValue(), ", "))); } return StringUtils.join(reportedNics, ", ");</technical_language>

Target:
private String constructNicsWithNetworksString(Map<String, Set<String>> nicsWithNetworks) { List<String> reportedNics = new ArrayList<>(nicsWithNetworks.size()); for (Entry<String, Set<String>> nicToNetworks : nicsWithNetworks.entrySet()) { reportedNics.add(String.format("%s (%s)", nicToNetworks.getKey(), StringUtils.join(nicToNetworks.getValue(), ", "))); } return StringUtils.join(reportedNics, ", "); }
Source:
<code>public String toString() { StringBuilder builder = new StringBuilder(); for (LogReplicationMetadataType type : LogReplicationMetadataType.values()) { builder.append(type).append(": "); switch (type) { case TOPOLOGY_CONFIG_ID: builder.append(getTopologyConfigId()); break; case LAST_SNAPSHOT_STARTED: builder.append(getLastSnapStartTimestamp()); break; case LAST_SNAPSHOT_TRANSFERRED: builder.append(getLastSnapTransferDoneTimestamp()); break; case LAST_SNAPSHOT_APPLIED: builder.append(getLastAppliedBaseSnapshotTimestamp()); break; case LAST_SNAPSHOT_SEQ_NUM: builder.append(getLastSnapSeqNum()); break; case LAST_LOG_ENTRY_PROCESSED: builder.append(getLastProcessedLogTimestamp()); break; case REMAINING_REPLICATION_PERCENT: <START> builder.append(getReplicationRemainingPercent()); <END> default: } builder.append(" "); } return builder.toString(); }</code><technical_language>break;</technical_language>

Target:
public String toString() { StringBuilder builder = new StringBuilder(); for (LogReplicationMetadataType type : LogReplicationMetadataType.values()) { builder.append(type).append(": "); switch (type) { case TOPOLOGY_CONFIG_ID: builder.append(getTopologyConfigId()); break; case LAST_SNAPSHOT_STARTED: builder.append(getLastSnapStartTimestamp()); break; case LAST_SNAPSHOT_TRANSFERRED: builder.append(getLastSnapTransferDoneTimestamp()); break; case LAST_SNAPSHOT_APPLIED: builder.append(getLastAppliedBaseSnapshotTimestamp()); break; case LAST_SNAPSHOT_SEQ_NUM: builder.append(getLastSnapSeqNum()); break; case LAST_LOG_ENTRY_PROCESSED: builder.append(getLastProcessedLogTimestamp()); break; default: } builder.append(" "); } builder.append("Replication Completion: "); Map<String, ReplicationStatusVal> replicationStatusMap = getReplicationRemainingPercent(); replicationStatusMap.entrySet().forEach( entry -> builder.append(entry.getKey()) .append(entry.getValue().getReplicationCompletion())); builder.append("Data Consistent: ").append(getDataConsistentOnStandby()); return builder.toString(); }
Source:
<code>protected RowExpression visitSearchedCaseExpression(SearchedCaseExpression node, Void context) { END to: RowExpression lhsArg = null; for (WhenClause whenClause : node.getWhenClauses()) { Expression predicate = whenClause.getOperand(); <START> if (ExpressionTreeUtils.isEqualComparisonExpression(predicate) || <END> ExpressionTreeUtils.isInValuesComparisonExpression(predicate)) { RowExpression operand = process(predicate.getChildren().get(0), context); if (lhsArg != null && !operand.equals(lhsArg)) { lhsArg = null; break; } lhsArg = operand; } else { lhsArg = null; break; } } if (lhsArg != null) { ImmutableList.Builder<WhenClause> newWhenClauses = ImmutableList.builder(); for (WhenClause whenClause : node.getWhenClauses()) { if (ExpressionTreeUtils.isInValuesComparisonExpression(whenClause.getOperand())) { for (Expression value : ((InListExpression) ((InPredicate) whenClause.getOperand()).getValueList()).getValues()) { newWhenClauses.add(new WhenClause(value, whenClause.getResult())); } } else { newWhenClauses.add( new WhenClause( (Expression) whenClause.getOperand().getChildren().get(1), whenClause.getResult())); } } return buildSwitch(lhsArg, newWhenClauses.build(), node.getDefaultValue(), getType(node), context); } END return buildSwitch(new ConstantExpression(true, BOOLEAN), node.getWhenClauses(), node.getDefaultValue(), getType(node), context); }</code><technical_language>static import</technical_language>

Target:
protected RowExpression visitSearchedCaseExpression(SearchedCaseExpression node, Void context) { END to: RowExpression caseOperand = null; for (WhenClause whenClause : node.getWhenClauses()) { Expression predicate = whenClause.getOperand(); if (isEqualComparisonExpression(predicate) || isInValuesComparisonExpression(predicate)) { RowExpression operand = process(predicate.getChildren().get(0), context); if (caseOperand != null && !operand.equals(caseOperand)) { caseOperand = null; break; } caseOperand = operand; } else { caseOperand = null; break; } } if (caseOperand != null) { ImmutableList.Builder<WhenClause> newWhenClauses = ImmutableList.builder(); for (WhenClause whenClause : node.getWhenClauses()) { if (isInValuesComparisonExpression(whenClause.getOperand())) { for (Expression value : ((InListExpression) ((InPredicate) whenClause.getOperand()).getValueList()).getValues()) { newWhenClauses.add(new WhenClause(value, whenClause.getResult())); } } else { newWhenClauses.add( new WhenClause( (Expression) whenClause.getOperand().getChildren().get(1), whenClause.getResult())); } } return buildSwitch(caseOperand, newWhenClauses.build(), node.getDefaultValue(), getType(node), context); } END return buildSwitch(new ConstantExpression(true, BOOLEAN), node.getWhenClauses(), node.getDefaultValue(), getType(node), context); }
Source:
<code>protected <T> T doFindOne(String collectionName, DBObject query, DBObject fields, Class<T> entityClass) { EntityReader<? super T, DBObject> readerToUse = this.mongoConverter; MongoPersistentEntity<?> entity = mappingContext.getPersistentEntity(entityClass); DBObject mappedQuery = queryMapper.getMappedObject(query, entity); DBObject mappedFields = entity == null ? fields : fields == null ? null : queryMapper.getMappedObject(fields, entity); <START> return executeFindOneInternal(new FindOneCallback(mappedQuery, mappedFields), new ReadDbObjectCallback<T>( <END> readerToUse, entityClass), collectionName); }</code><technical_language>this is place in MongoTemplate need massage fields</technical_language>

Target:
protected <T> T doFindOne(String collectionName, DBObject query, DBObject fields, Class<T> entityClass) { EntityReader<? super T, DBObject> readerToUse = this.mongoConverter; MongoPersistentEntity<?> entity = mappingContext.getPersistentEntity(entityClass); DBObject mappedQuery = queryMapper.getMappedObject(query, entity); DBObject mappedFields = fields == null ? null : queryMapper.getMappedObject(fields, entity); return executeFindOneInternal(new FindOneCallback(mappedQuery, mappedFields), new ReadDbObjectCallback<T>( readerToUse, entityClass), collectionName); }
Source:
<code>private void endProcessTracingSpan(Context processSpanContext, Signal<Void> signal) { if (!processSpanContext.getData("scope").isPresent() || tracerProvider == null) { return; } <START> Closeable close = (Closeable) processSpanContext.getData("scope").get(); <END> try { close.close(); } catch (IOException ioException) { logger.error("EventProcessor.run() endTracingSpan().close() failed with an error %s", ioException); } tracerProvider.endSpan(processSpanContext, signal); }</code><technical_language>get data once, processSpanContext.getData("scope"). save this in a local variable call twice</technical_language>

Target:
private void endProcessTracingSpan(Context processSpanContext, Signal<Void> signal) { Optional<Object> spanScope = processSpanContext.getData("scope"); if (!spanScope.isPresent() || !tracerProvider.isEnabled()) { return; } if (spanScope.get() instanceof Closeable) { Closeable close = (Closeable) processSpanContext.getData("scope").get(); try { close.close(); tracerProvider.endSpan(processSpanContext, signal); } catch (IOException ioException) { logger.error("EventProcessor.run() endTracingSpan().close() failed with an error %s", ioException); } } else { logger.warning(String.format(Locale.US, "Process span scope type is not of type Closeable, but type: %s. Not closing the scope and span", spanScope.get() != null ? spanScope.getClass() : "null")); } }
Source:
<code>public String translate(final WebApplicationService targetService, final String triggerValue) { for (final Pattern pattern : translationMap.keySet()) { if (pattern.matcher(triggerValue).matches()) { return this.translationMap.get(pattern); } } if (this.ignoreIfNoMatchIsFound) { return defaultMfaMethod; } <START> throw new UnrecognizedAuthenticationMethodException("MFA Method for " + triggerValue, targetService.getId()); <END> }</code><technical_language>This needs triggerValue, a message. in throw new UnrecognizedAuthenticationMethodException(triggerValue, targetService.getId());</technical_language>

Target:
public String translate(final WebApplicationService targetService, final String triggerValue) { for (final Pattern pattern : translationMap.keySet()) { if (pattern.matcher(triggerValue).matches()) { return this.translationMap.get(pattern); } } if (this.defaultMfaMethod != null) { return defaultMfaMethod; } throw new UnrecognizedAuthenticationMethodException(triggerValue, targetService.getId()); }
Source:
<code>private Map<String, Object> getAttributes() { Map<String, <START> Object> attributeValues <END> = new HashMap<String, Object>(); for (String attribute : this.attributes) { int equalsIndex = -1; if((equalsIndex = attribute.indexOf(ATTRIBUTE_SEPARATOR)) > -1) { extractAttributeNameAndValue(attributeValues, attribute, equalsIndex); } else { attributeValues.put(attribute, ""); } } return attributeValues; }</code><technical_language>produce String values map String</technical_language>

Target:
private Map<String, Object> getAttributes() { Map<String, Object> attributeValues = new HashMap<String, Object>(); for (String attribute : attributes) { int equalsIndex = attribute.indexOf(ATTRIBUTE_SEPARATOR); if(equalsIndex > -1) { String attributeName = attribute.substring(0, equalsIndex); String attributeValue = attribute.substring(equalsIndex+1, attribute.length()); attributeValues.put(attributeName, attributeValue); } else { attributeValues.put(attribute, ""); } } return attributeValues; }
Source:
<code>public GoalResource toResource(GoalDTO goal) { GoalResource goalResource = instantiateResource(goal); ControllerLinkBuilder selfLinkBuilder = getGoalLinkBuilder(userID, goal); addSelfLink(selfLinkBuilder, goalResource); <START> addRemoveLink(selfLinkBuilder, goalResource); <END> return goalResource; }</code><technical_language>Rename addEditLink, is added</technical_language>

Target:
public GoalResource toResource(GoalDTO goal) { GoalResource goalResource = instantiateResource(goal); ControllerLinkBuilder selfLinkBuilder = getGoalLinkBuilder(userID, goal); addSelfLink(selfLinkBuilder, goalResource); addEditLink(selfLinkBuilder, goalResource); return goalResource; }
Source:
<code>public static TopologyAPI.Config.Builder getConfigBuilder(Config config) { TopologyAPI.Config.Builder cBldr = TopologyAPI.Config.newBuilder(); Set<String> apiVars = config.getApiVars(); for (String key : config.keySet()) { <START> Object value = config.get(key); <END> if (key == null) { LOG.warning("ignore: null config key found"); continue; } if (value == null) { LOG.warning("ignore: config key " + key + " has null value"); continue; } TopologyAPI.Config.KeyValue.Builder b = TopologyAPI.Config.KeyValue.newBuilder(); b.setKey(key); if (apiVars.contains(key)) { b.setType(TopologyAPI.ConfigValueType.STRING_VALUE); b.setValue(value.toString()); } else { b.setType(TopologyAPI.ConfigValueType.JAVA_SERIALIZED_VALUE); b.setSerializedValue(ByteString.copyFrom(serialize(value))); } cBldr.addKvs(b); } return cBldr; }</code><technical_language>check if key is null fetching value</technical_language>

Target:
public static TopologyAPI.Config.Builder getConfigBuilder(Config config) { TopologyAPI.Config.Builder cBldr = TopologyAPI.Config.newBuilder(); Set<String> apiVars = config.getApiVars(); for (String key : config.keySet()) { if (key == null) { LOG.warning("ignore: null config key found"); continue; } Object value = config.get(key); if (value == null) { LOG.warning("ignore: config key " + key + " has null value"); continue; } TopologyAPI.Config.KeyValue.Builder b = TopologyAPI.Config.KeyValue.newBuilder(); b.setKey(key); if (apiVars.contains(key)) { b.setType(TopologyAPI.ConfigValueType.STRING_VALUE); b.setValue(value.toString()); } else { b.setType(TopologyAPI.ConfigValueType.JAVA_SERIALIZED_VALUE); b.setSerializedValue(ByteString.copyFrom(serialize(value))); } cBldr.addKvs(b); } return cBldr; }
Source:
<code>public LgoProductCurrency( @JsonProperty("id") String id, @JsonProperty("increment") BigDecimal increment, @JsonProperty("limits") LgoLimit limits) { this.id = id; <START> this.increment = increment != null ? increment.stripTrailingZeros() : null; <END> this.limits = limits; }</code><technical_language>DTOs represent exchange, this is premature adaptation</technical_language>

Target:
public LgoProductCurrency( @JsonProperty("id") String id, @JsonProperty("increment") BigDecimal increment, @JsonProperty("limits") LgoLimit limits) { this.id = id; this.increment = increment; this.limits = limits; }
Source:
<code>public boolean isEmpty() { <START> return blockBuilder == null || blockBuilder.getPositionCount() == 0; <END> }</code><technical_language>Change part of || assert (verify)</technical_language>

Target:
public boolean isEmpty() { if (blockBuilder == null) { return true; } verify(blockBuilder.getPositionCount() != 0); return false; }
Source:
<code>protected void verifyAssumptionFailure(String... parameters) throws Exception { try { Action c = gaeSimulation.getActionObject(uri, parameters); c.executeAndPostProcess(); signalFailureToDetectException(); } catch (Throwable e) { assertTrue(e instanceof AssertionError); <START> ignoreExpectedException(); <END> } }</code><technical_language>need for this change</technical_language>

Target:
protected void verifyAssumptionFailure(String... parameters) throws Exception { try { Action c = gaeSimulation.getActionObject(uri, parameters); c.executeAndPostProcess(); signalFailureToDetectException(); } catch (AssertionError e) { ignoreExpectedException(); } }
Source:
<code>public static IndexDocumentBuilder getIndexBuilder(File file, IndexWriter writer, TaggedValuePointable nodep, ArrayBackedValueStorage abvsFileNode, ITreeNodeIdProvider nodeIdProvider, ByteBufferInputStream bbis, DataInputStream di, String nodeId) throws IOException { <START> XMLParser parser = new XMLParser(false, nodeIdProvider, nodeId); <END> FunctionHelper.readInDocFromString(file.getPath(), bbis, di, abvsFileNode, parser); nodep.set(abvsFileNode.getByteArray(), abvsFileNode.getStartOffset(), abvsFileNode.getLength()); return new IndexDocumentBuilder(nodep, writer, file.getCanonicalPath()); }</code><technical_language>change IParser</technical_language>

Target:
public static IndexDocumentBuilder getIndexBuilder(File file, IndexWriter writer, TaggedValuePointable nodep, ArrayBackedValueStorage abvsFileNode, ITreeNodeIdProvider nodeIdProvider, ByteBufferInputStream bbis, DataInputStream di, String nodeId) throws IOException { IParser parser = new XMLParser(false, nodeIdProvider, nodeId); FunctionHelper.readInDocFromString(file.getPath(), bbis, di, abvsFileNode, parser); nodep.set(abvsFileNode.getByteArray(), abvsFileNode.getStartOffset(), abvsFileNode.getLength()); return new IndexDocumentBuilder(nodep, writer, file.getCanonicalPath()); }
Source:
<code>public Item build() { Item item = null; if (GroupItem.TYPE.equals(itemType)) { item = new GroupItem(name, baseItem, groupFunction); } else { for (ItemFactory itemFactory : itemFactories) { <START> item = itemFactory.createItem(itemType, name); <END> } } if (item == null) { throw new IllegalStateException("No item factory could handle type " + itemType); } if (item instanceof ActiveItem) { ActiveItem activeItem = (ActiveItem) item; activeItem.setLabel(label); activeItem.setCategory(category); activeItem.addGroupNames(groups); activeItem.addTags(tags); } return item; }</code><technical_language>wins? This is a pretty non-deterministic behaviour, it</technical_language>

Target:
public Item build() { Item item = null; if (GroupItem.TYPE.equals(itemType)) { item = new GroupItem(name, baseItem, groupFunction); } else { for (ItemFactory itemFactory : itemFactories) { item = itemFactory.createItem(itemType, name); if (item != null) { break; } } } if (item == null) { throw new IllegalStateException("No item factory could handle type " + itemType); } if (item instanceof ActiveItem) { ActiveItem activeItem = (ActiveItem) item; activeItem.setLabel(label); activeItem.setCategory(category); activeItem.addGroupNames(groups); } return item; }
Source:
<code>public void testProcessTimeout() throws Exception { WaitingStage ws = new WaitingStage(); ws.setName("stagename"); RemotePipeline rp = mock(RemotePipeline.class); ws.setRemotePipeline(rp); HashMap<String, Object> map = new HashMap<String, Object>(); map.put("timeout", 1000); ws.setParameters(map); LocalDocument ld = mock(LocalDocument.class); when(rp.getDocument(any(LocalQuery.class))).thenReturn(ld); when(rp.releaseLastDocument()).thenReturn(true); ws.start(); <START> Thread.sleep(1100); <END> verify(ld, times(1)).addError(eq(ws.getStageName()), any(Throwable.class)); }</code><technical_language>Depending actual system time in tests is a bad (TM). I suggest create interface provides time? java public interface TimeProvider { long currentTimeMillis(); } public enum SystemTimeProvider implements TimeProvider { INSTANCE; @Override public long currentTimeMillis() { return System.currentTimeMillis(); } } this dependency inject time, giving power tests runs in < 1ms. This is important</technical_language>

Target:
public void testProcessTimeout() throws Exception { WaitingStage ws = new WaitingStage(); ws.setName("stagename"); RemotePipeline rp = mock(RemotePipeline.class); ws.setRemotePipeline(rp); HashMap<String, Object> map = new HashMap<String, Object>(); map.put("timeout", 1000); ws.setParameters(map); LocalDocument ld = mock(LocalDocument.class); when(rp.getDocument(any(LocalQuery.class))).thenReturn(ld, (LocalDocument[]) null); when(rp.releaseLastDocument()).thenReturn(true); TimeProvider timeProvider = Mockito.mock(TimeProvider.class); when(timeProvider.getCurrentTime()).thenReturn(new Long(0), new Long(1001)); ws.setTimeProvider(timeProvider); ws.start(); verify(ld, times(1)).addError(eq(ws.getStageName()), any(Throwable.class)); }
Source:
<code>public JsonLoader(String inputFormatClassName) { this.inputFormatClassName = inputFormatClassName; try { <START> this.inputFormat = (FileInputFormat) Class.forName(inputFormatClassName).newInstance(); <END> } catch (InstantiationException e) { throw new RuntimeException("Failed creating input format " + inputFormatClassName, e); } catch (IllegalAccessException e) { throw new RuntimeException("Failed creating input format " + inputFormatClassName, e); } catch (ClassNotFoundException e) { throw new RuntimeException("Failed creating input format " + inputFormatClassName, e); } }</code><technical_language>moved getInputFormat(). need PigContext.resolveClasName() for Pig loaders</technical_language>

Target:
public JsonLoader(String inputFormatClassName) { this.inputFormatClassName = inputFormatClassName; }
Source:
<code>public void addResult(Resource resource, Collection<String> metrics) { <START> this.m_results.add(new Result(resource, metrics)); <END> }</code><technical_language>if this copied, fix this.m_ references :)</technical_language>

Target:
public void addResult(Resource resource, Collection<String> metrics) { this.results.add(new Result(resource, metrics)); }
Source:
<code>public static boolean hasPermission(EntityPlayer player, String node) { <START> return hasPermission(player.getGameProfile(), node, new PlayerContext(player)); <END> }</code><technical_language>Preconditions.checkNotNull(player, "Player null!");</technical_language>

Target:
public static boolean hasPermission(EntityPlayer player, String node) { Preconditions.checkNotNull(player, "Player can't be null!"); return hasPermission(player.getGameProfile(), node, new PlayerContext(player)); }
Source:
<code>public static Response handleIntercept(Chain chain, Tmdb tmdb) throws IOException { Request request = chain.request(); if (!Tmdb.API_HOST.equals(request.url().host())) { return chain.proceed(request); } AuthenticationType type = null; HttpUrl.Builder urlBuilder = request.url().newBuilder(); urlBuilder.setEncodedQueryParameter(Tmdb.PARAM_API_KEY, tmdb.apiKey()); if (request.url().pathSegments().get(1).equals("account") || request.url().pathSegments().get(request.url().pathSegments().size() - 1).equals("account_states")) { type = AuthenticationType.ACCOUNT; } else if (request.url().pathSegments().get(request.url().pathSegments().size() - 1).equals("rating") || !request.method().toLowerCase().equals("get")) { type = determineAuthenticationType(urlBuilder, tmdb); } addSessionToQuery(urlBuilder, type, tmdb); urlBuilder.removeAllEncodedQueryParameters("authentication"); if (type != null) { urlBuilder.fragment(type.toString()); } Request.Builder builder = request.newBuilder(); builder.url(urlBuilder.build()); Response response = chain.proceed(builder.build()); if (!response.isSuccessful()) { String retryAfter = response.header("Retry-After"); if (retryAfter != null) { try { Integer retry = Integer.parseInt(retryAfter); Thread.sleep((int) ((retry + 0.5) * 1000)); return handleIntercept(chain,tmdb); <START> } catch (Exception exc) { <END> } } } handleErrors(response, tmdb); return response; }</code><technical_language>right now: if do intend catching exception, please name instead of exc. IDEs pick warn empty catch block</technical_language>

Target:
public static Response handleIntercept(Chain chain, Tmdb tmdb) throws IOException { Request request = chain.request(); if (!Tmdb.API_HOST.equals(request.url().host())) { return chain.proceed(request); } AuthenticationType type = null; HttpUrl.Builder urlBuilder = request.url().newBuilder(); urlBuilder.setEncodedQueryParameter(Tmdb.PARAM_API_KEY, tmdb.apiKey()); if (request.url().pathSegments().get(1).equals("account") || request.url().pathSegments().get(request.url().pathSegments().size() - 1).equals("account_states")) { type = AuthenticationType.ACCOUNT; } else if (request.url().pathSegments().get(request.url().pathSegments().size() - 1).equals("rating") || !request.method().toLowerCase().equals("get")) { type = determineAuthenticationType(urlBuilder, tmdb); } addSessionToQuery(urlBuilder, type, tmdb); urlBuilder.removeAllEncodedQueryParameters("authentication"); if (type != null) { urlBuilder.fragment(type.toString()); } Request.Builder builder = request.newBuilder(); builder.url(urlBuilder.build()); Response response = chain.proceed(builder.build()); if (!response.isSuccessful()) { String retryAfter = response.header("Retry-After"); if (retryAfter != null) { try { Integer retry = Integer.parseInt(retryAfter); Thread.sleep((int) ((retry + 0.5) * 1000)); } catch (NumberFormatException | InterruptedException e) { return response; } return handleIntercept(chain,tmdb); } } handleErrors(response, tmdb); return response; }
Source:
<code>public void setTaskDetailsData(final TaskSummary model, Date logDate) { removeCSSClass(humanTaskContainer, "hidden"); taskId.setTextContent(model.getId().toString()); createdOn.setTextContent(DateUtils.getDateTimeStr(model.getCreatedOn())); if (model.getCreatedBy().isEmpty()) { createdByLabel.setHidden(true); createdBy.setHidden(true); } else { createdBy.setTextContent(model.getCreatedBy()); } updatedOn.setTextContent(DateUtils.getDateTimeStr(logDate)); taskId.setTextContent(model.getId().toString()); taskStatus.setTextContent(new TaskStatusConverter().toWidgetValue(model.getTaskStatus())); <START> if (model.getActualOwner().isEmpty()) { <END> actualOwner.setTextContent(constants.NotClaimed()); } else { actualOwner.setTextContent(model.getActualOwner()); } description.setTextContent(model.getDescription()); }</code><technical_language>this _model.getActualOwner() == null_</technical_language>

Target:
public void setTaskDetailsData(final TaskSummary model, Date logDate) { removeCSSClass(humanTaskContainer, "hidden"); taskId.setTextContent(model.getId().toString()); createdOn.setTextContent(DateUtils.getDateTimeStr(model.getCreatedOn())); if (model.getCreatedBy() != null && !model.getCreatedBy().isEmpty()) { createdBy.setTextContent(model.getCreatedBy()); } else { createdByLabel.setHidden(true); createdBy.setHidden(true); } updatedOn.setTextContent(DateUtils.getDateTimeStr(logDate)); taskStatus.setTextContent(new TaskStatusConverter().toWidgetValue(model.getTaskStatus())); if (model.getActualOwner() != null && !model.getActualOwner().isEmpty()) { actualOwner.setTextContent(model.getActualOwner()); } else { actualOwner.setTextContent(constants.NotClaimed()); } description.setTextContent(model.getDescription()); }
Source:
<code>protected void internalReceiveCommand(String itemName, Command command) { <START> logger.debug( <END> "internalReceiveCommand() is called! itemName {}, command {}", itemName, command); for (NeoHubBindingProvider provider : providers) { if (!provider.providesBindingFor(itemName)) { continue; } final String device = provider.getNeoStatDevice(itemName); switch (provider.getNeoStatProperty(itemName)) { case Away: if (command instanceof OnOffType) { OnOffType onOffType = (OnOffType) command; createProtocol().setAway(OnOffType.ON == onOffType, device); } break; case Standby: if (command instanceof OnOffType) { OnOffType onOffType = (OnOffType) command; createProtocol().setStandby(OnOffType.ON == onOffType, device); } default: break; } } }</code><technical_language>please decrease log level trace remove statement</technical_language>

Target:
protected void internalReceiveCommand(String itemName, Command command) { for (NeoHubBindingProvider provider : providers) { if (!provider.providesBindingFor(itemName)) { continue; } final String device = provider.getNeoStatDevice(itemName); switch (provider.getNeoStatProperty(itemName)) { case Away: if (command instanceof OnOffType) { OnOffType onOffType = (OnOffType) command; createProtocol().setAway(OnOffType.ON == onOffType, device); } break; case Standby: if (command instanceof OnOffType) { OnOffType onOffType = (OnOffType) command; createProtocol().setStandby(OnOffType.ON == onOffType, device); } default: break; } } }
Source:
<code>protected void childCommandsExecutionEnded(CommandBase<?> command, boolean anyFailed, List<Guid> childCmdIds, CommandExecutionStatus status, int completedChildren) { AddCinderDiskCommand addCinderDiskCommand = (AddCinderDiskCommand) command; <START> Guid diskId = ((AddDiskParameters) addCinderDiskCommand.getParameters()).getDiskInfo().getId(); <END> ImageStatus imageStatus = addCinderDiskCommand.getCinderBroker().getDiskStatus(diskId); DiskImage disk = (CinderDisk) DbFacade.getInstance().getDiskDao().get(diskId); if (imageStatus != null && imageStatus != disk.getImageStatus()) { switch (imageStatus) { case OK: setCommandEndStatus(command, false, status, childCmdIds); break; case ILLEGAL: setCommandEndStatus(command, true, status, childCmdIds); break; } } }</code><technical_language>getDiskId() method instead of removing it</technical_language>

Target:
protected void childCommandsExecutionEnded(CommandBase<?> command, boolean anyFailed, List<Guid> childCmdIds, CommandExecutionStatus status, int completedChildren) { AddCinderDiskCommand<AddDiskParameters> addCinderDiskCommand = (AddCinderDiskCommand<AddDiskParameters>) command; Guid diskId = getDiskId(addCinderDiskCommand); ImageStatus imageStatus = addCinderDiskCommand.getCinderBroker().getDiskStatus(diskId); DiskImage disk = (CinderDisk) command.getDiskDao().get(diskId); if (imageStatus != null && imageStatus != disk.getImageStatus()) { switch (imageStatus) { case OK: setCommandEndStatus(command, false, status, childCmdIds); break; case ILLEGAL: setCommandEndStatus(command, true, status, childCmdIds); break; } } }
Source:
<code><START> public AlarmNotificationsDto retrieveCurrentAlarmNotifications(final DlmsConnectionHolder conn) <END> throws IOException, TimeoutException, ProtocolAdapterException { final AttributeAddress alarmFilterValue = new AttributeAddress(CLASS_ID, OBIS_CODE, ATTRIBUTE_ID); if (conn.hasDlmsMessageListener()) { conn.getDlmsMessageListener() .setDescription("SetAlarmNotifications retrieve current value, retrieve attribute: " + this.describeAttributes(alarmFilterValue)); } LOGGER.info( "Retrieving current alarm filter by issuing get request for class id: {}, obis code: {}, attribute id: {}", CLASS_ID, OBIS_CODE, ATTRIBUTE_ID); final GetResult getResult = conn.getConnection().get(alarmFilterValue); if (getResult == null) { throw new ProtocolAdapterException("No GetResult received while retrieving current alarm filter."); } return this.alarmNotifications(getResult.getResultData()); }</code><technical_language>![MAJOR](<LINK_1> Refactor this method throw checked exception instead of: java.io.IOException, java.util.concurrent.TimeoutException, org.osgp.adapter.protocol.dlms.exceptions.ProtocolAdapterException [![rule](<LINK_2>](<LINK_0></technical_language>

Target:
public AlarmNotificationsDto retrieveCurrentAlarmNotifications(final DlmsConnectionHolder conn) throws IOException, TimeoutException, ProtocolAdapterException { final AttributeAddress alarmFilterValue = new AttributeAddress(CLASS_ID, OBIS_CODE, ATTRIBUTE_ID); conn.getDlmsMessageListener() .setDescription("SetAlarmNotifications retrieve current value, retrieve attribute: " + JdlmsObjectToStringUtil.describeAttributes(alarmFilterValue)); LOGGER.info( "Retrieving current alarm filter by issuing get request for class id: {}, obis code: {}, attribute id: {}", CLASS_ID, OBIS_CODE, ATTRIBUTE_ID); final GetResult getResult = conn.getConnection().get(alarmFilterValue); if (getResult == null) { throw new ProtocolAdapterException("No GetResult received while retrieving current alarm filter."); } return this.alarmNotifications(getResult.getResultData()); }
Source:
<code>protected void undeleteBlob(final String blobIdStr, final String serviceId, FutureResult<Void> futureResult, final Callback<Void> callback) { if (isMaybeMetadataBlob(blobIdStr)) { Callback<GetBlobResultInternal> internalCallback = (GetBlobResultInternal result, Exception exception) -> { if (exception != null) { completeOperation(futureResult, callback, null, exception, false); } else if (result.getBlobResult != null) { <START> exception = new RouterException( <END> "GET blob call returned the blob instead of just the store keys (before TTL update)", RouterErrorCode.UnexpectedInternalError); completeOperation(futureResult, callback, null, exception, false); } else { List<String> blobIdStrs = new ArrayList<>(); blobIdStrs.add(blobIdStr); if (result.storeKeys != null) { result.storeKeys.forEach(key -> blobIdStrs.add(key.getID())); } currentOperationsCount.addAndGet(blobIdStrs.size()); doUndeleteOperation(blobIdStrs, serviceId, futureResult, callback); } }; GetBlobOptions options = new GetBlobOptionsBuilder().operationType(GetBlobOptions.OperationType.All) .getOption(GetOption.None) .build(); GetBlobOptionsInternal optionsInternal = new GetBlobOptionsInternal(options, true, routerMetrics.ageAtTtlUpdate); try { getBlob(blobIdStr, optionsInternal, internalCallback); } catch (RouterException e) { completeUpdateBlobTtlOperation(e, futureResult, callback); } } else { routerMetrics.skippedGetBlobCount.inc(); doUndeleteOperation(Collections.singletonList(blobIdStr), serviceId, futureResult, callback); } }</code><technical_language>??? implementation is for GET</technical_language>

Target:
protected void undeleteBlob(final String blobIdStr, final String serviceId, FutureResult<Void> futureResult, final Callback<Void> callback) { doOperationTowardsMaybeCompositeBlob(blobIdStr, futureResult, callback, new CompositeBlobOperationHelper("UNDELETE", GetOption.Include_Deleted_Blobs, routerMetrics.ageAtUndelete, (blobIds) -> { doUndeleteOperation(blobIds, serviceId, futureResult, callback); }, (exception) -> { completeUndeleteBlobOperation(exception, futureResult, callback); })); }
Source:
<code>public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) { if (this.clientRegistrationRepository != null && this.authorizedClientRepository != null) { OAuth2AuthorizedClientProviderBuilder authorizedClientProviderBuilder = OAuth2AuthorizedClientProviderBuilder.builder() .authorizationCode() .refreshToken(); if (this.accessTokenResponseClient != null) { authorizedClientProviderBuilder.clientCredentials(configurer -> configurer.accessTokenResponseClient(this.accessTokenResponseClient)); <START> } <END> OAuth2AuthorizedClientProvider authorizedClientProvider = authorizedClientProviderBuilder.build(); DefaultOAuth2AuthorizedClientManager authorizedClientManager = new DefaultOAuth2AuthorizedClientManager( this.clientRegistrationRepository, this.authorizedClientRepository); authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider); argumentResolvers.add(new OAuth2AuthorizedClientArgumentResolver(authorizedClientManager)); } }</code><technical_language>This code changes existing functionality. If accessTokenResponseClient is null, clientCredentials enabled. Please add else statement authorizedClientProviderBuilder.clientCredentials() ensure clientCredentials is enabled default</technical_language>

Target:
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) { if (this.clientRegistrationRepository != null && this.authorizedClientRepository != null) { OAuth2AuthorizedClientProviderBuilder authorizedClientProviderBuilder = OAuth2AuthorizedClientProviderBuilder.builder() .authorizationCode() .refreshToken(); if (this.accessTokenResponseClient != null) { authorizedClientProviderBuilder.clientCredentials(configurer -> configurer.accessTokenResponseClient(this.accessTokenResponseClient)); } else { authorizedClientProviderBuilder.clientCredentials(); } OAuth2AuthorizedClientProvider authorizedClientProvider = authorizedClientProviderBuilder.build(); DefaultOAuth2AuthorizedClientManager authorizedClientManager = new DefaultOAuth2AuthorizedClientManager( this.clientRegistrationRepository, this.authorizedClientRepository); authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider); argumentResolvers.add(new OAuth2AuthorizedClientArgumentResolver(authorizedClientManager)); } }
Source:
<code><START> public double getMiningFeeInSatoshisPerByte() { <END> return CoinUtil.getFeePerByte(miningFee, txSize); }</code><technical_language>double for satoshis? Long better</technical_language>

Target:
public double getMiningFeeInSatoshisPerByte() { return CoinUtil.getFeePerVbyte(miningFee, txSize); }
Source:
<code>private static DetailAST getWhitespaceFollowedNode(DetailAST ast) { final DetailAST whitespaceFollowedAst; switch (ast.getType()) { case TokenTypes.TYPECAST: whitespaceFollowedAst = ast.findFirstToken(TokenTypes.RPAREN); break; case TokenTypes.ARRAY_DECLARATOR: whitespaceFollowedAst = getArrayDeclaratorPreviousElement(ast); break; case TokenTypes.INDEX_OP: final DetailAST resultAst = getIndexOpPreviousElement(ast); <START> if (resultAst == null) { <END> whitespaceFollowedAst = ast; } else { whitespaceFollowedAst = resultAst; } break; default: whitespaceFollowedAst = ast; } return whitespaceFollowedAst; }</code><technical_language>Please move getIndexOpPreviousElement</technical_language>

Target:
private static DetailAST getWhitespaceFollowedNode(DetailAST ast) { final DetailAST whitespaceFollowedAst; switch (ast.getType()) { case TokenTypes.TYPECAST: whitespaceFollowedAst = ast.findFirstToken(TokenTypes.RPAREN); break; case TokenTypes.ARRAY_DECLARATOR: whitespaceFollowedAst = getArrayDeclaratorPreviousElement(ast); break; case TokenTypes.INDEX_OP: whitespaceFollowedAst = getIndexOpPreviousElement(ast); break; default: whitespaceFollowedAst = ast; } return whitespaceFollowedAst; }
Source:
<code><START> private Entry<String, CycleDto> createZapiCycleIfNoneExist(ProjectDto targetProjectDto, VersionDto targetVersionDto) { <END> final Optional<Entry<String, CycleDto>> targetCycleEntry = getListOfCycles(targetProjectDto.id, targetVersionDto.id); targetCycleEntry.ifPresent(cycleDtoEntry -> logger.info(() -> format("Found in Zephyr; cycle: \"{0}\" with cycleId: \"{1}\"", Property.ZAPI_CYCLE_REGEX.getValue(), cycleDtoEntry.getKey()))); return targetCycleEntry.orElseGet(() -> { final String createdCycleId = jiraService.cycle().createNewCycle( CreateNewCycleDto.newBuilder().cycleLightDto( CycleLightDto.newBuilder() .versionId(targetVersionDto.id) .projectId(targetProjectDto.id) .name(Property.ZAPI_CYCLE_REGEX.getValue()) .build()) .build()).id; logger.info(() -> format("Created in Zephyr; cycle: \"{0}\" with cycleId: \"{1}\"", Property.ZAPI_CYCLE_REGEX.getValue(), createdCycleId)); return getListOfCycles(targetProjectDto.id, targetVersionDto.id) .orElseThrow(() -> new NotFoundException(format("Unable to find in JIRA newly created" + " cycle: \"{0}\" with cycleId: \"{1}\"; cycle creation may have failed", Property.ZAPI_CYCLE_REGEX.getValue(), createdCycleId))); }); }</code><technical_language>I if align params right, I if new lines e.g. private Entry<String, CycleDto> createZapiCycleIfNoneExist( ProjectDto targetProjectDto, VersionDto targetVersionDto) { if refactor name of method mis-aligned</technical_language>

Target:
private Entry<String, CycleDto> createZapiCycleIfNoneExist( ProjectDto targetProjectDto, VersionDto targetVersionDto) { final Optional<Entry<String, CycleDto>> targetCycleEntry = getListOfCycles(targetProjectDto.id, targetVersionDto.id); targetCycleEntry.ifPresent(cycleDtoEntry -> logger.info(() -> format("Found in Zephyr; [ cycle: %s ] with [ cycleId: %s ]", Property.ZAPI_CYCLE_REGEX.getValue(), cycleDtoEntry.getKey()))); return targetCycleEntry.orElseGet(() -> { final String createdCycleId = jiraService.cycle().createNewCycle( CreateNewCycleDto.newBuilder().cycleLightDto( CycleLightDto.newBuilder() .versionId(targetVersionDto.id) .projectId(targetProjectDto.id) .name(Property.ZAPI_CYCLE_REGEX.getValue()) .build()) .build()).id; logger.info(() -> format("Created in Zephyr; [ cycle: %s ] with [ cycleId: %s ]", Property.ZAPI_CYCLE_REGEX.getValue(), createdCycleId)); return getListOfCycles(targetProjectDto.id, targetVersionDto.id) .orElseThrow(() -> new NotFoundException(format("Unable to find in JIRA newly created" + " [ cycle: %s ] with [ cycleId: %s ]. Cycle creation may have failed", Property.ZAPI_CYCLE_REGEX.getValue(), createdCycleId))); }); }
Source:
<code>private static void printHelp() throws IOException { final StringBuilder sb = new StringBuilder(); sb.append("============================\n"); sb.append("Please provide the directory path to a configuration file!"); sb.append("\n"); sb.append("For an example, see: <LINK_0>"); sb.append("src/test/resources/spring/migration-bean.xml"); sb.append("\n\n"); sb.append("For detailed instructions, see: <LINK_0>README.md"); sb.append("\n"); <START> sb.append("============================\n"); <END> System.out.println(sb.toString()); }</code><technical_language>Ouch! I thought helpful able this in console, no</technical_language>

Target:
private static void printHelp() throws IOException { final StringBuilder sb = new StringBuilder(); sb.append("============================\n"); sb.append("Please provide the directory path to a configuration file!"); sb.append("\n"); sb.append("See: <LINK_0>"); sb.append("src/main/resources/spring/migration-bean.xml"); sb.append("\n\n"); sb.append("The configuration file should contain the following (with appropriate values):"); sb.append("\n"); sb.append("~~~~~~~~~~~~~~\n"); final ClassPathResource resource = new ClassPathResource("spring/migration-bean.xml"); final InputStream example = resource.getInputStream(); final BufferedReader reader = new BufferedReader(new InputStreamReader(example)); String line = reader.readLine(); while (null != line) { sb.append(line); sb.append("\n"); line = reader.readLine(); } sb.append("~~~~~~~~~~~~~~\n\n"); sb.append("See top of this output for details.\n"); sb.append("============================\n"); System.out.println(sb.toString()); }
Source:
<code>public Collection<String> getAliases(final KeyStore keyStore) throws ScriptSignatureException { try { if (keyStore != null) return Collections.list(keyStore.aliases()); } catch (KeyStoreException e) { throw new ScriptSignatureException("Keystore not initialized properly. Try again.", e); } <START> throw new ScriptSignatureException("Keystore not initialized properly. Try again.", null); <END> }</code><technical_language>instead of thowing return empty list</technical_language>

Target:
public Collection<String> getAliases(final KeyStore keyStore) { try { if (keyStore != null) return Collections.list(keyStore.aliases()); } catch (KeyStoreException e) { return null; } return null; }
Source:
<code>public Status delete(String table, String key) { try { <START> UpdateResponse res = (cloudMode) ? cloudClient.deleteById(table, key, 1000) <END> : httpClient.deleteById(table, key, 1000); if (res.getStatus() > 0) { throw new Exception(""); } return Status.OK; } catch (Exception e) { e.printStackTrace(); } return Status.ERROR; }</code><technical_language>maxcommittime is a performance attribute, pull a variable expose user a workload property, default here</technical_language>

Target:
public Status delete(String table, String key) { try { UpdateResponse response; if (batchMode) { response = client.deleteById(table, key, commitTime); } else { response = client.deleteById(table, key); client.commit(table); } return checkStatus(response.getStatus()); } catch (IOException | SolrServerException e) { e.printStackTrace(); } return Status.ERROR; }
Source:
<code>private Set<String> findQueryParams() { Set<String> result = new HashSet<>(); String query = this.request.getQueryString(); <START> String[] splitQuery = StringUtils.split(query, "&"); <END> if(splitQuery == null && query != null) { splitQuery = new String[]{query}; } if (splitQuery != null) { for (String value : splitQuery) { if (value.contains("=")) { value = value.substring(0, value.indexOf("=")); } result.add(value); } } return result; }</code><technical_language>I learned tokenizeToStringArray, clean this a bit</technical_language>

Target:
private Set<String> findQueryParams() { Set<String> result = new HashSet<>(); String query = this.request.getQueryString(); if (query != null) { for (String value : StringUtils.tokenizeToStringArray(query, "&")) { if (value.contains("=")) { value = value.substring(0, value.indexOf("=")); } result.add(value); } } return result; }