auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private Pair<ContainerPlacementMessage.StatusCode, String> validatePlacementAction(ContainerPlacementRequestMessage requestMessage) { <START> String errorMessagePrefix = ContainerPlacementMessage.StatusCode.BAD_REQUEST + " reason: "; <END> Boolean invalidAction = false; String errorMessage = null; if (!samzaApplicationState.runningProcessors.containsKey(requestMessage.getProcessorId()) && !samzaApplicationState.pendingProcessors.containsKey(requestMessage.getProcessorId()) ) { errorMessage = String.format("%s invalid processor id neither in running or pending processors", errorMessagePrefix); invalidAction = true; } else if (placementRequestsCache.containsKey(requestMessage.getUuid())) { errorMessage = String.format("%s duplicate UUID of the request, please retry", errorMessagePrefix); invalidAction = true; } else if (standbyContainerManager.isPresent() && !standbyContainerManager.get() .checkStandbyConstraints(requestMessage.getProcessorId(), requestMessage.getDestinationHost())) { errorMessage = String.format("%s destination host does not meet standby constraints", errorMessagePrefix); invalidAction = true; } if (invalidAction) { return new ImmutablePair<>(ContainerPlacementMessage.StatusCode.BAD_REQUEST, errorMessage); } return new ImmutablePair<>(ContainerPlacementMessage.StatusCode.ACCEPTED, "Request is accepted"); }</code><technical_language>Instead define errorMessage ContainerPlacementMessage.StatusCode.BAD_REQUEST + " reason: %s" String.format(errorMessage, reason);</technical_language>

Target:
private Pair<ContainerPlacementMessage.StatusCode, String> validatePlacementAction(ContainerPlacementRequestMessage requestMessage) { String errorMessagePrefix = ContainerPlacementMessage.StatusCode.BAD_REQUEST + " reason: %s"; Boolean invalidAction = false; String errorMessage = null; if (!samzaApplicationState.runningProcessors.containsKey(requestMessage.getProcessorId()) && !samzaApplicationState.pendingProcessors.containsKey(requestMessage.getProcessorId()) ) { errorMessage = String.format(errorMessagePrefix, "invalid processor id neither in running or pending processors"); invalidAction = true; } else if (placementRequestsCache.containsKey(requestMessage.getUuid())) { errorMessage = String.format(errorMessagePrefix, "duplicate UUID of the request, please retry"); invalidAction = true; } else if (standbyContainerManager.isPresent() && !standbyContainerManager.get() .checkStandbyConstraints(requestMessage.getProcessorId(), requestMessage.getDestinationHost())) { errorMessage = String.format(errorMessagePrefix, "destination host does not meet standby constraints"); invalidAction = true; } if (invalidAction) { return new ImmutablePair<>(ContainerPlacementMessage.StatusCode.BAD_REQUEST, errorMessage); } return new ImmutablePair<>(ContainerPlacementMessage.StatusCode.ACCEPTED, "Request is accepted"); }
Source:
<code>public BinaryData getBody() { final AmqpMessageBodyType type = amqpAnnotatedMessage.getBody().getBodyType(); switch (type) { case DATA: <START> Optional<byte[]> byteArrayData = amqpAnnotatedMessage.getBody().getData().stream().findFirst(); <END> final byte[] bytes; if (byteArrayData.isPresent()) { bytes = byteArrayData.get(); } else { logger.warning("Data not present."); bytes = new byte[0]; } return BinaryData.fromBytes(bytes); case SEQUENCE: case VALUE: throw logger.logExceptionAsError(new UnsupportedOperationException("Not supported AmqpBodyType: " + type.toString())); default: throw logger.logExceptionAsError(new IllegalArgumentException("Unknown AmqpBodyType: " + type.toString())); } }</code><technical_language>call getFirstData now, you</technical_language>

Target:
public BinaryData getBody() { final AmqpMessageBodyType type = amqpAnnotatedMessage.getBody().getBodyType(); switch (type) { case DATA: return BinaryData.fromBytes(amqpAnnotatedMessage.getBody().getFirstData()); case SEQUENCE: case VALUE: throw logger.logExceptionAsError(new UnsupportedOperationException("Not supported AmqpBodyType: " + type.toString())); default: throw logger.logExceptionAsError(new IllegalArgumentException("Unknown AmqpBodyType: " + type.toString())); } }
Source:
<code>private Mono<Void> afterProcessChanges(ChangeFeedObserverContext context) { <START> AutoCheckpointer self = this; <END> self.processedDocCount ++; if (self.isCheckpointNeeded()) { return context.checkpoint() .doOnSuccess((Void) -> { self.processedDocCount = 0; self.lastCheckpointTime = ZonedDateTime.now(ZoneId.of("UTC")); }); } return Mono.empty(); }</code><technical_language>here. final explicitly</technical_language>

Target:
private Mono<Void> afterProcessChanges(ChangeFeedObserverContext context) { this.processedDocCount ++; if (this.isCheckpointNeeded()) { return context.checkpoint() .doOnSuccess((Void) -> { this.processedDocCount = 0; this.lastCheckpointTime = ZonedDateTime.now(ZoneId.of("UTC")); }); } return Mono.empty(); }
Source:
<code>private Set<String> getLocalAddresses(ChannelHandlerContext ctx) { SocketAddress localAddress = ctx.channel().localAddress(); <START> if (!(localAddress instanceof InetSocketAddress)) { <END> return new HashSet<>(); } synchronized (localAddresses) { Set<String> localAddresses = this.localAddresses.get(localAddress); if (localAddresses != null) { return localAddresses; } InetSocketAddress inetSocketAddress = (InetSocketAddress) localAddress; String portExtension = ""; if (!(inetSocketAddress.getPort() == 443 && isSslEnabledUpstream(ctx.channel()) || inetSocketAddress.getPort() == 80)) { portExtension = ":" + inetSocketAddress.getPort(); } InetAddress socketAddress = inetSocketAddress.getAddress(); localAddresses = new HashSet<>(); localAddresses.add(socketAddress.getHostAddress() + portExtension); localAddresses.add(socketAddress.getCanonicalHostName() + portExtension); localAddresses.add(socketAddress.getHostName() + portExtension); localAddresses.add("localhost" + portExtension); localAddresses.add("127.0.0.1" + portExtension); this.localAddresses.put(inetSocketAddress, unmodifiableSet(localAddresses)); return localAddresses; } }</code><technical_language>please reverse this if statement this a return statement in middle need for !</technical_language>

Target:
private Set<String> getLocalAddresses(ChannelHandlerContext ctx) { SocketAddress localAddress = ctx.channel().localAddress(); Set<String> localAddresses = null; if (localAddress instanceof InetSocketAddress) { InetSocketAddress inetSocketAddress = (InetSocketAddress) localAddress; String portExtension = calculatePortExtension(inetSocketAddress, isSslEnabledUpstream(ctx.channel())); DefaultKeyValue<InetSocketAddress, String> cacheKey = new DefaultKeyValue<>(inetSocketAddress, portExtension); localAddresses = localAddressesCache.get(cacheKey); if (localAddresses == null) { localAddresses = calculateLocalAddresses(inetSocketAddress, portExtension); localAddressesCache.put(cacheKey, localAddresses); } } return (localAddresses == null) ? Collections.<String>emptySet() : localAddresses; }
Source:
<code>public Pageable getPageable(@Nullable Pageable optionalPageable) { <START> return optionalPageable != null ? optionalPageable : new PageRequest(0, 20); <END> }</code><technical_language>20 EMBEDDED_PAGE_SIZE</technical_language>

Target:
public Pageable getPageable(@Nullable Pageable optionalPageable) { return optionalPageable != null ? optionalPageable : new PageRequest(0, DEFAULT_PAGE_SIZE); }
Source:
<code>protected void execute() { if (!bindingsExist()) { logger.debug("There is no existing DSMR binding configuration => refresh cycle aborted!"); return; } if (dsmrPort != null) { boolean receivedData = dsmrPort.portReceivedData(); long autoDetectDuration = dsmrPort.getDetectingDuration(); logger.debug("Port received any data:" + receivedData + ", auto detect duration:" + autoDetectDuration); if (!receivedData && autoDetectDuration > 2 * DSMR_UPDATE_INTERVAL) { logger.info("No valid data received for " + autoDetectDuration + "ms during autodetection, switch speed"); dsmrPort.close(); switch (portSpeed) { case LOW_SPEED: portSpeed = DSMRPort.PortSpeed.HIGH_SPEED; break; case HIGH_SPEED: portSpeed = DSMRPort.PortSpeed.LOW_SPEED; <START> break; <END> } } } if (dsmrPort == null || !dsmrPort.isOpen()) { logger.debug("Creating DSMR Port:" + port + ", speed:" + portSpeed); dsmrPort = new DSMRPort(port, portSpeed, dsmrMeters, DSMR_UPDATE_INTERVAL); } List<OBISMessage> messages = dsmrPort.read(); logger.debug("Received " + messages.size() + " messages"); for (OBISMessage msg : messages) { logger.debug("Read message:" + msg); for (DSMRBindingProvider provider : providers) { for (String itemName : provider.getItemNames()) { String dsmrItemId = provider.getDSMRItemID(itemName); for (CosemValue<? extends State> openHABValue : msg .getOpenHABValues()) { if (dsmrItemId.equals(openHABValue.getDsmrItemId())) { logger.debug("Publish data(" + dsmrItemId + ") to " + itemName); eventPublisher.postUpdate(itemName, openHABValue.getValue()); } } } } } }</code><technical_language>Mapping other around</technical_language>

Target:
protected void execute() { if (!bindingsExist()) { logger.debug("There is no existing DSMR binding configuration => refresh cycle aborted!"); return; } if (dsmrPort == null || !dsmrPort.isOpen()) { logger.debug("Creating DSMR Port:" + port); dsmrPort = new DSMRPort(port, new P1TelegramParser( new OBISMsgFactory(dsmrMeters)), DSMR_UPDATE_INTERVAL / 2, DSMR_UPDATE_INTERVAL * 2); } List<OBISMessage> messages = dsmrPort.read(); logger.debug("Received " + messages.size() + " messages"); for (OBISMessage msg : messages) { logger.debug("Read message:" + msg); for (DSMRBindingProvider provider : providers) { for (String itemName : provider.getItemNames()) { String dsmrItemId = provider.getDSMRItemID(itemName); for (CosemValue<? extends State> openHABValue : msg .getOpenHABValues()) { if (dsmrItemId.equals(openHABValue.getDsmrItemId())) { logger.debug("Publish data(" + dsmrItemId + ") to " + itemName); eventPublisher.postUpdate(itemName, openHABValue.getValue()); } } } } } }
Source:
<code>public Mono<ClientHttpResponse> connect(HttpMethod method, URI uri, Function<? super ClientHttpRequest, Mono<Void>> requestCallback) { <START> HttpClientContext context = this.contextSupplier.get(); <END> if (context.getCookieStore() == null) { context.setCookieStore(new BasicCookieStore()); } HttpComponentsClientHttpRequest request = new HttpComponentsClientHttpRequest(method, uri, context, this.dataBufferFactory); return requestCallback.apply(request).then(Mono.defer(() -> execute(request, context))); }</code><technical_language>I live idea of a function (instead of overloadable method) for HttpContext, I nicer if user access method URI, anyway. a BiFunction<HttpMethod, URI, HttpClientContext> instead of a Supplier<HttpClientContext></technical_language>

Target:
public Mono<ClientHttpResponse> connect(HttpMethod method, URI uri, Function<? super ClientHttpRequest, Mono<Void>> requestCallback) { HttpClientContext context = this.contextProvider.apply(method, uri); if (context.getCookieStore() == null) { context.setCookieStore(new BasicCookieStore()); } HttpComponentsClientHttpRequest request = new HttpComponentsClientHttpRequest(method, uri, context, this.dataBufferFactory); return requestCallback.apply(request).then(Mono.defer(() -> execute(request, context))); }
Source:
<code>private List<ChannelRecord> determineWritingChannels(final WireRecord record) { requireNonNull(record, message.wireRecordNonNull()); <START> final List<ChannelRecord> assetRecordsToWriteChannels = CollectionUtil.newArrayList(); <END> final AssetConfiguration assetConfiguration = getAssetConfiguration(); final Map<String, Channel> channels = assetConfiguration.getAssetChannels(); for (final Entry<String, Channel> channelEntry : channels.entrySet()) { final Channel channel = channelEntry.getValue(); final String channelName = channel.getName(); final ChannelType channelType = channel.getType(); if (channelType != WRITE && channelType != READ_WRITE) { continue; } Map<String, TypedValue<?>> wireRecordProperties = record.getProperties(); if (wireRecordProperties.containsKey(channelName)) { final TypedValue<?> value = wireRecordProperties.get(channelName); if (channel.getValueType() == value.getType()) { assetRecordsToWriteChannels.add(channel.createWriteRecord(value)); } } } return assetRecordsToWriteChannels; }</code><technical_language>channelRecordsToWriteChannels</technical_language>

Target:
private List<ChannelRecord> determineWritingChannels(final WireRecord record) { requireNonNull(record, message.wireRecordNonNull()); final List<ChannelRecord> channelRecordsToWrite = CollectionUtil.newArrayList(); final AssetConfiguration assetConfiguration = getAssetConfiguration(); final Map<String, Channel> channels = assetConfiguration.getAssetChannels(); for (final Entry<String, Channel> channelEntry : channels.entrySet()) { final Channel channel = channelEntry.getValue(); final String channelName = channel.getName(); final ChannelType channelType = channel.getType(); if (channelType != WRITE && channelType != READ_WRITE) { continue; } Map<String, TypedValue<?>> wireRecordProperties = record.getProperties(); if (wireRecordProperties.containsKey(channelName)) { final TypedValue<?> value = wireRecordProperties.get(channelName); if (channel.getValueType() == value.getType()) { channelRecordsToWrite.add(channel.createWriteRecord(value)); } } } return channelRecordsToWrite; }
Source:
<code>private Map<String, SymbolReference> getUpdatedAssignments(Assignments assignments) { <START> HashMap<String, SymbolReference> mapUpdate = new HashMap<>(); <END> for (Map.Entry<Symbol, Expression> assignment : assignments.getMap().entrySet()) { for (Map.Entry<String, SymbolReference> existingAlias : map.entrySet()) { if (assignment.getValue().equals(existingAlias.getValue())) { mapUpdate.put(existingAlias.getKey(), assignment.getKey().toSymbolReference()); } else if (assignment.getKey().toSymbolReference().equals(existingAlias.getValue())) { mapUpdate.put(existingAlias.getKey(), existingAlias.getValue()); } } } return ImmutableMap.copyOf(mapUpdate); }</code><technical_language>a change here</technical_language>

Target:
private Map<String, SymbolReference> getUpdatedAssignments(Assignments assignments) { ImmutableMap.Builder<String, SymbolReference> mapUpdate = ImmutableMap.builder(); for (Map.Entry<Symbol, Expression> assignment : assignments.getMap().entrySet()) { for (Map.Entry<String, SymbolReference> existingAlias : map.entrySet()) { if (assignment.getValue().equals(existingAlias.getValue())) { mapUpdate.put(existingAlias.getKey(), assignment.getKey().toSymbolReference()); } else if (assignment.getKey().toSymbolReference().equals(existingAlias.getValue())) { mapUpdate.put(existingAlias.getKey(), existingAlias.getValue()); } } } return mapUpdate.build(); }
Source:
<code>@Test public void getWithQueryThenUrlThrows() { class Example { @GET("foo/bar") Call<Object> method(@Query("hey") String hey, @Url Object url) { return null; } } try { <START> buildRequest(Example.class, "hey", "foo/bar/"); <END> } catch (IllegalArgumentException e) { assertThat(e).hasMessage("A @Url parameter must not come after a @Query (parameter #2)\n" + " for method Example.method"); } }</code><technical_language>fail</technical_language>

Target:
@Test public void getWithQueryThenUrlThrows() { class Example { @GET("foo/bar") Call<Object> method(@Query("hey") String hey, @Url Object url) { return null; } } try { buildRequest(Example.class, "hey", "foo/bar/"); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage("A @Url parameter must not come after a @Query (parameter #2)\n" + " for method Example.method"); } }
Source:
<code>public boolean containsKey(Object key) { <START> return validate().litems.containsKey(key); <END> }</code><technical_language>need add overload takes a namespace in well</technical_language>

Target:
public boolean containsKey(Object key) { return validate().linkedListItems.containsKey(key); }
Source:
<code>public boolean offer(Runnable event) { if (EVENT_LISTENER_DEPTH.get().intValue() > 0) { if (!super.offer(event)) { LOG.warn("Execution queue is full, executing Runnable on current thread"); <START> event.run(); <END> } return true; } else { try { super.put(event); return true; } catch(InterruptedException ie) { Thread.currentThread().interrupt(); } return false; } }</code><technical_language>logging prefix needs set running this</technical_language>

Target:
public boolean offer(Runnable event) { if (EVENT_LISTENER_DEPTH.get().intValue() > 0) { if (!super.offer(event)) { LOG.warn("Execution queue is full, executing Runnable on current thread"); Logging.withPrefix(Eventd.LOG4J_CATEGORY, event); } return true; } else { try { super.put(event); return true; } catch(InterruptedException ie) { Thread.currentThread().interrupt(); } return false; } }
Source:
<code>public Response isValidToken(@Context HttpServletRequest request) { TOTPManager totpManager = (TOTPManager) PrivilegedCarbonContext.getThreadLocalCarbonContext().getOSGiService (TOTPManager.class); String username = request.getParameter("username"); int token = Integer.parseInt(request.getParameter("token")); boolean isvalid = false; try { isvalid = totpManager.isValidTokenLocalUser(token, username); if (isvalid) { <START> log.info("TOTP token is accepted"); <END> return Response.status(Response.Status.ACCEPTED).type(MediaType.APPLICATION_JSON_TYPE) .entity("Token is verified").build(); } else { log.info("TOTP token is not valid"); return Response.status(Response.Status.BAD_REQUEST).type(MediaType.APPLICATION_JSON_TYPE) .entity("Token is not valid").build(); } } catch (TOTPException e) { log.error("Error when validating the token", e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).type(MediaType.APPLICATION_JSON_TYPE) .entity("Error while validating the token").build(); } }</code><technical_language>debug level instead of info</technical_language>

Target:
public Response isValidToken(@Context HttpServletRequest request) { Hashtable<String, String> props = new Hashtable<String, String>(); TOTPManager totpManager = (TOTPManager) CarbonContext.getThreadLocalCarbonContext().getOSGiService (TOTPManager.class, props); String username = CharacterEncoder.getSafeText(request.getParameter("username")); int token = Integer.parseInt(CharacterEncoder.getSafeText(request.getParameter("token"))); boolean isvalid = false; try { isvalid = totpManager.isValidTokenLocalUser(token, username); if (isvalid) { if (log.isDebugEnabled()) { log.debug("TOTP token is accepted"); } return Response.status(Response.Status.ACCEPTED).type(MediaType.APPLICATION_JSON_TYPE) .entity("Token is verified").build(); } else { if (log.isDebugEnabled()) { log.debug("TOTP token is not valid"); } return Response.status(Response.Status.BAD_REQUEST).type(MediaType.APPLICATION_JSON_TYPE) .entity("Token is not valid").build(); } } catch (TOTPException e) { log.error("Error when validating the token", e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).type(MediaType.APPLICATION_JSON_TYPE) .entity("Error while validating the token").build(); } }
Source:
<code>static int getExitOrientationFromFile(ContentResolver contentResolver, Uri uri) { Cursor cursor = null; try { contentResolver.openInputStream(uri); cursor = contentResolver.query(uri, CONTENT_DATA, null, null, null); if (cursor == null || !cursor.moveToFirst()) { return 0; } String filePath = cursor.getString(0); ExifInterface exifInterface = new ExifInterface(filePath); return exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED); <START> } catch (Exception ignored) { <END> return ExifInterface.ORIENTATION_UNDEFINED; } finally { if (cursor != null) { cursor.close(); } } }</code><technical_language>Instead of catching ignoring exceptions, I proper retrieve mime type of image attempt get orientation exif metadata if type supports exif (jpeg), return undefined</technical_language>

Target:
static int getExitOrientationFromFile(ContentResolver contentResolver, Uri uri) { Cursor cursor = null; try { cursor = contentResolver.query(uri, CONTENT_DATA, null, null, null); if (cursor == null || !cursor.moveToFirst()) { return 0; } String filePath = cursor.getString(0); ExifInterface exifInterface = new ExifInterface(filePath); return exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED); } catch (Exception ignored) { return ExifInterface.ORIENTATION_UNDEFINED; } finally { if (cursor != null) { cursor.close(); } } }
Source:
<code><START> Question question(Long id) { <END> return questions.get(id); }</code><technical_language>I this private</technical_language>

Target:
private Question question(Long id) { return questions.get(id); }
Source:
<code>private void sendTupleDomain() { if (positionCount > positionsLimit) { <START> client.ifPresent(client -> client.storeSummary(new DynamicFilterSummary(TupleDomain.all()))); <END> return; } ImmutableMap.Builder<String, Domain> domainsBuilder = ImmutableMap.builder(); for (int channelIndex = 0; channelIndex < filterChannels.size(); channelIndex++) { Integer channel = filterChannels.get(channelIndex); List<Object> values = valuesBuilder.get(channelIndex).build(); Domain domain; if (values.isEmpty()) { domain = Domain.none(types.get(channel)); } else { domain = Domain.create(ValueSet.copyOf(types.get(channel), values), nullsAllowed[channelIndex]); } domainsBuilder.put(filterDynamicFilterNames.get(channelIndex).toString(), domain); } client.ifPresent(client -> client.storeSummary(new DynamicFilterSummary(TupleDomain.withColumnDomains(domainsBuilder.build())))); }</code><technical_language>optional please</technical_language>

Target:
private void sendTupleDomain() { if (positionCount > positionsLimit) { client.storeSummary(new DynamicFilterSummary(TupleDomain.all())); return; } ImmutableMap.Builder<String, Domain> domainsBuilder = ImmutableMap.builder(); for (int channelIndex = 0; channelIndex < filterChannels.size(); channelIndex++) { Integer channel = filterChannels.get(channelIndex); List<Object> values = valuesBuilder.get(channelIndex).build(); Domain domain; if (values.isEmpty()) { domain = Domain.none(types.get(channel)); } else { domain = Domain.create(ValueSet.copyOf(types.get(channel), values), nullsAllowed[channelIndex]); } domainsBuilder.put(filterDynamicFilterNames.get(channelIndex).toString(), domain); } client.storeSummary(new DynamicFilterSummary(TupleDomain.withColumnDomains(domainsBuilder.build()))); }
Source:
<code>public Token selectToken(Text service, Collection<Token<? extends TokenIdentifier>> tokens) { LOG.trace("Getting token for service {}", service); Token token = super.selectToken(service, tokens); <START> LOG.info("Got tokens: for service {}", token, service); <END> return token; }</code><technical_language>dial debug level</technical_language>

Target:
public Token selectToken(Text service, Collection<Token<? extends TokenIdentifier>> tokens) { LOG.trace("Getting token for service {}", service); Token token = super.selectToken(service, tokens); LOG.debug("Got tokens: for service {}", token, service); return token; }
Source:
<code>public void poll() { if (isMonitoringNeeded(vdsManager.getStatus())) { VmsListFetcher fetcher = new VmsStatisticsFetcher(vdsManager); long fetchTime = System.nanoTime(); if (fetcher.fetch()) { getVmsMonitoring().perform(fetcher.getChangedVms(), fetchTime, vdsManager, true); List<VdsmVm> <START> vdsmVmsToMonitor = <END> fetcher.getChangedVms().stream(). filter(monitoredVm -> monitoredVm.getFirst() != null). map(Pair::getSecond).collect(Collectors.toList()); processDevices(vdsmVmsToMonitor.stream(), fetchTime); } else { log.info("Failed to fetch vms info for host '{}' - skipping VMs monitoring.", vdsManager.getVdsName()); } } }</code><technical_language>reportsOnExistingVmsInDb</technical_language>

Target:
public void poll() { if (isMonitoringNeeded(vdsManager.getStatus())) { VmsListFetcher fetcher = new VmsStatisticsFetcher(vdsManager); long fetchTime = System.nanoTime(); if (fetcher.fetch()) { getVmsMonitoring().perform(fetcher.getChangedVms(), fetchTime, vdsManager, true); Stream<VdsmVm> vdsmVmsToMonitor = fetcher.getChangedVms().stream(). filter(monitoredVm -> monitoredVm.getFirst() != null). map(Pair::getSecond); processDevices(vdsmVmsToMonitor, fetchTime); } else { log.info("Failed to fetch vms info for host '{}' - skipping VMs monitoring.", vdsManager.getVdsName()); } } }
Source:
<code>private static Collection<EObject> getDeployableObjects(ISelection selection){ Set<EObject> retVal = new HashSet<>(); if (selection instanceof StructuredSelection) { for (Iterator iterator = (( StructuredSelection)selection).iterator(); iterator.hasNext();) { <START> Object selectedObject = iterator.next(); <END> if(selectedObject instanceof EObject) { addEObject((EObject)selectedObject, retVal); } else if(selectedObject instanceof EditorPart && ((EditPart)selectedObject).getModel() instanceof EObject) { addEObject((EObject)((EditPart)selectedObject).getModel(), retVal); } } } return retVal; }</code><technical_language>is this idiomatic java</technical_language>

Target:
private static Collection<EObject> getDeployableObjects(ISelection selection){ Set<EObject> retVal = new HashSet<>(); if (selection instanceof StructuredSelection) { for (Object selectedObject : (( StructuredSelection)selection).toArray()) { if(selectedObject instanceof EObject) { addEObject((EObject)selectedObject, retVal); } else if(selectedObject instanceof EditorPart && ((EditPart)selectedObject).getModel() instanceof EObject) { addEObject((EObject)((EditPart)selectedObject).getModel(), retVal); } } } return retVal; }
Source:
<code>private void processAnnotations(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { Set<? extends Element> elements = roundEnv.getElementsAnnotatedWith(AutoService.class); log(annotations.toString()); log(elements.toString()); for (Element e : elements) { TypeElement providerImplementer = (TypeElement) e; AnnotationMirror annotationMirror = getAnnotationMirror(e, AutoService.class) .get(); Set<DeclaredType> providerInterfaces = getFieldOfClasses( annotationMirror, "value", processingEnv.getElementUtils()); <START> for (DeclaredType providerInterface : providerInterfaces) { <END> TypeElement providerType = (TypeElement) providerInterface.asElement(); log("provider interface: " + providerType.getQualifiedName()); log("provider implementer: " + providerImplementer.getQualifiedName()); if (!checkImplementer(providerImplementer, providerType)) { String message = "ServiceProviders must implement their service provider interface. " + providerImplementer.getQualifiedName() + " does not implement " + providerType.getQualifiedName(); error(message, e, annotationMirror); } String providerTypeName = getBinaryName(providerType); String providerImplementerName = getBinaryName(providerImplementer); log("provider interface binary name: " + providerTypeName); log("provider implementer binary name: " + providerImplementerName); providers.put(providerTypeName, providerImplementerName); } } }</code><technical_language>gonna want validate !providerInterfaces.isEmpty()</technical_language>

Target:
private void processAnnotations(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { Set<? extends Element> elements = roundEnv.getElementsAnnotatedWith(AutoService.class); log(annotations.toString()); log(elements.toString()); for (Element e : elements) { TypeElement providerImplementer = (TypeElement) e; AnnotationMirror annotationMirror = getAnnotationMirror(e, AutoService.class).get(); Set<DeclaredType> providerInterfaces = getValueFieldOfClasses(annotationMirror); if (providerInterfaces.isEmpty()) { error(MISSING_SERVICES_ERROR, e, annotationMirror); continue; } for (DeclaredType providerInterface : providerInterfaces) { TypeElement providerType = MoreTypes.asTypeElement(providerInterface); log("provider interface: " + providerType.getQualifiedName()); log("provider implementer: " + providerImplementer.getQualifiedName()); if (checkImplementer(providerImplementer, providerType)) { providers.put(getBinaryName(providerType), getBinaryName(providerImplementer)); } else { String message = "ServiceProviders must implement their service provider interface. " + providerImplementer.getQualifiedName() + " does not implement " + providerType.getQualifiedName(); error(message, e, annotationMirror); } } } }
Source:
<code>public int hashCode() { <START> return Objects.hash(repository, tag, authConfigs, doForcePull, memoryLimit, memorySwapLimit, files, dockerfile, remote, q, nocache, <END> rm, forceRm, buildArgs); }</code><technical_language>Please reformat 1 column</technical_language>

Target:
public int hashCode() { return Objects.hash(repository, tag, authConfigs, doForcePull, memoryLimit, memorySwapLimit, files, dockerfile, remote, quiet, noCache, removeIntermediateContainer, forceRemoveIntermediateContainers, buildArgs); }
Source:
<code>public void logIn(final String email, final String password, final ApiCallback<Object> callback) { if (failOnNoInternet(callback)) { <START> callback.onFailure("Active internet connection."); <END> return; } RequestParams params = new RequestParams(); params.put("username", email); params.put("password", password); Log.d(TAG, "logging in as " + email); client.post(sessionUrl, params, new JsonHttpResponseHandler() { @Override public void onSuccess(JSONObject obj) { Log.d(TAG, "User " + email + " logged in"); if (callback != null) { callback.onSuccess(null); } } @Override public void onFailure(Throwable t, JSONObject obj) { String message = "Invalid email/password combination."; if (callback != null) { try { String nameErr = obj.getJSONArray("username").getString(0); String passErr = obj.getJSONArray("password_digest").getString(0); final String errMessage = nameErr + " " + passErr; Log.d(TAG, "errors: " + errMessage); callback.onFailure(message); } catch (JSONException ej) { Log.d(TAG, "JSON problems on log in: " + t.getMessage()); callback.onFailure(message); } } } @Override public void onFailure(Throwable t, String message) { if (t instanceof SocketTimeoutException) { callback.onFailure("Network Timeout"); } else { callback.onFailure(message); } } }); }</code><technical_language>string moved resources for localization</technical_language>

Target:
public void logIn(final String email, final String password, final ApiCallback<Object> callback) { if (failOnNoInternet(callback)) { return; } RequestParams params = new RequestParams(); params.put("username", email); params.put("password", password); Log.d(TAG, "logging in as " + email); client.post(sessionUrl, params, new JsonHttpResponseHandler() { @Override public void onSuccess(JSONObject obj) { Log.d(TAG, "User " + email + " logged in"); if (callback != null) { callback.onSuccess(null); } } @Override public void onFailure(Throwable t, JSONObject obj) { if (callback != null) { try { String message = obj.getString("login"); Log.d(TAG, "Login Error: " + message); callback.onFailure(message); } catch (JSONException ej) { Log.d(TAG, "JSON problems on log in: " + t.getMessage()); onFailure(t, t.getMessage()); } } } @Override public void onFailure(Throwable t, String message) { if (t instanceof SocketTimeoutException) { callback.onFailure(UBudgetApp.getAppContext() .getString(R.string.error_network)); } else { callback.onFailure(message); } } }); }
Source:
<code>public void testListInfoTypes() throws Exception { InfoTypesList.listInfoTypes("supported_by=INSPECT", "en-US"); String output = bout.toString(); <START> assertTrue(output.contains("Name") && output.contains("Display name")); <END> }</code><technical_language>protip: tests easier debug if this format: java Assert.assertThat(x, CoreMatchers.containsString("foo")); error message more descriptive easier debug (Expected x foo, "" instead)</technical_language>

Target:
public void testListInfoTypes() throws Exception { InfoTypesList.listInfoTypes(); String output = bout.toString(); assertThat(output, CoreMatchers.containsString("Name")); assertThat(output, CoreMatchers.containsString("Display name")); }
Source:
<code>protected void executeQueryCommand() { <START> Map<String, String> glusterServers = null; <END> VDS upServer = getClusterUtils().getUpServer(getParameters().getClusterId()); if(upServer != null ) { VDSReturnValue returnValue = getBackendInstance().RunVdsCommand(VDSCommandType.GlusterServersList, new VdsIdVDSCommandParametersBase(upServer.getId())); glusterServers = getAddedGlusterServers((List<GlusterServerInfo>) returnValue.getReturnValue()); } else { glusterServers = new HashMap<String, String>(); } getQueryReturnValue().setReturnValue(glusterServers); }</code><technical_language>initialize empty hash map instead of null avoid else section. Map<String, String> glusterServers = new HashMap<String, String>()</technical_language>

Target:
protected void executeQueryCommand() { Map<String, String> glusterServers = new HashMap<String, String>(); VDS upServer = getClusterUtils().getUpServer(getParameters().getClusterId()); if(upServer != null ) { VDSReturnValue returnValue = getBackendInstance().RunVdsCommand(VDSCommandType.GlusterServersList, new VdsIdVDSCommandParametersBase(upServer.getId())); glusterServers = getAddedGlusterServers((List<GlusterServerInfo>) returnValue.getReturnValue()); } getQueryReturnValue().setReturnValue(glusterServers); }
Source:
<code>public synchronized void createRemoteConsumer(FederatedConsumerKey key, Transformer transformer, ClientSessionCallback callback) { if (started) { FederatedQueueConsumer remoteQueueConsumer = remoteQueueConsumers.get(key); if (remoteQueueConsumer == null) { if (server.hasBrokerFederationPlugins()) { try { server.callBrokerFederationPlugins(plugin -> plugin.beforeCreateFederatedQueueConsumer(key)); } catch (ActiveMQException t) { logger.warn("Error executing beforeCreateFederatedQueueConsumer plugin method: {}", t.getMessage(), t); throw new IllegalStateException(t.getMessage(), t.getCause()); } } remoteQueueConsumer = new FederatedQueueConsumer(federation, server, transformer, key, upstream, callback); remoteQueueConsumer.start(); remoteQueueConsumers.put(key, remoteQueueConsumer); if (server.hasBrokerFederationPlugins()) { try { final FederatedQueueConsumer finalConsumer = remoteQueueConsumer; server.callBrokerFederationPlugins(plugin -> plugin.afterCreateFederatedQueueConsumer(finalConsumer)); <START> } catch (ActiveMQException t) { <END> logger.warn("Error executing afterCreateFederatedQueueConsumer plugin method: {}", t.getMessage(), t); throw new IllegalStateException(t.getMessage(), t.getCause()); } } } remoteQueueConsumer.incrementCount(); } }</code><technical_language>extract interface of FederationQueueConsumer, plugin interface, concrete implementation, this plugins a public api for end users, making future refactoring impossible</technical_language>

Target:
public synchronized void createRemoteConsumer(FederatedConsumerKey key, Transformer transformer, ClientSessionCallback callback) { if (started) { FederatedQueueConsumer remoteQueueConsumer = remoteQueueConsumers.get(key); if (remoteQueueConsumer == null) { if (server.hasBrokerFederationPlugins()) { try { server.callBrokerFederationPlugins(plugin -> plugin.beforeCreateFederatedQueueConsumer(key)); } catch (ActiveMQException t) { ActiveMQServerLogger.LOGGER.federationPluginExecutionError(t, "beforeCreateFederatedQueueConsumer"); throw new IllegalStateException(t.getMessage(), t.getCause()); } } remoteQueueConsumer = new FederatedQueueConsumerImpl(federation, server, transformer, key, upstream, callback); remoteQueueConsumer.start(); remoteQueueConsumers.put(key, remoteQueueConsumer); if (server.hasBrokerFederationPlugins()) { try { final FederatedQueueConsumer finalConsumer = remoteQueueConsumer; server.callBrokerFederationPlugins(plugin -> plugin.afterCreateFederatedQueueConsumer(finalConsumer)); } catch (ActiveMQException t) { ActiveMQServerLogger.LOGGER.federationPluginExecutionError(t, "afterCreateFederatedQueueConsumer"); throw new IllegalStateException(t.getMessage(), t.getCause()); } } } remoteQueueConsumer.incrementCount(); } }
Source:
<code>private static TLSClientParameters constructTLSClient(TLSClientParameters tlsClientParameters) { try { SSLContext context = SSLUtils.getSSLContext(tlsClientParameters); <START> SSLSocketFactory factory = context.getSocketFactory(); <END> if (factory != null) { tlsClientParameters.setSSLSocketFactory(factory); } else { throw new RuntimeException("Couldn't get the SSLSocketFactory."); } tlsClientParameters.setDisableCNCheck(true); } catch (GeneralSecurityException | IllegalStateException e) { LOG.error("Could not get TLS client parameters: ", e.getLocalizedMessage(), e); throw new RuntimeException("Could not create SSL Context.", e); } return tlsClientParameters; }</code><technical_language>is need create context separately. inline</technical_language>

Target:
private static TLSClientParameters constructTLSClient(TLSClientParameters tlsClientParameters) { try { SSLSocketFactory factory = SSLUtils.getSSLContext(tlsClientParameters).getSocketFactory(); if (factory != null) { tlsClientParameters.setSSLSocketFactory(factory); } else { throw new SecurityException("Couldn't get the SSLSocketFactory."); } tlsClientParameters.setDisableCNCheck(true); } catch (GeneralSecurityException | IllegalStateException e) { LOG.error("Could not get TLS client parameters: ", e.getLocalizedMessage(), e); throw new SecurityException("Could not create SSL Context.", e); } return tlsClientParameters; }
Source:
<code>public void hideChild(MElementContainer<MUIElement> parentElement, MUIElement child) { super.hideChild(parentElement, child); if (child.getRenderer() != null) { Widget widget = (Widget) child.getWidget(); if (widget != null && !widget.isDisposed()) { widget.dispose(); } ToolBar toolbar = (ToolBar) getUIContainer(child); if (toolbar != null && !toolbar.isDisposed()) { <START> toolbar.pack(true); <END> toolbar.requestLayout(); } } }</code><technical_language>Remove call pack</technical_language>

Target:
public void hideChild(MElementContainer<MUIElement> parentElement, MUIElement child) { super.hideChild(parentElement, child); if (child.getRenderer() != null) { Widget widget = (Widget) child.getWidget(); if (widget != null && !widget.isDisposed()) { widget.dispose(); } ToolBar toolbar = (ToolBar) getUIContainer(child); if (toolbar != null && !toolbar.isDisposed()) { toolbar.requestLayout(); } } }
Source:
<code>public Set<Usermetadata> getUserMetadataByLogs(List<Integer> logIds, UserMetadataTypeEnum userMetadataTypeEnum) { <START> if (null == logIds || logIds.size() == 0) { return null; } <END> List<Set<Usermetadata>> lists = new ArrayList<>(); for (Integer logId : logIds) { lists.add(getUserMetadataByLog(logId, userMetadataTypeEnum)); } Set<Usermetadata> result = new HashSet<>(); for (Set<Usermetadata> umSet : lists) { for (Usermetadata u : umSet) { int count = 0; Set<UsermetadataLog> umlSet = u.getUsermetadataLog(); if (umlSet.size() == logIds.size()) { for (UsermetadataLog uml : umlSet) { if (logIds.contains(uml.getLog().getId())) { count += 1; } } if (count == logIds.size()) { result.add(u); } } } } return result; }</code><technical_language>Return empty set avoid NPE calling side code "if else" block</technical_language>

Target:
public Set<Usermetadata> getUserMetadataByLogs(List<Integer> logIds, UserMetadataTypeEnum userMetadataTypeEnum) { Set<Usermetadata> result = new HashSet<>(); if (null == logIds || logIds.size() == 0) { return result; } List<Set<Usermetadata>> lists = new ArrayList<>(); for (Integer logId : logIds) { lists.add(getUserMetadataByLog(logId, userMetadataTypeEnum)); } for (Set<Usermetadata> umSet : lists) { for (Usermetadata u : umSet) { int count = 0; Set<UsermetadataLog> umlSet = u.getUsermetadataLog(); if (umlSet.size() == logIds.size()) { for (UsermetadataLog uml : umlSet) { if (logIds.contains(uml.getLog().getId())) { count += 1; } } if (count == logIds.size()) { result.add(u); } } } } return result; }
Source:
<code>public void register() { boolean isLeader = leaderElector.tryBecomeLeader(); if(isLeader) { <START> listenToProcessorLiveness(); <END> debounceTimer.scheduleAfterDebounceTime(ScheduleAfterDebounceTime.ON_PROCESSOR_CHANGE, ScheduleAfterDebounceTime.DEBOUNCE_TIME_MS, () -> zkListener.onBecomeLeader()); } zkUtils.subscribeToJobModelVersionChange(new ZkJobModelVersionChangeHandler(debounceTimer)); }</code><technical_language>listenToProcessorLiveness() process leader in synchronous (return leaderElector.tryBecomeLeader()). For other case, processor a leader original leader dies, invoke listenToProessorLiveness()</technical_language>

Target:
public void register() { leaderElector.tryBecomeLeader(); zkUtils.subscribeToJobModelVersionChange(new ZkJobModelVersionChangeHandler(debounceTimer)); }
Source:
<code>public void testNoAddressResolutionForGraphite() throws Exception { <START> this.graphiteReporterFactory.build(new MetricRegistry()); <END> final ArgumentCaptor<Graphite> argument = ArgumentCaptor.forClass(Graphite.class); verify(this.builderSpy).build(argument.capture()); final Graphite graphite = argument.getValue(); assertThat(getField(graphite, "hostname")).isEqualTo("localhost"); assertThat(getField(graphite, "port")).isEqualTo(8080); assertThat(getField(graphite, "address")).isNull(); }</code><technical_language>remove this. references? this is scoped in class</technical_language>

Target:
public void testNoAddressResolutionForGraphite() throws Exception { graphiteReporterFactory.build(new MetricRegistry()); final ArgumentCaptor<Graphite> argument = ArgumentCaptor.forClass(Graphite.class); verify(builderSpy).build(argument.capture()); final Graphite graphite = argument.getValue(); assertThat(getField(graphite, "hostname")).isEqualTo("localhost"); assertThat(getField(graphite, "port")).isEqualTo(8080); assertThat(getField(graphite, "address")).isNull(); }
Source:
<code>public int getMaxIntermediateSize() { <START> return Double.BYTES; <END> }</code><technical_language>if this a difference not, max size Float.BYTES if storeDoubleAsFloat is true? I pattern is in DoubleFirstAggregatorFactory - a bug in both</technical_language>

Target:
public int getMaxIntermediateSize() { return Double.BYTES + Byte.BYTES; }
Source:
<code>public static BlobId craft(BlobId inputId, short targetVersion, short accountId, short containerId) { if (targetVersion < BLOB_ID_V3) { throw new IllegalArgumentException("Target version for crafting must be V3 or higher"); } return new BlobId(targetVersion, BlobIdType.CRAFTED, inputId.getDatacenterId(), accountId, containerId, <START> inputId.partitionId, inputId.isEncrypted, null, inputId.uuid); <END> }</code><technical_language>pass blobDataType here</technical_language>

Target:
public static BlobId craft(BlobId inputId, short targetVersion, short accountId, short containerId) { if (targetVersion < BLOB_ID_V3) { throw new IllegalArgumentException("Target version for crafting must be V3 or higher"); } return new BlobId(targetVersion, BlobIdType.CRAFTED, inputId.getDatacenterId(), accountId, containerId, inputId.partitionId, inputId.isEncrypted, inputId.blobDataType, inputId.uuid); }
Source:
<code>private static void checkDictionaries(SubscriptionContext ctx, StringFormat format, DictionaryLiteral dict) { if (format.hasPositionalFields()) { ctx.addIssue(dict, "Replace this formatting argument with a tuple."); return; } if (dict.elements().stream().anyMatch(StringFormatMisuseCheck::isOutOfScopeDictionaryElement)) { return; } Map<String, List<StringFormat.ReplacementField>> fieldMap = format.replacementFields().stream().collect( Collectors.groupingBy(StringFormat.ReplacementField::mappingKey)); <START> if (fieldMap.size() != dict.elements().size()) { <END> reportInvalidArgumentSize(ctx, dict, fieldMap.size(), dict.elements().size()); return; } for (DictionaryLiteralElement element : dict.elements()) { KeyValuePair pair = (KeyValuePair) element; String key = ((StringLiteral) pair.key()).trimmedQuotesValue(); List<StringFormat.ReplacementField> fields = fieldMap.remove(key); if (fields == null) { continue; } fields.forEach(field -> field.validateArgument(pair.value())); } fieldMap.keySet().forEach(fieldName -> ctx.addIssue(dict, String.format("Provide a value for field \"%s\".", fieldName))); }</code><technical_language>I want detect missing arguments in case of a dictionary. case fail, I part of scope of this rule: print("Hello %(first_name)s" % {"first_name": "John", "last_name": "Doe"})</technical_language>

Target:
private static void checkDictionaries(SubscriptionContext ctx, StringFormat format, DictionaryLiteral dict) { for (DictionaryLiteralElement element : dict.elements()) { if (!element.is(Tree.Kind.KEY_VALUE_PAIR)) { return; } KeyValuePair pair = (KeyValuePair) element; if (!pair.key().type().canOnlyBe("str")) { ctx.addIssue(pair.key(), "Replace this key; %-format accepts only string keys."); return; } if (!pair.key().is(Tree.Kind.STRING_LITERAL)) { return; } } Map<String, List<StringFormat.ReplacementField>> fieldMap = format.replacementFields().stream().collect( Collectors.groupingBy(StringFormat.ReplacementField::mappingKey)); for (DictionaryLiteralElement element : dict.elements()) { KeyValuePair pair = (KeyValuePair) element; String key = ((StringLiteral) pair.key()).trimmedQuotesValue(); List<StringFormat.ReplacementField> fields = fieldMap.remove(key); if (fields == null) { continue; } fields.forEach(field -> field.validateArgument(pair.value())); } fieldMap.keySet().forEach(fieldName -> ctx.addIssue(dict, String.format("Provide a value for field \"%s\".", fieldName))); }
Source:
<code>protected UserCommandElement(@Nullable Text key, boolean returnSource) { super(key); <START> this.possiblePlayer = new PlayerCommandElement(key, false); <END> this.returnSource = returnSource; }</code><technical_language>This change is good</technical_language>

Target:
protected UserCommandElement(@Nullable Text key, boolean returnSource) { super(key); this.returnSource = returnSource; }
Source:
<code>public XpathFilter(Pattern files, Pattern checks, Pattern message, String moduleId, String query) { if (files == null) { filePattern = null; fileRegexp = null; } else { filePattern = files.pattern(); <START> fileRegexp = files; <END> } if (checks == null) { checkPattern = null; checkRegexp = null; } else { checkPattern = checks.pattern(); checkRegexp = checks; } if (message == null) { messagePattern = null; messageRegexp = null; } else { messagePattern = message.pattern(); messageRegexp = message; } this.moduleId = moduleId; xpathQuery = query; if (xpathQuery == null) { xpathExpression = null; } else { final XPathEvaluator xpathEvaluator = new XPathEvaluator(); try { xpathExpression = xpathEvaluator.createExpression(xpathQuery); } catch (XPathException ex) { throw new IllegalStateException("Illegal xpath query: " + xpathQuery, ex); } } }</code><technical_language><LINK_0> > drop String field forms of expressions for important, swap Pattern form. in equals hashCode methods. preventing removing fields</technical_language>

Target:
public XpathFilter(Pattern files, Pattern checks, Pattern message, String moduleId, String query) { if (files == null) { filePattern = null; fileRegexp = null; } else { filePattern = files.pattern(); fileRegexp = files; } if (checks == null) { checkPattern = null; checkRegexp = null; } else { checkPattern = checks.pattern(); checkRegexp = checks; } if (message == null) { messagePattern = null; messageRegexp = null; } else { messagePattern = message.pattern(); messageRegexp = message; } this.moduleId = moduleId; xpathQuery = query; if (xpathQuery == null) { xpathExpression = null; } else { final XPathEvaluator xpathEvaluator = new XPathEvaluator(); try { xpathExpression = xpathEvaluator.createExpression(xpathQuery); } catch (XPathException ex) { throw new IllegalArgumentException("Incorrect xpath query: " + xpathQuery, ex); } } }
Source:
<code>public String getAttributeValue(String namespace, String localPart) { final String result; if (VALUE_ATTRIBUTE_NAME.equals(localPart)) { result = value; } else if (TEXT_ATTRIBUTE_NAME.equals(localPart)) { <START> result = ident; <END> } else { throw throwUnsupportedOperationException(); } return result; }</code><technical_language>I lost a meaning of private AbstractNode[] attributes; place ident in this collection in time separate in special fields. is a reason</technical_language>

Target:
public String getAttributeValue(String namespace, String localPart) { final AttributeNode attribute = attributes.get(localPart); final String result; if (attribute == null) { result = null; } else { result = attribute.getStringValue(); } return result; }