auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void sendOrQueueSubscribeMessage(final InternalChannel channel) { factory.queueOnEventThread(new Runnable() { @Override public void run() { if (connection.getState() == ConnectionState.CONNECTED) { try { if (channel instanceof PrivateEncryptedChannelImpl) { <START> ((PrivateEncryptedChannelImpl)channel).prepareChannel(); <END> } final String message = channel.toSubscribeMessage(); connection.sendMessage(message); channel.updateState(ChannelState.SUBSCRIBE_SENT); } catch (final AuthorizationFailureException e) { clearDownSubscription(channel, e); } } } }); }</code><technical_language>potential race-condition other points [this bit of feedback](<LINK_0> apply too. I a need require client code call a separate method here, logic trigged form existing toSubscribeMessage</technical_language>

Target:
private void sendOrQueueSubscribeMessage(final InternalChannel channel) { factory.queueOnEventThread(new Runnable() { @Override public void run() { if (connection.getState() == ConnectionState.CONNECTED) { try { final String message = channel.toSubscribeMessage(); connection.sendMessage(message); channel.updateState(ChannelState.SUBSCRIBE_SENT); } catch (final AuthorizationFailureException e) { handleAuthenticationFailure(channel, e); } } } }); }
Source:
<code>public boolean contains(Command command) { final Message message = Commands.getMessage(command); if (messages.contains(message)) { final int messageIndex = messages.indexOf(message); final CommandContext actualContext = command.getContext(); <START> final CommandContext expectedContext = contexts.get(messageIndex); <END> return actualContext.equals(expectedContext); } return false; }</code><technical_language>storedContext</technical_language>

Target:
public boolean contains(Command command) { final Message message = Commands.getMessage(command); if (messages.contains(message)) { final int messageIndex = messages.indexOf(message); final CommandContext actualContext = command.getContext(); final CommandContext storedContext = contexts.get(messageIndex); return actualContext.equals(storedContext); } return false; }
Source:
<code>protected void doStart() throws Exception { if (jobLauncher == null) { jobLauncher = resolveJobLauncher(); } <START> if (job == null && jobName != null && jobName.compareTo("dynamic")!=0) { <END> job = CamelContextHelper.mandatoryLookup(getCamelContext(), jobName, Job.class); } }</code><technical_language>"dynamic".equals(jobName)? But, is wrong setting initial jobName in URI path? AFAIK this concept is anywhare in Camel, please remove check for "dynamic"</technical_language>

Target:
protected void doStart() throws Exception { if (jobLauncher == null) { jobLauncher = resolveJobLauncher(); } if (job == null && jobName != null && jobFromHeader == null) { job = CamelContextHelper.mandatoryLookup(getCamelContext(), jobName, Job.class); } }
Source:
<code>public LocalDBEntry getLocalDBEntry(final FileUploadResult fileUploadResult) throws Exception { LocalDB localDB = getLocalDB(fileUploadResult); <START> if (localDB == null || localDB.getLocalDb() == null || localDB.getLocalDb().isEmpty()) <END> return null; return getLocalDBEntry(fileUploadResult, localDB); }</code><technical_language>verify attributes, call getLocalDBEntry(a, b) method below. do verification instead of twice</technical_language>

Target:
public LocalDBEntry getLocalDBEntry(final FileUploadResult fileUploadResult) throws Exception { LocalDB localDB = readAndGetLocalDB(fileUploadResult); return getLocalDBEntry(fileUploadResult, localDB); }
Source:
<code>@Test public void testDistinctCountOnMetric() { String sql = "select count(distinct \"store_sales\") from \"foodmart\" " + "where \"store_state\" = 'WA'"; String expectedSubExplain = "PLAN=EnumerableInterpreter\n" + " BindableAggregate(group=[{}], EXPR$0=[COUNT($0)])\n" + " DruidQuery(table=[[foodmart, foodmart]], " + "intervals=[[1900-01-09T00:00:00.000Z/2992-01-10T00:00:00.000Z]], filter=[=($63, 'WA')" + "], groups=[{90}], aggs=[[]])\n" <START> + "\n"; <END> testCountWithApproxDistinct(true, sql, expectedSubExplain, "\"queryType\":\"groupBy\""); testCountWithApproxDistinct(false, sql, expectedSubExplain, "\"queryType\":\"groupBy\""); }</code><technical_language>"\n" removed</technical_language>

Target:
@Test public void testDistinctCountOnMetric() { String sql = "select count(distinct \"store_sales\") from \"foodmart\" " + "where \"store_state\" = 'WA'"; String expectedSubExplain = "PLAN=EnumerableInterpreter\n" + " BindableAggregate(group=[{}], EXPR$0=[COUNT($0)])\n" + " DruidQuery(table=[[foodmart, foodmart]], " + "intervals=[[1900-01-09T00:00:00.000Z/2992-01-10T00:00:00.000Z]], filter=[=($63, 'WA')" + "], groups=[{90}], aggs=[[]])"; testCountWithApproxDistinct(true, sql, expectedSubExplain, "\"queryType\":\"groupBy\""); testCountWithApproxDistinct(false, sql, expectedSubExplain, "\"queryType\":\"groupBy\""); }
Source:
<code>private void addRowModels( List<@NonNull ITimeGraphRowModel> rows, RosMessageFlowSegment segment, @NonNull Map<@NonNull Integer, @NonNull Predicate<@NonNull Map<@NonNull String, @NonNull String>>> predicates, @Nullable IProgressMonitor monitor) { <START> @NonNull <END> List<@NonNull ITimeGraphState> eventList = new ArrayList<>(); long entryId = fSegmentToId.computeIfAbsent(segment, i -> ATOMIC_LONG.getAndIncrement()); long startTime = segment.getStartTime(); long duration = segment.getEndTime() - startTime + 1; String label = String.valueOf(duration); TimeGraphState state = new TimeGraphState(startTime, duration, 0, label); addToStateList(eventList, state, entryId, predicates, monitor); rows.add(new TimeGraphRowModel(entryId, eventList)); Collection<RosMessageFlowSegment> next = segment.getNext(); for (RosMessageFlowSegment n : next) { addRowModels(rows, n, predicates, monitor); } }</code><technical_language>line</technical_language>

Target:
private void addRowModels( List<@NonNull ITimeGraphRowModel> rows, RosMessageFlowSegment segment, @NonNull Map<@NonNull Integer, @NonNull Predicate<@NonNull Map<@NonNull String, @NonNull String>>> predicates, @Nullable IProgressMonitor monitor) { @NonNull List<@NonNull ITimeGraphState> eventList = new ArrayList<>(); long entryId = getSegmentId(segment); long startTime = segment.getStartTime(); long duration = segment.getEndTime() - startTime + 1; String label = StringUtils.EMPTY; TimeGraphState state = new TimeGraphState(startTime, duration, 0, label); addToStateList(eventList, state, entryId, predicates, monitor); rows.add(new TimeGraphRowModel(entryId, eventList)); Collection<RosMessageFlowSegment> next = segment.getNext(); for (RosMessageFlowSegment n : next) { addRowModels(rows, n, predicates, monitor); } }
Source:
<code>private void setConnection(final IDockerConnection connection) { if (connection != null && connection.equals(this.connection)) { return; } if (this.connection != null) { this.connection.removeImageListener(this); } this.connection = connection; if (this.viewer != null && this.connection != null) { final Job refreshJob = new Job( DVMessages.getString("ImagesRefresh.msg")) { @Override protected IStatus run(IProgressMonitor monitor) { connection.getImages(true); return Status.OK_STATUS; } }; <START> refreshJob.addJobChangeListener(new <END> JobChangeAdapter() { @Override public void done(IJobChangeEvent event) { connection.addImageListener(DockerImagesView.this); Display.getDefault().asyncExec(() -> { viewer.setInput(connection); refreshViewTitle(); }); } }); refreshJob.schedule(); } else if (this.viewer != null) { viewer.setInput(new IDockerContainer[0]); form.setText(DVMessages.getString(NoConnectionSelected)); } }</code><technical_language>I get rid of JobChangeListener simply leave order of execution I this is changing anything</technical_language>

Target:
private void setConnection(final IDockerConnection connection) { if (connection != null && connection.equals(this.connection)) { return; } if (this.connection != null) { this.connection.removeImageListener(this); } this.connection = connection; if (this.viewer != null && this.connection != null) { final Job refreshJob = new Job( DVMessages.getString("ImagesRefresh.msg")) { @Override protected IStatus run(IProgressMonitor monitor) { connection.getImages(true); connection.addImageListener(DockerImagesView.this); Display.getDefault().asyncExec(() -> { viewer.setInput(connection); refreshViewTitle(); }); return Status.OK_STATUS; } }; refreshJob.schedule(); } else if (this.viewer != null) { viewer.setInput(new IDockerContainer[0]); form.setText(DVMessages.getString(NoConnectionSelected)); } }
Source:
<code>public void testCreateExplorer() throws Exception { MapJobRepositoryFactoryBean repositoryFactory = new MapJobRepositoryFactoryBean(); JobExecution jobExecution = repositoryFactory.getObject().createJobExecution("foo", new JobParameters()); jobExecution.setStartTime(new Date()); <START> repositoryFactory.getObject().update(jobExecution); <END> MapJobExplorerFactoryBean tested = new MapJobExplorerFactoryBean(repositoryFactory); tested.afterPropertiesSet(); JobExplorer explorer = tested.getObject(); assertEquals(1, explorer.findRunningJobExecutions("foo").size()); }</code><technical_language>calls repositoryFactory.getObject(); in this method extracted a variable</technical_language>

Target:
public void testCreateExplorer() throws Exception { MapJobRepositoryFactoryBean repositoryFactory = new MapJobRepositoryFactoryBean(); JobRepository jobRepository = repositoryFactory.getObject(); JobExecution jobExecution = jobRepository.createJobExecution("foo", new JobParameters()); jobExecution.setStartTime(new Date()); jobRepository.update(jobExecution); MapJobExplorerFactoryBean tested = new MapJobExplorerFactoryBean(repositoryFactory); tested.afterPropertiesSet(); JobExplorer explorer = tested.getObject(); assertEquals(1, explorer.findRunningJobExecutions("foo").size()); }
Source:
<code>public void upgradeWithMultipleConnectionHeaders() { setUpServerChannel(); String upgradeString = "GET / HTTP/1.1\r\n" + "Host: example.com\r\n" + "Connection: keep-alive\r\n" + "Connection: Upgrade, HTTP2-Settings\r\n" + "Upgrade: h2c\r\n" + "HTTP2-Settings: AAMAAABkAAQAAP__\r\n\r\n"; <START> ByteBuf upgrade = Unpooled.copiedBuffer(upgradeString, CharsetUtil.US_ASCII); <END> assertFalse(channel.writeInbound(upgrade)); assertEquals(1, userEvents.size()); Object userEvent = userEvents.get(0); assertTrue(userEvent instanceof UpgradeEvent); assertEquals("h2c", ((UpgradeEvent) userEvent).protocol()); ReferenceCountUtil.release(userEvent); assertEquals(100, http2ConnectionHandler.connection().local().maxActiveStreams()); assertEquals(65535, http2ConnectionHandler.connection().local().flowController().initialWindowSize()); assertEquals(1, http2ConnectionHandler.connection().numActiveStreams()); assertNotNull(http2ConnectionHandler.connection().stream(1)); Http2Stream stream = http2ConnectionHandler.connection().stream(1); assertEquals(State.HALF_CLOSED_REMOTE, stream.state()); assertFalse(stream.isHeadersSent()); String expectedHttpResponse = "HTTP/1.1 101 Switching Protocols\r\n" + "connection: upgrade\r\n" + "upgrade: h2c\r\n\r\n"; ByteBuf responseBuffer = channel.readOutbound(); assertEquals(expectedHttpResponse, responseBuffer.toString(CharsetUtil.UTF_8)); responseBuffer.release(); ByteBuf settingsBuffer = channel.readOutbound(); assertNotNull(settingsBuffer); settingsBuffer.release(); assertNull(channel.readOutbound()); }</code><technical_language>@arukshani test code is completely identical upgradeString. Consider moving code extra method pass in upgradeString of test methods remove code-duplication</technical_language>

Target:
public void upgradeWithMultipleConnectionHeaders() { String upgradeString = "GET / HTTP/1.1\r\n" + "Host: example.com\r\n" + "Connection: keep-alive\r\n" + "Connection: Upgrade, HTTP2-Settings\r\n" + "Upgrade: h2c\r\n" + "HTTP2-Settings: AAMAAABkAAQAAP__\r\n\r\n"; validateClearTextUpgrade(upgradeString); }
Source:
<code>void setup() { <START> map = new HashMap<>(); <END> map.put("name", "bepson"); map.put("age", 10); }</code><technical_language>org.assertj.core.test.Maps.mapOf code lighter</technical_language>

Target:
void setup() { map = mapOf(entry("name", "bepson"), entry("age", 10)); }
Source:
<code>public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == MENU_ITEM_ADD_NEW_CHARGES) { ChargeDialogFragment chargeDialogFragment = ChargeDialogFragment.newInstance(clientId); FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager() .beginTransaction(); fragmentTransaction.addToBackStack(FragmentConstants.FRAG_CHARGE_LIST); chargeDialogFragment.show(fragmentTransaction, <START> getString(R.string.change_dialog_fragment)); <END> } return super.onOptionsItemSelected(item); }</code><technical_language>This is charge_dialog_fragment change_dialog_fragment</technical_language>

Target:
public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == MENU_ITEM_ADD_NEW_CHARGES) { ChargeDialogFragment chargeDialogFragment = ChargeDialogFragment.newInstance(clientId); FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager() .beginTransaction(); fragmentTransaction.addToBackStack(FragmentConstants.FRAG_CHARGE_LIST); chargeDialogFragment.show(fragmentTransaction, getString(R.string.charge_dialog_fragment)); } return super.onOptionsItemSelected(item); }
Source:
<code>public List<ContentProposal> getProposals(IInterpreter interpreter, ContentContext context) { List<ContentProposal> proposals = new ArrayList(); if (interpreter instanceof AQLSiriusInterpreter) { ExpressionTrimmer trimer = new ExpressionTrimmer(context.getContents()); if (trimer.positionIsWithinAQL(context.getPosition())) { IQueryEnvironment queryEnvironment = ((AQLSiriusInterpreter) interpreter).getEnvironment(); for (EPackage pak : context.getInterpreterContext().getAvailableEPackages()) { if (pak != null) { <START> queryEnvironment.registerEPackage(pak); <END> } } Map<String, Set<IType>> variableTypes = TypesUtil.createAQLVariableTypesFromInterpreterContext(context.getInterpreterContext(), queryEnvironment); addProposals(proposals, trimer, context.getPosition(), queryEnvironment, variableTypes); } } return proposals; }</code><technical_language>I AQL APIs, is OK modify environement reset original done</technical_language>

Target:
public List<ContentProposal> getProposals(IInterpreter interpreter, ContentContext context) { List<ContentProposal> proposals = new ArrayList(); if (interpreter instanceof AQLSiriusInterpreter) { ExpressionTrimmer trimer = new ExpressionTrimmer(context.getContents()); if (trimer.positionIsWithinAQL(context.getPosition())) { IQueryEnvironment queryEnvironment = createEnvironment(context); Map<String, Set<IType>> variableTypes = TypesUtil.createAQLVariableTypesFromInterpreterContext(context.getInterpreterContext(), queryEnvironment); addProposals(proposals, trimer, context.getPosition(), queryEnvironment, variableTypes); } } return proposals; }
Source:
<code>private static boolean isInputFormatSupported(Properties schema) { <START> String inputFormat = HiveUtil.getInputFormatName(schema); <END> if (!supportedInputFormats.contains(inputFormat)) { log.debug("Unsupported S3Select input format found: " + inputFormat); return false; } return true; }</code><technical_language>static import getInputFormatName</technical_language>

Target:
private static boolean isInputFormatSupported(Properties schema) { String inputFormat = getInputFormatName(schema); if (!SUPPORTED_INPUT_FORMATS.contains(inputFormat)) { return false; } return true; }
Source:
<code><START> public static String decrypt(String codedText, String secret) throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException, NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException { <END> Base64 encoder = new Base64(32, linebreak, true); byte[] encypted = encoder.decode(codedText.getBytes()); Cipher cipher = Cipher.getInstance(TRANSFORMATION, PROVIDER); cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(secret.getBytes(), ALGORITHM)); byte[] decrypted = cipher.doFinal(encypted); return new String(decrypted); }</code><technical_language>null checks for codedTest secret</technical_language>

Target:
public static String decrypt(String codedText, String secret) { String toReturn = ""; try { toReturn = decrypt_with_exceptions(codedText, secret); } catch (Exception ex) { throw new OseeCoreException(ex); } return toReturn; }
Source:
<code><START> public boolean equals(final Object obj) { <END> if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (this.getClass() != obj.getClass()) { return false; } final SmartMeterConverter other = (SmartMeterConverter) obj; if (this.helper == null) { if (other.helper != null) { return false; } } else if (!this.helper.equals(other.helper)) { return false; } return true; }</code><technical_language>java.util.Objects</technical_language>

Target:
public boolean equals(final Object obj) { return super.equals(obj) && Objects.equals(this.helper, ((SmartMeterConverter) obj).helper); }
Source:
<code>public static UUID makeUUID(byte bytes[]) { long high = 0; long low = 0; if (bytes.length < Utils.UUID_LEN) { <START> throw new IllegalArgumentException("UUID byte field must be 16 bytes long"); <END> } final int bitsPerByte = Byte.SIZE; int bitMask = (1 << bitsPerByte) - 1; for (int i = 0; i < bitsPerByte; i++) { low = (low << bitsPerByte) | (bytes[i + bitsPerByte] & bitMask); high = (high << bitsPerByte) | (bytes[i] & bitMask); } UUID uuid = new UUID(high, low); return uuid; }</code><technical_language>CTFException instead</technical_language>

Target:
public static UUID makeUUID(byte bytes[]) throws CTFException { long high = 0; long low = 0; if (bytes.length < Utils.UUID_LEN) { throw new CTFException("UUID byte field must be 16 bytes long"); } final int bitsPerByte = Byte.SIZE; int bitMask = (1 << bitsPerByte) - 1; for (int i = 0; i < bitsPerByte; i++) { low = (low << bitsPerByte) | (bytes[i + bitsPerByte] & bitMask); high = (high << bitsPerByte) | (bytes[i] & bitMask); } return new UUID(high, low); }
Source:
<code>public Collection<Integer> selectNextChildren(long t) throws TimeRangeException { if (t < getNodeStart() || (isOnDisk() && t > getNodeEnd())) { throw new TimeRangeException("Requesting children outside the node's range: " + t); } rwl.readLock().lock(); try { <START> int potentialNextSeqNb = getSequenceNumber(); <END> for (int i = 0; i < nbChildren; i++) { if (t >= childStart[i]) { potentialNextSeqNb = children[i]; } else { break; } } if (potentialNextSeqNb == getSequenceNumber()) { throw new IllegalStateException("No next child node found"); } return Collections.singleton(potentialNextSeqNb); } finally { rwl.readLock().unlock(); } }</code><technical_language>instead of initializing getSequencenNumber(), initialize (and check for) -1. more obvious is invalid value</technical_language>

Target:
public Collection<Integer> selectNextChildren(long t) throws TimeRangeException { if (t < getNodeStart() || (isOnDisk() && t > getNodeEnd())) { throw new TimeRangeException("Requesting children outside the node's range: " + t); } rwl.readLock().lock(); try { int potentialNextSeqNb = -1; for (int i = 0; i < nbChildren; i++) { if (t >= childStart[i]) { potentialNextSeqNb = children[i]; } else { break; } } if (potentialNextSeqNb == -1) { throw new IllegalStateException("No next child node found"); } return Collections.singleton(potentialNextSeqNb); } finally { rwl.readLock().unlock(); } }
Source:
<code><START> private void convertLoadBalancer(CloudLoadBalancer cloudLoadBalancer, List<CloudResource> instances, <END> AwsNetworkView awsNetworkView, AmazonEC2Client amazonEC2Client, List<AwsLoadBalancer> awsLoadBalancers) { Set<String> subnetIds = selectLoadBalancerSubnetIds(cloudLoadBalancer.getType(), awsNetworkView); AwsLoadBalancerScheme scheme = determinePublicVsPrivateSchema(subnetIds, awsNetworkView.getExistingVpc(), amazonEC2Client); Optional<AwsLoadBalancer> existingLoadBalancer = awsLoadBalancers.stream() .filter(lb -> lb.getScheme() == scheme) .findFirst(); AwsLoadBalancer currentLoadBalancer; if (existingLoadBalancer.isPresent()) { currentLoadBalancer = existingLoadBalancer.get(); } else { currentLoadBalancer = new AwsLoadBalancer(scheme); awsLoadBalancers.add(currentLoadBalancer); } currentLoadBalancer.addSubnets(subnetIds); setupLoadBalancer(cloudLoadBalancer, instances, currentLoadBalancer); }</code><technical_language>a converter anymore creates loadbalancers. I returned loadbalancer instead of adding a list in parameters</technical_language>

Target:
private AwsLoadBalancer convertLoadBalancer(CloudLoadBalancer cloudLoadBalancer, List<CloudResource> instances, AwsNetworkView awsNetworkView, AmazonEC2Client amazonEC2Client, List<AwsLoadBalancer> awsLoadBalancers) { Set<String> subnetIds = selectLoadBalancerSubnetIds(cloudLoadBalancer.getType(), awsNetworkView); AwsLoadBalancerScheme scheme = determinePublicVsPrivateSchema(subnetIds, awsNetworkView.getExistingVpc(), amazonEC2Client); Optional<AwsLoadBalancer> existingLoadBalancer = awsLoadBalancers.stream() .filter(lb -> lb.getScheme() == scheme) .findFirst(); AwsLoadBalancer currentLoadBalancer; if (existingLoadBalancer.isPresent()) { currentLoadBalancer = existingLoadBalancer.get(); } else { currentLoadBalancer = new AwsLoadBalancer(scheme); } currentLoadBalancer.addSubnets(subnetIds); setupLoadBalancer(cloudLoadBalancer, instances, currentLoadBalancer); return currentLoadBalancer; }
Source:
<code>private static void checkAllProperty(SubscriptionContext ctx, AssignmentStatement assignmentStatement) { Expression assignedValue = assignmentStatement.assignedValue(); if (!assignedValue.is(Tree.Kind.LIST_LITERAL) && !assignedValue.is(Tree.Kind.TUPLE)) { return; } List<Expression> expressions = getAllExpressions(assignedValue); for (Expression element : expressions) { <START> if (element instanceof HasSymbol) { Symbol symbol = ((HasSymbol) element).symbol(); if (isClassOrFunctionSymbol(symbol)) { ctx.addIssue(element, MESSAGE); continue; } } <END> if (!couldBeString(element)) { ctx.addIssue(element, MESSAGE); } } }</code><technical_language>I move this code couldBeString</technical_language>

Target:
private static void checkAllProperty(SubscriptionContext ctx, AssignmentStatement assignmentStatement) { Expression assignedValue = assignmentStatement.assignedValue(); if (!assignedValue.is(Tree.Kind.LIST_LITERAL) && !assignedValue.is(Tree.Kind.TUPLE)) { return; } List<Expression> expressions = getAllExpressions(assignedValue); for (Expression element : expressions) { if (!couldBeString(element)) { ctx.addIssue(element, MESSAGE); } } }
Source:
<code>private boolean hasSuspendedVms() { List<VM> vmList = vmDao.getAllForStoragePool(getStoragePool().getId()); String suspendedVms = vmList.stream() .filter(vm -> vm.getStatus().isSuspended() && vm.getCustomCompatibilityVersion() != null) .filter(vm -> getStoragePool().getCompatibilityVersion().greater(vm.getCustomCompatibilityVersion())) .map(VM::getName) .map(name -> "<li>" + name + "</li>") .collect(Collectors.joining()); <START> suspendedVms = "<ul>" + suspendedVms + "</ul>"; <END> if (!suspendedVms.isEmpty()) { addValidationMessage(EngineMessage.ERROR_CANNOT_UPDATE_STORAGE_POOL_SUSPENDED_VM_COMPATIBILITY_VERSION_NOT_SUPPORTED); addValidationMessageVariable("VmsList", suspendedVms); return true; } return false; }</code><technical_language>moved "if" statement. a must. a minor optimization</technical_language>

Target:
private boolean hasSuspendedVms() { List<VM> vmList = vmDao.getAllForStoragePool(getStoragePool().getId()); String suspendedVms = vmList.stream() .filter(vm -> vm.getStatus().isSuspended() && vm.getCustomCompatibilityVersion() != null) .filter(vm -> getStoragePool().getCompatibilityVersion().greater(vm.getCustomCompatibilityVersion())) .map(VM::getName) .map(name -> "<li>" + name + "</li>") .collect(Collectors.joining()); if (!suspendedVms.isEmpty()) { suspendedVms = "<ul>" + suspendedVms + "</ul>"; addValidationMessage(EngineMessage.ERROR_CANNOT_UPDATE_STORAGE_POOL_SUSPENDED_VM_COMPATIBILITY_VERSION_NOT_SUPPORTED); addValidationMessageVariable("VmsList", suspendedVms); return true; } return false; }
Source:
<code>protected void updateCurrentCd(String cdPath) { cdPath = <START> cdPath.isEmpty() ? <END> null : cdPath; VmHandler.updateCurrentCd(getVdsId(), getVm(), cdPath); }</code><technical_language>if cdPath is null</technical_language>

Target:
protected void updateCurrentCd(String cdPath) { cdPath = StringUtils.isEmpty(cdPath) ? null : cdPath; VmHandler.updateCurrentCd(getVdsId(), getVm(), cdPath); }
Source:
<code>public synchronized void resumeJob(final String jobName, final String groupName) throws SchedulerException { if (!ifJobExist(jobName, groupName)) { throw new SchedulerException( <START> "can not find job with group name: " + groupName + " in quartz."); <END> } else { this.scheduler.resumeJob(new JobKey(jobName, groupName)); } }</code><technical_language>exception needs modified a bit</technical_language>

Target:
public synchronized void resumeJob(final String jobName, final String groupName) throws SchedulerException { checkJobExistence(jobName, groupName); this.scheduler.resumeJob(new JobKey(jobName, groupName)); }
Source:
<code>public void printUsageAndExit(final String message, final CmdLineParser clp) { System.err.println(message); System.err.print("jgit "); System.err.print(commandName); <START> OutputStreamWriter writer = new OutputStreamWriter(System.err); <END> ResourceBundle resourceBundle = getResourceBundle(); clp.printSingleLineUsage(writer, resourceBundle); System.err.println(); System.err.println(); clp.printUsage(writer, resourceBundle); System.err.println(); System.exit(1); }</code><technical_language>If a writer System.err, I I prefer this method. do this start, replace System.err.print* invocations calls writer sharing args4j library</technical_language>

Target:
public void printUsageAndExit(final String message, final CmdLineParser clp) { PrintWriter writer = new PrintWriter(System.err); writer.println(message); writer.print("jgit "); writer.print(commandName); clp.printSingleLineUsage(writer, getResourceBundle()); writer.println(); writer.println(); clp.printUsage(writer, getResourceBundle()); writer.println(); writer.flush(); System.exit(1); }
Source:
<code>public void createPollMetrics() { <START> _numPolls = new Meter(); <END> _eventCountsPerPoll = new Histogram(new SlidingTimeWindowReservoir(1, TimeUnit.MINUTES)); _numPolls = DYNAMIC_METRICS_MANAGER.registerMetric(_className, _metricsKey, NUM_POLLS, Meter.class); _eventCountsPerPoll = DYNAMIC_METRICS_MANAGER.registerMetric(_className, _metricsKey, EVENT_COUNTS_PER_POLL, Histogram.class); _aggregatedClientPollOverTimeout = DYNAMIC_METRICS_MANAGER.registerMetric(_className, AGGREGATE, CLIENT_POLL_OVER_TIMEOUT, Counter.class); _aggregatedClientPollIntervalOverSessionTimeout = DYNAMIC_METRICS_MANAGER.registerMetric(_className, AGGREGATE, CLIENT_POLL_INTERVAL_OVER_SESSION_TIMEOUT, Counter.class); }</code><technical_language>Remove instance creation other places</technical_language>

Target:
public void createPollMetrics() { _pollMetrics = new PollMetrics(_className, _key); _metricsList.add(_pollMetrics); }
Source:
<code><START> public MediaListMode getMediaListMode() { <END> MediaListMode mediaListMode = null; if(getMediaPreference().equals(MediaListMode.GRID.toString())){ mediaListMode = MediaListMode.GRID; }else if(getMediaPreference().equals(MediaListMode.LIST.toString())){ mediaListMode = MediaListMode.LIST; } return mediaListMode; }</code><technical_language>This method public this data source return settings domain entity</technical_language>

Target:
private MediaListMode getMediaListMode() { MediaListMode mediaListMode = null; if(getMediaPreference().equals(MediaListMode.GRID.toString())){ mediaListMode = MediaListMode.GRID; }else if(getMediaPreference().equals(MediaListMode.LIST.toString())){ mediaListMode = MediaListMode.LIST; } return mediaListMode; }
Source:
<code>public Mono<AccountProperties> getAccountProperties() { try { return getAccountPropertiesWithResponse().flatMap(FluxUtil::toMono); <START> } catch (RuntimeException ex) { <END> return monoError(logger, ex); } }</code><technical_language>need catch exception here, done in overload</technical_language>

Target:
public Mono<AccountProperties> getAccountProperties() { return getAccountPropertiesWithResponse().flatMap(FluxUtil::toMono); }
Source:
<code>public static WebViewClient getWebViewClient(final boolean ignoreErrors, final boolean followLinks, final Form form, final Component component) { return new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { return !followLinks; } @Override public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) { if (ignoreErrors) { handler.proceed(); } else { handler.cancel(); form.dispatchErrorOccurredEvent(component, "WebView", ErrorMessages.ERROR_WEBVIEW_SSL_ERROR); } } @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { EventDispatcher.dispatchEvent(component, "BeforePageLoad", url); } @Override public void onPageFinished(WebView view, String url) { EventDispatcher.dispatchEvent(component, "PageLoaded", url); } @Override public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { <START> container.$form().runOnUiThread(new Runnable() { <END> public void run() { EventDispatcher.dispatchEvent(component, "ErrorOccurred", errorCode, description, failingUrl); } }); } }; }</code><technical_language>In this context, form is a final variable</technical_language>

Target:
public static WebViewClient getWebViewClient(final boolean ignoreErrors, final boolean followLinks, final Form form, final Component component) { return new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { return !followLinks; } @Override public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) { if (ignoreErrors) { handler.proceed(); } else { handler.cancel(); form.dispatchErrorOccurredEvent(component, "WebView", ErrorMessages.ERROR_WEBVIEW_SSL_ERROR); } } @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { EventDispatcher.dispatchEvent(component, "BeforePageLoad", url); } @Override public void onPageFinished(WebView view, String url) { EventDispatcher.dispatchEvent(component, "PageLoaded", url); } @Override public void onReceivedError(WebView view, final int errorCode, final String description, final String failingUrl) { form.runOnUiThread(new Runnable() { public void run() { EventDispatcher.dispatchEvent(component, "ErrorOccurred", errorCode, description, failingUrl); } }); } }; }
Source:
<code>private Map<String, Map<String, Object>> readDatabase(File inputFile) { try { final Map<String, Map<String, Object>> inputMap = new ConcurrentHashMap<String, Map<String, Object>>(); FileReader reader = new FileReader(inputFile); <START> Map<String, Map<String, Object>> type = new HashMap<String, Map<String, Object>>(); <END> Map<String, Map<String, Object>> loadedMap = outerMapper.fromJson(reader, type.getClass()); if (loadedMap != null && loadedMap.size() != 0) { inputMap.putAll(loadedMap); } return inputMap; } catch (JsonSyntaxException | JsonIOException | FileNotFoundException e) { logger.error("Error reading JsonDB from {}. Cause {}.", inputFile.getPath(), e.getMessage()); return null; } }</code><technical_language>type is created retrieve Class later. HashMap.class in line 211? Wouldnt generics erased type runtime anyway</technical_language>

Target:
private Map<String, StorageEntry> readDatabase(File inputFile) { try { final Map<String, StorageEntry> inputMap = new ConcurrentHashMap<>(); FileReader reader = new FileReader(inputFile); Map<String, StorageEntry> loadedMap = internalMapper.fromJson(reader, map.getClass()); if (loadedMap != null && loadedMap.size() != 0) { inputMap.putAll(loadedMap); } return inputMap; } catch (JsonSyntaxException | JsonIOException | FileNotFoundException e) { logger.error("Error reading JsonDB from {}. Cause {}.", inputFile.getPath(), e.getMessage()); return null; } }
Source:
<code>public MojoExecution setupMojoExecution(final MavenProject project, final MojoExecution execution, IProgressMonitor monitor) throws CoreException { <START> return context().execute(project, new ICallable<MojoExecution>() { <END> public MojoExecution call(IMavenExecutionContext context, IProgressMonitor monitor) throws CoreException { return setupMojoExecution(context.getSession(), project, execution); } }, monitor); }</code><technical_language>unnecessary change</technical_language>

Target:
public MojoExecution setupMojoExecution(final MavenProject project, final MojoExecution execution, IProgressMonitor monitor) throws CoreException { return context().execute(project, (context, pm) -> setupMojoExecution(context.getSession(), project, execution), monitor); }
Source:
<code>public float getProgress() throws IOException, InterruptedException { <START> return 0; <END> }</code><technical_language>current event row count / QueryableIndex.getNumRows()</technical_language>

Target:
public float getProgress() throws IOException, InterruptedException { if (numRows > 0) { return (rowNum * 1.0f) / numRows; } else { return 0; } }
Source:
<code>private static OnlineHmmPriors getPriorsFromS3Object(final AmazonS3 s3,final String bucket, final String key) { OnlineHmmPriors onlineHmmPriors = OnlineHmmPriors.createEmpty(); final S3Object s3Object = s3.getObject(bucket, key); final Reader inputStream = new InputStreamReader(s3Object.getObjectContent()); <START> try { <END> final String base64data = CharStreams.toString(inputStream); byte bindata = Base64.decodeBase64(base64data); final int len = bindata.length; final Optional<OnlineHmmPriors> priorsOptional = OnlineHmmPriors.createFromProtoBuf(bindata); if (priorsOptional.isPresent()) { onlineHmmPriors = priorsOptional.get(); LOGGER.info("successfully pulled default models from {}/{}",bucket,key); } else { LOGGER.error("failed to find default models for the ensemble"); } } catch (IOException e) { LOGGER.error(e.getMessage()); } return onlineHmmPriors; }</code><technical_language>inputStream is closed, leak connections S3. Recommended in Java7+ is use: java try(final Reader inputStream = new InputStreamReader(s3Object.getObjectContent())) { ... } close resource in case of exceptions</technical_language>

Target:
private static OnlineHmmPriors getPriorsFromS3Object(final AmazonS3 s3,final String bucket, final String key) { final S3Object s3Object = s3.getObject(bucket, key); try (final Reader inputStream = new InputStreamReader(s3Object.getObjectContent())) { final String base64data = CharStreams.toString(inputStream); byte bindata = Base64.decodeBase64(base64data); final int len = bindata.length; final Optional<OnlineHmmPriors> priorsOptional = OnlineHmmPriors.createFromProtoBuf(bindata); if (!priorsOptional.isPresent()) { LOGGER.error("failed to find default models for the ensemble"); return OnlineHmmPriors.createEmpty(); } LOGGER.info("successfully pulled default models from {}/{}",bucket,key); return priorsOptional.get(); } catch (IOException e) { LOGGER.error(e.getMessage()); } return OnlineHmmPriors.createEmpty(); }
Source:
<code>public ExecutionResult compare(FileElement localFile, FileElement remoteFile, ExternalDiffTool tool, boolean trustExitCode) throws ToolException { try { if (tool == null) { throw new ToolException( <START> "External diff tool specified in git attributes can not be found."); END> } String command = ExternalToolUtils.prepareCommand(tool.getCommand(), localFile, remoteFile, null, null); Map<String, String> env = ExternalToolUtils.prepareEnvironment( gitDir, localFile, remoteFile, null, null); CommandExecutor cmdExec = new CommandExecutor(fs, trustExitCode); return cmdExec.run(command, workTree, env); } catch (IOException | InterruptedException e) { throw new ToolException(e); } finally { localFile.cleanTemporaries(); remoteFile.cleanTemporaries(); } }</code><technical_language>here, externalized string</technical_language>

Target:
public ExecutionResult compare(FileElement localFile, FileElement remoteFile, ExternalDiffTool tool, boolean trustExitCode) throws ToolException { try { if (tool == null) { throw new ToolException(JGitText .get().diffToolNotSpecifiedInGitAttributesError); } String command = ExternalToolUtils.prepareCommand(tool.getCommand(), localFile, remoteFile, null, null); Map<String, String> env = ExternalToolUtils.prepareEnvironment( gitDir, localFile, remoteFile, null, null); CommandExecutor cmdExec = new CommandExecutor(fs, trustExitCode); return cmdExec.run(command, workTree, env); } catch (IOException | InterruptedException e) { throw new ToolException(e); } finally { localFile.cleanTemporaries(); remoteFile.cleanTemporaries(); } }
Source:
<code>public void fixScrollPositionByNavbarOnF2(boolean isMobile) { <START> if(isMobile){ <END> int mobileNavbarHeight = -1 * driver.findElement(F2_MOBILE_NAVIGATION_BAR).getSize().getHeight(); jsActions.scrollBy(0, mobileNavbarHeight); } else { int desktopNavbarHeight = -1 * driver.findElement(F2_DESKTOP_NAVIGATION_BAR).getSize().getHeight(); jsActions.scrollBy(0, desktopNavbarHeight); } }</code><technical_language>cases if common logic, if statement determine element use, refactor</technical_language>

Target:
public void fixScrollPositionByNavbarOnF2(boolean isMobile) { By element = isMobile ? MOBILE_NAVIGATION_BAR : DESKTOP_NAVIGATION_BAR; int navbarHeight = driver.findElement(element).getSize().getHeight(); jsActions.scrollBy(0, -navbarHeight); }
Source:
<code>private boolean isUnsupportedParamWithNonBlankValue(Map.Entry<String, String> queryParam) { <START> return !(getSupportedSearchParams().contains(queryParam.getKey()) || isBlank(queryParam.getValue())); <END> }</code><technical_language>De Morgan is earning this week! java return !getSupportedSearchParams().contains(queryParam.getKey()) && !isBlank(queryParam.getValue());</technical_language>

Target:
private boolean isUnsupportedParamWithNonBlankValue(Map.Entry<String, String> queryParam) { return !getSupportedSearchParams().contains(queryParam.getKey()) && isNotBlank(queryParam.getValue()); }
Source:
<code>public void finish() { try { CryptoFileSystemProvider.changePassphrase(vault.getPath(), MASTERKEY_FILENAME, oldPasswordField.getCharacters(), newPassword.get()); <START> LOG.info("Successful changed password for {}", vault.getDisplayableName()); <END> window.close(); updatePasswordInSystemkeychain(); } catch (IOException e) { LOG.error("IO error occured during password change. Unable to perform operation.", e); errorComponent.cause(e).window(window).returnToScene(window.getScene()).build().showErrorScene(); } catch (InvalidPassphraseException e) { Animations.createShakeWindowAnimation(window).play(); oldPasswordField.selectAll(); oldPasswordField.requestFocus(); } }</code><technical_language>I this blame, while it, change this "Successfully" :wink:</technical_language>

Target:
public void finish() { try { CryptoFileSystemProvider.changePassphrase(vault.getPath(), MASTERKEY_FILENAME, oldPasswordField.getCharacters(), newPassword.get()); LOG.info("Successfully changed password for {}", vault.getDisplayableName()); window.close(); updatePasswordInSystemkeychain(); } catch (IOException e) { LOG.error("IO error occured during password change. Unable to perform operation.", e); errorComponent.cause(e).window(window).returnToScene(window.getScene()).build().showErrorScene(); } catch (InvalidPassphraseException e) { Animations.createShakeWindowAnimation(window).play(); oldPasswordField.selectAll(); oldPasswordField.requestFocus(); } }
Source:
<code>protected @NonNull Iterable<@NonNull IAnalysisModule> getDependentAnalyses() { try { ITmfTrace trace = getTrace(); if (trace != null) { <START> final XmlPatternStateSystemModule stateSystemModule = new XmlPatternStateSystemModule(getId()); <END> stateSystemModule.setXmlFile(fXmlFile); stateSystemModule.setTrace(trace); setDependentModule(stateSystemModule); return ImmutableList.of((IAnalysisModule) stateSystemModule); } } catch (TmfAnalysisException e) { Activator.logError("Failed to set dependent analysis trace."); } return super.getDependentAnalyses(); }</code><technical_language>new module id returned getDependentAnalysisId()</technical_language>

Target:
protected @NonNull Iterable<@NonNull IAnalysisModule> getDependentAnalyses() { try { ITmfTrace trace = getTrace(); if (trace != null) { final XmlPatternStateSystemModule stateSystemModule = new XmlPatternStateSystemModule(getDependentAnalysisId()); stateSystemModule.setXmlFile(fXmlFile); stateSystemModule.setTrace(trace); setDependentModule(stateSystemModule); return ImmutableList.of((IAnalysisModule) stateSystemModule); } } catch (TmfAnalysisException e) { Activator.logError("Failed to set dependent analysis trace."); } return super.getDependentAnalyses(); }
Source:
<code>protected Slice getKey(Object tuple) { Object key = keyGetter.get(tuple); <START> return new Slice(key.toString().getBytes()); <END> }</code><technical_language>This right serialize key. This depends toString method default (if implemented) returns address dedup</technical_language>

Target:
protected Slice getKey(Object tuple) { Object key = keyGetter.get(tuple); return streamCodec.toByteArray(key); }
Source:
<code>private void setSearchFilter(String string) { if <START> (patternFilter == null) { <END> patternFilter = new TypeListPatternFilter(); commonViewer.addFilter(patternFilter); } patternFilter.setPattern(string); commonViewer.refresh(false); handleTreeExpansion(string); }</code><technical_language>this be: null == patternFilter</technical_language>

Target:
private void setSearchFilter(String string) { if (null == patternFilter) { patternFilter = new TypeListPatternFilter(); commonViewer.addFilter(patternFilter); } patternFilter.setPattern(string); commonViewer.refresh(false); handleTreeExpansion(string); }
Source:
<code>public List<String> resolveVirtualAttributeValueChange(PerunSessionImpl session, String message) throws WrongReferenceAttributeValueException, AttributeNotExistsException, WrongAttributeAssignmentException { Matcher statusChangeMatcher = statusChange.matcher(message); if (statusChangeMatcher.find() && (statusChangeMatcher.group(2).equals("expired") || statusChangeMatcher.group(2).equals("disabled") || statusChangeMatcher.group(2).equals("validated"))) { try { int memberId = Integer.valueOf(statusChangeMatcher.group(1)); Member member = session.getPerunBl().getMembersManagerBl().getMemberById(session, memberId); Attribute attribute = session.getPerunBl().getAttributesManagerBl().getAttribute(session, member, AttributesManager.NS_MEMBER_ATTR_DEF + ":suspensionInfo"); attribute.setValue(new LinkedHashMap<String, String>()); session.getPerunBl().getAttributesManagerBl().setAttribute(session, member, attribute); } catch (AttributeNotExistsException e) { <START> } catch (Exception e) { <END> log.error("Can't resolve auditer's message for " + this.getClass().getSimpleName() + " module because of exception.", e); } } return new ArrayList<>(); }</code><technical_language>I mentioned, do catch Exceptions here, thrown in try block. suggestion } catch (InternalErrorException | MemberNotExistsException | WrongAttributeValueException e) {</technical_language>

Target:
public List<String> resolveVirtualAttributeValueChange(PerunSessionImpl session, String message) throws WrongReferenceAttributeValueException, AttributeNotExistsException, WrongAttributeAssignmentException { Matcher statusChangeMatcher = statusChange.matcher(message); if (statusChangeMatcher.find() && (statusChangeMatcher.group(2).equals("expired") || statusChangeMatcher.group(2).equals("disabled") || statusChangeMatcher.group(2).equals("validated"))) { try { int memberId = Integer.valueOf(statusChangeMatcher.group(1)); Member member = session.getPerunBl().getMembersManagerBl().getMemberById(session, memberId); Attribute attribute = session.getPerunBl().getAttributesManagerBl().getAttribute(session, member, AttributesManager.NS_MEMBER_ATTR_DEF + ":suspensionInfo"); attribute.setValue(new LinkedHashMap<String, String>()); session.getPerunBl().getAttributesManagerBl().setAttribute(session, member, attribute); } catch (AttributeNotExistsException e) { } catch (MemberNotExistsException | WrongAttributeValueException | InternalErrorException e) { log.error("Can't resolve auditer's message for " + this.getClass().getSimpleName() + " module because of exception.", e); } } return new ArrayList<>(); }
Source:
<code>public void scanFile(JavaFileScannerContext context) { Preconditions.checkNotNull(sensorContext); JavaFilesCache javaFilesCache = new JavaFilesCache(); javaFilesCache.scanFile(context); InputFile inputFile = fs.inputFile(fs.predicates().is(context.getFile())); org.sonar.api.resources.File currentResource = (org.sonar.api.resources.File) sensorContext.getResource(inputFile); String fileKey = context.getFileKey(); if (currentResource == null) { throw new IllegalStateException("resource not found : " + fileKey); } resourceMapping.addResource(currentResource, fileKey); for (Map.Entry<String, File> classIOFileEntry : javaFilesCache.getResourcesCache().entrySet()) { resourcesByClass.put(classIOFileEntry.getKey(), currentResource); if (fileKey != null) { sourceFileByClass.put(classIOFileEntry.getKey(), fileKey); } } methodStartLines.putAll(javaFilesCache.getMethodStartLines()); String componentKey = currentResource.getEffectiveKey(); if (javaFilesCache.hasSuppressWarningLines()) { suppressWarningsFilter.addComponent(componentKey, javaFilesCache.getSuppressWarningLines()); } for (JavaIssueFilter javaIssueFilter : issueFilters) { <START> javaIssueFilter.addComponent(fileKey, componentKey); <END> javaIssueFilter.scanFile(context); } }</code><technical_language>For I read need set component key, need for internal map filters objects</technical_language>

Target:
public void scanFile(JavaFileScannerContext context) { Preconditions.checkNotNull(sensorContext); JavaFilesCache javaFilesCache = new JavaFilesCache(); javaFilesCache.scanFile(context); InputFile inputFile = fs.inputFile(fs.predicates().is(context.getFile())); org.sonar.api.resources.File currentResource = (org.sonar.api.resources.File) sensorContext.getResource(inputFile); if (currentResource == null) { throw new IllegalStateException("resource not found : " + context.getFileKey()); } resourceMapping.addResource(currentResource, context.getFileKey()); for (Map.Entry<String, File> classIOFileEntry : javaFilesCache.getResourcesCache().entrySet()) { resourcesByClass.put(classIOFileEntry.getKey(), currentResource); if (context.getFileKey() != null) { sourceFileByClass.put(classIOFileEntry.getKey(), context.getFileKey()); } } methodStartLines.putAll(javaFilesCache.getMethodStartLines()); if (javaFilesCache.hasSuppressWarningLines()) { suppressWarningsFilter.addComponent(currentResource.getEffectiveKey(), javaFilesCache.getSuppressWarningLines()); } }