auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public String toString() { StringBuilder b = new StringBuilder(); long elapsed = getElapsedTime(); int day = (int) (elapsed / 86400000); <START> elapsed -= day * 86400000; <END> int hour = (int) (elapsed / 3600000); elapsed -= hour * 3600000; int minute = (int) (elapsed / 60000); elapsed -= minute * 60000; int second = (int) (elapsed / 1000); if (day > 0) { b.append(day < 10 ? "0" : "").append(day).append("d:"); } b.append(hour < 10 ? "0" : "").append(hour).append(":"); b.append(minute < 10 ? "0" : "").append(minute).append(":"); b.append(second < 10 ? "0" : "").append(second); return new String(b); }</code><technical_language>is reason do follow standards</technical_language>

Target:
public String toString() { StringBuilder b = new StringBuilder(); long elapsed = getElapsedTime(); int day = (int) (elapsed / 86400000); elapsed -= day * 86400000; int hour = (int) (elapsed / 3600000); elapsed -= hour * 3600000; int minute = (int) (elapsed / 60000); elapsed -= minute * 60000; int second = (int) (elapsed / 1000); if (day > 0) { b.append(day).append("d:"); } b.append(hour < 10 ? "0" : "").append(hour).append(":"); b.append(minute < 10 ? "0" : "").append(minute).append(":"); b.append(second < 10 ? "0" : "").append(second); return new String(b); }
Source:
<code>public void testAMeetingCannotBeCreatedWithoutAttendees() { ExcelReader excelReader = new ExcelReader(EXCEL_INPUT_DATA); List<Map<String, String>> meetingData = excelReader.getMapValues("MeetingData"); String organizer = meetingData.get(0).get("Organizer"); String subject = meetingData.get(0).get("Subject"); String startTime = meetingData.get(0).get("Start time"); String endTime = meetingData.get(0).get("End time"); String body = meetingData.get(0).get("Body"); HomeTabletPage homeTabletPage = new HomeTabletPage(); SchedulePage schedulePage = homeTabletPage.clickScheduleBtn(); schedulePage.setOrganizerTxtBox(organizer) .setSubjectTxtBox(subject) .setStartTimeDate(startTime) .setEndTimeDate(endTime) <START> .setBodyTxtBox(body) <END> .clickCreateBtn() .clickCancelButton(); Assert.assertTrue(schedulePage.isErrorAttendeeLblDisplayed()); }</code><technical_language>steps 36, 37, 38 necessary, please check this.... omit this steps</technical_language>

Target:
public void testAMeetingCannotBeCreatedWithoutAttendees() { ExcelReader excelReader = new ExcelReader(EXCEL_INPUT_DATA); List<Map<String, String>> meetingData = excelReader.getMapValues("MeetingData"); String organizer = meetingData.get(0).get("Organizer"); String subject = meetingData.get(0).get("Subject"); String body = meetingData.get(0).get("Body"); HomeTabletPage homeTabletPage = new HomeTabletPage(); SchedulePage schedulePage = homeTabletPage.clickScheduleBtn(); schedulePage .setOrganizerTxtBox(organizer) .setSubjectTxtBox(subject) .setBodyTxtBox(body) .clickCreateBtn() .clickCancelButton(); Assert.assertTrue(schedulePage.isErrorAttendeeLblDisplayed()); }
Source:
<code>public TeamServiceImpl(TeamRepository teamRepository, UserService userService, MailService mailService, TeamInviteTokenRepository teamInviteTokenRepository) { this.teamRepository = teamRepository; this.teamInviteTokenRepository = teamInviteTokenRepository; this.userService = userService; <START> this.mailService = mailService; <END> }</code><technical_language>Aaagh, _superautism_ variable assignments in a order parameters declarations</technical_language>

Target:
public TeamServiceImpl(TeamRepository teamRepository, UserService userService, MailService mailService, TeamInviteTokenRepository teamInviteTokenRepository) { this.teamRepository = teamRepository; this.userService = userService; this.mailService = mailService; this.teamInviteTokenRepository = teamInviteTokenRepository; }
Source:
<code>public Serializer getSerializer(String id) { SerializerContribution contrib = getDescriptor(EXTENSION_POINT_NAME, id); if (contrib == null) { contrib = getDescriptor(EXTENSION_POINT_NAME, DEFAULT_SERIALIZER_NAME); if (contrib == null) { <START> throw new UnknownSerializer(id); <END> } } return contrib.getImplementation(); }</code><technical_language>a NuxeoException message wrote in UnknowSerializer is enough</technical_language>

Target:
public Serializer getSerializer(String id) { SerializerContribution contrib = getDescriptor(EXTENSION_POINT_NAME, id); if (contrib == null) { contrib = getDescriptor(EXTENSION_POINT_NAME, DEFAULT_SERIALIZER_NAME); if (contrib == null) { throw new NuxeoException("UnknownSerializer named " + id); } } return contrib.getImplementation(); }
Source:
<code>protected List<StorageDomainStatic> filterAttachedStorageDomains() { List<StorageDomain> connectedStorageDomainsToVds = new ArrayList<>(); for (StorageDomain storageDomain : getParameters().getStorageDomainList()) { if (!connectStorageDomain(storageDomain)) { logErrorMessage(storageDomain); } else { connectedStorageDomainsToVds.add(storageDomain); } } List<StorageDomainStatic> storageDomainsWithAttachedStoragePoolId = getAttachedStorageDomains(connectedStorageDomainsToVds); for (StorageDomain storageDomain : connectedStorageDomainsToVds) { if (containsRunningVMs(storageDomain)) { log.warn( <START> "Skipping disconnect Storage Domain from VDS '{}' because it has running VMs on it. ", <END> storageDomain.getName(), getVdsId() ); continue; } if (!disconnectStorageDomain(storageDomain)) { log.warn("Could not disconnect Storage Domain from VDS '{}'. ", storageDomain.getName(), getVdsId()); } } return storageDomainsWithAttachedStoragePoolId; }</code><technical_language>1. need warn, info enough 2. remove redundant space end of sentence. 3. Please rephrase log this is related Hosted Engine</technical_language>

Target:
protected List<StorageDomainStatic> filterAttachedStorageDomains() { List<StorageDomain> connectedStorageDomainsToVds = new ArrayList<>(); for (StorageDomain storageDomain : getParameters().getStorageDomainList()) { if (!connectStorageDomain(storageDomain)) { logErrorMessage(storageDomain); } else { connectedStorageDomainsToVds.add(storageDomain); } } List<StorageDomainStatic> storageDomainsWithAttachedStoragePoolId = getAttachedStorageDomains(connectedStorageDomainsToVds); for (StorageDomain storageDomain : connectedStorageDomainsToVds) { if (containsRunningHostedEngine(storageDomain)) { log.info( "Skipping disconnect Storage Domain from VDS '{}' because Hosted Engine VM is running on it.", storageDomain.getName(), getVdsId() ); continue; } if (!disconnectStorageDomain(storageDomain)) { log.warn("Could not disconnect Storage Domain from VDS '{}'. ", storageDomain.getName(), getVdsId()); } } return storageDomainsWithAttachedStoragePoolId; }
Source:
<code>public double getSchedulingJitterPercent() { if (containsKey(CONFIG_SCHEDULING_JITTER_PERCENT)) { return getDouble(CONFIG_SCHEDULING_JITTER_PERCENT) / 100.0; } <START> return 0; <END> }</code><technical_language>a constant DEFAULT_SCHEDULING_INTERVAL_IN_MS</technical_language>

Target:
public double getSchedulingJitterPercent() { return getDouble(CONFIG_SCHEDULING_JITTER_PERCENT, DEFAULT_SCHEDULING_JITTER_PERCENT); }
Source:
<code>static boolean isIdempotent(Object value) { if (value == null) { return true; } else if (value instanceof Assignment) { Assignment assignment = (Assignment) value; return assignment.isIdempotent(); } else if (value instanceof FCall) { return false; } else if (value instanceof RawString) { return false; } else if (value instanceof Collection) { for (Object elt : ((Collection) value)) { if (!isIdempotent(elt)) return false; } return true; } else if (value instanceof Map) { for (Map.Entry<?, ?> entry : ((Map<?, ?>) value).entrySet()) { if (!isIdempotent(entry.getKey()) || !isIdempotent(entry.getValue())) return false; } } else if (value instanceof Clause){ Object clauseValue = ((Clause) value).firstValue(); <START> return !(clauseValue instanceof FCall); <END> } return true; }</code><technical_language>This be: return isIdempotent(clauseValue)</technical_language>

Target:
static boolean isIdempotent(Object value) { if (value == null) { return true; } else if (value instanceof Assignment) { Assignment assignment = (Assignment) value; return assignment.isIdempotent(); } else if (value instanceof FCall) { return false; } else if (value instanceof RawString) { return false; } else if (value instanceof Collection) { for (Object elt : ((Collection) value)) { if (!isIdempotent(elt)) return false; } return true; } else if (value instanceof Map) { for (Map.Entry<?, ?> entry : ((Map<?, ?>) value).entrySet()) { if (!isIdempotent(entry.getKey()) || !isIdempotent(entry.getValue())) return false; } } else if (value instanceof Clause) { Object clauseValue = ((Clause) value).firstValue(); return isIdempotent(clauseValue); } return true; }
Source:
<code>boolean update(WatermarkMessage watermarkMessage, SystemStreamPartition ssp) { WatermarkState state = watermarkStates.get(ssp); boolean updated = state.update(watermarkMessage.getTimestamp(), watermarkMessage.getTaskName()); if (updated) { long minTimestamp = watermarkStates.entrySet().stream() .filter(entry -> entry.getKey().getSystemStream().equals(ssp.getSystemStream())) .map(entry -> entry.getValue().getWatermarkTime()) .min(Long::compare) .get(); Long curWatermark = watermarks.get(ssp.getSystemStream()); <START> if (curWatermark == null || curWatermark < minTimestamp) { <END> watermarks.put(ssp.getSystemStream(), minTimestamp); return true; } } return false; }</code><technical_language>I condition hold in implementation. In case clearer assert that</technical_language>

Target:
void update(WatermarkMessage watermarkMessage, SystemStreamPartition ssp) { WatermarkState state = watermarkStates.get(ssp); if (state != null) { state.update(watermarkMessage.getTimestamp(), watermarkMessage.getTaskName()); } else { LOG.error("SSP doesn't have watermark states", ssp); } }
Source:
<code>Integer getFreeIndex() { Integer index; if (freeIndexList.isEmpty()) { index = arrayList.size(); } else { int freeIndexToRemove = freeIndexList.size() - 1; index = freeIndexList.get(freeIndexToRemove); <START> freeIndexList.remove(freeIndexToRemove); <END> } return index; }</code><technical_language>lines index = freeIndexList.remove(freeIndexList.size() - 1); if ArrayDeque instead of ArrayList, write index = freeIndexList.removeLast()</technical_language>

Target:
Integer getFreeIndex() { Integer index; int freeIndexListSize = freeIndexList.size(); if (freeIndexListSize == 0) { index = pool.size(); } else { index = freeIndexList.remove(freeIndexListSize - 1); } return index; }
Source:
<code>private String getCharactersCount(String content) { int numChars = content.length(); String charCountString = mFragment.getResources().getQuantityString(R.plurals.char_count,numChars); <START> return String.format("%s %s", numChars , charCountString); <END> }</code><technical_language>Formatting: numChars, ..</technical_language>

Target:
private String getCharactersCount(String content) { int numChars = content.length(); String charCount = NumberFormat.getInstance().format(numChars); String charCountString = mFragment.getResources().getQuantityString(R.plurals.char_count, numChars); return String.format("%s %s", charCount, charCountString); }
Source:
<code>public HttpResponse doCancelItem(@QueryParameter long id) { Item item = getItem(id); if (item != null) { if(item.hasCancelPermission()){ if(cancel(item)) { return HttpResponses.status(HttpServletResponse.SC_NO_CONTENT); } return HttpResponses.error(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Could not cancel run for id " + id); } return HttpResponses.error(422, "Item for id (" + id + ") is not cancellable"); } <START> return HttpResponses.error(422, "Provided id (" + id + ") does not exist"); <END> }</code><technical_language>404 instead</technical_language>

Target:
public HttpResponse doCancelItem(@QueryParameter long id) throws IOException, ServletException { Item item = getItem(id); if (item != null) { if(item.hasCancelPermission()){ if(cancel(item)) { return HttpResponses.status(HttpServletResponse.SC_NO_CONTENT); } return HttpResponses.error(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Could not cancel run for id " + id); } return HttpResponses.error(422, "Item for id (" + id + ") is not cancellable"); } return HttpResponses.error(HttpServletResponse.SC_NOT_FOUND, "Provided id (" + id + ") not found"); }
Source:
<code>private static void populate(int size, int[] fuzz, ISegmentStore<@NonNull ISegment> store, long low, long high) { <START> for (int i = (int) low; i < high; i++) { <END> long start = (long) i + fuzz[i % size]; store.add(new BasicSegment(start, start + 10)); } }</code><technical_language>a long here, big benchmark (for disk stores) extend this class overflow if int</technical_language>

Target:
private static void populate(int size, int[] fuzz, ISegmentStore<@NonNull ISegment> store, long low, long high) { for (long i = low; i < high; i++) { long start = i + fuzz[(int) (i % size)]; store.add(new BasicSegment(start, start + 10)); } }
Source:
<code>private static Class<?> getClass(String className) { try { return Class.forName(className); } catch (ClassNotFoundException e) { <START> throw new IllegalStateException("Java 8 or later but class " + className + " is missing"); <END> } }</code><technical_language>Add original ClassNotFoundException cause</technical_language>

Target:
private static Class<?> getClass(String className) { try { return Class.forName(className); } catch (ClassNotFoundException e) { throw new IllegalStateException("Java 8 or later but class " + className + " is missing", e); } }
Source:
<code>public void fireChangeEventsOnFields() { <START> NativeEvent event = Document.get().createChangeEvent(); <END> DomEvent.fireNativeEvent(event, userNameEditor.asValueBox()); event = Document.get().createChangeEvent(); DomEvent.fireNativeEvent(event, passwordEditor.asValueBox()); }</code><technical_language>Lets try do this GWT, I manual DOM manipulations I start cringing. get in this case a public 'fireChangeEvent' in AbstractValidatedWidgetWithLabel ValueChangeEvent.fire(getContentWidget(), getContentWidget().getValue()); simply call userNameEditor.fireChangeEvent() passwordEditor.firstChangeEvent()</technical_language>

Target:
public void fireChangeEventsOnFields() { userNameEditor.fireChangeEvent(); passwordEditor.fireChangeEvent(); profileEditor.fireChangeEvent(); }
Source:
<code>public void stop(ComponentContext context) throws InterruptedException { <START> super.stop(context); <END> executor.shutdownNow(); executor.awaitTermination(10, TimeUnit.SECONDS); executor = null; }</code><technical_language>In general call super.stop last, other cleanups</technical_language>

Target:
public void stop(ComponentContext context) throws InterruptedException { executor.shutdownNow(); executor.awaitTermination(10, TimeUnit.SECONDS); executor = null; super.stop(context); }
Source:
<code>public static void restartJobServiceTriggerAt(Context context, long triggerAtMillis) { JobInfo.Builder builder = getFeedUpdateJobBuilder(context); builder.setMinimumLatency(triggerAtMillis); <START> JobScheduler jobScheduler = context.getSystemService(JobScheduler.class); <END> if (jobScheduler != null) { jobScheduler.cancel(JOB_ID_FEED_UPDATE); jobScheduler.schedule(builder.build()); Log.d(TAG, "JobScheduler was set for " + triggerAtMillis); } }</code><technical_language>push top need builder is scheduler is null</technical_language>

Target:
private static void restartJobServiceTriggerAt(Context context, long triggerAtMillis) { JobScheduler jobScheduler = context.getSystemService(JobScheduler.class); if (jobScheduler == null) { Log.d(TAG, "JobScheduler was null."); return; } JobInfo.Builder builder = getFeedUpdateJobBuilder(context); builder.setMinimumLatency(triggerAtMillis); jobScheduler.cancel(JOB_ID_FEED_UPDATE); jobScheduler.schedule(builder.build()); Log.d(TAG, "JobScheduler was set for " + triggerAtMillis); }
Source:
<code>protected Expression getExpressionFromOperationList(List<Operation> operations, long expressionDefinitionId) { for (Operation operation : operations) { final Expression expression = getExpressionFromContainer(operation, expressionDefinitionId); <START> if (expression == null) { <END> return expression; } } return null; }</code><technical_language>!= null</technical_language>

Target:
protected Expression getExpressionFromOperationList(List<Operation> operations, long expressionDefinitionId) { for (Operation operation : operations) { final Expression expression = getExpressionFromContainer(operation, expressionDefinitionId); if (expression != null) { return expression; } } return null; }
Source:
<code>private void assertResult(String moveCode, boolean doable, OrderByMoveIndexBlockingQueue.MoveResult<TestdataSolution> result) { assertCode(moveCode, result.getMove()); boolean y = result.isMoveDoable(); if (doable) { assertThat(y).isTrue(); } else { assertThat(y).isFalse(); <START> } <END> }</code><technical_language>Is this if intentional</technical_language>

Target:
private void assertResult(String moveCode, boolean doable, OrderByMoveIndexBlockingQueue.MoveResult<TestdataSolution> result) { assertCode(moveCode, result.getMove()); assertThat(result.isMoveDoable()).isEqualTo(doable); }
Source:
<code>State setState(final State newState) { final State oldState; synchronized (stateLock) { oldState = state; if (state == State.PENDING_SHUTDOWN && newState != State.DEAD) { log.debug("Invalid transition from PENDING_SHUTDOWN to {}: " + <START> "only DEAD state is a valid next state", newState); <END> ENDING_SHUTDOWN, all other transitions will be return null; } else if (state == State.DEAD) { log.debug("Invalid transition from DEAD to {}: " + "no valid next state after DEAD", newState); return null; } else if (state == State.PARTITIONS_REVOKED && newState == State.PARTITIONS_REVOKED) { log.debug("Invalid transition from PARTITIONS_REVOKED to PARTITIONS_REVOKED: " + "self transition is not allowed"); return null; } else if (!state.isValidTransition(newState)) { log.error("Unexpected state transition from to {}", oldState, newState); throw new StreamsException(logPrefix + "Unexpected state transition from " + oldState + " to " + newState); } else { log.info("State transition from to {}", oldState, newState); } state = newState; if (newState == State.RUNNING) { updateThreadMetadata(taskManager.activeTasks(), taskManager.standbyTasks()); } else { updateThreadMetadata(Collections.emptyMap(), Collections.emptyMap()); } } if (stateListener != null) { stateListener.onChange(this, state, oldState); } return oldState; }</code><technical_language>This miss leading for users details. about: log.debug("Ignoring request transit PENDING_SHUTDOWN {}", newState);</technical_language>

Target:
State setState(final State newState) { final State oldState; synchronized (stateLock) { oldState = state; if (state == State.PENDING_SHUTDOWN && newState != State.DEAD) { log.debug("Ignoring request to transit from PENDING_SHUTDOWN to {}: " + "only DEAD state is a valid next state", newState); ENDING_SHUTDOWN, all other transitions will be return null; } else if (state == State.DEAD) { log.debug("Ignoring request to transit from DEAD to {}: " + "no valid next state after DEAD", newState); return null; } else if (state == State.PARTITIONS_REVOKED && newState == State.PARTITIONS_REVOKED) { log.debug("Ignoring request to transit from PARTITIONS_REVOKED to PARTITIONS_REVOKED: " + "self transition is not allowed"); return null; } else if (!state.isValidTransition(newState)) { log.error("Unexpected state transition from to {}", oldState, newState); throw new StreamsException(logPrefix + "Unexpected state transition from " + oldState + " to " + newState); } else { log.info("State transition from to {}", oldState, newState); } state = newState; if (newState == State.RUNNING) { updateThreadMetadata(taskManager.activeTasks(), taskManager.standbyTasks()); } else { updateThreadMetadata(Collections.emptyMap(), Collections.emptyMap()); } } if (stateListener != null) { stateListener.onChange(this, state, oldState); } return oldState; }
Source:
<code>private void handshakeReq(ProtocolVersion proposedVer, String user, String pwd, Map<String, String> userAttrs) throws ClientConnectionException { BinaryContext ctx = new BinaryContext(BinaryCachingMetadataHandler.create(), new IgniteConfiguration(), null); <START> try (BinaryWriterExImpl writer = new BinaryWriterExImpl(ctx, new BinaryHeapOutputStream(32), null, null)) { <END> ProtocolContext protocolContext = protocolContextFromVersion(proposedVer); writer.writeInt(0); writer.writeByte((byte) ClientListenerRequest.HANDSHAKE); writer.writeShort(proposedVer.major()); writer.writeShort(proposedVer.minor()); writer.writeShort(proposedVer.patch()); writer.writeByte(ClientListenerNioListener.THIN_CLIENT); if (protocolContext.isFeaturesSupported()) { byte[] features = ThinProtocolFeature.featuresAsBytes(protocolContext.features()); writer.writeByteArray(features); } if (protocolContext.isUserAttributesSupported()) writer.writeMap(userAttrs); if (protocolContext.isAuthorizationSupported() && user != null && !user.isEmpty()) { writer.writeString(user); writer.writeString(pwd); } writer.out().writeInt(0, writer.out().position() - 4); write(writer.array(), writer.out().position()); } }</code><technical_language>Newline missed (codestyle)</technical_language>

Target:
private void handshakeReq(ProtocolVersion proposedVer, String user, String pwd, Map<String, String> userAttrs) throws ClientConnectionException { BinaryContext ctx = new BinaryContext(BinaryCachingMetadataHandler.create(), new IgniteConfiguration(), null); try (BinaryWriterExImpl writer = new BinaryWriterExImpl(ctx, new BinaryHeapOutputStream(32), null, null)) { ProtocolContext protocolCtx = protocolContextFromVersion(proposedVer); writer.writeInt(0); writer.writeByte((byte) ClientListenerRequest.HANDSHAKE); writer.writeShort(proposedVer.major()); writer.writeShort(proposedVer.minor()); writer.writeShort(proposedVer.patch()); writer.writeByte(ClientListenerNioListener.THIN_CLIENT); if (protocolCtx.isFeatureSupported(BITMAP_FEATURES)) { byte[] features = ProtocolBitmaskFeature.featuresAsBytes(protocolCtx.features()); writer.writeByteArray(features); } if (protocolCtx.isFeatureSupported(USER_ATTRIBUTES)) writer.writeMap(userAttrs); boolean authSupported = protocolCtx.isFeatureSupported(AUTHORIZATION); if (authSupported && user != null && !user.isEmpty()) { writer.writeString(user); writer.writeString(pwd); } writer.out().writeInt(0, writer.out().position() - 4); write(writer.array(), writer.out().position()); } }
Source:
<code>protected List<Bundle> installCoreBundles() { List<Bundle> bundles = new ArrayList<>(); try { List<String> locationPatterns = new ArrayList<>(); locationPatterns.add(blueprintBundlesLocation); if (StringUtils.hasText(standardBundlesLocation)) { locationPatterns.add(standardBundlesLocation); } if (StringUtils.hasText(customBundlesLocation)) { locationPatterns.add(customBundlesLocation); } for (String locationPattern : locationPatterns) { try { for (Resource bundleResource : resourcePatternResolver.getResources(locationPattern)) { String location = bundleResource.getURI().toString(); logger.debug("Installing Bundle: {}", location); try { Bundle bundle = installBundle(bundleResource, location); bundles.add(bundle); } catch (BundleException e) { <START> logger.error("Error installing Bundle: $location", e); <END> } } } catch (FileNotFoundException e) { logger.debug("Could not find Bundles at location '{}'.", locationPattern); } } } catch (IOException ioe) { throw new RuntimeException("Error installing core Bundles: " + ioe.getMessage(), ioe); } return bundles; }</code><technical_language>location logged</technical_language>

Target:
protected List<Bundle> installCoreBundles() { List<Bundle> bundles = new ArrayList<>(); try { List<String> locationPatterns = new ArrayList<>(); locationPatterns.add(blueprintBundlesLocation); if (StringUtils.hasText(standardBundlesLocation)) { locationPatterns.add(standardBundlesLocation); } if (StringUtils.hasText(customBundlesLocation)) { locationPatterns.add(customBundlesLocation); } for (String locationPattern : locationPatterns) { try { for (Resource bundleResource : resourcePatternResolver.getResources(locationPattern)) { String location = bundleResource.getURI().toString(); logger.debug("Installing Bundle: {}", location); try { Bundle bundle = installBundle(bundleResource, location); bundles.add(bundle); } catch (BundleException e) { logger.error("Error installing Bundle in {}: {}", location, e); } } } catch (FileNotFoundException e) { logger.debug("Could not find Bundles at location '{}'.", locationPattern); } } } catch (IOException ioe) { throw new RuntimeException("Error installing core Bundles: " + ioe.getMessage(), ioe); } return bundles; }
Source:
<code>public Iterable<Issue> search( @NotNull(message = "Sort field can't be NULL") final Sort sort, @NotNull(message = "Sort direction can't be NULL") final Search.Order direction, @NotNull(message = "Search qualifiers can't be NULL") <START> final EnumMap<Qualifier, String> qualifiers) <END> throws IOException { final Map<String, String> params = new HashMap<String, String>(); for (final EnumMap.Entry<Qualifier, String> entry : qualifiers .entrySet()) { params.put(entry.getKey().getQualifier(), entry.getValue()); } params.put("sort", sort.getSort()); params.put("direction", direction.getOrder()); return this.iterate(params); }</code><technical_language>do need EnumMap instead of Map in this method</technical_language>

Target:
public Iterable<Issue> search( @NotNull(message = "Sort field can't be NULL") final Sort sort, @NotNull(message = "Sort direction can't be NULL") final Search.Order direction, @NotNull(message = "Search qualifiers can't be NULL") final EnumMap<Qualifier, String> qualifiers) throws IOException { final Map<String, String> params = new HashMap<String, String>(); for (final EnumMap.Entry<Qualifier, String> entry : qualifiers .entrySet()) { params.put(entry.getKey().identifier(), entry.getValue()); } params.put("sort", sort.identifier()); params.put("direction", direction.identifier()); return this.iterate(params); }
Source:
<code>public boolean isValid(ComplaintValidationContext context) { this.context = context; try { this.complainantTypes = context.getComplaintDAO().getComplainantTypes(); if (context.getComplaintDTO().getComplainantType() == null || context.getComplaintDTO().getComplainantType().getId() == null) { getMessages().add(getErrorMessage("complaints.complainantType.required")); return false; } if (!doesComplainantTypeExist(context.getComplaintDTO().getComplainantType().getId())) { getMessages().add(getErrorMessage("complaints.complainantType.notExists")); return false; } if (isComplainantTypeSetToOther(context.getComplaintDTO().getComplainantType()) && (context.getComplaintDTO().getComplainantTypeOther() == null <START> || context.getComplaintDTO().getComplainantTypeOther().trim() == "")) { <END> getMessages().add(getErrorMessage("complaints.complainantType.otherMissing")); return false; } return true; } catch (Exception e) { String error = getErrorMessage("complaints.error"); LOGGER.error(error, e); getMessages().add(error); return false; } }</code><technical_language>StringUtils.isEmpty function work here? I expect handle null empty cases (you'd need trim I think... brings another issue thinking need trim input user do consistently)</technical_language>

Target:
public boolean isValid(ComplaintValidationContext context) { this.context = context; try { this.complainantTypes = context.getComplaintDAO().getComplainantTypes(); if (context.getComplaintDTO().getComplainantType() == null || context.getComplaintDTO().getComplainantType().getId() == null) { getMessages().add(getErrorMessage("complaints.complainantType.required")); return false; } if (!doesComplainantTypeExist(context.getComplaintDTO().getComplainantType().getId())) { getMessages().add(getErrorMessage("complaints.complainantType.notExists")); return false; } if (isComplainantTypeSetToOther(context.getComplaintDTO().getComplainantType()) && StringUtils.isEmpty(context.getComplaintDTO().getComplainantTypeOther())) { getMessages().add(getErrorMessage("complaints.complainantType.otherMissing")); return false; } return true; } catch (Exception e) { String error = getErrorMessage("complaints.error"); LOGGER.error(error, e); getMessages().add(error); return false; } }
Source:
<code><START> public Set<String> getDisabledAdministrativeMonitors(){ <END> return disabledAdministrativeMonitors; }</code><technical_language>buggy CopyOnWriteArraySet</technical_language>

Target:
public Set<String> getDisabledAdministrativeMonitors(){ synchronized (this.disabledAdministrativeMonitors) { return new HashSet<>(disabledAdministrativeMonitors); } }
Source:
<code>public void verify(byte[] contentBytes, byte[] signatureBytes) throws SignatureVerificationException { try { if (publicKey == null) { <START> throw new IllegalArgumentException("The given Public Key is null."); <END> } if (!isDERSignature(signatureBytes)) { signatureBytes = JOSEToDER(signatureBytes); } boolean valid = crypto.verifySignatureFor(getDescription(), publicKey, contentBytes, signatureBytes); if (!valid) { throw new SignatureVerificationException(this); } } catch (NoSuchAlgorithmException | SignatureException | InvalidKeyException | IllegalArgumentException e) { throw new SignatureVerificationException(this, e); } }</code><technical_language>IllegalStateException</technical_language>

Target:
public void verify(byte[] contentBytes, byte[] signatureBytes) throws SignatureVerificationException { try { if (publicKey == null) { throw new IllegalStateException("The given Public Key is null."); } if (!isDERSignature(signatureBytes)) { signatureBytes = JOSEToDER(signatureBytes); } boolean valid = crypto.verifySignatureFor(getDescription(), publicKey, contentBytes, signatureBytes); if (!valid) { throw new SignatureVerificationException(this); } } catch (NoSuchAlgorithmException | SignatureException | InvalidKeyException | IllegalStateException e) { throw new SignatureVerificationException(this, e); } }
Source:
<code>private IStatus unzip(byte[] byteArray, IPath location) { ZipInputStream stream = new ZipInputStream(new ByteArrayInputStream(byteArray)); ZipEntry entry; IStatus status = Status.OK_STATUS; try { while ((entry = stream.getNextEntry()) != null) { <START> try { <END> String name = skipOneLevel(entry.getName()); if (!name.isEmpty()) { Path path = Paths.get(location.toOSString(), name); if (entry.isDirectory()) { Files.createDirectories(path); } else { try (OutputStream output = new FileOutputStream(path.toFile())) { IOUtils.copy(stream, output); } } } } catch (InvalidPathException e) } } catch (IOException e) { status = new Status(IStatus.ERROR, LauncherUIPlugin.PLUGIN_ID, e.getLocalizedMessage(), e); } return status; }</code><technical_language>l147-158 extracted a separate method for improved readability</technical_language>

Target:
private IStatus unzip(byte[] byteArray, IPath location) { ZipInputStream stream = new ZipInputStream(new ByteArrayInputStream(byteArray)); ZipEntry entry; IStatus status = Status.OK_STATUS; try { while ((entry = stream.getNextEntry()) != null) { unzipEntry(location, stream, entry); } } catch (IOException e) { status = new Status(IStatus.ERROR, LauncherUIPlugin.PLUGIN_ID, e.getLocalizedMessage(), e); } return status; }
Source:
<code>protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException { <START> Map<String, Object> state = new TreeMap<String, Object>(jsm.getState()); <END> String path = request.getParameter("path"); if (path != null) { Iterator<String> it = state.keySet().iterator(); while (it.hasNext()) { if(!it.next().startsWith(path)) { it.remove(); } } } if (state.containsKey("ScoreBoard.Twitter.AccessTokenSecret")) { state.put("ScoreBoard.Twitter.AccessTokenSecret", "<removed>"); } if (state.isEmpty()) { response.sendError(HttpServletResponse.SC_NOT_FOUND, "No objects found."); } else { response.setContentType("application/json"); String json = JSON.std .with(JSON.Feature.PRETTY_PRINT_OUTPUT) .composeString() .startObject() .putObject("state", state) .end() .finish(); response.setHeader("Cache-Control", "no-cache"); response.setHeader("Expires", "-1"); response.setCharacterEncoding("utf-8"); response.getOutputStream().print(json); response.getOutputStream().flush(); response.setStatus(HttpServletResponse.SC_OK); } }</code><technical_language>Type Arguments TreeMap redundant</technical_language>

Target:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException { Map<String, Object> state = new TreeMap<>(jsm.getState()); String path = request.getParameter("path"); if (path != null) { Iterator<String> it = state.keySet().iterator(); while (it.hasNext()) { if(!it.next().startsWith(path)) { it.remove(); } } } if (state.containsKey("ScoreBoard.Twitter.AccessTokenSecret")) { state.put("ScoreBoard.Twitter.AccessTokenSecret", "<removed>"); } if (state.isEmpty()) { response.sendError(HttpServletResponse.SC_NOT_FOUND, "No objects found."); } else { response.setContentType("application/json"); String json = JSON.std .with(JSON.Feature.PRETTY_PRINT_OUTPUT) .composeString() .startObject() .putObject("state", state) .end() .finish(); response.setHeader("Cache-Control", "no-cache"); response.setHeader("Expires", "-1"); response.setCharacterEncoding("utf-8"); response.getOutputStream().print(json); response.getOutputStream().flush(); response.setStatus(HttpServletResponse.SC_OK); } }
Source:
<code>public FilterPanel addPanelAt(int index) { FilterPanel panel = new ListPanel(ui, model, this, index); getChildren().add(index, panel); guiController.panelFilterExpressionChanged(panel); updatePanelIndices(); setCurrentlySelectedPanel(Optional.of(index)); <START> mainStage.show(); <END> return panel; }</code><technical_language>Is this needed? If not, PanelControl longer needs stage</technical_language>

Target:
public FilterPanel addPanelAt(int index) { FilterPanel panel = new ListPanel(ui, model, this, index); getChildren().add(index, panel); guiController.panelFilterExpressionChanged(panel); updatePanelIndices(); setCurrentlySelectedPanel(Optional.of(index)); ui.showMainStage(); return panel; }
Source:
<code>private boolean compareSortKeys(IndexSortKey sortKey, String fieldName, Object dir) { String field = sortKey.getField().toString(); if (sortKey.isCaseInsensitive()) { field = Translator.getHiddenForField(sortKey.getField()).toString(); <START> } <END> if (field.equals(fieldName)) { int direction = ((Number) dir).intValue(); return sortKey.isDesc() == (direction < 0); } return false; }</code><technical_language>field.toString()</technical_language>

Target:
private boolean compareSortKeys(IndexSortKey sortKey, String fieldName, Object dir) { String field = sortKey.getField().toString(); if (sortKey.isCaseInsensitive()) { field = Translator.translatePath(Translator.getHiddenForField(sortKey.getField())); } if (field.equals(fieldName)) { int direction = ((Number) dir).intValue(); return sortKey.isDesc() == (direction < 0); } return false; }
Source:
<code>private void storeCert() throws IOException, KeyStoreException, CertificateException, NoSuchAlgorithmException { final Map<String, String> trustStoreProperties = getTrustStoreSystemProperties(); String storeType = trustStoreProperties.get(TRUST_STORE_TYPE_KEY); final String password = trustStoreProperties.get(TRUST_STORE_PASSWORD_KEY); final String storeLoc = trustStoreProperties.get(TRUST_STORE_KEY); if (storeType == null) { LOG.warn(STORE_TYPE_ERROR, TRUST_STORE_TYPE_KEY); storeType = JKS_TYPE; } if (password != null && !PKCS11_TYPE.equalsIgnoreCase(storeType)) { <START> FileOutputStream os = null; <END> try { os = new FileOutputStream(storeLoc); trustStore.store(os, password.toCharArray()); } finally { IOUtils.closeQuietly(os); } } }</code><technical_language>Optional: Try-with-resource</technical_language>

Target:
private void storeCert() throws IOException, KeyStoreException, CertificateException, NoSuchAlgorithmException { final Map<String, String> trustStoreProperties = getTrustStoreSystemProperties(); String storeType = trustStoreProperties.get(TRUST_STORE_TYPE_KEY); final String password = trustStoreProperties.get(TRUST_STORE_PASSWORD_KEY); final String storeLoc = trustStoreProperties.get(TRUST_STORE_KEY); if (storeType == null) { LOG.warn(STORE_TYPE_ERROR, TRUST_STORE_TYPE_KEY); storeType = JKS_TYPE; } if (password != null && !PKCS11_TYPE.equalsIgnoreCase(storeType)) { try (FileOutputStream os = new FileOutputStream(storeLoc)) { trustStore.store(os, password.toCharArray()); } } }
Source:
<code>public void execute() throws ExecutionException, InterruptedException { final String discountCodeId = UUID.randomUUID().toString(); final DefaultRemoveDiscountCodeFormData removeDiscountCodeFormData = new DefaultRemoveDiscountCodeFormData(); removeDiscountCodeFormData.setDiscountCodeId(discountCodeId); when: { when(hookRunner.runUnaryOperatorHook(any(), any(), cartUpdateCommandCaptor.capture())) .thenAnswer(invocation -> invocation.getArgument(2)); when(hookRunner.runActionHook(any(), any(), any())) .thenAnswer(invocation -> CompletableFuture.completedFuture(invocation.getArgument(2))); when(sphereClient.execute(any())) .thenReturn(CompletableFuture.completedFuture(cart)); } final Cart updatedCart = defaultRemoveDiscountCodeControllerAction.apply(cart, removeDiscountCodeFormData) .toCompletableFuture().get(); then: { assertThat(updatedCart).isNotNull(); final CartUpdateCommand cartUpdateCommand = cartUpdateCommandCaptor.getValue(); assertThat(cartUpdateCommand.getUpdateActions()).hasSize(1); final UpdateAction<Cart> cartUpdateAction = cartUpdateCommand.getUpdateActions().get(0); assertThat(cartUpdateAction).isInstanceOf(RemoveDiscountCode.class); final RemoveDiscountCode removeDiscountCode = (RemoveDiscountCode) cartUpdateAction; <START> assertThat(removeDiscountCode.getDiscountCode().getId()).isEqualTo(discountCodeId); <END> } }</code><technical_language>super verbose, I remember fighting smaller failed miserably of List<? extend UpdateAction<Cart>> :\</technical_language>

Target:
public void execute() throws ExecutionException, InterruptedException { final String discountCodeId = UUID.randomUUID().toString(); final DefaultRemoveDiscountCodeFormData removeDiscountCodeFormData = new DefaultRemoveDiscountCodeFormData(); removeDiscountCodeFormData.setDiscountCodeId(discountCodeId); mockHookRunnerThatReturnsCart(); mockSphereClientThatReturnsCart(); final Cart updatedCart = defaultRemoveDiscountCodeControllerAction.apply(cart, removeDiscountCodeFormData) .toCompletableFuture().get(); assertThat(updatedCart).isNotNull(); final CartUpdateCommand cartUpdateCommand = cartUpdateCommandCaptor.getValue(); assertThat(cartUpdateCommand.getUpdateActions()) .hasSize(1) .hasOnlyElementsOfType(RemoveDiscountCode.class); final RemoveDiscountCode removeDiscountCode = (RemoveDiscountCode) cartUpdateCommand.getUpdateActions().get(0); assertThat(removeDiscountCode.getDiscountCode().getId()).isEqualTo(discountCodeId); }
Source:
<code>public Resource display(@PathVariable("type") ModuleType type, @PathVariable("name") String name) { final ModuleDefinition definition = this.repository.findByNameAndType(name, type); if (definition == null) { throw new DefinitionNotFoundException(String.format( "There is no definition named '%s' for module type '%s'.", name, type.name())); } final Resource resource = definition.getResource(); if (!definition.getResource().exists()) { throw new ConfigurationFileNotFoundException(String.format("The Resourse ('%s" + "') associated with the module named '%s' (%s) does not exist.", definition.getResource().getFilename(), name, type.name())); } try { if (resource.getFile().length() == 0 && logger.isWarnEnabled()) { <START> logger.warn(String.format("The length of the file '%s' for module '%s' (%s) is zero.", <END> resource.getFilename(), definition.getName(), definition.getType().name())); } } catch (IOException e) { throw new IllegalStateException("Unable to return the file for the provided resource: " + resource.getFilename(), e); } return resource; }</code><technical_language>info. A warn user needs action. This is state a file data. know, empty</technical_language>

Target:
public Resource display(@PathVariable("type") ModuleType type, @PathVariable("name") String name) { final ModuleDefinition definition = this.repository.findByNameAndType(name, type); if (definition == null) { throw new NoSuchDefinitionException(name, String.format( "There is no definition named '%s' for module type '%s'.", name, type.name())); } final Resource resource = definition.getResource(); try { if (resource.getFile().length() == 0 && logger.isWarnEnabled()) { logger.warn(String.format("The length of the file '%s' for module '%s' (%s) is zero.", resource.getFilename(), definition.getName(), definition.getType().name())); } } catch (IOException e) { throw new IllegalStateException("Unable to return the file for the provided resource: " + resource.getFilename(), e); } return resource; }
Source:
<code>public void run() { while (currentPutCount.get() < totalPutCount) { try { int burstCount = threadLocalRandom.nextInt(maxParallelRequest) + 1; logger.trace("PutThread producing " + burstCount + " times "); final CountDownLatch countDownLatch = new CountDownLatch(burstCount); final AtomicInteger failureCount = new AtomicInteger(0); for (int j = 0; j < burstCount; j++) { Callback<Pair<String, byte[]>> callback = new Callback<Pair<String, byte[]>>() { @Override public void onCompletion(Pair<String, byte[]> result, Exception exception) { if (exception == null) { if (currentPutCount.get() < totalPutCount) { blobAccessInfos.add(new BlobAccessInfo(result.getFirst(), result.getSecond())); currentPutCount.incrementAndGet(); } <START> } else { <END> logger.error("PutBlob failed with " + exception.getStackTrace()); failureCount.incrementAndGet(); } countDownLatch.countDown(); } }; FutureResult futureResult = new FutureResult(); putHelper.putBlob(futureResult, callback); } countDownLatch.await(); if (failureCount.get() > maxFailuresPerPutBatchToStopPuts) { logger.error(failureCount.get() + " failures during this batch, hence exiting the Put Thread"); break; } Thread.sleep(threadLocalRandom.nextLong(sleepTimeBetweenBatchPutsInMs)); } catch (InterruptedException ex) { logger.error("InterruptedException in putThread " + ex.getStackTrace()); } } putComplete.set(true); logger.info( "Exiting Producer. Current Put Count " + currentPutCount.get() + ", total Put Count " + totalPutCount); }</code><technical_language>test immediately failed</technical_language>

Target:
public void run() { try { while (currentPutCount.get() < totalPutCount) { int burstCount = threadLocalRandom.nextInt(maxParallelRequest) + 1; logger.info("PutThread producing " + burstCount + " times "); final CountDownLatch countDownLatch = new CountDownLatch(burstCount); final AtomicInteger failureCount = new AtomicInteger(0); for (int j = 0; j < burstCount; j++) { Callback<Pair<String, byte[]>> callback = new Callback<Pair<String, byte[]>>() { @Override public void onCompletion(Pair<String, byte[]> result, Exception exception) { if (exception == null) { if (currentPutCount.get() < totalPutCount) { generatedBlobAccessInfos.add(new BlobAccessInfo(result.getFirst(), result.getSecond())); currentPutCount.incrementAndGet(); } } else { logger.error("PutBlob failed with ", exception); failureCount.incrementAndGet(); } countDownLatch.countDown(); } }; putHelper.putBlob(callback); } countDownLatch.await(5, TimeUnit.MINUTES); if (failureCount.get() > maxFailuresPerPutBatchToStopPuts) { logger.error(failureCount.get() + " failures during this batch, hence exiting the Put Thread"); break; } Thread.sleep(threadLocalRandom.nextLong(sleepTimeBetweenBatchPutsInMs)); } } catch (InterruptedException ex) { logger.error("InterruptedException in putThread ", ex); } finally { putComplete.set(true); } logger.info( "Exiting Producer. Current Put Count " + currentPutCount.get() + ", total Put Count " + totalPutCount); }
Source:
<code>protected void processFiltered(File file, FileText fileText) throws CheckstyleException { if (CommonUtils.matchesFileExtension(file, getFileExtensions())) { final String msg = "%s occurred during the analysis of file %s."; final String fileName = file.getPath(); try { if (!ordinaryChecks.isEmpty() || !commentChecks.isEmpty()) { <START> final FileText text = new FileText(fileText); <END> final FileContents contents = new FileContents(text); final DetailAST rootAST = parse(contents); if (!ordinaryChecks.isEmpty()) { walk(rootAST, contents, AstState.ORDINARY); } if (!commentChecks.isEmpty()) { final DetailAST astWithComments = appendHiddenCommentNodes(rootAST); walk(astWithComments, contents, AstState.WITH_COMMENTS); } } } catch (final TokenStreamRecognitionException tre) { final String exceptionMsg = String.format(Locale.ROOT, msg, "TokenStreamRecognitionException", fileName); throw new CheckstyleException(exceptionMsg, tre); } catch (RecognitionException | TokenStreamException ex) { final String exceptionMsg = String.format(Locale.ROOT, msg, ex.getClass().getSimpleName(), fileName); throw new CheckstyleException(exceptionMsg, ex); } } }</code><technical_language>do need a new instance of class? Is this for test testFileTextRecreation mentioned in issue</technical_language>

Target:
protected void processFiltered(File file, FileText fileText) throws CheckstyleException { if (CommonUtils.matchesFileExtension(file, getFileExtensions())) { final String msg = "%s occurred during the analysis of file %s."; final String fileName = file.getPath(); try { if (!ordinaryChecks.isEmpty() || !commentChecks.isEmpty()) { final FileContents contents = new FileContents(fileText); final DetailAST rootAST = parse(contents); if (!ordinaryChecks.isEmpty()) { walk(rootAST, contents, AstState.ORDINARY); } if (!commentChecks.isEmpty()) { final DetailAST astWithComments = appendHiddenCommentNodes(rootAST); walk(astWithComments, contents, AstState.WITH_COMMENTS); } } } catch (final TokenStreamRecognitionException tre) { final String exceptionMsg = String.format(Locale.ROOT, msg, "TokenStreamRecognitionException", fileName); throw new CheckstyleException(exceptionMsg, tre); } catch (RecognitionException | TokenStreamException ex) { final String exceptionMsg = String.format(Locale.ROOT, msg, ex.getClass().getSimpleName(), fileName); throw new CheckstyleException(exceptionMsg, ex); } } }
Source:
<code>public boolean isHangoutJoinerAutomationServiceEnabled() { List<AccessibilityServiceInfo> visualFeedbackServices = getVisualFeedbackServices(); for (AccessibilityServiceInfo service : visualFeedbackServices) { <START> if (service.getId().equalsIgnoreCase(SERVICE_ID)) { <END> return true; } } return false; }</code><technical_language>flip equals? SERVICE_ID.equals(service.getId())? ignoreCase</technical_language>

Target:
public boolean isHangoutJoinerAutomationServiceEnabled() { List<AccessibilityServiceInfo> visualFeedbackServices = getVisualFeedbackServices(); for (AccessibilityServiceInfo service : visualFeedbackServices) { if (SERVICE_ID.equals(service.getId())) { return true; } } return false; }
Source:
<code>private void viewPages() { requestNextStepOfActiveQuickStartTask(); SiteModel selectedSite = getSelectedSite(); if (selectedSite != null) { <START> ToastUtils.showToast(getActivity(), R.string.site_cannot_be_loaded); <END> ActivityLauncher.viewCurrentBlogPages(requireActivity(), selectedSite); } }</code><technical_language>this line in else clause? Wdyt</technical_language>

Target:
private void viewPages() { requestNextStepOfActiveQuickStartTask(); SiteModel selectedSite = getSelectedSite(); if (selectedSite != null) { ActivityLauncher.viewCurrentBlogPages(requireActivity(), selectedSite); } else { ToastUtils.showToast(getActivity(), R.string.site_cannot_be_loaded); } }
Source:
<code>private EnvVars buildEnv(final Job<?, ?> job) { <START> EnvVars env = new EnvVars(); <END> for (EnvironmentContributor contributor : EnvironmentContributor.all()) { try { contributor.buildEnvironmentFor(job, env, TaskListener.NULL); } catch (Exception e) { LOGGER.warning("failed to build env, skipping"); } } return env; }</code><technical_language>finals for EnvVars EnvironmentContributor in for</technical_language>

Target:
private EnvVars buildEnv(final Job<?, ?> job) { final EnvVars env = new EnvVars(); for (final EnvironmentContributor contributor : EnvironmentContributor.all()) { try { contributor.buildEnvironmentFor(job, env, TaskListener.NULL); } catch (Exception e) { LOGGER.warning("failed to build env, skipping"); } } return env; }