auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void storeSettings() { if (preferences.getBoolean(JabRefPreferences.OVERRIDE_DEFAULT_FONT_SIZE) != fontOverrideProperty.getValue()) { restartWarnings.add(Localization.lang("Override font settings")); preferences.putBoolean(JabRefPreferences.OVERRIDE_DEFAULT_FONT_SIZE, fontOverrideProperty.getValue()); } int newFontSize = Integer.parseInt(fontSizeProperty.getValue()); if (preferences.getInt(JabRefPreferences.MAIN_FONT_SIZE) != newFontSize) { restartWarnings.add(Localization.lang("Override font size")); preferences.putInt(JabRefPreferences.MAIN_FONT_SIZE, newFontSize); } if (themeLightProperty.getValue() && !preferences.get(JabRefPreferences.FX_THEME).equals(ThemeLoader.MAIN_CSS)) { <START> restartWarnings.add(Localization.lang("Theme changed:") + " " + ThemeLoader.MAIN_DESCRIPTION); <END> preferences.put(JabRefPreferences.FX_THEME, ThemeLoader.MAIN_CSS); } else if (themeDarkProperty.getValue() && !preferences.get(JabRefPreferences.FX_THEME).equals(ThemeLoader.DARK_CSS)) { restartWarnings.add(Localization.lang("Theme changed:") + " " + ThemeLoader.DARK_DESCRIPTION); preferences.put(JabRefPreferences.FX_THEME, ThemeLoader.DARK_CSS); } }</code><technical_language>I include theme name in localization: Localization.lang("Theme changed light theme");. This way, theme name is translated. I accept new localization strings</technical_language>

Target:
public void storeSettings() { if (preferences.getBoolean(JabRefPreferences.OVERRIDE_DEFAULT_FONT_SIZE) != fontOverrideProperty.getValue()) { restartWarnings.add(Localization.lang("Override font settings")); preferences.putBoolean(JabRefPreferences.OVERRIDE_DEFAULT_FONT_SIZE, fontOverrideProperty.getValue()); } int newFontSize = Integer.parseInt(fontSizeProperty.getValue()); if (preferences.getInt(JabRefPreferences.MAIN_FONT_SIZE) != newFontSize) { restartWarnings.add(Localization.lang("Override font size")); preferences.putInt(JabRefPreferences.MAIN_FONT_SIZE, newFontSize); } if (themeLightProperty.getValue() && !preferences.get(JabRefPreferences.FX_THEME).equals(ThemeLoader.MAIN_CSS)) { restartWarnings.add(Localization.lang("Theme changed to light theme.")); preferences.put(JabRefPreferences.FX_THEME, ThemeLoader.MAIN_CSS); } else if (themeDarkProperty.getValue() && !preferences.get(JabRefPreferences.FX_THEME).equals(ThemeLoader.DARK_CSS)) { restartWarnings.add(Localization.lang("Theme changed to dark theme.")); preferences.put(JabRefPreferences.FX_THEME, ThemeLoader.DARK_CSS); } }
Source:
<code>public TestingLabDTO create(final TestingLabDTO atl) throws UserRetrievalException, EntityCreationException, EntityRetrievalException, JsonProcessingException { String maxCode = testingLabDAO.getMaxCode(); int maxCodeValue = Integer.parseInt(maxCode); int nextCodeValue = maxCodeValue + 1; String nextAtlCode = ""; if (nextCodeValue < 10) { nextAtlCode = "0" + nextCodeValue; } else if (nextCodeValue > 99) { throw new EntityCreationException( "Cannot create a 2-digit ATL code since there are more than 99 ATLs in the system."); } else { nextAtlCode = nextCodeValue + ""; } atl.setTestingLabCode(nextAtlCode); atl.setRetired(false); TestingLabDTO result = testingLabDAO.create(atl); <START> userPermissionsManager.addAtlPermission(result, Util.getCurrentUser().getId()); <END> LOGGER.debug("Created testing lab " + result + " and granted admin permission to recipient " + gov.healthit.chpl.auth.Util.getUsername()); String activityMsg = "Created Testing Lab " + result.getName(); activityManager.addActivity(ActivityConcept.ACTIVITY_CONCEPT_ATL, result.getId(), activityMsg, null, result); return result; }</code><technical_language>new impersonation in place, this Util.getAuditId() stands grand permission Impersonated user, impersonation. ROLEs change in impersonation state, impersonating user is ROLEs apply to, I authority ATL (& ACB if right) set</technical_language>

Target:
public TestingLabDTO create(final TestingLabDTO atl) throws UserRetrievalException, EntityCreationException, EntityRetrievalException, JsonProcessingException { String maxCode = testingLabDAO.getMaxCode(); int maxCodeValue = Integer.parseInt(maxCode); int nextCodeValue = maxCodeValue + 1; String nextAtlCode = ""; if (nextCodeValue < 10) { nextAtlCode = "0" + nextCodeValue; } else if (nextCodeValue > 99) { throw new EntityCreationException( "Cannot create a 2-digit ATL code since there are more than 99 ATLs in the system."); } else { nextAtlCode = nextCodeValue + ""; } atl.setTestingLabCode(nextAtlCode); atl.setRetired(false); TestingLabDTO result = testingLabDAO.create(atl); userPermissionsManager.addAtlPermission(result, Util.getAuditId()); LOGGER.debug("Created testing lab " + result + " and granted admin permission to recipient " + gov.healthit.chpl.auth.Util.getUsername()); String activityMsg = "Created Testing Lab " + result.getName(); activityManager.addActivity(ActivityConcept.ACTIVITY_CONCEPT_ATL, result.getId(), activityMsg, null, result); return result; }
Source:
<code>public void endActivity(){ <START> this.getActivity().finish(); <END> }</code><technical_language>remove this simplify getActivity().finish();</technical_language>

Target:
public void endActivity(){ getActivity().finish(); }
Source:
<code><START> private BlobId createBlobId(String hexBlobId) throws IOException { <END> return new BlobId(hexBlobId, clusterMap); }</code><technical_language>minor: a function is required</technical_language>

Target:
private BlobId createBlobId(String hexBlobId) throws IOException { if (hexBlobId == null) { return null; } return new BlobId(hexBlobId, clusterMap); }
Source:
<code>public void testEdgeLabelMoveFromBorder() { String diagramName = "EdgeWith3SegmentsHVH"; diagramEditor = setUpEditorAccordingToDimensions(diagramName, ZoomLevel.ZOOM_100); SWTBotGefEditPart editPart = diagramEditor.getEditPart("refToBCenter"); editPart.select(); GraphicalEditPart part = (GraphicalEditPart) editPart.part(); IFigure figure = part.getFigure(); figure.translateToAbsolute(figure.getBounds()); int originalX = part.getFigure().getBounds().x; int originalY = part.getFigure().getBounds().y; CheckEditPartMoved checkEditPartMoved = new CheckEditPartMoved(editPart); diagramEditor.dragWithKey(part.getFigure().getBounds().x + 10, part.getFigure().getBounds().y, part.getFigure().getBounds().x + 10, part.getFigure().getBounds().y - 10, SWT.None); bot.waitUntil(checkEditPartMoved); assertEquals("The x <START> corrdinate should <END> be the same as the move is only on y axis.", originalX, part.getFigure().getBounds().x); assertEquals("The y coordinate should be different as the label has been moved by moving its border.", originalY - 10, part.getFigure().getBounds().y); }</code><technical_language>Typo: "coordinate"</technical_language>

Target:
public void testEdgeLabelMoveFromBorder() { String diagramName = "EdgeWith3SegmentsHVH"; diagramEditor = setUpEditorAccordingToDimensions(diagramName, ZoomLevel.ZOOM_100); SWTBotGefEditPart editPart = diagramEditor.getEditPart("refToBCenter"); editPart.select(); GraphicalEditPart part = (GraphicalEditPart) editPart.part(); IFigure figure = part.getFigure(); figure.translateToAbsolute(figure.getBounds()); int originalX = part.getFigure().getBounds().x; int originalY = part.getFigure().getBounds().y; CheckEditPartMoved checkEditPartMoved = new CheckEditPartMoved(editPart); diagramEditor.dragWithKey(part.getFigure().getBounds().x + 10, part.getFigure().getBounds().y, part.getFigure().getBounds().x + 10, part.getFigure().getBounds().y - 10, SWT.None); bot.waitUntil(checkEditPartMoved); assertEquals("The x coordinate should be the same as the move is only on y axis.", originalX, part.getFigure().getBounds().x); assertEquals("The y coordinate should be different as the label has been moved by moving its border.", originalY - 10, part.getFigure().getBounds().y); }
Source:
<code>private String parseFan(String value) { if (value.equals("FA")) return "FAuto"; if (value.equals("F1")) return "Fun1"; if (value.equals("F2")) return "Fun2"; if (value.equals("F3")) return "Fun3"; if (value.equals("F4")) return "Fun4"; <START> if (value.equals("F5")) return "Fun5"; <END> return "None"; }</code><technical_language>please refactor Enumerations instead</technical_language>

Target:
private DaikinFan parseFan(String value) { if (value.equals("FA")) return DaikinFan.Auto; if (value.equals("F1")) return DaikinFan.F1; if (value.equals("F2")) return DaikinFan.F2; if (value.equals("F3")) return DaikinFan.F3; if (value.equals("F4")) return DaikinFan.F4; if (value.equals("F5")) return DaikinFan.F5; return DaikinFan.None; }
Source:
<code>public char peekPrevious() { if (index > 0) { int prev = index - 1; <START> return line.charAt(prev); <END> } else { if (lineIndex > 0) { return '\n'; } else { return '\0'; } } }</code><technical_language>I this symbol in multiple places. do extract constant Character class? Character.MIN_VALUE</technical_language>

Target:
public char peekPrevious() { if (index > 0) { int prev = index - 1; return line.charAt(prev); } else { if (lineIndex > 0) { return '\n'; } else { return END; } } }
Source:
<code>StandardExports(StatusReader statusReader, OperatingSystemMXBean osBean, RuntimeMXBean runtimeBean) { this.statusReader = statusReader; this.osBean = osBean; this.runtimeBean = runtimeBean; this.unix = osBean instanceof UnixOperatingSystemMXBean; <START> this.linux = osBean.getName().indexOf("Linux") == 0; <END> }</code><technical_language>this is a magic side, put RHS in parens</technical_language>

Target:
StandardExports(StatusReader statusReader, OperatingSystemMXBean osBean, RuntimeMXBean runtimeBean) { this.statusReader = statusReader; this.osBean = osBean; this.runtimeBean = runtimeBean; this.unix = (osBean instanceof UnixOperatingSystemMXBean); this.linux = (osBean.getName().indexOf("Linux") == 0); }
Source:
<code><START> public void shouldUserCancelSubmittedStateBeResolvedToUserCancelledState() { <END> cancelStatusResolver = new CancelStatusResolver(); ChargeEntity mockChargeEntity = mock(ChargeEntity.class); when(mockChargeEntity.getStatus()).thenReturn(ChargeStatus.USER_CANCEL_SUBMITTED.getValue()); Optional<InternalExternalStatus> result = cancelStatusResolver.resolve(mockChargeEntity); assertTrue(result.isPresent()); ChargeStatus chargeStatus = (ChargeStatus) result.get(); assertThat(chargeStatus.getValue(), is(ChargeStatus.USER_CANCELLED.getValue())); }</code><technical_language>here, test name reads a question a statement</technical_language>

Target:
public void shouldUserCancelSubmittedStateBeResolvedToUserCancelledState() { cancelStatusResolver = new CancelStatusResolver(); ChargeEntity mockChargeEntity = mock(ChargeEntity.class); when(mockChargeEntity.getStatus()).thenReturn(ChargeStatus.USER_CANCEL_SUBMITTED.getValue()); Optional<Status> result = cancelStatusResolver.resolve(mockChargeEntity); assertTrue(result.isPresent()); ChargeStatus chargeStatus = (ChargeStatus) result.get(); assertThat(chargeStatus.getValue(), is(ChargeStatus.USER_CANCELLED.getValue())); }
Source:
<code>protected void markAsMerged(Diff diff, MergeMode mode, boolean mergeRightToLeft, Registry mergerRegistry) { if (isInTerminalState(diff)) { return; } updateDiffStateAdapter(diff); if <START> (AbstractMerger.isAccepting(diff, <END> mergeRightToLeft)) { final Set<Diff> implied = MergeDependenciesUtil.getAllResultingMerges(diff, mergerRegistry, mergeRightToLeft); final Set<Diff> rejections = MergeDependenciesUtil.getAllResultingRejections(diff, mergerRegistry, mergeRightToLeft); for (Diff impliedDiff : Sets.difference(implied, rejections)) { impliedDiff.setState(DifferenceState.MERGED); } for (Diff impliedRejection : rejections) { impliedRejection.setState(DifferenceState.DISCARDED); } } else { final Set<Diff> implied = MergeDependenciesUtil.getAllResultingMerges(diff, mergerRegistry, mergeRightToLeft); for (Diff impliedDiff : implied) { impliedDiff.setState(DifferenceState.DISCARDED); } } }</code><technical_language>Please static import. Eventually, want moving this method a utility</technical_language>

Target:
protected void markAsMerged(Diff diff, MergeMode mode, boolean mergeRightToLeft, Registry mergerRegistry) { if (isInTerminalState(diff)) { return; } if (isAccepting(diff, mergeRightToLeft)) { final Set<Diff> implied = MergeDependenciesUtil.getAllResultingMerges(diff, mergerRegistry, mergeRightToLeft); final Set<Diff> rejections = MergeDependenciesUtil.getAllResultingRejections(diff, mergerRegistry, mergeRightToLeft); for (Diff impliedDiff : Sets.difference(implied, rejections)) { impliedDiff.setState(MERGED); } for (Diff impliedRejection : rejections) { impliedRejection.setState(DISCARDED); } } else { final Set<Diff> implied = MergeDependenciesUtil.getAllResultingMerges(diff, mergerRegistry, mergeRightToLeft); for (Diff impliedDiff : implied) { impliedDiff.setState(DISCARDED); } } }
Source:
<code>public void execute() { if (Strings.isNullOrEmpty(getCfgName())) { throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "Empty configuration name provided"); } if (getCfgName().equalsIgnoreCase(RoleService.EnableDynamicApiChecker.key())) { throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "Restricted configuration update not allowed"); } Configuration cfg = _configService.updateConfiguration(this); if (cfg != null) { ConfigurationResponse response = _responseGenerator.createConfigurationResponse(cfg); response.setResponseName(getCommandName()); if (getZoneId() != null) { response.setScope("zone"); } if (getClusterId() != null) { response.setScope("cluster"); } if (getStoragepoolId() != null) { response.setScope("storagepool"); } if (getAccountId() != null) { response.setScope("account"); } if (getImageStoreId() != null) { response.setScope("imagestore"); <START> } <END> response.setValue(value); this.setResponseObject(response); } else { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to update config"); } }</code><technical_language>Please remove this check adding validations = PositiveNumber imageStoreId @Parameter annotation</technical_language>

Target:
public void execute() { if (Strings.isNullOrEmpty(getCfgName())) { throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "Empty configuration name provided"); } if (getCfgName().equalsIgnoreCase(RoleService.EnableDynamicApiChecker.key())) { throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "Restricted configuration update not allowed"); } Configuration cfg = _configService.updateConfiguration(this); if (cfg != null) { ConfigurationResponse response = _responseGenerator.createConfigurationResponse(cfg); response.setResponseName(getCommandName()); if (getZoneId() != null) { response.setScope("zone"); } if (getClusterId() != null) { response.setScope("cluster"); } if (getStoragepoolId() != null) { response.setScope("storagepool"); } if (getAccountId() != null) { response.setScope("account"); } response.setValue(value); this.setResponseObject(response); } else { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to update config"); } }
Source:
<code>private ApnsClient buildApnsClient(final iOSVariant iOSVariant) { if (iOSVariant.getCertificate() != null && iOSVariant.getPassphrase() != null) { <START> if (ApnsUtil.checkValidity(iOSVariant.getCertificate(), iOSVariant.getPassphrase().toCharArray())) { <END> try { final ByteArrayInputStream stream = new ByteArrayInputStream(iOSVariant.getCertificate()); final ApnsClientBuilder builder = new ApnsClientBuilder(); builder.setClientCredentials(stream, iOSVariant.getPassphrase()); if (ProxyConfiguration.hasHttpProxyConfig()) { if (ProxyConfiguration.hasBasicAuth()) { String user = ProxyConfiguration.getProxyUser(); String pass = ProxyConfiguration.getProxyPass(); builder.setProxyHandlerFactory(new HttpProxyHandlerFactory(ProxyConfiguration.proxyAddress(), user, pass)); } else { builder.setProxyHandlerFactory(new HttpProxyHandlerFactory(ProxyConfiguration.proxyAddress())); } } else if (ProxyConfiguration.hasSocksProxyConfig()) { builder.setProxyHandlerFactory(new Socks5ProxyHandlerFactory(ProxyConfiguration.socks())); } final ApnsClient apnsClient = builder.build(); stream.close(); return apnsClient; } catch (Exception e) { logger.error("Error reading certificate", e); } } else { return null; } } throw new IllegalArgumentException("Not able to construct APNS client"); }</code><technical_language>this is done in buildApnsClient checked cached client right? (So check for batch, unneccessary)</technical_language>

Target:
private ApnsClient buildApnsClient(final iOSVariant iOSVariant) { if (iOSVariant.getCertificate() != null && iOSVariant.getPassphrase() != null) { try(final ByteArrayInputStream stream = new ByteArrayInputStream(iOSVariant.getCertificate())) { final ApnsClientBuilder builder = new ApnsClientBuilder(); builder.setClientCredentials(stream, iOSVariant.getPassphrase()); if (ProxyConfiguration.hasHttpProxyConfig()) { if (ProxyConfiguration.hasBasicAuth()) { String user = ProxyConfiguration.getProxyUser(); String pass = ProxyConfiguration.getProxyPass(); builder.setProxyHandlerFactory(new HttpProxyHandlerFactory(ProxyConfiguration.proxyAddress(), user, pass)); } else { builder.setProxyHandlerFactory(new HttpProxyHandlerFactory(ProxyConfiguration.proxyAddress())); } } else if (ProxyConfiguration.hasSocksProxyConfig()) { builder.setProxyHandlerFactory(new Socks5ProxyHandlerFactory(ProxyConfiguration.socks())); } final ApnsClient apnsClient = builder.build(); return apnsClient; } catch (Exception e) { logger.error("Error reading certificate", e); } } throw new IllegalArgumentException("Not able to construct APNS client"); }
Source:
<code><START> public void assign(AssignableReplica assignableReplica) { <END> if (!addToAssignmentRecord(assignableReplica, _currentAssignments)) { throw new HelixException(String .format("Resource %s already has a replica from partition %s on node %s", assignableReplica.getResourceName(), assignableReplica.getPartitionName(), getInstanceName())); } else { if (assignableReplica.isReplicaTopState()) { addToAssignmentRecord(assignableReplica, _currentTopStateAssignments); } assignableReplica.getCapacity().entrySet().stream().forEach( capacity -> updateCapacityAndUtilization(capacity.getKey(), capacity.getValue())); } }</code><technical_language>Please methods public. designed package-private intentionally. idea is update assignment done ClusterModel interfaces. easier ensure model is consistent. If assign/release public here, if caller call node assign call context addPartitionToFaultZone? cluster model in a inconsistent state</technical_language>

Target:
void assign(AssignableReplica assignableReplica) { addToAssignmentRecord(assignableReplica); assignableReplica.getCapacity().entrySet().stream() .forEach(capacity -> updateCapacityAndUtilization(capacity.getKey(), capacity.getValue())); }
Source:
<code>public MoveDiskCommand(MoveDiskParameters parameters) { <START> super(parameters); <END> diskValidator = new DiskValidator(getParameters().getDiskImageId()); vmValidator = new VmValidator(getParameters().getVmId()); sourceDomainValidator = new StorageDomainValidator(getParameters().getSourceDomainId(), getParameters().getStoragePoolId()); targetDomainValidator = new StorageDomainValidator(getParameters().getDestinationDomain(), getParameters().getStoragePoolId()); diskImage = DbFacade.getInstance().getDiskImageDAO().get(getParameters().getDiskImageId()); }</code><technical_language>I constructor, creation of class perform a queries DB, if for some reason failed , exception java.lang.ReflectionException InvocationException, provide clue for reason of failure</technical_language>

Target:
public MoveDiskCommand(MoveDiskParameters parameters) { super(parameters); }
Source:
<code>private Promise<TemplateStore> loadTemplateStore() { Deferred<TemplateStore> deferred = new Deferred<>(); Promise<TemplateStore> promise = deferred.getPromise(); <START> Executors.newSingleThreadExecutor().submit(()->{ <END> TemplateStore templateStore = null; IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore(); boolean alreadyMigrated= store.getBoolean(CODE_TEMPLATES_MIGRATION_KEY); if (alreadyMigrated) templateStore= new ContributionTemplateStore(getCodeTemplateContextRegistry(), store, CODE_TEMPLATES_KEY); else { templateStore= new CompatibilityTemplateStore(getCodeTemplateContextRegistry(), store, CODE_TEMPLATES_KEY, getOldCodeTemplateStoreInstance()); store.setValue(CODE_TEMPLATES_MIGRATION_KEY, true); } try { templateStore.load(); } catch (IOException e) { JavaPlugin.log(e); } templateStore.startListeningForPreferenceChanges(); CompatibilityTemplateStore.pruneDuplicates(templateStore, true); deferred.resolve(templateStore); }); return promise.thenAccept((ts)->{ JavaManipulation.setCodeTemplateStore(ts); JavaManipulation.setCodeTemplateContextRegistry(getCodeTemplateContextRegistry()); }); }</code><technical_language>Please check if this get re-formatted Ctrl+Shift+F</technical_language>

Target:
public TemplateStore loadTemplateStore() { TemplateStore templateStore= null; IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore(); boolean alreadyMigrated= store.getBoolean(CODE_TEMPLATES_MIGRATION_KEY); if (alreadyMigrated) templateStore= new ContributionTemplateStore(getCodeTemplateContextRegistry(), store, CODE_TEMPLATES_KEY); else { templateStore= new CompatibilityTemplateStore(getCodeTemplateContextRegistry(), store, CODE_TEMPLATES_KEY, getOldCodeTemplateStoreInstance()); store.setValue(CODE_TEMPLATES_MIGRATION_KEY, true); } try { templateStore.load(); } catch (IOException e) { JavaPlugin.log(e); } templateStore.startListeningForPreferenceChanges(); CompatibilityTemplateStore.pruneDuplicates(templateStore, true); setTemplateStore(templateStore); return templateStore; }
Source:
<code>public void testPhiroMoveMotorBackwardBrick() { <START> int SET_SPEED = 30; <END> checkIfBrickAtPositionShowsString(0, R.string.brick_when_started); checkIfBrickAtPositionShowsString(brickPosition, R.string.brick_phiro_motor_backward_action); List<Integer> spinnerValuesResourceIds = Arrays.asList( R.string.phiro_motor_right, R.string.phiro_motor_left, R.string.phiro_motor_both); checkIfValuesAvailableInSpinnerOnBrick(spinnerValuesResourceIds, R.id.brick_phiro_motor_backward_action_spinner, brickPosition); enterValueInFormulaTextFieldOnBrickAtPosition(SET_SPEED, R.id.brick_phiro_motor_backward_action_speed_edit_text, brickPosition); }</code><technical_language>constants in caps, this is a local variable</technical_language>

Target:
public void testPhiroMoveMotorBackwardBrick() { int setSpeed = 30; checkIfBrickAtPositionShowsString(0, R.string.brick_when_started); checkIfBrickAtPositionShowsString(brickPosition, R.string.brick_phiro_motor_backward_action); List<Integer> spinnerValuesResourceIds = Arrays.asList( R.string.phiro_motor_right, R.string.phiro_motor_left, R.string.phiro_motor_both); checkIfValuesAvailableInSpinnerOnBrick(spinnerValuesResourceIds, R.id.brick_phiro_motor_backward_action_spinner, brickPosition); enterValueInFormulaTextFieldOnBrickAtPosition(setSpeed, R.id.brick_phiro_motor_backward_action_speed_edit_text, brickPosition); }
Source:
<code>public static boolean pathMatches(@Nullable String pathA, @Nullable String pathB) { if (pathA == null || pathA.isEmpty()) { return true; } if (pathB == null || pathB.isEmpty()) { return false; } if (pathA.matches("/") && pathB.isEmpty()) { return true; } boolean exactMatch = pathA.endsWith("/") ? false : true; List<String> pathListA = Arrays.asList(pathA.split("/")); List<String> pathListB = Arrays.asList(pathB.split("/")); <START> long countA = pathA.chars().filter(ch -> ch =='/').count(); <END> long countB = pathB.chars().filter(ch -> ch =='/').count(); if (pathListA.size() > pathListB.size() || countA > countB) return false; if (exactMatch && (pathListA.size() != pathListB.size() || countA != countB)) { return false; } StringTokenizer st = new StringTokenizer(pathA, "/"); int z = st.countTokens(); Iterator it1 = pathListA.iterator(); Iterator it2 = pathListB.iterator(); while (it1.hasNext() && it2.hasNext()) { String a = decodeString((String) it1.next()); String b = decodeString((String) it2.next()); if (!a.equals(b)) { return false; } } return true; }</code><technical_language>I understand reason for countA countB variables usages. if removed 6.6.1.10 directly</technical_language>

Target:
public static boolean pathMatches(@Nullable String pathA, @Nullable String pathB) { if (pathA == null || pathA.isEmpty()) { return true; } if (pathB == null || pathB.isEmpty()) { return false; } if (pathA.matches("/") && pathB.isEmpty()) { return true; } boolean exactMatch = pathA.endsWith("/") ? false : true; List<String> pathListA = splitBySpec(pathA, '/'); List<String> pathListB = splitBySpec(pathB, '/'); if (pathListA.size() > pathListB.size()) return false; if (exactMatch && pathListA.size() != pathListB.size()) { return false; } if (!exactMatch) { pathListA.remove(pathListA.size() - 1); } Iterator it1 = pathListA.iterator(); Iterator it2 = pathListB.iterator(); while (it1.hasNext()) { String a = decodeString((String) it1.next()); String b = decodeString((String) it2.next()); if (!a.equals(b)) { return false; } } return true; }
Source:
<code>public void execute() throws MojoExecutionException, MojoFailureException { copyContents(); <START> try (FileInputStream configStream = new FileInputStream(new File(project.getBasedir(), configFile))) { <END> Properties properties = new Properties(); properties.putAll(project.getProperties()); properties.putAll(System.getProperties()); properties.put("project.version", project.getVersion()); final FeaturePackBuild build = new FeaturePackBuildModelParser(new MapPropertyResolver(properties)).parse(configStream); File target = new File(buildName, serverName); FeaturePackBuilder.build(build, target, new MavenProjectArtifactResolver(project), new AetherArtifactFileResolver(repoSystem, repoSession, remoteRepos)); } catch (Exception e) { throw new RuntimeException(e); } }</code><technical_language>This change work if default is left ${basedir}/feature-pack-build.xml. essentially result in ${basedir}${basedir}/feature-pack-build.xml defaults</technical_language>

Target:
public void execute() throws MojoExecutionException, MojoFailureException { if (!resourcesDir.isEmpty()) { switch (resourcesDir.charAt(0)) { case '/': case '\\': break; default: resourcesDir = "/" + resourcesDir; break; } } copyContents(); try (FileInputStream configStream = new FileInputStream(new File(configDir, configFile))) { Properties properties = new Properties(); properties.putAll(project.getProperties()); properties.putAll(System.getProperties()); properties.put("project.version", project.getVersion()); final FeaturePackBuild build = new FeaturePackBuildModelParser(new MapPropertyResolver(properties)).parse(configStream); File target = new File(buildName, serverName); FeaturePackBuilder.build(build, target, new MavenProjectArtifactResolver(project), new AetherArtifactFileResolver(repoSystem, repoSession, remoteRepos)); } catch (Exception e) { throw new RuntimeException(e); } }
Source:
<code>public <I> void hear(TypeLiteral<I> type, TypeEncounter<I> encounter) { Class<?> clazz = type.getRawType(); while (clazz != null && !Collection.class.isAssignableFrom(clazz) && !clazz.isArray()) { for (final Method method : clazz.getDeclaredMethods()) { if(method.isAnnotationPresent(EventListener.class)) { if(method.getReturnType().equals(Void.TYPE) && method.getParameterTypes().length == 1 && ApplicationEvent.class.isAssignableFrom(method.getParameterTypes()[0])) { encounter.register(new InjectionListener<Object>() { @Override public void afterInjection(Object injectee) { GuavaSubscriberProxy proxy = new GuavaSubscriberProxy(injectee, method); eventBus.register(proxy); } }); } <START> else <END> { LOG.warn("@EventListener {}.{} skipped. Methods must be public, void, and accept exactly" + " one argument extending com.netflix.governator.event.ApplicationEvent.", clazz.getName(), method.getName()); } } } clazz = clazz.getSuperclass(); } }</code><technical_language>OCD. { spacing style consistent</technical_language>

Target:
public <I> void hear(TypeLiteral<I> type, TypeEncounter<I> encounter) { final Class<?> clazz = type.getRawType(); final List<Method> handlerMethods = getAllDeclaredHandlerMethods(clazz); if(!handlerMethods.isEmpty()) { encounter.register(new InjectionListener<Object>() { @Override public void afterInjection(Object injectee) { for (final Method handlerMethod : handlerMethods) { dispatcherProvider.get().registerListener(injectee, handlerMethod, (Class<? extends ApplicationEvent>) handlerMethod.getParameterTypes()[0]); } } }); } }
Source:
<code>private FileAlterationObserver createObserver(String fileName) { <START> File file = new File(fileName); <END> if (file.isDirectory()) { return new FileAlterationObserver(file); } else { return new FileAlterationObserver(FilenameUtils.getFullPathNoEndSeparator(fileName), FileFilterUtils .nameFileFilter(FilenameUtils.getName(fileName))); } }</code><technical_language>final! :)</technical_language>

Target:
private FileAlterationObserver createObserver(String fileName) { final File file = new File(fileName); if (file.isDirectory()) { return new FileAlterationObserver(file); } else { return new FileAlterationObserver(FilenameUtils.getFullPathNoEndSeparator(fileName), FileFilterUtils .nameFileFilter(FilenameUtils.getName(fileName))); } }
Source:
<code>@Override public Session create(CassandraStorage cassandra) { Closer closer = Closer.create(); try { Cluster cluster = closer.register(buildCluster(cassandra)); cluster.register(new QueryLogger.Builder().build()); Session session; if (cassandra.ensureSchema()) { session = closer.register(cluster.connect()); Schema.ensureExists(cassandra.keyspace(), cassandra.searchEnabled(), session); <START> Schema.ensureExists(DEFAULT_KEYSPACE + "_udts", false, session); <END> session.execute("USE " + cassandra.keyspace()); } else { session = cluster.connect(cassandra.keyspace()); } initializeUDTs(session); return session; } catch (RuntimeException e) { try { closer.close(); } catch (IOException ignored) { } throw e; } }</code><technical_language>I suggest add more debug logs key places? hard for find cassandra.ensureSchema set false, I thought error set variable... I worth logging well, debug this PR, I great a command line option zipkin server dump spring config. hard do, extremely helpful for user</technical_language>

Target:
@Override public Session create(CassandraStorage cassandra) { Closer closer = Closer.create(); try { Cluster cluster = closer.register(buildCluster(cassandra)); cluster.register(new QueryLogger.Builder().build()); Session session; String keyspace = cassandra.keyspace(); if (cassandra.ensureSchema()) { session = closer.register(cluster.connect()); Schema.ensureExists(keyspace, cassandra.searchEnabled(), session); Schema.ensureExists(DEFAULT_KEYSPACE + "_udts", false, session); session.execute("USE " + keyspace); } else { LOG.debug("Skipping schema check on keyspace as ensureSchema was false", keyspace); session = cluster.connect(keyspace); } initializeUDTs(session); return session; } catch (RuntimeException e) { try { closer.close(); } catch (IOException ignored) { } throw e; } }
Source:
<code>public void createsARefundTransactionEntityFromRefundEntity() throws Exception { long amount = 123L; String externalId = "someExternalId"; RefundEntity refundEntity = RefundEntityFixture.aValidRefundEntity() .withAmount(amount) .withExternalId(externalId) .withStatus(RefundStatus.REFUND_ERROR) .build(); RefundTransactionEntity transactionEntity = RefundTransactionEntity.from(refundEntity); assertThat(transactionEntity.getAmount(), is(amount)); assertThat(transactionEntity.getRefundExternalId(), is(externalId)); assertThat(transactionEntity.getUserExternalId(), is(refundEntity.getUserExternalId())); <START> assertThat(transactionEntity.getStatus(), is(RefundStatus.REFUND_ERROR)); <END> }</code><technical_language>I nicer if user external ID explicitly (in externalId amount are)</technical_language>

Target:
public void createsARefundTransactionEntityFromRefundEntity() throws Exception { long amount = 123L; String externalId = "someExternalId"; String refundReference = "refundReference"; RefundEntity refundEntity = RefundEntityFixture.aValidRefundEntity() .withAmount(amount) .withExternalId(externalId) .withStatus(RefundStatus.REFUND_ERROR) .withReference(refundReference) .build(); RefundTransactionEntity transactionEntity = RefundTransactionEntity.from(refundEntity); assertThat(transactionEntity.getAmount(), is(amount)); assertThat(transactionEntity.getRefundExternalId(), is(externalId)); assertThat(transactionEntity.getUserExternalId(), is(RefundEntityFixture.userExternalId)); assertThat(transactionEntity.getStatus(), is(RefundStatus.REFUND_ERROR)); }
Source:
<code>protected Position handlePosition(Position position) { String attributesString = Context.getDeviceManager().lookupAttributeString( <START> position.getDeviceId(), "processing.copyAttributes", Position.KEY_DRIVER_UNIQUE_ID + ",", true); <END> Position last = getLastPosition(position.getDeviceId()); if (last != null) { for (String attribute : attributesString.split("[ ,]")) { if (last.getAttributes().containsKey(attribute) && !position.getAttributes().containsKey(attribute)) { position.getAttributes().put(attribute, last.getAttributes().get(attribute)); } } } return position; }</code><technical_language>do need extra comma here</technical_language>

Target:
protected Position handlePosition(Position position) { String attributesString = Context.getDeviceManager().lookupAttributeString( position.getDeviceId(), "processing.copyAttributes", "", true); Position last = getLastPosition(position.getDeviceId()); if (attributesString.isEmpty()) { attributesString = Position.KEY_DRIVER_UNIQUE_ID; } else { attributesString += "," + Position.KEY_DRIVER_UNIQUE_ID; } if (last != null) { for (String attribute : attributesString.split("[ ,]")) { if (last.getAttributes().containsKey(attribute) && !position.getAttributes().containsKey(attribute)) { position.getAttributes().put(attribute, last.getAttributes().get(attribute)); } } } return position; }
Source:
<code>public <T> Flowable<T> method(String name, Entity<?> entity, GenericType<T> responseType) { Flowable<T> flowable = Flowable.create(new FlowableOnSubscribe<T>() { @Override <START> public void subscribe(FlowableEmitter<T> emitter) throws Exception { <END> try { T response = syncInvoker.method(name, entity, responseType); emitter.onNext(response); emitter.onComplete(); } catch (Throwable e) { emitter.onError(e); } } }, BackpressureStrategy.DROP); if (sc == null) { return flowable; } return flowable.subscribeOn(sc).observeOn(sc); }</code><technical_language>generalize code a bit, repetition I think: private <T> Flowable<T> create(Supplier<T> supplier) { Flowable<T> flowable = Flowable.create(new FlowableOnSubscribe<T>() { @Override public void subscribe(FlowableEmitter<T> emitter) throws Exception { try { T response = supplier.get(); if (!emitter.isCancelled()) { emitter.onNext(response); } if (!emitter.isCancelled()) { emitter.onComplete(); } } catch (Throwable e) { if (!emitter.isCancelled()) { emitter.onError(e); } } } }, BackpressureStrategy.DROP); if (sc == null) { return flowable; } return flowable.subscribeOn(sc).observeOn(sc); } implementation is needs a supplier: @Override public <T> Flowable<T> method(String name, Entity<?> entity, GenericType<T> responseType) { return create(() -> syncInvoker.method(name, entity, responseType)); } @Override public <T> Flowable<T> method(String name, Class<T> responseType) { return create(() -> syncInvoker.method(name, responseType)); } @Override public <T> Flowable<T> method(String name, GenericType<T> responseType) { return create(() -> syncInvoker.method(name, responseType)); } do think</technical_language>

Target:
public <T> Flowable<T> method(String name, Entity<?> entity, GenericType<T> responseType) { return create(() -> syncInvoker.method(name, entity, responseType)); }
Source:
<code>private void setRowStateOnDownload(ViewHolder row, DownloadEntry.DownloadedState state , View.OnClickListener listener) { switch (state) { case DOWNLOADING: row.bulkDownload.setIcon(Iconify.IconValue.fa_spinner); row.bulkDownload.setRotating(true); row.bulkDownload.setIconColorResource(R.color.edx_brand_primary_base); <START> row.numOfVideoAndDownloadArea.setOnClickListener(listener); <END> break; case DOWNLOADED: row.bulkDownload.setIcon(Iconify.IconValue.fa_check); row.bulkDownload.setRotating(false); row.bulkDownload.setIconColorResource(R.color.edx_grayscale_neutral_base); row.numOfVideoAndDownloadArea.setOnClickListener(listener); break; default: row.bulkDownload.setIcon(Iconify.IconValue.fa_arrow_down); row.bulkDownload.setRotating(false); row.bulkDownload.setIconColorResource(R.color.edx_grayscale_neutral_base); row.numOfVideoAndDownloadArea.setOnClickListener(listener); break; } }</code><technical_language>listener is set in cases, moved switch block</technical_language>

Target:
private void setRowStateOnDownload(ViewHolder row, DownloadEntry.DownloadedState state , View.OnClickListener listener) { switch (state) { case DOWNLOADING: row.bulkDownload.setIcon(Iconify.IconValue.fa_spinner); row.bulkDownload.setRotating(true); row.bulkDownload.setIconColorResource(R.color.edx_brand_primary_base); break; case DOWNLOADED: row.bulkDownload.setIcon(Iconify.IconValue.fa_check); row.bulkDownload.setRotating(false); row.bulkDownload.setIconColorResource(R.color.edx_grayscale_neutral_base); break; case ONLINE: row.bulkDownload.setIcon(Iconify.IconValue.fa_arrow_down); row.bulkDownload.setRotating(false); row.bulkDownload.setIconColorResource(R.color.edx_grayscale_neutral_base); break; } row.numOfVideoAndDownloadArea.setOnClickListener(listener); }
Source:
<code>protected IContributionItem[] getContributionItems() { Set<String> selectedTraceTypes = new HashSet<String>(); IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); IWorkbenchPage page = window.getActivePage(); ISelection selection = page.getSelection(); boolean forTraces = false, forExperiments = false; if (selection instanceof StructuredSelection) { for (Object element : ((StructuredSelection) selection).toList()) { if (element instanceof TmfTraceElement) { TmfTraceElement trace = (TmfTraceElement) element; selectedTraceTypes.add(trace.getTraceType()); forTraces = true; } else if (element instanceof TmfExperimentElement) { TmfExperimentElement trace = (TmfExperimentElement) element; selectedTraceTypes.add(trace.getTraceType()); forExperiments = true; } } } if (forTraces && forExperiments) { <START> throw new RuntimeException(Messages.SelectElementTypeContributionItem_ElementSelection); <END> } if (forExperiments) { return getExperimentContributionItems(selectedTraceTypes); } return getTraceContributionItems(selectedTraceTypes); }</code><technical_language>happen plugin.xml, handle simpler (just return array other, empty array). worth define NLS message for this..</technical_language>

Target:
protected IContributionItem[] getContributionItems() { Set<String> selectedTraceTypes = new HashSet<String>(); IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); IWorkbenchPage page = window.getActivePage(); ISelection selection = page.getSelection(); boolean forTraces = false, forExperiments = false; if (selection instanceof StructuredSelection) { for (Object element : ((StructuredSelection) selection).toList()) { if (element instanceof TmfTraceElement) { TmfTraceElement trace = (TmfTraceElement) element; selectedTraceTypes.add(trace.getTraceType()); forTraces = true; } else if (element instanceof TmfExperimentElement) { TmfExperimentElement trace = (TmfExperimentElement) element; selectedTraceTypes.add(trace.getTraceType()); forExperiments = true; } } } if (forTraces && forExperiments) { throw new RuntimeException("You must select only experiments or only traces to set the element type"); } if (forExperiments) { return getExperimentContributionItems(selectedTraceTypes); } return getTraceContributionItems(selectedTraceTypes); }
Source:
<code><START> public Serializable retrieveConfigurationObjects(final ClientConnection conn, final DlmsDevice device, <END> final RetrieveConfigurationObjectsRequest request) throws OsgpException, ProtocolAdapterException, SessionProviderException { return this.retrieveConfigurationObjectsCommandExecutor.execute(conn, device, null); }</code><technical_language>![MAJOR](<LINK_0> Remove unused method parameter(s) "request". [![rule](<LINK_1>](<LINK_2></technical_language>

Target:
public Serializable retrieveConfigurationObjects(final ClientConnection conn, final DlmsDevice device, final RetrieveConfigurationObjectsRequest request) throws ProtocolAdapterException { return this.retrieveConfigurationObjectsCommandExecutor.execute(conn, device, null); }
Source:
<code>public static void fetchViewers(final String blogId, final int localTableBlogId, final int offset, final FetchViewersCallback callback) { com.wordpress.rest.RestRequest.Listener listener = new RestRequest.Listener() { @Override public void onResponse(JSONObject jsonObject) { if (jsonObject != null && callback != null) { try { JSONArray jsonArray = jsonObject.getJSONArray("viewers"); List<Person> people = peopleListFromJSON(jsonArray, localTableBlogId, false, false, true); int numberOfUsers = jsonObject.optInt("found"); boolean isEndOfList = (people.size() + offset) >= numberOfUsers; callback.onSuccess(people, isEndOfList); } catch (JSONException e) { AppLog.e(T.API, "JSON exception occurred while parsing the response for " + "sites/%s/viewers: " + e); callback.onError(); } } } }; RestRequest.ErrorListener errorListener = new RestRequest.ErrorListener() { @Override public void onErrorResponse(VolleyError volleyError) { AppLog.e(T.API, volleyError); if (callback != null) { callback.onError(); } } }; <START> int page = (int) Math.floor(offset / FETCH_LIMIT) + 1; <END> Map<String, String> params = new HashMap<>(); params.put("number", Integer.toString(FETCH_LIMIT)); params.put("page", Integer.toString(page)); String path = String.format("sites/%s/viewers", blogId); WordPress.getRestClientUtilsV1_1().get(path, params, null, listener, errorListener); }</code><technical_language>This a division (positive) integers, Math.floor usage is offering division "floor" result return int anyway. I missing</technical_language>

Target:
public static void fetchViewers(final String blogId, final int localTableBlogId, final int offset, final FetchViewersCallback callback) { com.wordpress.rest.RestRequest.Listener listener = new RestRequest.Listener() { @Override public void onResponse(JSONObject jsonObject) { if (jsonObject != null && callback != null) { try { JSONArray jsonArray = jsonObject.getJSONArray("viewers"); List<Person> people = peopleListFromJSON(jsonArray, localTableBlogId, Person.PersonType.VIEWER); int numberOfUsers = jsonObject.optInt("found"); boolean isEndOfList = (people.size() + offset) >= numberOfUsers; callback.onSuccess(people, isEndOfList); } catch (JSONException e) { AppLog.e(T.API, "JSON exception occurred while parsing the response for " + "sites/%s/viewers: " + e); callback.onError(); } } } }; RestRequest.ErrorListener errorListener = new RestRequest.ErrorListener() { @Override public void onErrorResponse(VolleyError volleyError) { AppLog.e(T.API, volleyError); if (callback != null) { callback.onError(); } } }; int page = (offset / FETCH_LIMIT) + 1; Map<String, String> params = new HashMap<>(); params.put("number", Integer.toString(FETCH_LIMIT)); params.put("page", Integer.toString(page)); String path = String.format("sites/%s/viewers", blogId); WordPress.getRestClientUtilsV1_1().get(path, params, null, listener, errorListener); }
Source:
<code>private synchronized void validate(String partitionKey, String rowKey) { if (this.frozen) { throw logger.logExceptionAsError( new IllegalStateException("Operations can't be modified once a batch is submitted.")); } if (!this.partitionKey.equals(partitionKey)) { throw logger.logExceptionAsError( new IllegalArgumentException("All operations in a batch must share the same partition key.")); } <START> if (rowKey == null || rowKey.isEmpty()) { <END> throw logger.logExceptionAsError( new IllegalArgumentException("The row key must not be null or empty.")); } if (rowKeys.contains(rowKey)) { throw logger.logExceptionAsError( new IllegalArgumentException("Every operation in a batch must use a different row key.")); } else { rowKeys.add(rowKey); } }</code><technical_language>CoreUtils.isNullorEmpty</technical_language>

Target:
private synchronized void validate(String partitionKey, String rowKey) { if (this.frozen) { throw logger.logExceptionAsError( new IllegalStateException("Operations can't be modified once a batch is submitted.")); } if (!this.partitionKey.equals(partitionKey)) { throw logger.logExceptionAsError( new IllegalArgumentException("All operations in a batch must share the same partition key.")); } if (CoreUtils.isNullOrEmpty(rowKey)) { throw logger.logExceptionAsError( new IllegalArgumentException("The row key must not be null or empty.")); } if (rowKeys.contains(rowKey)) { throw logger.logExceptionAsError( new IllegalArgumentException("Every operation in a batch must use a different row key.")); } else { rowKeys.add(rowKey); } }
Source:
<code>@Override public Response load(Uri uri, int networkPolicy) throws IOException { CacheControl cacheControl; if (NetworkPolicy.isOfflineOnly(networkPolicy)) { cacheControl = CacheControl.FORCE_CACHE; } else { CacheControl.Builder builder = new CacheControl.Builder(); if (!NetworkPolicy.shouldReadFromDiskCache(networkPolicy)) { builder.noCache(); } if (!NetworkPolicy.shouldWriteToDiskCache(networkPolicy)) { builder.noStore(); } cacheControl = builder.build(); } com.squareup.okhttp.Request.Builder requestBuilder = <START> new com.squareup.okhttp.Request.Builder().cacheControl(cacheControl).url(uri.toString()); <END> com.squareup.okhttp.Response response = client.newCall(requestBuilder.build()).execute(); int responseCode = response.code(); if (responseCode >= 300) { response.body().close(); throw new ResponseException(responseCode + " " + response.message(), networkPolicy, responseCode); } boolean fromCache = response.cacheResponse() != null; ResponseBody responseBody = response.body(); return new Response(responseBody.byteStream(), fromCache, responseBody.contentLength()); }</code><technical_language>call .build() get Request</technical_language>

Target:
@Override public Response load(Uri uri, int networkPolicy) throws IOException { CacheControl cacheControl = null; if (networkPolicy != 0) { if (NetworkPolicy.isOfflineOnly(networkPolicy)) { cacheControl = CacheControl.FORCE_CACHE; } else { CacheControl.Builder builder = new CacheControl.Builder(); if (!NetworkPolicy.shouldReadFromDiskCache(networkPolicy)) { builder.noCache(); } if (!NetworkPolicy.shouldWriteToDiskCache(networkPolicy)) { builder.noStore(); } cacheControl = builder.build(); } } Request.Builder builder = new Request.Builder().url(uri.toString()); if (cacheControl != null) { builder.cacheControl(cacheControl); } com.squareup.okhttp.Response response = client.newCall(builder.build()).execute(); int responseCode = response.code(); if (responseCode >= 300) { response.body().close(); throw new ResponseException(responseCode + " " + response.message(), networkPolicy, responseCode); } boolean fromCache = response.cacheResponse() != null; ResponseBody responseBody = response.body(); return new Response(responseBody.byteStream(), fromCache, responseBody.contentLength()); }
Source:
<code>public void setTextShouldNotAddClearKeysForTextInputWithEmptyText() { when(webElement.getAttribute("value")).thenReturn(""); <START> textInput.setText("qwerty"); <END> }</code><technical_language>is assertion for this test</technical_language>

Target:
public void setTextShouldNotAddClearKeysForTextInputWithEmptyText() { when(webElement.getAttribute("value")).thenReturn(""); textInput.setText("qwerty"); verify(webElement).sendKeys("qwerty"); }