auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public static PlanMatchPattern semiJoin(String sourceSymbolAlias, String filteringSymbolAlias, String outputAlias, PlanMatchPattern source, PlanMatchPattern filtering) { <START> return node(SemiJoinNode.class, source, filtering).with(new SemiJoinMatcher(sourceSymbolAlias, filteringSymbolAlias, outputAlias, Optional.empty())); <END> }</code><technical_language>reuse overloaded semiJoin method passing distribution type Optional.empty()</technical_language>

Target:
public static PlanMatchPattern semiJoin(String sourceSymbolAlias, String filteringSymbolAlias, String outputAlias, PlanMatchPattern source, PlanMatchPattern filtering) { return semiJoin(sourceSymbolAlias, filteringSymbolAlias, outputAlias, Optional.empty(), source, filtering); }
Source:
<code>String[] removeNegativeNumberOptions(String[] args) { for (int i = 0; i < args.length; i++) { if (isNegativeNumber.test(args[i])) { String param = args[i]; <START> negativeNumberParams.put(i - 1, new BigDecimal(param).toString()); <END> args[i] = "0"; } } return args; }</code><technical_language>put i-1? more natural i</technical_language>

Target:
String[] removeNegativeNumberOptions(String[] args) { for (int i = 1; i < args.length; i++) { if (isNegativeNumber.test(args[i])) { String param = args[i]; negativeNumberParams.put(i - 1, new BigDecimal(param).toString()); args[i] = "0"; } } return args; }
Source:
<code>public @Nonnull FormValidation doCheckNewName(@QueryParameter String newName) { if (!hasPermission(Item.CONFIGURE)) { <START> checkPermission(Item.CREATE); <END> checkPermission(Item.DELETE); } newName = newName == null ? null : newName.trim(); try { Jenkins.checkGoodName(newName); assert newName != null; checkIfNameIsUsed(newName); checkRename(newName); } catch (Failure e) { return FormValidation.error(e.getMessage()); } return FormValidation.ok(); }</code><technical_language>noted in JENKINS-18649 this is wrong</technical_language>

Target:
public @Nonnull FormValidation doCheckNewName(@QueryParameter String newName) { if (!hasPermission(Item.CONFIGURE)) { if (parent instanceof AccessControlled) { ((AccessControlled)parent).checkPermission(Item.CREATE); } checkPermission(Item.DELETE); } newName = newName == null ? null : newName.trim(); try { Jenkins.checkGoodName(newName); assert newName != null; Jenkins.get().getProjectNamingStrategy().checkName(newName); checkIfNameIsUsed(newName); checkRename(newName); } catch (Failure e) { return FormValidation.error(e.getMessage()); } return FormValidation.ok(); }
Source:
<code>public ByteBuffer encode(BaseOperation<K> operation) { BaseOperation.Code opCode = operation.getOpCode(); <START> switch (opCode) { <END> case PUT: return codecFactory.getPutOperationCodec().encode((PutOperation<K, V>)operation); default: throw new AssertionError("Invalid operation " + opCode); } }</code><technical_language>switch feels encapsulation breakage. I a specific recommendation now</technical_language>

Target:
public ByteBuffer encode(BaseOperation<K> operation) { OperationCode opCode = operation.getOpCode(); return codecProvider.getOperationCodec(opCode).encode(operation); }
Source:
<code>protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); binding = ActivitySplashBinding.inflate(getLayoutInflater()); setContentView(binding.getRoot()); Typeface typeface = Typeface.createFromAsset(getAssets(), "fonts/OpenSans/Montserrat.ttf"); binding.organizationName.setTypeface(typeface); binding.organizationName.setText(R.string.organization_name); <START> <END> binding.clientName.setTypeface(typeface); binding.clientName.setText(R.string.client_name); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); Animation move = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.splash_screen_logo_anim); AnimationSet set = new AnimationSet(true); Animation fadeIn = new AlphaAnimation(0, 1); fadeIn.setInterpolator(new AccelerateInterpolator()); fadeIn.setDuration(1000); set.addAnimation(fadeIn); set.addAnimation(move); binding.logo.startAnimation(set); mRunnable = () -> { Intent intent = new Intent(SplashActivity.this, IntroActivity.class); startActivity(intent); finish(); }; mHandler.postDelayed(mRunnable, SPLASH_TIMER); }</code><technical_language>@rishabh-997 assigning text fonts in xml file, reduce code here</technical_language>

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); binding = ActivitySplashBinding.inflate(getLayoutInflater()); setContentView(binding.getRoot()); Typeface typeface = Typeface.createFromAsset(getAssets(), "fonts/Roboto/Montserrat.ttf"); binding.organizationName.setTypeface(typeface); binding.organizationName.setText(R.string.organization_name); binding.clientName.setTypeface(typeface); binding.clientName.setText(R.string.client_name); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); Animation move = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.splash_screen_logo_anim); AnimationSet set = new AnimationSet(true); Animation fadeIn = new AlphaAnimation(0, 1); fadeIn.setInterpolator(new AccelerateInterpolator()); fadeIn.setDuration(1000); set.addAnimation(fadeIn); set.addAnimation(move); binding.logo.startAnimation(set); mRunnable = () -> { Intent intent = new Intent(SplashActivity.this, IntroActivity.class); startActivity(intent); finish(); }; mHandler.postDelayed(mRunnable, SPLASH_TIMER); }
Source:
<code>private ContextForm() { <START> Language currentLanguage = Language.getLanguage(); <END> setWriteThrough(false); yearMonthField.setValue(new DateTime(year, month, 1, 0, 0, 0, 0).toDate()); yearMonthField.setResolution(InlineDateField.RESOLUTION_MONTH); addField("yearMonth", yearMonthField); accountabilityTypesField.addContainerProperty("name", String.class, null); accountabilityTypesField.setItemCaptionMode(Select.ITEM_CAPTION_MODE_PROPERTY); accountabilityTypesField.setItemCaptionPropertyId("name"); final Set<AccountabilityType> accountabilityTypes = MissionSystem.getInstance().getAccountabilityTypesRequireingAuthorization(); for (final AccountabilityType accountabilityType : accountabilityTypes) { final Item item = accountabilityTypesField.addItem(accountabilityType); final Property itemProperty = item.getItemProperty("name"); itemProperty.setValue(accountabilityType.getName().getContent(currentLanguage)); } accountabilityTypesField.setRows(accountabilityTypes.size()); accountabilityTypesField.setNullSelectionAllowed(false); accountabilityTypesField.setMultiSelect(true); accountabilityTypesField.setValue(Collections.unmodifiableSet(accountabilityTypes)); addField("accountabilityTypes", accountabilityTypesField); }</code><technical_language>This is important, a suggestion: Code variables more simple, is (usually) easier read. variable "currentLanguage" is in 1 place. I suggest remove variable declaration, Language.getLanguage() directly</technical_language>

Target:
private ContextForm() { setWriteThrough(false); yearMonthField.setValue(new DateTime(year, month, 1, 0, 0, 0, 0).toDate()); yearMonthField.setResolution(InlineDateField.RESOLUTION_MONTH); addField("yearMonth", yearMonthField); accountabilityTypesField.addContainerProperty("name", String.class, null); accountabilityTypesField.setItemCaptionMode(Select.ITEM_CAPTION_MODE_PROPERTY); accountabilityTypesField.setItemCaptionPropertyId("name"); final Set<AccountabilityType> accountabilityTypes = MissionSystem.getInstance().getAccountabilityTypesRequireingAuthorization(); for (final AccountabilityType accountabilityType : accountabilityTypes) { final Item item = accountabilityTypesField.addItem(accountabilityType); final Property itemProperty = item.getItemProperty("name"); itemProperty.setValue(accountabilityType.getName().getContent(Language.getLanguage())); } accountabilityTypesField.setRows(accountabilityTypes.size()); accountabilityTypesField.setNullSelectionAllowed(false); accountabilityTypesField.setMultiSelect(true); accountabilityTypesField.setValue(Collections.unmodifiableSet(accountabilityTypes)); addField("accountabilityTypes", accountabilityTypesField); }
Source:
<code>public void testAllScriptsContainAPIBinding() throws InvalidScriptException { Script s = scriptWithApiBindingClient(); Script s1 = scriptWithApiBindingUser(); Script s2 = scriptWithApiBindingGlobal(); FlowScript fs = flowScriptWithApiBindingClient(); Mockito.when(it.getPreScript()).thenReturn(s1); Mockito.when(it.getPostScript()).thenReturn(s2); Mockito.when(sec.getScript()).thenReturn(s); Mockito.when(fe.getEnvScript()).thenReturn(s); Mockito.when(it.getFlowScript()).thenReturn(fs); Boolean result = new CheckEligibleTaskDescriptorScript().isTaskContainsAPIBinding(etd); <START> assertEquals(true, result); <END> }</code><technical_language>assertTrue(result) assertThat(result, isTrue) instead of assertEquals is relevant in this case</technical_language>

Target:
public void testAllScriptsContainAPIBinding() throws InvalidScriptException { Script s = scriptWithApiBindingClient(); Script s1 = scriptWithApiBindingUser(); Script s2 = scriptWithApiBindingGlobal(); FlowScript fs = flowScriptWithApiBindingClient(); Mockito.when(it.getPreScript()).thenReturn(s1); Mockito.when(it.getPostScript()).thenReturn(s2); Mockito.when(sec.getScript()).thenReturn(s); Mockito.when(fe.getEnvScript()).thenReturn(s); Mockito.when(it.getFlowScript()).thenReturn(fs); assertTrue(new CheckEligibleTaskDescriptorScript().isTaskContainsAPIBinding(etd)); }
Source:
<code>public static ConfigurationLoader from(final Properties props) throws IOException { return new ConfigurationLoader(new Function<String, String>() { @SuppressFBWarnings(value = "NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE", justification = "False positive. I don't know what spotbugs is doing here.") public String apply(String from) { <START> return props.getProperty(from); <END> } }); }</code><technical_language>BTW convert lambda</technical_language>

Target:
public static ConfigurationLoader from(final Properties props) throws IOException { return new ConfigurationLoader(from -> props.getProperty(from)); }
Source:
<code>private static String[] removeNullsFromArgArray(String[] argArray) { List<String> argList = new ArrayList(Arrays.asList(argArray)); argList.removeAll(Collections.singleton(null)); <START> return argList.toArray(new String[0]); <END> }</code><technical_language>"return argList.toArray(new String[argList.size()]);" String array length is preallocated</technical_language>

Target:
private static String[] removeNullsFromArgArray(String[] argArray) { List<String> argList = new ArrayList(Arrays.asList(argArray)); argList.removeAll(Collections.singleton(null)); return argList.toArray(new String[argList.size()]); }
Source:
<code>@NotNull public static XmlBlock create(FsFile fsFile, String packageName) throws RoboNotFoundException { Document document = parse(fsFile); if (document == null) { <START> throw new RoboNotFoundException("couldn't find resource " + fsFile.getPath()); <END> } return new XmlBlock(document, fsFile.getPath(), packageName); }</code><technical_language>null instead of a custom exception</technical_language>

Target:
public static XmlBlock create(FsFile fsFile, String packageName) { Document document = parse(fsFile); return document == null ? null : new XmlBlock(document, fsFile.getPath(), packageName); }
Source:
<code>private void open(final IDockerConnection connection) { final Job pingJob = new LoadingJob(DVMessages.getString("PingJob.msg"), connection) { @Override protected IStatus run(final IProgressMonitor monitor) { try { connection.open(true); connection.ping(); return Status.OK_STATUS; } catch (DockerException e) { <START> Display.getDefault().asyncExec(() -> { <END> MessageDialog.openError( Display.getDefault().getActiveShell(), DVMessages.getString("Error"), DVMessages.getFormattedString( "PingJobError.msg.withExplanation", connection.getName(), e.getMessage())); }); return Status.CANCEL_STATUS; } } }; pingJob.schedule(); }</code><technical_language>log a warning message AERI register a problem? This a dialog pop time annoying end-user</technical_language>

Target:
private void open(final IDockerConnection connection) { final Job pingJob = new LoadingJob(DVMessages.getString("PingJob.msg"), connection) { @Override protected IStatus run(final IProgressMonitor monitor) { try { connection.open(true); connection.ping(); return Status.OK_STATUS; } catch (DockerException e) { Activator.logWarningMessage(DVMessages.getFormattedString( "PingJobError.msg.withExplanation", connection.getName(), e.getMessage())); return Status.CANCEL_STATUS; } } }; pingJob.schedule(); }
Source:
<code><START> public static void annotateMutationWithMetadata(PTable table, Mutation mutation) { <END> if (mutation.getDurability() == Durability.SKIP_WAL) { return; } if (table.getTenantId() != null) { mutation.setAttribute(MutationMetadataType.TENANT_ID.toString(), table.getTenantId().getBytes()); } if (table.getSchemaName() != null) { mutation.setAttribute(MutationMetadataType.SCHEMA_NAME.toString(), table.getSchemaName().getBytes()); } if (table.getTableName() != null) { mutation.setAttribute(MutationMetadataType.LOGICAL_TABLE_NAME.toString(), table.getTableName().getBytes()); } if (table.getLastDDLTimestamp() != null) { mutation.setAttribute(MutationMetadataType.TIMESTAMP.toString(), Bytes.toBytes(table.getLastDDLTimestamp())); } mutation.setAttribute(MutationMetadataType.TABLE_TYPE.toString(), table.getType().getValue().getBytes()); }</code><technical_language>nit: util methods private</technical_language>

Target:
private void annotateMutationWithMetadata(PTable table, Mutation mutation) { byte[] tenantId = table.getTenantId() != null ? table.getTenantId().getBytes() : null; byte[] schemaName = table.getSchemaName() != null ? table.getSchemaName().getBytes() : null; byte[] tableName = table.getTableName() != null ? table.getTableName().getBytes() : null; byte[] tableType = table.getType().getValue().getBytes(); byte[] lastDDLTimestamp = table.getLastDDLTimestamp() != null ? Bytes.toBytes(table.getLastDDLTimestamp()) : null; WALAnnotationUtil.annotateMutation(mutation, tenantId, schemaName, tableName, tableType, lastDDLTimestamp); }
Source:
<code>public InetSocketAddress getAddressForHost(String host) throws UnknownHostException { if (config.addressTranslation().containsKey(host)) { <START> log.info("Found address translation mapping for host {}. The InetSocketAddress this host maps to is {}.", <END> SafeArg.of("host", host), SafeArg.of("address", config.addressTranslation().get(host))); return config.addressTranslation().get(host); } InetAddress resolvedHost = InetAddress.getByName(host); Set<InetSocketAddress> allKnownHosts = Sets.union(currentPools.keySet(), config.servers()); for (InetSocketAddress address : allKnownHosts) { if (Objects.equals(address.getAddress(), resolvedHost)) { return address; } } Set<Integer> allKnownPorts = allKnownHosts.stream() .map(InetSocketAddress::getPort) .collect(Collectors.toSet()); if (allKnownPorts.size() == 1) { return new InetSocketAddress(resolvedHost, Iterables.getOnlyElement(allKnownPorts)); } else { throw new UnknownHostException("Couldn't find the provided host in server list or current servers"); } }</code><technical_language>this is useful - if translation is required, clear signal translation working, cassandra operation fail, this is high volume</technical_language>

Target:
public InetSocketAddress getAddressForHost(String host) throws UnknownHostException { if (config.addressTranslation().containsKey(host)) { return config.addressTranslation().get(host); } InetAddress resolvedHost = InetAddress.getByName(host); Set<InetSocketAddress> allKnownHosts = Sets.union(currentPools.keySet(), config.servers()); for (InetSocketAddress address : allKnownHosts) { if (Objects.equals(address.getAddress(), resolvedHost)) { return address; } } Set<Integer> allKnownPorts = allKnownHosts.stream() .map(InetSocketAddress::getPort) .collect(Collectors.toSet()); if (allKnownPorts.size() == 1) { return new InetSocketAddress(resolvedHost, Iterables.getOnlyElement(allKnownPorts)); } else { throw new UnknownHostException("Couldn't find the provided host in server list or current servers"); } }
Source:
<code><START> public static List<Overlay> convert(MapView map, File file, ValidationPreferences pref) throws Exception { <END> return convert(map, file, pref, Color.TRANSPARENT, Color.BLACK, 5, defaultBubbleText); }</code><technical_language>Legacy version: OK it</technical_language>

Target:
public static List<Overlay> convert(MapView map, File file, ValidationPreferences pref) throws Exception { return convert(map, file, pref, new DefaultShapeMetaSetter()); }
Source:
<code>private void updateModuleInformation() { Set<Name> filtered = ImmutableSet.of(ENGINE_MODULE_NAME, new Name("engine-test")); for (RemoteModule remote : metaDownloader.getModules()) { ModuleSelectionInfo info = modulesLookup.get(remote.getId()); if (!filtered.contains(remote.getId())) { if (info == null) { info = ModuleSelectionInfo.remote(remote); modulesLookup.put(remote.getId(), info); int pos = Collections.binarySearch(sortedModules, info, moduleInfoComparator); if (pos < 0) { sortedModules.add(-pos - 1, info); <START> allSortedModules = new ArrayList<>(sortedModules); <END> } } info.setOnlineVersion(remote); } } }</code><technical_language>creating a new ArrayList for module - loop, I guess. clear() addAll() avoid some memory allocation, I prefer that</technical_language>

Target:
private void updateModuleInformation() { Set<Name> filtered = ImmutableSet.of(ENGINE_MODULE_NAME, new Name("engine-test")); for (RemoteModule remote : metaDownloader.getModules()) { ModuleSelectionInfo info = modulesLookup.get(remote.getId()); if (!filtered.contains(remote.getId())) { if (info == null) { info = ModuleSelectionInfo.remote(remote); modulesLookup.put(remote.getId(), info); int pos = Collections.binarySearch(sortedModules, info, moduleInfoComparator); if (pos < 0) { sortedModules.add(-pos - 1, info); allSortedModules.clear(); allSortedModules.addAll(sortedModules); } } info.setOnlineVersion(remote); } } }
Source:
<code>public void addPullRequestReviewer(String project, String repository, String pullRequestId, String user, StashClient stashClient){ try { StashPullRequest pullRequest = stashClient.getPullRequest(project, repository, pullRequestId); StashUser reviewer = pullRequest.getReviewer(user); if (reviewer == null) { reviewer = stashClient.getUser(project, repository, pullRequestId, user); stashClient.addPullRequestReviewer(project, repository, pullRequestId, pullRequest.getVersion(), reviewer); <START> LOGGER.debug("User \"{}\" is now a reviewer of the pull-request #{}", user, pullRequestId, project, repository); <END> } } catch(StashClientException e){ LOGGER.error("Unable to add a new reviewer to the pull-request: {}", e.getMessage()); LOGGER.debug("Exception stack trace", e); } }</code><technical_language>other logs level info, sense this well? question is open, is a "final" action</technical_language>

Target:
public void addPullRequestReviewer(String project, String repository, String pullRequestId, String user, StashClient stashClient){ try { StashPullRequest pullRequest = stashClient.getPullRequest(project, repository, pullRequestId); StashUser reviewer = pullRequest.getReviewer(user); if (reviewer == null) { ArrayList<StashUser> reviewers = new ArrayList<>(pullRequest.getReviewers()); reviewers.add(stashClient.getUser(project, repository, pullRequestId, user)); stashClient.addPullRequestReviewer(project, repository, pullRequestId, pullRequest.getVersion(), reviewers); LOGGER.info("User \"{}\" is now a reviewer of the pull-request #{}", user, pullRequestId, project, repository); } } catch(StashClientException e){ LOGGER.error("Unable to add a new reviewer to the pull-request: {}", e.getMessage()); LOGGER.debug("Exception stack trace", e); } }
Source:
<code>private Scenario giveResourcesToPlayerForSettlementBuilding(int moveOrder) { return scenario <START> .nextRandomDiceValues(asList(moveOrder, moveOrder, moveOrder, moveOrder == 3 ? moveOrder + 2 : moveOrder + 1, 6, 6)) <END> .THROW_DICE(moveOrder) .END_TURN(moveOrder) .THROW_DICE(moveOrder == 1 ? 2 : moveOrder == 2 ? 3 : 1) .END_TURN(moveOrder == 1 ? 2 : moveOrder == 2 ? 3 : 1) .THROW_DICE(moveOrder == 1 ? 3 : moveOrder == 2 ? 1 : 2) .END_TURN(moveOrder == 1 ? 3 : moveOrder == 2 ? 1 : 2); }</code><technical_language>strange logic: player 2: player 3 player 12 if this method called for player moveorder 3, gots: player 6: player 8 player 12</technical_language>

Target:
private Scenario giveResourcesToPlayerForSettlementBuilding(int moveOrder) { return scenario .nextRandomDiceValues(asList(moveOrder, moveOrder)) .THROW_DICE(moveOrder) .END_TURN(moveOrder) .nextRandomDiceValues(asList(moveOrder, moveOrder == 3 ? moveOrder + 2 : moveOrder + 1)) .THROW_DICE(moveOrder == 1 ? 2 : moveOrder == 2 ? 3 : 1) .END_TURN(moveOrder == 1 ? 2 : moveOrder == 2 ? 3 : 1) .nextRandomDiceValues(asList(6, 6)) .THROW_DICE(moveOrder == 1 ? 3 : moveOrder == 2 ? 1 : 2) .END_TURN(moveOrder == 1 ? 3 : moveOrder == 2 ? 1 : 2); }
Source:
<code>private void onInsertedData(Metric<?> metric) { log.tracef("Inserted metric: %s", metric); <START> if (publish.isPublished(metric.getMetricId())) { <END> pendingMetrics.add(metric); } }</code><technical_language>Also, RxJava is otherwise.. this code follow RxJava patterns. Basically, instead of this codeblock, java metrics.filter(m -> publish.isPublished(m.getMetricId())).map(pendingMetrics:add) prettier some more reactive handling</technical_language>

Target:
private void onInsertedData(Metric<?> metric) { log.tracef("Inserted metric: %s", metric); if (metric.getMetricId().getType() == AVAILABILITY) { @SuppressWarnings("unchecked") Metric<AvailabilityType> avail = (Metric<AvailabilityType>) metric; publishAvailablility(avail); } else { @SuppressWarnings("unchecked") Metric<? extends Number> numeric = (Metric<? extends Number>) metric; publishNumeric(numeric); } }
Source:
<code>public Map<String, byte[]> get(Set<String> keys) { Objects.requireNonNull(keys); <START> Map<String, byte[]> kvMap = new HashMap<>(keys.size()); <END> List<byte[]> values = getValuesForKeys(keys); int i = 0; for (String key : keys) { byte[] value = values.get(i++); if (value != null) { kvMap.put(key, value); } } return kvMap; }</code><technical_language>rename kvMap in this other files too</technical_language>

Target:
public Map<String, byte[]> get(Set<String> keys) { Objects.requireNonNull(keys); Map<String, byte[]> map = new HashMap<>(keys.size()); List<byte[]> values = getValuesForKeys(keys); int i = 0; for (String key : keys) { byte[] value = values.get(i++); if (value != null) { map.put(key, value); } } return map; }
Source:
<code>synchronized void add(PcapPacket packet) { Packet newPacket = packet.getPacket(fProtocol); if (newPacket == null) { return; } if (fEndpointPair.getFirstEndpoint().equals(newPacket.getSourceEndpoint()) && fEndpointPair.getSecondEndpoint().equals(newPacket.getDestinationEndpoint())) { fNbPacketsAtoB++; fNbBytesAtoB += packet.getOriginalLength(); } else if (fEndpointPair.getFirstEndpoint().equals(newPacket.getDestinationEndpoint()) && fEndpointPair.getSecondEndpoint().equals(newPacket.getSourceEndpoint())) { fNbPacketsBtoA++; fNbBytesBtoA += packet.getOriginalLength(); } else { <START> return; <END> } long timestamp; switch (packet.getTimestampScale()) { case MICROSECOND: timestamp = packet.getTimestamp() * 1000; break; case NANOSECOND: timestamp = packet.getTimestamp(); break; default: throw new IllegalArgumentException("The timestamp precision is not valid!"); } if ((fStartTime == -1) || (fStartTime > timestamp)) { fStartTime = timestamp; } if ((fStopTime == -1) || (fStopTime < timestamp)) { fStopTime = timestamp; } }</code><technical_language>if this happen of code's logic, do a throw IllegalStateException() instead, if happen, want catch fix right away</technical_language>

Target:
synchronized void add(PcapPacket packet) { Packet newPacket = packet.getPacket(fProtocol); if (newPacket == null) { return; } if (fEndpointPair.getFirstEndpoint().equals(newPacket.getSourceEndpoint()) && fEndpointPair.getSecondEndpoint().equals(newPacket.getDestinationEndpoint())) { fNbPacketsAtoB++; fNbBytesAtoB += packet.getOriginalLength(); } else if (fEndpointPair.getFirstEndpoint().equals(newPacket.getDestinationEndpoint()) && fEndpointPair.getSecondEndpoint().equals(newPacket.getSourceEndpoint())) { fNbPacketsBtoA++; fNbBytesBtoA += packet.getOriginalLength(); } else { throw new IllegalStateException(); } long timestamp; switch (packet.getTimestampScale()) { case MICROSECOND: timestamp = packet.getTimestamp() * 1000; break; case NANOSECOND: timestamp = packet.getTimestamp(); break; default: throw new IllegalArgumentException("The timestamp precision is not valid!"); } fStartTime = Math.min(fStartTime, timestamp); fEndTime = Math.max(fEndTime, timestamp); }
Source:
<code>public void destroyCache(final String alias) throws CachePersistenceException { if (alias == null) { throw new NullPointerException("Alias cannot be null"); } LOGGER.debug("Destroying Cache '{}' in {}.", alias, simpleName); StatusTransitioner.Transition maintenance = null; try { maintenance = statusTransitioner.maintenance(); } catch(IllegalStateException e) { statusTransitioner.checkAvailable(); } if(maintenance != null) { try { startMaintainableServices(MaintainableService.MaintenanceScope.CACHE); maintenance.succeeded(); } catch (Throwable t) { throw maintenance.failed(t); } } try { <START> removeCache(alias); <END> destroyPersistenceSpace(alias); } finally { if(maintenance != null) { StatusTransitioner.Transition st = statusTransitioner.exitMaintenance(); try { stopMaintainableServices(); st.succeeded(); } catch (Throwable t) { throw st.failed(t); } } } LOGGER.info("Cache '{}' successfully destroyed in {}.", alias, simpleName); }</code><technical_language>This method is longer needed, remove</technical_language>

Target:
public void destroyCache(final String alias) throws CachePersistenceException { if (alias == null) { throw new NullPointerException("Alias cannot be null"); } LOGGER.debug("Destroying Cache '{}' in {}.", alias, simpleName); StatusTransitioner.Transition maintenance = null; try { maintenance = statusTransitioner.maintenance(); } catch(IllegalStateException e) { statusTransitioner.checkAvailable(); } if(maintenance != null) { try { startMaintainableServices(MaintainableService.MaintenanceScope.CACHE); maintenance.succeeded(); } catch (Throwable t) { throw maintenance.failed(t); } } try { removeCache(alias, true); destroyPersistenceSpace(alias); } finally { if(maintenance != null) { StatusTransitioner.Transition st = statusTransitioner.exitMaintenance(); try { stopMaintainableServices(); st.succeeded(); } catch (Throwable t) { throw st.failed(t); } } } LOGGER.info("Cache '{}' successfully destroyed in {}.", alias, simpleName); }
Source:
<code>private long determineDelayForMessage(Message<?> message) { long delay = this.defaultDelay; if (this.delayExpression != null) { String delayValueExceptionMessage = null; Object delayValue = null; try { delayValue = this.delayExpression.getValue(this.evaluationContext, message); } catch (EvaluationException e) { delayValueExceptionMessage = e.getMessage(); } if (delayValue instanceof Date) { delay = ((Date) delayValue).getTime() - new Date().getTime(); } else if (delayValue != null) { try { delay = Long.valueOf(delayValue.toString()); } catch (NumberFormatException e) { delayValueExceptionMessage = e.getMessage(); } } if (delayValueExceptionMessage != null && logger.isWarnEnabled()) { <START> logger.warn("Failed to get delay value from 'delayExpression': " + delayValueExceptionMessage + <END> ". Will fall back to default delay: " + this.defaultDelay); } } return delay; }</code><technical_language>Yes, I agree - DEBUG - I important note, change reference manual examples "proper" syntax for headers headers['delay'] instead of headers.delay. Because, discussed before, this shorthand form fail if header is present. While work functionally, catch EvaluationException, more expensive runtime headers['delay'] return null</technical_language>

Target:
private long determineDelayForMessage(Message<?> message) { long delay = this.defaultDelay; if (this.delayExpression != null) { Exception delayValueException = null; Object delayValue = null; try { delayValue = this.delayExpression.getValue(this.evaluationContext, message); } catch (EvaluationException e) { delayValueException = e; } if (delayValue instanceof Date) { delay = ((Date) delayValue).getTime() - new Date().getTime(); } else if (delayValue != null) { try { delay = Long.valueOf(delayValue.toString()); } catch (NumberFormatException e) { delayValueException = e; } } if (delayValueException != null) { if (this.ignoreExpressionFailures) { if (logger.isDebugEnabled()) { logger.debug("Failed to get delay value from 'delayExpression': " + delayValueException.getMessage() + ". Will fall back to default delay: " + this.defaultDelay); } } else { throw new MessageHandlingException(message, "Error occurred during 'delay' value determination", delayValueException); } } } return delay; }
Source:
<code><START> public void removeVmDevices(List<VmDevice> devices, int numberOfDevicesToRemove) { int size = devices.size(); int maxIndex = Math.min(numberOfDevicesToRemove, size); for (int index = 1; index <= maxIndex; index++) { vmDeviceDao.remove(devices.get(size - index).getId()); } } <END></code><technical_language>a bit different: change #1259 like: devices.stream().map(VmDevice::getId).forEach(vmDeviceDao::remove) this method like: removeVmDevice(devices.subList(...))</technical_language>

Target:
public void removeVmDevices(List<VmDevice> devices, int numberOfDevicesToRemove) { int size = devices.size(); removeVmDevices(devices.subList(Math.max(size - numberOfDevicesToRemove, 0), size)); }
Source:
<code>public void dispose() { <START> synchronized(PhoneProxy.lockForRadioTechnologyChange) { <END> mCM.unregisterForAvailable(h); mSIMRecords.unregisterForRecordsLoaded(h); mCM.unregisterForOffOrNotAvailable(h); mCM.unregisterForOn(h); mSST.unregisterForNetworkAttach(h); mCM.unSetOnUSSD(h); mCM.unSetOnSuppServiceNotification(h); mCM.unSetOnCallRing(h); mPendingMMIs.removeAll(mPendingMMIs); h.removeCallbacksAndMessages(null); mStkService.dispose(); mCT.dispose(); mDataConnection.dispose(); mSST.dispose(); ((SIMFileHandler)mIccFileHandler).dispose(); mSIMRecords.dispose(); mSimCard.dispose(); mSimPhoneBookIntManager.dispose(); mSimSmsIntManager.dispose(); mSubInfo.dispose(); this.mIccFileHandler = null; this.mSimCard = null; this.debugSocket = null; this.debugPortThread = null; this.mSimulatedRadioControl = null; this.mPendingMMIs = null; this.mStkService = null; this.mCM = null; this.mDataConnection = null; this.mSsnRegistrants = null; this.mCT = null; this.mPostDialHandler = null; this.mSimPhoneBookIntManager = null; this.mSIMRecords = null; this.mSimSmsIntManager = null; this.mSMS = null; this.mSST = null; this.mSubInfo = null; this.h = null; } }</code><technical_language>I mIsRadioTechnologyChangeOnGoing set true here</technical_language>

Target:
public void dispose() { synchronized(PhoneProxy.lockForRadioTechnologyChange) { mCM.unregisterForAvailable(h); mSIMRecords.unregisterForRecordsLoaded(h); mCM.unregisterForOffOrNotAvailable(h); mCM.unregisterForOn(h); mSST.unregisterForNetworkAttach(h); mCM.unSetOnUSSD(h); mCM.unSetOnSuppServiceNotification(h); mCM.unSetOnCallRing(h); mPendingMMIs.clear(); mStkService.dispose(); mCT.dispose(); mDataConnection.dispose(); mSST.dispose(); mIccFileHandler.dispose(); mSIMRecords.dispose(); mSimCard.dispose(); mSimPhoneBookIntManager.dispose(); mSimSmsIntManager.dispose(); mSubInfo.dispose(); } }
Source:
<code><START> public void dropTable(String tableName) <END> { queryExecutor.executeQuery("DROP TABLE " + tableName); }</code><technical_language>a b/c other is marked @Override, I feel strongly</technical_language>

Target:
public void dropTable(String tableName) { executeQueryIgnoreTypeError("DROP TABLE " + tableName); }
Source:
<code>private static String format(final String format, final Object... parameters) { List<String> parts = Arrays.asList(format.split("[%][s]", -1)); if (parts.size() - 1 != parameters.length) { throw new IllegalArgumentException("Format string \"" + format + "\" does not have " + parameters.length + " substitution variables."); } StringBuffer buffer = new StringBuffer(parts.get(0)); for (int i = 0; i < parameters.length ; ) { <START> buffer.append(parameters[i]).append(parts.get(++i)); <END> } return buffer.toString(); }</code><technical_language>do incrementing in for loop</technical_language>

Target:
private static String format(final String format, final Object... parameters) { List<String> parts = Arrays.asList(format.split("[%][s]", -1)); if (parts.size() - 1 != parameters.length) { throw new IllegalArgumentException("Format string \"" + format + "\" does not have " + parameters.length + " substitution variables."); } StringBuffer buffer = new StringBuffer(parts.get(0)); for (int i = 0; i < parameters.length ; i++) { buffer.append(parameters[i]).append(parts.get(i+1)); } return buffer.toString(); }
Source:
<code>public Void call() throws Exception { s_logger.info("Updating configurations"); Thread.currentThread().setName(getClass().getSimpleName()); try { List<ComponentConfiguration> configImpls = this.m_xmlConfigurations != null <START> ? this.m_xmlConfigurations.getConfigurations() : null; <END> if (configImpls == null) { return null; } List<ComponentConfiguration> configs = new ArrayList<>(); configs.addAll(configImpls); if (this.m_pid == null) { this.m_configurationService.updateConfigurations(configs); } else { for (ComponentConfiguration config : configs) { if (this.m_pid.equals(config.getPid())) { this.m_configurationService.updateConfiguration(this.m_pid, config.getConfigurationProperties()); } } } } catch (KuraException e) { s_logger.error("Error updating configurations: {}", e); throw new KuraException(KuraErrorCode.CONFIGURATION_UPDATE, e); } return null; }</code><technical_language>Please rename this.m_xmlConfigurations this.xmlConfigurations</technical_language>

Target:
public Void call() throws Exception { logger.info("Updating configurations"); Thread.currentThread().setName(getClass().getSimpleName()); try { List<ComponentConfiguration> configImpls = this.xmlConfigurations != null ? this.xmlConfigurations.getConfigurations() : null; if (configImpls == null) { return null; } List<ComponentConfiguration> configs = new ArrayList<>(); configs.addAll(configImpls); if (this.pid == null) { this.configurationService.updateConfigurations(configs); } else { for (ComponentConfiguration config : configs) { if (this.pid.equals(config.getPid())) { this.configurationService.updateConfiguration(this.pid, config.getConfigurationProperties()); } } } } catch (KuraException e) { logger.error("Error updating configurations: {}", e); throw new KuraException(KuraErrorCode.CONFIGURATION_UPDATE, e); } return null; }
Source:
<code>PluginInfo(Plugin p) { id = Url.encode(p.getName()); version = p.getVersion(); disabled = p.isDisabled() ? true : null; if (p.getJarFile() != null) { indexUrl = String.format("plugins/%s/", p.getName()); try { <START> adminUrl = p.getJarFile().getManifest().getMainAttributes().getValue("Gerrit-AdminUrl"); <END> } catch (IOException e) { log.error(String.format("Failed to read admin URL from plugin '%s'.", p.getName()), e); } } }</code><technical_language>JarPlugin holds Manifest object. expose expose a read attributes it</technical_language>

Target:
PluginInfo(Plugin p) { id = Url.encode(p.getName()); version = p.getVersion(); disabled = p.isDisabled() ? true : null; if (p.getJarFile() != null) { indexUrl = String.format("plugins/%s/", p.getName()); } }
Source:
<code>public void testValidationMetaModelsVSM() { TransactionalEditingDomain <START> editingDomain = <END> new TransactionalEditingDomainImpl(new ComposedAdapterFactory(ComposedAdapterFactory.Descriptor.Registry.INSTANCE), modeler.eResource().getResourceSet()); CommandStack commandStack = editingDomain.getCommandStack(); RepresentationDescription repDescription = modeler.getOwnedViewpoints().iterator().next().getOwnedRepresentations().iterator().next(); EList<EPackage> metamodel = repDescription.getMetamodel(); Command removeMMCommand = RemoveCommand.create(editingDomain, repDescription, DescriptionPackage.Literals.REPRESENTATION_DESCRIPTION__METAMODEL, metamodel); assertTrue(removeMMCommand.canExecute()); commandStack.execute(removeMMCommand); Diagnostician diagnostician = new Diagnostician(); Diagnostic diagnostic = diagnostician.validate(repDescription); assertEquals("The RepresentationDescription should have a warning because there is no meta-models on RepresentationDescription", Diagnostic.WARNING, diagnostic.getSeverity()); }</code><technical_language>This editing domain disposed. No</technical_language>

Target:
public void testValidationMetaModelsVSM() { editingDomain = new TransactionalEditingDomainImpl(new ComposedAdapterFactory(ComposedAdapterFactory.Descriptor.Registry.INSTANCE), modeler.eResource().getResourceSet()); CommandStack commandStack = editingDomain.getCommandStack(); RepresentationDescription repDescription = modeler.getOwnedViewpoints().iterator().next().getOwnedRepresentations().iterator().next(); EList<EPackage> metamodel = repDescription.getMetamodel(); Command removeMMCommand = RemoveCommand.create(editingDomain, repDescription, DescriptionPackage.Literals.REPRESENTATION_DESCRIPTION__METAMODEL, metamodel); assertTrue(removeMMCommand.canExecute()); commandStack.execute(removeMMCommand); Diagnostician diagnostician = new Diagnostician(); Diagnostic diagnostic = diagnostician.validate(repDescription); List<Diagnostic> children = diagnostic.getChildren(); String message = "Bad diagnostic {0} on the RepresentationDescription " + repDescription.getName(); assertEquals(MessageFormat.format(message, "number"), 1, children.size()); assertEquals(MessageFormat.format(message, "type"), Diagnostic.WARNING, diagnostic.getSeverity()); assertEquals(MessageFormat.format(message, "message"), Messages.RepresentationDescriptionMetaModelsConstraint_noMetaModel, children.get(0).getMessage()); }
Source:
<code>public void testValidModifiedBondsFailsWhenBondNotHaveNameAndId() throws Exception { doTestValidModifiedBonds(new Bond(), ValidationResult.VALID, <START> new ValidationResult(EngineMessage.HOST_NETWORK_INTERFACE_DOES_NOT_HAVE_NAME_SET), <END> ValidationResult.VALID); }</code><technical_language>change to- BOND_DOES_NOT_HAVE_NEITHER_ID_NOR_NAME_SPECIFIED</technical_language>

Target:
public void testValidModifiedBondsFailsWhenBondNotHaveNameAndId() throws Exception { doTestValidModifiedBonds(new Bond(), ValidationResult.VALID, new ValidationResult(EngineMessage.BOND_DOES_NOT_HAVE_NEITHER_ID_NOR_NAME_SPECIFIED), ValidationResult.VALID); }
Source:
<code>private Point getStartPoint(BufferedImage patternImage, boolean isLeft) { <START> return isLeft ? <END> new Point(articleLeftSideX - patternImage.getWidth(), startSkinY) : new Point(articleRightSideX, startSkinY); }</code><technical_language>A ternary operator replaced for more visibility, please do it</technical_language>

Target:
private Point getStartPoint(BufferedImage patternImage, boolean isLeft) { if (isLeft) { return new Point(articleLeftSideX - patternImage.getWidth(), startSkinY); } else { return new Point(articleRightSideX, startSkinY); } }
Source:
<code>private void testBlobRecordV2(int blobSize, BlobType blobType) throws IOException, MessageFormatException { ByteBuffer blobContent = ByteBuffer.allocate(blobSize); new Random().nextBytes(blobContent.array()); int size = (int) MessageFormatRecord.Blob_Format_V2.getBlobRecordSize(blobSize); <START> ByteBuffer entireBlob = ByteBuffer.allocate((int) size); <END> BlobOutput outputData = getBlobRecordV2(blobSize, blobType, blobContent, entireBlob); Assert.assertEquals(outputData.getSize(), blobSize); byte[] verify = new byte[blobSize]; outputData.getStream().read(verify); Assert.assertArrayEquals(verify, blobContent.array()); entireBlob.flip(); byte currentRandomByte = entireBlob.get(16); entireBlob.put(16, (byte) (currentRandomByte + 1)); try { MessageFormatRecord.deserializeBlob(new ByteBufferInputStream(entireBlob)); Assert.fail("Failed to dedect corruption of blob record"); } catch (MessageFormatException e) { Assert.assertEquals(e.getErrorCode(), MessageFormatErrorCodes.Data_Corrupt); } }</code><technical_language>size is int</technical_language>

Target:
private void testBlobRecordV2(int blobSize, BlobType blobType) throws IOException, MessageFormatException { ByteBuffer blobContent = ByteBuffer.allocate(blobSize); new Random().nextBytes(blobContent.array()); int size = (int) MessageFormatRecord.Blob_Format_V2.getBlobRecordSize(blobSize); ByteBuffer entireBlob = ByteBuffer.allocate(size); BlobData blobData = getBlobRecordV2(blobSize, blobType, blobContent, entireBlob); Assert.assertEquals("Blob size mismatch", blobSize, blobData.getSize()); byte[] verify = new byte[blobSize]; blobData.getStream().read(verify); Assert.assertArrayEquals("BlobContent mismatch", blobContent.array(), verify); entireBlob.flip(); byte savedByte = entireBlob.get(blobSize / 2); entireBlob.put(blobSize / 2, (byte) (savedByte + 1)); try { MessageFormatRecord.deserializeBlob(new ByteBufferInputStream(entireBlob)); Assert.fail("Failed to detect corruption of blob record"); } catch (MessageFormatException e) { Assert.assertEquals("Error code mismatch", MessageFormatErrorCodes.Data_Corrupt, e.getErrorCode()); } }
Source:
<code>public static Set<String> initRange(String start, String end) { String parsedRangeStart = parseRangePart(start); String parsedRangeEnd = parseRangePart(end); if (parsedRangeEnd == null || parsedRangeStart == null) { return Collections.emptySet(); } long startNum = Long.parseLong(parseRangePart(start), HEX_RADIX); long endNum = Long.parseLong(parseRangePart(end), HEX_RADIX); if (startNum > endNum) { return Collections.emptySet(); } Set<String> macAddresses = new HashSet<String>(); for (long i = startNum; i <= endNum; i++) { <START> String value = String.format("%x", i); <END> if (value.length() > 12) { return macAddresses; } else if (value.length() < 12) { value = StringUtils.leftPad(value, 12, '0'); } value = createMacAddress(value); if (value == null) { break; } macAddresses.add(value); } return macAddresses; }</code><technical_language>I good check this point: if (0x01000000 & != 0) { continue; } This moch more efficient check LSB of MAC for multicast address</technical_language>

Target:
public static List<String> initRange(String start, String end) { String parsedRangeStart = StringUtils.remove(start, ':'); String parsedRangeEnd = StringUtils.remove(end, ':'); if (parsedRangeEnd == null || parsedRangeStart == null) { return Collections.emptyList(); } long startNum = Long.parseLong(parsedRangeStart, HEX_RADIX); long endNum = Long.parseLong(parsedRangeEnd, HEX_RADIX); if (startNum > endNum) { return Collections.emptyList(); } List<String> macAddresses = new ArrayList<String>(); for (long i = startNum; i <= endNum; i++) { if ((MAC_ADDRESS_MULTICAST_BIT & i) != 0) { continue; } String value = String.format("%012x", i); macAddresses.add(StringUtils.join(value.split(".."), ':')); } return macAddresses; }
Source:
<code><START> public void setup() throws Exception { <END> System.setProperty(CARBON_HOME, ""); PrivilegedCarbonContext privilegedCarbonContext = Mockito.mock(PrivilegedCarbonContext.class); PowerMockito.mockStatic(PrivilegedCarbonContext.class); PowerMockito.when(PrivilegedCarbonContext.getThreadLocalCarbonContext()).thenReturn(privilegedCarbonContext); }</code><technical_language>need this setup method static mocking test method</technical_language>

Target:
public void setup() throws Exception { System.setProperty(CARBON_HOME, ""); privilegedCarbonContext = Mockito.mock(PrivilegedCarbonContext.class); subscriptionDataHolder = Mockito.mock(SubscriptionDataHolder.class); tenantSubscriptionStore = Mockito.mock(SubscriptionDataStore.class); PowerMockito.mockStatic(PrivilegedCarbonContext.class); PowerMockito.mockStatic(SubscriptionDataHolder.class); PowerMockito.when(PrivilegedCarbonContext.getThreadLocalCarbonContext()).thenReturn(privilegedCarbonContext); }
Source:
<code>public double getProducerMetricValue(MetricName metricName) { Producer<?, ?> producer = _kafkaProducer; if (producer != null) { Metric metric = producer.metrics().get(metricName); if (metric != null) { return metric.value(); } } <START> return 0; <END> }</code><technical_language>Is this acceptable for metrics? distinguish a legitimate 0 case metrics found</technical_language>

Target:
public Optional<Double> getProducerMetricValue(MetricName metricName) { return Optional.ofNullable(_kafkaProducer).map(p -> p.metrics().get(metricName)).map(Metric::value); }
Source:
<code>private void subscribeDataChange(String path, NotificationContext.Type callbackType) { <START> if (callbackType == NotificationContext.Type.INIT <END> || callbackType == NotificationContext.Type.CALLBACK) { if (logger.isDebugEnabled()) { logger.debug("{} subscribe data-change. path: {}, listener: {}", _manager.getInstanceName(), path, _listener); } boolean subStatus = _zkClient.subscribeDataChanges(path, this, callbackType != Type.INIT); logger.debug("CallbackHandler subscribe data path result {}", this, path, subStatus); if (!subStatus) { logger.info("CallbackHandler subscribe data path failed!", this, path); } } else if (callbackType == NotificationContext.Type.FINALIZE) { logger.info("{} unsubscribe data-change. path: {}, listener: {}", _manager.getInstanceName(), path, _listener); _zkClient.unsubscribeDataChanges(path, this); } }</code><technical_language>I main issue is line 551 _zkClient.subscribeChildChanges(path, this, callbackType != Type.INIT); code path. if callbackType is init, parent path of callback handler created. Thus, return null, empty? Please verify. potentially issue is note default, re-use return children list here. Note, original code retrieve children more time retrieve node then. Here, not. This is previous logic. if this bring a bug not</technical_language>

Target:
private void subscribeDataChange(String path, NotificationContext.Type callbackType) { if (callbackType == NotificationContext.Type.INIT || callbackType == NotificationContext.Type.CALLBACK) { if (logger.isDebugEnabled()) { logger.debug("CallbackHandler {}, subscribe data-change. path: {}, listener: {}", _uid, _manager.getInstanceName(), path, _listener); } boolean subStatus = _zkClient.subscribeDataChanges(path, this, callbackType != Type.INIT); logger.debug("CallbackHandler subscribe data path result {}", _uid, path, subStatus); if (!subStatus) { logger.info("CallbackHandler subscribe data path failed!", _uid, path); } } else if (callbackType == NotificationContext.Type.FINALIZE) { logger.info("CallbackHandler{}, unsubscribe data-change. path: {}, listener: {}", _uid, _manager.getInstanceName(), path, _listener); _zkClient.unsubscribeDataChanges(path, this); } }