auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public Response toResponse(ServiceException exception) { int httpStatus = exception.getErrorType().httpErrorCode(); if (Response.Status.Family.familyOf(httpStatus) .equals(Response.Status.Family.CLIENT_ERROR)) { log.info("Error handling request {}", SafeArg.of("errorId", exception.getErrorId()), exception); } else { log.error("Error handling request {}", SafeArg.of("errorId", exception.getErrorId()), exception); } ResponseBuilder builder = Response.status(httpStatus); try { SerializableError error = SerializableError.forException(exception); builder.type(MediaType.APPLICATION_JSON); String json = MAPPER.writeValueAsString(error); builder.entity(json); } catch (RuntimeException | JsonProcessingException e) { log.warn("Unable to translate exception to json for request {}", SafeArg.of("errorId", exception.getErrorId()), e); <START> builder = Response.status(httpStatus); <END> builder.type(MediaType.TEXT_PLAIN); builder.entity(Objects.toString(exception.getMessage())); } return builder.build(); }</code><technical_language>this is done in line 55</technical_language>

Target:
public Response toResponse(ServiceException exception) { int httpStatus = exception.getErrorType().httpErrorCode(); if (Response.Status.Family.familyOf(httpStatus) .equals(Response.Status.Family.CLIENT_ERROR)) { log.info("Error handling request {}", SafeArg.of("errorInstanceId", exception.getErrorInstanceId()), exception); } else { log.error("Error handling request {}", SafeArg.of("errorInstanceId", exception.getErrorInstanceId()), exception); } ResponseBuilder builder = Response.status(httpStatus); try { SerializableError error = SerializableError.builder() .from(SerializableError.forException(exception)) .message("Refer to the server logs with this errorInstanceId: " + exception.getErrorInstanceId()) .build(); builder.type(MediaType.APPLICATION_JSON); String json = MAPPER.writeValueAsString(error); builder.entity(json); } catch (RuntimeException | JsonProcessingException e) { log.warn("Unable to translate exception to json for request {}", SafeArg.of("errorInstanceId", exception.getErrorInstanceId()), e); builder.type(MediaType.TEXT_PLAIN); builder.entity("Unable to translate exception to json. Refer to the server logs with this errorInstanceId: " + exception.getErrorInstanceId()); } return builder.build(); }
Source:
<code>public List<TokenCacheItem> getTokensForResource(String resource) { Iterator<TokenCacheItem> results = this.getAll(); <START> List<TokenCacheItem> tokenItems = new ArrayList<>(); <END> while (results.hasNext()) { final TokenCacheItem tokenCacheItem = results.next(); if (resource.equals(tokenCacheItem.getResource())) { tokenItems.add(tokenCacheItem); } } return tokenItems; }</code><technical_language>final</technical_language>

Target:
public List<TokenCacheItem> getTokensForResource(String resource) { Iterator<TokenCacheItem> results = this.getAll(); final List<TokenCacheItem> tokenItems = new ArrayList<>(); while (results.hasNext()) { final TokenCacheItem tokenCacheItem = results.next(); if (resource.equals(tokenCacheItem.getResource())) { tokenItems.add(tokenCacheItem); } } return tokenItems; }
Source:
<code>public void UpdateDynamicData(VdsDynamic dynamicData) { if (dynamicData != null && _vds != null && _vds.getDynamicData() != null <START> && (!dynamicData.equals(_vds.getDynamicData()) || dynamicData.getprevious_status() != dynamicData.getStatus())) { <END> DbFacade.getInstance().getVdsDynamicDao().update(dynamicData); } else { log.debug("Ignoring unneeded update of VDSDynamic"); } }</code><technical_language>work..see callers of this method. example is : UpdateVdsVMsClearedVDSCommand.executeVdsIdCommand</technical_language>

Target:
public void UpdateDynamicData(VdsDynamic dynamicData) { log.debug("Updated VDS dynamic without checking if update is needed"); DbFacade.getInstance().getVdsDynamicDao().update(dynamicData); }
Source:
<code>void convertWithServiceEventData() { ActorBase actor = ActorCrn.builder().withActorCrn(USER_CRN).build(); EventData eventData = ServiceEventData.builder() .withVersion(SERVICE_EVENT_VERSION) <START> .withEventDetails(SERVICE_EVENT_DETAILS) .build(); AuditEvent source = makeAuditEvent(actor, eventData); underTest = new AuditEventToGrpcAuditEventConverter(createMockUtilizer(ServiceEventData.class)); <END> AuditProto.AuditEvent target = underTest.convert(source); assertGeneric(target); verify(mockEventDataUtilizer, times(1)).modifyAuditEventBuilderWithEventData(any(), any()); }</code><technical_language>I miss tests in for refactored converter classes</technical_language>

Target:
void convertWithServiceEventData() { ActorBase actor = ActorCrn.builder().withActorCrn(USER_CRN).build(); EventData eventData = ServiceEventData.builder() .withVersion(SERVICE_EVENT_VERSION) .withEventDetails(SERVICE_EVENT_DETAILS) .build(); AuditEvent source = makeAuditEvent(actor, eventData); underTest = new AuditEventToGrpcAuditEventConverter(createMockUtilizer(ServiceEventData.class), mockBuilderProvider); underTest.convert(source); assertGeneric(); verify(mockAuditEventBuilderUpdater, times(1)).update(any(), any()); }
Source:
<code>public void escapeHTMLCharsInAttributes() throws Exception { String htmlInput = "<div foo=\"aaa&quot;bbb&amp;ccc&gt;ddd&lt;eee&apos;fff\">content</div>"; Document document = this.cleaner.clean(new StringReader(htmlInput)); String textContent = document.getElementsByTagName("div").item(0).getAttributes().getNamedItem("foo").getTextContent(); <START> assertEquals("aaa&quot;bbb&amp;ccc&gt;ddd&lt;eee&apos;fff", textContent); <END> htmlInput = "<div foo='aaa&quot;bbb&amp;ccc&gt;ddd&lt;eee&apos;fff'>content</div>"; document = this.cleaner.clean(new StringReader(htmlInput)); textContent = document.getElementsByTagName("div").item(0).getAttributes().getNamedItem("foo").getTextContent(); assertEquals("aaa&quot;bbb&amp;ccc&gt;ddd&lt;eee&apos;fff", textContent); assertHTML("<div foo=\"aaa&quot;bbb&amp;ccc&gt;ddd&lt;eee&apos;fff\">content</div>", "<div foo=\"aaa&quot;bbb&amp;ccc&gt;ddd&lt;eee&apos;fff\">content</div>"); assertHTML("<div foo=\"aaa&quot;bbb&amp;ccc&gt;ddd&lt;eee&apos;fff\">content</div>", "<div foo='aaa&quot;bbb&amp;ccc&gt;ddd&lt;eee&apos;fff'>content</div>"); }</code><technical_language>I issue is HtmlUtils is XMLOutputter, account HTML entities all. XML entities... serializer escape needs escaped in context of a specific encoding (usually UTF8 in case). While parser need understand kind of entities encounter resolve properly of characters represent needed escaped in place in UTF8 (probably of actually)</technical_language>

Target:
void escapeHTMLCharsInAttributes() throws Exception { String htmlInput = "<div foo=\"aaa&quot;bbb&amp;ccc&gt;ddd&lt;eee&apos;fff\">content</div>"; Document document = this.cleaner.clean(new StringReader(htmlInput)); String textContent = document.getElementsByTagName("div").item(0).getAttributes().getNamedItem("foo").getTextContent(); assertEquals("aaa\"bbb&ccc>ddd<eee'fff", textContent); htmlInput = "<div foo='aaa&quot;bbb&amp;ccc&gt;ddd&lt;eee&apos;fff'>content</div>"; document = this.cleaner.clean(new StringReader(htmlInput)); textContent = document.getElementsByTagName("div").item(0).getAttributes().getNamedItem("foo").getTextContent(); assertEquals("aaa\"bbb&ccc>ddd<eee'fff", textContent); assertHTML("<div foo=\"aaa&quot;bbb&amp;ccc&gt;ddd&lt;eee'fff\">content</div>", "<div foo=\"aaa&quot;bbb&amp;ccc&gt;ddd&lt;eee&apos;fff\">content</div>"); assertHTML("<div foo=\"aaa&quot;bbb&amp;ccc&gt;ddd&lt;eee'fff\">content</div>", "<div foo='aaa&quot;bbb&amp;ccc&gt;ddd&lt;eee&apos;fff'>content</div>"); }
Source:
<code>public <I extends T> LazyRegistryObject<I> lazyRegister(final String name, final Supplier<? extends I> sup) { Objects.requireNonNull(name); Objects.requireNonNull(sup); final ResourceLocation key = new ResourceLocation(modid, name); <START> LazyRegistryObject<I> lazyRet = new LazyRegistryObject<>(()->RegistryObject.of(key, this.type)); <END> if (lazyEntries.putIfAbsent(lazyRet.cast(), () -> sup.get().setRegistryName(key)) != null) { throw new IllegalArgumentException("Duplicate registration " + name); } return lazyRet; }</code><technical_language>Instead of giving this.type in supplier for lazy registry object, getFromSupplier() slightly reliance making getFromSupplier() called supplier is ran. I this case if getEntries() is called new registry event entries added in addEntries (Not I of a case for call in stage)</technical_language>

Target:
public <I extends T> LazyRegistryObject<I> lazyRegister(final String name, final Supplier<? extends I> sup) { Objects.requireNonNull(name); Objects.requireNonNull(sup); final ResourceLocation key = new ResourceLocation(modid, name); LazyRegistryObject<I> lazyRet = new LazyRegistryObject<>(()->RegistryObject.of(key, this.getType())); if (lazyEntries.putIfAbsent((LazyRegistryObject<T>)lazyRet, () -> sup.get().setRegistryName(key)) != null) { throw new IllegalArgumentException("Duplicate registration " + name); } return lazyRet; }
Source:
<code><START> public void setProjectSaver(ProjectSaver projectSaver) { <END> this.projectSaver = projectSaver; }</code><technical_language>need for public setter set in constructor</technical_language>

Target:
protected void setProjectSaver(ProjectSaver projectSaver) { this.projectSaver = projectSaver; }
Source:
<code>public Object deserialize(ByteBuf b, CorfuRuntime rt) { try (ByteBufInputStream bbis = new ByteBufInputStream(b)) { MessageType type = MessageType.valueOf(bbis.readInt()); int size = bbis.readInt(); byte[] data = new byte[size]; bbis.readFully(data); Record record = Record.parseFrom(data); Any payload = record.getPayload(); FileDescriptor valueFileDescriptor = getDescriptor(messagesFdProtoNameMap.get(getFullMessageName(payload))); Descriptor valueDescriptor = valueFileDescriptor.findMessageTypeByName(getMessageName(payload)); DynamicMessage value = DynamicMessage.parseFrom(valueDescriptor, payload.getValue()); <START> if (type.equals(MessageType.KEY)) { <END> return new DynamicCorfuKey(payload.getTypeUrl(), value); } String metadataTypeUrl = null; DynamicMessage metadata = null; if (record.hasMetadata()) { Any anyMetadata = record.getMetadata(); metadataTypeUrl = anyMetadata.getTypeUrl(); FileDescriptor metaFileDescriptor = getDescriptor(messagesFdProtoNameMap.get(getFullMessageName(anyMetadata))); Descriptor metaDescriptor = metaFileDescriptor.findMessageTypeByName(getMessageName(anyMetadata)); metadata = DynamicMessage.parseFrom(metaDescriptor, anyMetadata.getValue()); } return new DynamicCorfuRecord(payload.getTypeUrl(), value, metadataTypeUrl, metadata); } catch (IOException | DescriptorValidationException ie) { log.error("Exception during deserialization!", ie); throw new SerializerException(ie); } }</code><technical_language>explicitly a MessageType for VALUE</technical_language>

Target:
public Object deserialize(ByteBuf b, CorfuRuntime rt) { try (ByteBufInputStream bbis = new ByteBufInputStream(b)) { MessageType type = MessageType.valueOf(bbis.readInt()); int size = bbis.readInt(); byte[] data = new byte[size]; bbis.readFully(data); Record record = Record.parseFrom(data); Any payload = record.getPayload(); FileDescriptor valueFileDescriptor = getDescriptor(messagesFdProtoNameMap.get(getFullMessageName(payload))); Descriptor valueDescriptor = valueFileDescriptor.findMessageTypeByName(getMessageName(payload)); DynamicMessage value = DynamicMessage.parseFrom(valueDescriptor, payload.getValue()); if (type.equals(MessageType.KEY)) { return new CorfuDynamicKey(payload.getTypeUrl(), value); } String metadataTypeUrl = null; DynamicMessage metadata = null; if (record.hasMetadata()) { Any anyMetadata = record.getMetadata(); metadataTypeUrl = anyMetadata.getTypeUrl(); FileDescriptor metaFileDescriptor = getDescriptor(messagesFdProtoNameMap.get(getFullMessageName(anyMetadata))); Descriptor metaDescriptor = metaFileDescriptor.findMessageTypeByName(getMessageName(anyMetadata)); metadata = DynamicMessage.parseFrom(metaDescriptor, anyMetadata.getValue()); } return new CorfuDynamicRecord(payload.getTypeUrl(), value, metadataTypeUrl, metadata); } catch (IOException | DescriptorValidationException ie) { log.error("Exception during deserialization!", ie); throw new SerializerException(ie); } }
Source:
<code>public void onModuleLoad() { Debug.injectDebug(); <START> Debug.devlog("onModuleLoad()!"); <END> maybeDelayLoadApplication(this); }</code><technical_language>Nit: remove debug logging</technical_language>

Target:
public void onModuleLoad() { Debug.injectDebug(); maybeDelayLoadApplication(this); }
Source:
<code>public void removeTimestampedSnapshots(String storageId, String repositoryId, String artifactPath, int numberToKeep, int keepPeriod) throws IOException { try { DateFormat formatter = new SimpleDateFormat(TIMESTAMP_FORMAT); Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.DAY_OF_MONTH, -keepPeriod); Date keepDate = formatter.parse(formatter.format(calendar.getTime())); removeTimestampedSnapshots(storageId, repositoryId, artifactPath, numberToKeep, keepDate); } catch (ParseException e) { <START> logger.error(e.getMessage(), e); <END> } }</code><technical_language>please throw new IOException(e) instead of logger</technical_language>

Target:
public void removeTimestampedSnapshots(String storageId, String repositoryId, String artifactPath, int numberToKeep, int keepPeriod) throws IOException { try { DateFormat formatter = new SimpleDateFormat(MavenSnapshotManager.TIMESTAMP_FORMAT); Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.DAY_OF_MONTH, -keepPeriod); Date keepDate = formatter.parse(formatter.format(calendar.getTime())); removeTimestampedSnapshots(storageId, repositoryId, artifactPath, numberToKeep, keepDate); } catch (ParseException e) { throw new IOException(e); } }
Source:
<code>private static ConjureLockRequest clampLockRequestToDeadline(ConjureLockRequest request, Duration remainingTime) { return ConjureLockRequest.builder() .from(request) <START> .acquireTimeoutMs(Ints.saturatedCast(remainingTime.toMillis())) <END> .build(); }</code><technical_language>Ints.checkedCast this? This is a long if a bug</technical_language>

Target:
private static ConjureLockRequest clampLockRequestToDeadline(ConjureLockRequest request, Duration remainingTime) { return ConjureLockRequest.builder() .from(request) .acquireTimeoutMs(Ints.checkedCast(remainingTime.toMillis())) .build(); }
Source:
<code>public void testCreateListenerWithLocationIllegalStateException() throws Exception { final Method method = Main.class.getDeclaredMethod("createListener", String.class, String.class); method.setAccessible(true); final String outDir = "myfolder123"; final LocalizedMessage createListenerMessage = new LocalizedMessage(0, Definitions.CHECKSTYLE_BUNDLE, "Main.createListener", <START> new String[] {"myformat", "plain", "xml"}, null, getClass(), null); <END> try { method.invoke(null, "myformat", outDir); fail("InvocationTargetException is expected"); } catch (InvocationTargetException ex) { assertEquals(createListenerMessage.getMessage(), ex.getCause().getLocalizedMessage()); assertTrue(ex.getCause() instanceof IllegalStateException); } finally { FileUtils.deleteQuietly(new File(outDir)); } }</code><technical_language>please move close usage possible</technical_language>

Target:
public void testCreateListenerWithLocationIllegalStateException() throws Exception { final Method method = Main.class.getDeclaredMethod("createListener", String.class, String.class); method.setAccessible(true); final String outDir = "myfolder123"; try { method.invoke(null, "myformat", outDir); fail("InvocationTargetException is expected"); } catch (InvocationTargetException ex) { final LocalizedMessage createListenerMessage = new LocalizedMessage(0, Definitions.CHECKSTYLE_BUNDLE, "Main.createListener", new String[] {"myformat", "plain", "xml"}, null, getClass(), null); assertEquals(createListenerMessage.getMessage(), ex.getCause().getLocalizedMessage()); assertTrue(ex.getCause() instanceof IllegalStateException); } finally { FileUtils.deleteQuietly(new File(outDir)); } }
Source:
<code>protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { StringBuilder response = new StringBuilder(); String requestedInfo = req.getParameter(PARAM); if (requestedInfo.equals(PARAM_STARTED)) { getStartedInfo(response); } else if (requestedInfo.equals(PARAM_SUMMARY)) { String givenKey = req.getParameter(PARAM_SUMMARY_KEY); if (getRuntimeService().getProperty(Environment.SERVER_STATUS_KEY).equals(givenKey)) { getSummaryInfo(response); } else { resp.setStatus(HttpServletResponse.SC_FORBIDDEN); } } else if (requestedInfo.equals(PARAM_RELOAD)) { if (isStarted()) { response.append("reload();"); } else { resp.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } } else if (requestedInfo.equals(PROBE_PARAM)) { String probetoEval = req.getParameter(PARAM_SUMMARY_KEY); HealthCheckResult result = getOrRunHealthCheck(probetoEval); <START> if (result.toJson().isEmpty()) { <END> resp.setStatus(HttpServletResponse.SC_NOT_FOUND); } else { sendHealthCheckResponse(resp, result); } } sendResponse(resp, response.toString()); }</code><technical_language>rely fact string is empty guess probe found. getOrRunHealthCheck send exception cought here</technical_language>

Target:
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { StringBuilder response = new StringBuilder(); String requestedInfo = req.getParameter(PARAM); if (requestedInfo.equals(PARAM_STARTED)) { getStartedInfo(response); } else if (requestedInfo.equals(PARAM_SUMMARY)) { String givenKey = req.getParameter(PARAM_SUMMARY_KEY); if (getRuntimeService().getProperty(Environment.SERVER_STATUS_KEY).equals(givenKey)) { getSummaryInfo(response); } else { resp.setStatus(HttpServletResponse.SC_FORBIDDEN); } } else if (requestedInfo.equals(PARAM_RELOAD)) { if (isStarted()) { response.append("reload();"); } else { resp.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } } else if (requestedInfo.equals(PROBE_PARAM)) { String probetoEval = req.getParameter(PARAM_SUMMARY_KEY); try { HealthCheckResult result = getOrRunHealthCheck(probetoEval); sendHealthCheckResponse(resp, result); } catch (IllegalArgumentException e) { resp.setStatus(HttpServletResponse.SC_NOT_FOUND); } } sendResponse(resp, response.toString()); }
Source:
<code>private void waitForMockServer() throws Exception { RetryPolicy retryPolicy = new RetryPolicy() .withMaxDuration(2, TimeUnit.MINUTES) .withDelay(SLEEP_TIME, TimeUnit.MILLISECONDS); Failsafe.with(retryPolicy) .run( <START> () -> <END> given() .auth() .preemptive() .basic(ADMIN, ADMIN) .body( "<csw:GetCapabilities service=\"CSW\" xmlns:csw=\"<LINK_1>\" xmlns:ows=\"<LINK_0>\"/>") .header("Content-Type", "text/xml") .expect() .log() .ifValidationFails() .statusCode(200) .when() .post(CSW_PATH.getUrl())); }</code><technical_language>move lambda a private method</technical_language>

Target:
private void waitForMockServer() throws Exception { RetryPolicy retryPolicy = new RetryPolicy() .withMaxDuration(2, TimeUnit.MINUTES) .withDelay(SLEEP_TIME, TimeUnit.MILLISECONDS); Failsafe.with(retryPolicy).run(this::mockServerIsReady); }
Source:
<code>public void testBulkApiWithPkChunking() throws Throwable { TSalesforceInputProperties properties = createTSalesforceInputProperties(false, true); properties.manualQuery.setValue(false); List<IndexedRecord> readRows = readRows(properties); int defaultRecordsInSalesforce = readRows.size(); properties.pkChunking.setValue(true); properties.chunkSize.setValue(TSalesforceInputProperties.DEFAULT_CHUNK_SIZE); int count = 1500; String random = createNewRandom(); List<IndexedRecord> outputRows = makeRows(random, count, true); outputRows = writeRows(random, properties, outputRows); try { readRows = readRows(properties); LOGGER.info("Read rows count - {}", readRows.size()); <START> Assert.assertTrue((readRows.size() - defaultRecordsInSalesforce) == outputRows.size()); <END> } finally { deleteRows(outputRows, properties); } }</code><technical_language>please, assertEquals instead</technical_language>

Target:
public void testBulkApiWithPkChunking() throws Throwable { TSalesforceInputProperties properties = createTSalesforceInputProperties(false, true); properties.manualQuery.setValue(false); List<IndexedRecord> readRows = readRows(properties); int defaultRecordsInSalesforce = readRows.size(); properties.pkChunking.setValue(true); properties.chunkSize.setValue(TSalesforceInputProperties.DEFAULT_CHUNK_SIZE); int count = 1500; String random = createNewRandom(); List<IndexedRecord> outputRows = makeRows(random, count, true); outputRows = writeRows(random, properties, outputRows); try { readRows = readRows(properties); LOGGER.info("Read rows count - {}", readRows.size()); Assert.assertEquals((readRows.size() - defaultRecordsInSalesforce), outputRows.size()); } finally { deleteRows(outputRows, properties); } }
Source:
<code>public void tileEntity(AttachCapabilitiesEvent<TileEntity> event) { final TileEntity entity = event.getObject(); for (final Class<? extends TileEntity> c: kitchenItemProviderEntities) { if (! c.isInstance(entity)) continue; event.addCapability(capabilityKitchenItemProvider, crateItemCapabilityProvider(entity, false)); return; } for (final Class<? extends TileEntity> c: dynKitchenItemProviderEntities) { if (! c.isInstance(entity)) continue; event.addCapability(capabilityKitchenItemProvider, crateItemCapabilityProvider(entity, true)); return; } for (final Class<? extends TileEntity> c: kitchenConnectorEntities) { if (! c.isInstance(entity)) continue; event.addCapability(capabilityKitchenConnector, <START> new ICapabilityProvider() { <END> @Override public boolean hasCapability(Capability<?> capability, EnumFacing facing) { return CapabilityKitchenConnector.CAPABILITY == capability; } @Override public <T> T getCapability(Capability<T> capability, EnumFacing facing) { return null; } }); return; } }</code><technical_language>This extracted a private static class for readability</technical_language>

Target:
public void tileEntity(AttachCapabilitiesEvent<TileEntity> event) { final TileEntity entity = event.getObject(); final Class<? extends TileEntity> entityClass = entity.getClass(); final CapabilityType type = tilesClasses.get(entityClass); if (type == null) { return; } switch (type) { case CONNECTOR: event.addCapability(connectorResourceKey, connectorCapabilityProvider); break; case ITEM_PROVIDER: event.addCapability(itemProviderResourceKey, new KitchenItemCapabilityProvider(entity)); break; } }
Source:
<code>private void checkLastScalingActivity(AmazonAutoScalingClient asClient, AmazonAutoScalingRetryClient asRetryClient, String autoScalingGroupName, Date timeBeforeASUpdate) throws AmazonAutoscalingFailed { try { Waiter<DescribeScalingActivitiesRequest> autoscalingActivitesWaiter = customAmazonWaiterProvider .getAutoscalingActivitesWaiter(asClient, timeBeforeASUpdate); autoscalingActivitesWaiter.run(new WaiterParameters<>(new DescribeScalingActivitiesRequest().withAutoScalingGroupName(autoScalingGroupName))); } catch (Exception e) { LOGGER.error("Failed to list activities: {}", e.getMessage(), e); throw new AmazonAutoscalingFailed(e.getMessage(), e); } <START> DescribeScalingActivitiesResult describeScalingActivitiesResult = asRetryClient <END> .describeScalingActivities(new DescribeScalingActivitiesRequest().withAutoScalingGroupName(autoScalingGroupName)); Optional<Activity> firstActivity = describeScalingActivitiesResult.getActivities().stream().findFirst() .filter(activity -> "failed".equals(activity.getStatusCode().toLowerCase())); if (firstActivity.isPresent()) { Activity activity = firstActivity.get(); LOGGER.error("Cannot execute autoscale, because last activity is failed: {}", activity); throw new AmazonAutoscalingFailed(activity.getDescription() + " " + activity.getCause()); } }</code><technical_language>a solid try-catch this provider call</technical_language>

Target:
void checkLastScalingActivity(AmazonAutoScalingClient asClient, AmazonAutoScalingRetryClient asRetryClient, String autoScalingGroupName, Date timeBeforeASUpdate) throws AmazonAutoscalingFailed { Optional<Activity> firstActivity; try { Waiter<DescribeScalingActivitiesRequest> autoscalingActivitiesWaiter = customAmazonWaiterProvider .getAutoscalingActivitesWaiter(asClient, timeBeforeASUpdate); autoscalingActivitiesWaiter.run(new WaiterParameters<>(new DescribeScalingActivitiesRequest().withAutoScalingGroupName(autoScalingGroupName))); DescribeScalingActivitiesResult describeScalingActivitiesResult = asRetryClient .describeScalingActivities(new DescribeScalingActivitiesRequest().withAutoScalingGroupName(autoScalingGroupName)); firstActivity = describeScalingActivitiesResult.getActivities().stream().findFirst() .filter(activity -> "failed".equals(activity.getStatusCode().toLowerCase())); } catch (Exception e) { LOGGER.error("Failed to list activities: {}", e.getMessage(), e); throw new AmazonAutoscalingFailed(e.getMessage(), e); } if (firstActivity.isPresent()) { Activity activity = firstActivity.get(); LOGGER.error("Cannot execute autoscale, because last activity is failed: {}", activity); throw new AmazonAutoscalingFailed(activity.getDescription() + " " + activity.getCause()); } }
Source:
<code>public boolean isSealed() { <START> return false; <END> }</code><technical_language>If partition replicated is sealed, reflect here? (Not if info available.)</technical_language>

Target:
public boolean isSealed() { return partitionId.getPartitionState().equals(PartitionState.READ_ONLY); }
Source:
<code>public void SetVmUnknown(VM vm) { RemoveAsyncRunningVm(vm.getId()); <START> InternalSetVmStatus(vm, VMStatus.Unknown, vm.getStatusUpdatedTime()); <END> AuditLogableBase logable = new AuditLogableBase(); logable.setVmId(vm.getId()); auditLogDirector.log(logable, AuditLogType.VM_SET_TO_UNKNOWN_STATUS); storeVm(vm); }</code><technical_language>needed (the is null anyway)</technical_language>

Target:
public void SetVmUnknown(VM vm) { RemoveAsyncRunningVm(vm.getId()); InternalSetVmStatus(vm, VMStatus.Unknown); AuditLogableBase logable = new AuditLogableBase(); logable.setVmId(vm.getId()); auditLogDirector.log(logable, AuditLogType.VM_SET_TO_UNKNOWN_STATUS); storeVm(vm); }
Source:
<code><START> private void processInput() { <END> if(getThreadCount() == 1 && getCallContexts().size() == 1) processInput(getCallContext()); else if(getThreadCount() == 1 && getCallContexts().size()>1) { while(!getCallContexts().isEmpty()) { CallContext callContext = getCallContexts().poll(); if(callContext != null) processInput(callContext); } } else { try { for (int i = 0; i < getThreadCount(); i++) { BulkCallableImpl bulkCallableImpl = new BulkCallableImpl(this); submitTask(bulkCallableImpl); } getCallerThreadPoolExecutor().awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS); } catch(Throwable throwable) { throw new RuntimeException("Error occurred while awaiting termination "+throwable.getMessage()); } } }</code><technical_language>implementation uncovered a design issue in technical story: adding a task task queue claim input input queue. solve this problem, no-arguments processInput() method - change existing processInput(CallContext callContext) signature processInput(CallContext callContext, InputStream[] inputBatch) - replace existing call getInputBatch() line 195 inputBatch parameter - define a new local InputStream[] inputBatch variable initialized calling getInputBatch(getQueue(), getBatchSize()) line of existing processInput() method - call processInput() call context inputBatch in single callContext field case - pass inputBatch BulkCallableImpl() constructor in callContexts (aka callContextQueue) field case - assign inputBatch a private field of BulkCallableImpl class - private inputBatch field calling processInput() BulkCallableImpl.call() method If possible, if BulkCallableImpl a static class elsewhere,</technical_language>

Target:
private void processInput() { InputStream[] inputBatch = getInputBatch(getQueue(), getBatchSize()); if(getCallContext()!=null) processInput(getCallContext(), inputBatch); else if(getCallContextQueue() != null && !getCallContextQueue().isEmpty()){ BulkCallableImpl bulkCallableImpl = new BulkCallableImpl(this, inputBatch); submitTask(bulkCallableImpl); } else { throw new IllegalArgumentException("Cannot process input without Callcontext."); } }
Source:
<code>void addDoneListenerToFormatJob() { formatJob.addJobChangeListener(new JobChangeAdapter() { public void done(IJobChangeEvent event) { if (!event.getResult().isOK()) return; final StyledText text = getTextWidget(); if (text == null || text.isDisposed()) return; final FormatJob job = (FormatJob) event.getJob(); text.getDisplay().asyncExec(new Runnable() { public void run() { if (text.isDisposed()) return; setDocument(new Document(job.getFormatResult() .getCommitInfo())); List<StyleRange> styleRangeList = new ArrayList<StyleRange>(); for (StyleRange styleRange : job.getFormatResult() .getStyleRange()) styleRangeList.add(styleRange); StyleRange[] hyperlinkDetectorStyleRanges = getHyperlinkDetectorStyleRanges(); for (StyleRange styleRange : hyperlinkDetectorStyleRanges) styleRangeList.add(styleRange); styleRanges = new StyleRange[styleRangeList .size()]; styleRangeList.toArray(styleRanges); Arrays.sort(styleRanges, new Comparator<StyleRange>() { public int compare(StyleRange o1, StyleRange o2) { if (o2.start > o1.start) return -1; if (o1.start > o2.start) return 1; return 0; } }); text.setStyleRanges(new StyleRange[0]); <START> for (StyleRange sr : styleRanges) { <END> text.setStyleRange(sr); } } }); } }); }</code><technical_language>style nit: braces single line blocks</technical_language>

Target:
void addDoneListenerToFormatJob() { formatJob.addJobChangeListener(new JobChangeAdapter() { public void done(IJobChangeEvent event) { if (!event.getResult().isOK()) return; final StyledText text = getTextWidget(); if (text == null || text.isDisposed()) return; final FormatJob job = (FormatJob) event.getJob(); text.getDisplay().asyncExec(new Runnable() { public void run() { if (text.isDisposed()) return; setDocument(new Document(job.getFormatResult() .getCommitInfo())); List<StyleRange> styleRangeList = new ArrayList<StyleRange>(); for (StyleRange styleRange : job.getFormatResult() .getStyleRange()) styleRangeList.add(styleRange); StyleRange[] hyperlinkDetectorStyleRanges = UIUtils .getHyperlinkDetectorStyleRanges( CommitMessageViewer.this, fHyperlinkDetectors); for (StyleRange styleRange : hyperlinkDetectorStyleRanges) styleRangeList.add(styleRange); styleRanges = new StyleRange[styleRangeList .size()]; styleRangeList.toArray(styleRanges); Arrays.sort(styleRanges, new Comparator<StyleRange>() { public int compare(StyleRange o1, StyleRange o2) { if (o2.start > o1.start) return -1; if (o1.start > o2.start) return 1; return 0; } }); text.setStyleRanges(new StyleRange[0]); for (StyleRange sr : styleRanges) text.setStyleRange(sr); } }); } }); }
Source:
<code>public String isCan_delete() { <START> return can_delete; <END> }</code><technical_language>return a boolean</technical_language>

Target:
public boolean isCan_delete() { return can_delete; }
Source:
<code><START> public static WebArchive createDeployment() { <END> return ShrinkWrap.create(WebArchive.class, "ContextTrackerRegistryTest.war") .addClass(TrackerCountReportingRouteBuilder.class) .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml"); }</code><technical_language>I notice a bunch of tests camel-undertow switched WAR. mandating WAR for camel-undertow consumer usage</technical_language>

Target:
public static WebArchive createDeployment() { return ShrinkWrap.create(WebArchive.class, "ContextTrackerRegistryTest.war") .addClass(TrackerCountReportingRouteBuilder.class) .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml"); }
Source:
<code>private void executeOpenCommandWithConfirmation(String refName) { if (!BranchOperationUI.checkoutWillShowQuestionDialog(refName)) { String shortName = Repository.shortenRefName(refName); IPreferenceStore store = Activator.getDefault() .getPreferenceStore(); if (store.getBoolean(UIPreferences.SHOW_CHECKOUT_CONFIRMATION)) { String toggleMessage = UIText.RepositoriesView_CheckoutConfirmationToggleMessage; MessageDialogWithToggle dlg = null; boolean <START> canUseNewApi = <END> Platform.getBundle("org.eclipse.jface") .getVersion() .compareTo(Version.valueOf("3.13.0.qualifier")) >= 0; if(canUseNewApi) { LinkedHashMap<String, Integer> buttonLabelToIdMap = new LinkedHashMap<>(); buttonLabelToIdMap.put( UIText.RepositoriesView_CheckoutConfirmationOkButtonLabel, IDialogConstants.OK_ID); buttonLabelToIdMap.put(IDialogConstants.CANCEL_LABEL, IDialogConstants.CANCEL_ID); dlg = MessageDialogWithToggle.open(MessageDialog.CONFIRM, getViewSite().getShell(), UIText.RepositoriesView_CheckoutConfirmationTitle, MessageFormat.format( UIText.RepositoriesView_CheckoutConfirmationMessage, shortName), toggleMessage, false, store, UIPreferences.SHOW_CHECKOUT_CONFIRMATION, SWT.NONE, buttonLabelToIdMap); } else { dlg = MessageDialogWithToggle.openOkCancelConfirm( getViewSite().getShell(), UIText.RepositoriesView_CheckoutConfirmationTitle, MessageFormat.format( UIText.RepositoriesView_CheckoutConfirmationMessage, shortName), toggleMessage, false, store, UIPreferences.SHOW_CHECKOUT_CONFIRMATION); } if (dlg.getReturnCode() != Window.OK) return; } } executeOpenCommand(); }</code><technical_language>This is a constant value, recomputed call</technical_language>

Target:
private void executeOpenCommandWithConfirmation(String refName) { if (!BranchOperationUI.checkoutWillShowQuestionDialog(refName)) { String shortName = Repository.shortenRefName(refName); IPreferenceStore store = Activator.getDefault() .getPreferenceStore(); if (store.getBoolean(UIPreferences.SHOW_CHECKOUT_CONFIRMATION)) { MessageDialogWithToggle dlg = showCheckoutConfirmationDialog( shortName, store); if (dlg.getReturnCode() != Window.OK) return; } } executeOpenCommand(); }
Source:
<code>private String getNextUidNumber(LdapServer ldapServer) { Hashtable<String, String> ldapEnvironment = initializeWithLdapConnectionSettings(ldapServer); DirContext ctx; String rueckgabe = ""; try { ctx = new InitialDirContext(ldapEnvironment); Attributes attrs = ctx.getAttributes(ldapServer.getNextFreeUnixIdPattern()); Attribute la = attrs.get("uidNumber"); rueckgabe = (String) la.get(0); ctx.close(); } catch (NamingException e) { <START> logger.error(e.getMessage(), e); <END> Helper.setFehlerMeldung(e.getMessage()); } return rueckgabe; }</code><technical_language>setErrorMessage</technical_language>

Target:
private String getNextUidNumber(LdapServer ldapServer) { Hashtable<String, String> ldapEnvironment = initializeWithLdapConnectionSettings(ldapServer); DirContext ctx; String rueckgabe = ""; try { ctx = new InitialDirContext(ldapEnvironment); Attributes attrs = ctx.getAttributes(ldapServer.getNextFreeUnixIdPattern()); Attribute la = attrs.get("uidNumber"); rueckgabe = (String) la.get(0); ctx.close(); } catch (NamingException e) { Helper.setErrorMessage(e.getMessage(), logger, e); } return rueckgabe; }
Source:
<code>protected InputStream getImageInput(String ref) throws IOException { File f = new File(imageTargetFolder + ref); if (!f.exists()) { FileOutputStream fos = new FileOutputStream(f); String url = wikiFileDownloadBaseUrl + documentName + "/" + ref; System.out.println("Downloading image " + url + " to " + f.getAbsolutePath() + "..."); try { WGet wget = new WGet(); wget.fetchURL(url, fos); } catch (Exception e) { <START> LOGGER.error("Error while getting image input",e);; <END> } fos.flush(); fos.close(); } FileInputStream fis = new FileInputStream(f); return fis; }</code><technical_language>This class is class wikimodel integrated. AFAICS finished work System.out/err in places. I simply removing this class. need check (we a latex Renderer AFAIR). Small note: forgot a space commas. Also, writing debug logs need provide max relevant info debugged easily. For example forgot add URL some kind of image reference identify image input. Thanks</technical_language>

Target:
protected InputStream getImageInput(String ref) throws IOException { File f = new File(imageTargetFolder + ref); if (!f.exists()) { FileOutputStream fos = new FileOutputStream(f); String url = wikiFileDownloadBaseUrl + documentName + "/" + ref; System.out.println("Downloading image " + url + " to " + f.getAbsolutePath() + "..."); try { WGet wget = new WGet(); wget.fetchURL(url, fos); } catch (Exception e) { LOGGER.error("Error while getting image input with ref [{}], and url [{}]", ref, url, e); } fos.flush(); fos.close(); } FileInputStream fis = new FileInputStream(f); return fis; }
Source:
<code>private void contextMenuActionDelete(String tagName) { openActionBarOverflowOrOptionsMenu(InstrumentationRegistry.getTargetContext()); onView(withText(R.string.delete)) .perform(click()); onView(withText(tagName)) .perform(click()); onView(withContentDescription(R.string.done)).perform(click()); <START> onView(allOf(withId(android.R.id.button1), withText(R.string.yes))) <END> .check(matches(isDisplayed())); onView(allOf(withId(android.R.id.button2), withText(R.string.no))) .check(matches(isDisplayed())); onView(allOf(withId(android.R.id.button1), withText(R.string.yes))) .perform(click()); onView(withText(tagName)) .check(doesNotExist()); }</code><technical_language>if tags displayed in a list, onData get hold of</technical_language>

Target:
private void contextMenuActionDelete(String tagName) { openActionBarOverflowOrOptionsMenu(InstrumentationRegistry.getTargetContext()); onView(withText(R.string.delete)) .perform(click()); onData(allOf(instanceOf(NfcTagData.class), NFCTagDataNameMatchers.isNFCTagDataName(tagName))) .inAdapterView(NFCTagListMatchers.isNFCTagListView()) .onChildView(withText(tagName)) .perform(click()); onView(withContentDescription(R.string.done)) .perform(click()); onView(allOf(withId(android.R.id.button1), withText(R.string.yes))) .perform(click()); onView(withText(tagName)) .check(doesNotExist()); }
Source:
<code>private boolean checkCertificate(X509Certificate cert, AuditLogType alertExpirationEventType, AuditLogType alertAboutToExpireEventType, AuditLogType warnAboutToExpireEventType, VDS host) { Date expirationDate = cert.getNotAfter(); Date certWarnTime = getExpirationDate(expirationDate, ConfigValues.CertExpirationWarnPeriodInDays); Date certAlertTime = getExpirationDate(expirationDate, ConfigValues.CertExpirationAlertPeriodInDays); Date now = new Date(); AuditLogType eventType = null; if (now.compareTo(expirationDate) > 0) { eventType = alertExpirationEventType; } else if (now.compareTo(certAlertTime) > 0) { eventType = alertAboutToExpireEventType; } else if (now.compareTo(certWarnTime) > 0) { eventType = warnAboutToExpireEventType; } if (eventType != null) { AuditLogableBase event = new AuditLogableBase(); event.addCustomValue("ExpirationDate", new SimpleDateFormat("yyyy-MM-dd").format(expirationDate)); if (host != null) { <START> event.setVds(host); <END> } auditLogDirector.log(event, eventType); return false; } return true; }</code><technical_language>want invoke setVds, get VDS object is fetched db saving audit log db. If invoke setVdsName, spare this unnecessary VDS fetch. if (host != null) { event.setVdsName(host.getName()); }</technical_language>

Target:
private boolean checkCertificate(X509Certificate cert, AuditLogType alertExpirationEventType, AuditLogType alertAboutToExpireEventType, AuditLogType warnAboutToExpireEventType, VDS host) { Date expirationDate = cert.getNotAfter(); Date certWarnTime = getExpirationDate(expirationDate, ConfigValues.CertExpirationWarnPeriodInDays); Date certAlertTime = getExpirationDate(expirationDate, ConfigValues.CertExpirationAlertPeriodInDays); Date now = new Date(); AuditLogType eventType = null; if (now.compareTo(expirationDate) > 0) { eventType = alertExpirationEventType; } else if (now.compareTo(certAlertTime) > 0) { eventType = alertAboutToExpireEventType; } else if (now.compareTo(certWarnTime) > 0) { eventType = warnAboutToExpireEventType; } if (eventType != null) { AuditLogableBase event = new AuditLogableBase(); event.addCustomValue("ExpirationDate", new SimpleDateFormat("yyyy-MM-dd").format(expirationDate)); if (host != null) { event.setVdsName(host.getName()); } auditLogDirector.log(event, eventType); return false; } return true; }
Source:
<code>public void enQueue(Mail mail, long delay, TimeUnit unit) throws MailQueueException { final String key = mail.getName() + "-" + COUNTER.incrementAndGet(); try { int i = RANDOM.nextInt(SPLITCOUNT) + 1; String name = queueDirName + "/" + i + "/" + key; final FileItem item = FileItem.of(name + OBJECT_EXTENSION, name + MSG_EXTENSION); if (delay > 0) { mail.setAttribute(NEXT_DELIVERY, System.currentTimeMillis() + unit.toMillis(delay)); } try (FileOutputStream foout = new FileOutputStream(item.getObjectFile()); ObjectOutputStream oout = new ObjectOutputStream(foout)) { oout.writeObject(mail); oout.flush(); if (sync) { foout.getFD().sync(); } } try (FileOutputStream out = new FileOutputStream(item.getMessageFile())) { mail.getMessage().writeTo(out); out.flush(); if (sync) { out.getFD().sync(); } } <START> indexWriter.addDocument(toIndexDocument(mail, key)); <END> indexWriter.commit(); keyMappings.put(key, item); if (delay > 0) { scheduler.schedule(() -> enqueueInMemory(key), delay, unit); } else { inmemoryQueue.put(key); } } catch (IOException | MessagingException | InterruptedException e) { throw new MailQueueException("Unable to enqueue mail", e); } }</code><technical_language>flush index disk</technical_language>

Target:
public void enQueue(Mail mail, long delay, TimeUnit unit) throws MailQueueException { final String key = mail.getName() + "-" + COUNTER.incrementAndGet(); try { int i = RANDOM.nextInt(SPLITCOUNT) + 1; String name = queueDirName + "/" + i + "/" + key; final FileItem item = FileItem.of(name + OBJECT_EXTENSION, name + MSG_EXTENSION); if (delay > 0) { mail.setAttribute(NEXT_DELIVERY, System.currentTimeMillis() + unit.toMillis(delay)); } try (FileOutputStream foout = new FileOutputStream(item.getObjectFile()); ObjectOutputStream oout = new ObjectOutputStream(foout)) { oout.writeObject(mail); oout.flush(); if (sync) { foout.getFD().sync(); } } try (FileOutputStream out = new FileOutputStream(item.getMessageFile())) { mail.getMessage().writeTo(out); out.flush(); if (sync) { out.getFD().sync(); } } mailQueueIndex.index(mail, key); keyMappings.put(key, item); if (delay > 0) { scheduler.schedule(() -> enqueueInMemory(key), delay, unit); } else { inmemoryQueue.put(key); } } catch (IOException | MessagingException | InterruptedException e) { throw new MailQueueException("Unable to enqueue mail", e); } }
Source:
<code>public IRateSource createRateSource(String sourceLogin) { if (sourceLogin != null && !sourceLogin.trim().isEmpty()) { StringTokenizer st = new StringTokenizer(sourceLogin, ":"); String exchangeType = st.nextToken(); if ("lskFix".equalsIgnoreCase(exchangeType)) { String preferedFiatCurrency = Currencies.USD; if (st.hasMoreTokens()) { preferedFiatCurrency = st.nextToken().toUpperCase(); } <START> return new BinanceRateSource(preferedFiatCurrency); <END> } } return null; }</code><technical_language>for "lskFix" return BinanceRateSource. return FixPriceRateSource add another if for eg. "binanceRateSource" returns BinanceRateSource</technical_language>

Target:
public IRateSource createRateSource(String sourceLogin) { if (sourceLogin != null && !sourceLogin.trim().isEmpty()) { StringTokenizer st = new StringTokenizer(sourceLogin, ":"); String exchangeType = st.nextToken(); if ("lskFix".equalsIgnoreCase(exchangeType)) { BigDecimal rate = BigDecimal.ZERO; if (st.hasMoreTokens()) { try { rate = new BigDecimal(st.nextToken()); } catch (Throwable e) { } } String preferedFiatCurrency = Currencies.USD; if (st.hasMoreTokens()) { preferedFiatCurrency = st.nextToken().toUpperCase(); } return new FixPriceRateSource(rate, preferedFiatCurrency); } else if ("binanceRateSource".equalsIgnoreCase(exchangeType)) { String preferedFiatCurrency = Currencies.USD; if (st.hasMoreTokens()) { preferedFiatCurrency = st.nextToken().toUpperCase(); } return new BinanceRateSource(preferedFiatCurrency); } } return null; }
Source:
<code>public void checkOpenFileFeatureTest() throws Exception { createProject(PROJECT_NAME); projectExplorer.waitItem(PROJECT_NAME); dashboard.open(); dashboard.selectFactoriesOnDashbord(); dashboardFactories.clickOnAddFactoryBtn(); dashboardFactories.selectWorkspaceForCreation(testWorkspace.getName()); dashboardFactories.setFactoryName(FACTORY_NAME); dashboardFactories.clickOnCreateFactoryBtn(); dashboardFactories.selectAction(OPEN_FILE); dashboardFactories.enterParamValue(OPEN_FILE_URL); dashboardFactories.clickAddOnAddAction(); dashboardFactories.clickOnOpenFactory(); String currentWin = seleniumWebDriver.getWindowHandle(); seleniumWebDriverHelper.switchToNextWindow(currentWin); loadingBehaviorPage.waitWhileLoadPageIsClosed(); seleniumWebDriverHelper.switchToIdeFrameAndWaitAvailability(); projectExplorer.waitItem(PROJECT_NAME); try { editor.waitTabIsPresent("web-java-spring", WIDGET_TIMEOUT_SEC); } catch (TimeoutException ex) { <START> fail("Known issue <LINK_0>"); <END> } }</code><technical_language>Please, express if is permanent random in error message: permanent failure <LINK_1></technical_language>

Target:
public void checkOpenFileFeatureTest() throws Exception { createProject(PROJECT_NAME); projectExplorer.waitItem(PROJECT_NAME); dashboard.open(); dashboard.selectFactoriesOnDashbord(); dashboardFactories.clickOnAddFactoryBtn(); dashboardFactories.selectWorkspaceForCreation(testWorkspace.getName()); dashboardFactories.setFactoryName(FACTORY_NAME); dashboardFactories.clickOnCreateFactoryBtn(); dashboardFactories.selectAction(OPEN_FILE); dashboardFactories.enterParamValue(OPEN_FILE_URL); dashboardFactories.clickAddOnAddAction(); dashboardFactories.clickOnOpenFactory(); String currentWin = seleniumWebDriver.getWindowHandle(); seleniumWebDriverHelper.switchToNextWindow(currentWin); loadingBehaviorPage.waitWhileLoadPageIsClosed(); seleniumWebDriverHelper.switchToIdeFrameAndWaitAvailability(); projectExplorer.waitItem(PROJECT_NAME); try { editor.waitTabIsPresent("web-java-spring", WIDGET_TIMEOUT_SEC); } catch (TimeoutException ex) { fail("Known random failure <LINK_0>"); } }
Source:
<code>public boolean isQuestionSkipped(String[] answer) { boolean allAnswersEmpty = true; <START> if(answer!=null){ <END> for(int i=0 ; i<answer.length ; i++){ if(answer[i]!=null && !answer[i].trim().isEmpty()){ allAnswersEmpty = false; } } } return answer == null || allAnswersEmpty; }</code><technical_language>do early return if answer == null</technical_language>

Target:
public boolean isQuestionSkipped(String[] answer) { if (answer == null) { return true; } boolean allAnswersEmpty = true; for(int i=0 ; i<answer.length ; i++) { if (answer[i] != null && !answer[i].trim().isEmpty()) { allAnswersEmpty = false; break; } } return allAnswersEmpty; }
Source:
<code>protected List<String> getTabCompleteOptions(final Server server, final CommandSource sender, final String commandLabel, final String[] args) { if (args.length == 1) { <START> return new ArrayList<>(ess.getWarps().getList()); <END> } else { return Collections.emptyList(); } }</code><technical_language>REEEEEEEE STREAMS suggestion if (ess.getSettings().getPerWarpPermission() && sender.isPlayer()) { List<String> list = new ArrayList<>(); for (String curWarp : ess.getWarps().getList()) { if (sender.isAuthorized("essentials.warps." + curWarp)) { list.add(curWarp); } } return list; } return new ArrayList<>(ess.getWarps().getList());</technical_language>

Target:
protected List<String> getTabCompleteOptions(final Server server, final CommandSource sender, final String commandLabel, final String[] args) { if (args.length == 1) { if (ess.getSettings().getPerWarpPermission() && sender.isPlayer()) { final List<String> list = new ArrayList<>(); for (String curWarp : ess.getWarps().getList()) { if (sender.isAuthorized("essentials.warps." + curWarp, ess)) { list.add(curWarp); } } return list; } return new ArrayList<>(ess.getWarps().getList()); } else { return Collections.emptyList(); } }