auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private boolean requestDetailFileLineIsCashAdvance(ConcurRequestExtractRequestDetailFileLine detailFileLine) { if (StringUtils.isNotEmpty(detailFileLine.getRequestEntryExpenseType()) && <START> detailFileLine.getRequestEntryExpenseType().equalsIgnoreCase(ConcurConstants.CASH_ADVANCE_INDICATOR)) { <END> detailFileLine.getValidationResult().setCashAdvanceLine(true); } else { detailFileLine.getValidationResult().setCashAdvanceLine(false); detailFileLine.getValidationResult().addMessage(new String(getConfigurationService().getPropertyValueAsString(ConcurKeyConstants.CONCUR_REQUEST_EXTRACT_NOT_CASH_ADVANCE_DATA_LINE))); } return detailFileLine.getValidationResult().isCashAdvanceLine(); }</code><technical_language>simply this if statement StringUtils.equalsIgnoreCase(detailFileLine.getRequestEntryExpenseType(), (ConcurConstants.CASH_ADVANCE_INDICATOR)</technical_language>

Target:
private boolean requestDetailFileLineIsCashAdvance(ConcurRequestExtractRequestDetailFileLine detailFileLine) { if (StringUtils.isNotEmpty(detailFileLine.getRequestEntryExpenseType()) && StringUtils.equalsIgnoreCase(detailFileLine.getRequestEntryExpenseType(), ConcurConstants.REQUEST_EXTRACT_CASH_ADVANCE_INDICATOR)) { detailFileLine.getValidationResult().setCashAdvanceLine(true); } else { detailFileLine.getValidationResult().setCashAdvanceLine(false); detailFileLine.getValidationResult().addMessage(getConfigurationService().getPropertyValueAsString(ConcurKeyConstants.CONCUR_REQUEST_EXTRACT_NOT_CASH_ADVANCE_DATA_LINE)); } return detailFileLine.getValidationResult().isCashAdvanceLine(); }
Source:
<code>public ValidationResult validate(EnvironmentDto environmentDto, ParametersDto parametersDto, ValidationResultBuilder validationResultBuilder) { AwsParametersDto awsParametersDto = parametersDto.getAwsParametersDto(); if (Objects.isNull(awsParametersDto)) { return validationResultBuilder.build(); } <START> if (StringUtils.isNotBlank(awsParametersDto.getS3GuardTableName())) { <END> boolean tableAlreadyAttached = isTableAlreadyAttached(environmentDto, awsParametersDto); if (tableAlreadyAttached) { validationResultBuilder.error(String.format("S3Guard table '%s' is already attached to another active environment. " + "Please select another unattached table or specify a non-existing name to create it.", awsParametersDto.getS3GuardTableName())); } else { determineAwsParameters(environmentDto, parametersDto); } } if (awsParametersDto.getFreeIpaSpotPercentage() < PERCENTAGE_MIN || awsParametersDto.getFreeIpaSpotPercentage() > PERCENTAGE_MAX) { validationResultBuilder.error(String.format("FreeIpa spot percentage must be between %d and %d.", PERCENTAGE_MIN, PERCENTAGE_MAX)); } return validationResultBuilder.build(); }</code><technical_language>This @Override</technical_language>

Target:
public ValidationResult validate(EnvironmentDto environmentDto, ParametersDto parametersDto, ValidationResultBuilder validationResultBuilder) { LOGGER.debug("ParametersDto: {}", parametersDto); AwsParametersDto awsParametersDto = parametersDto.getAwsParametersDto(); if (Objects.isNull(awsParametersDto)) { LOGGER.debug("No aws parameters defined."); return validationResultBuilder.build(); } if (StringUtils.isNotBlank(awsParametersDto.getS3GuardTableName())) { LOGGER.debug("S3Guard table name defined: {}", awsParametersDto.getS3GuardTableName()); boolean tableAlreadyAttached = isTableAlreadyAttached(environmentDto, awsParametersDto); if (tableAlreadyAttached) { validationResultBuilder.error(String.format("S3Guard table '%s' is already attached to another active environment. " + "Please select another unattached table or specify a non-existing name to create it.", awsParametersDto.getS3GuardTableName())); } else { determineAwsParameters(environmentDto, parametersDto); } } if (awsParametersDto.getFreeIpaSpotPercentage() < PERCENTAGE_MIN || awsParametersDto.getFreeIpaSpotPercentage() > PERCENTAGE_MAX) { validationResultBuilder.error(String.format("FreeIpa spot percentage must be between %d and %d.", PERCENTAGE_MIN, PERCENTAGE_MAX)); } return validationResultBuilder.build(); }
Source:
<code>public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { if (viewType == RowType.PROGRESS) { return new RecyclerView.ViewHolder(LayoutInflater. from(parent.getContext()). inflate(R.layout.list_view_footer_progress, parent, false)) { }; } @LayoutRes <START> int layout = R.layout.row_discussion_comments_comment; <END> if (viewType == RowType.RESPONSE) { layout = R.layout.row_discussion_comments_response; } return new ResponseAndCommentViewHolder(LayoutInflater. from(parent.getContext()). inflate(layout, parent, false)); }</code><technical_language>This assignment in else clause I suppose. declared final in case</technical_language>

Target:
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { if (viewType == RowType.PROGRESS) { return new RecyclerView.ViewHolder(LayoutInflater. from(parent.getContext()). inflate(R.layout.list_view_footer_progress, parent, false)) { }; } @LayoutRes final int layout; if (viewType == RowType.RESPONSE) { layout = R.layout.row_discussion_comments_response; } else { layout = R.layout.row_discussion_comments_comment; } return new ResponseOrCommentViewHolder(LayoutInflater. from(parent.getContext()). inflate(layout, parent, false)); }
Source:
<code>public MessageMonitor<? extends Message<?>> registerComponent(Class<?> componentType, String componentName) { if (EventProcessor.class.isAssignableFrom(componentType)) { <START> return registerEventProcessor(EVENT_PROCESSOR_METRICS_NAME, <END> message -> Tags.of(TagsUtil.PAYLOAD_TYPE_TAG, message.getPayloadType().getSimpleName(), TagsUtil.PROCESSOR_NAME_TAG, componentName)); } if (CommandBus.class.isAssignableFrom(componentType)) { return registerCommandBus(componentName); } if (EventBus.class.isAssignableFrom(componentType)) { return registerEventBus(componentName); } if (QueryBus.class.isAssignableFrom(componentType)) { return registerQueryBus(componentName); } logger.warn("Cannot provide MessageMonitor for component of type [{}]. Returning No-Op instance.", componentName, componentType.getSimpleName()); return NoOpMessageMonitor.instance(); }</code><technical_language>Understand this, I this is overly ideal... add a toggle in GlobalMetricRegistry dimensions yes/no? default, approach, if builds a new GlobalMetricRegistry(metricRegistry, {yes-to-dimensions!}) this dimension logic added? way, users switch for command, event query bus GlobalMetricRegistry. a step spring auto configuration, this a property set application.properties/application.yml, making easier. Adding this done MetricsProperties class, a subclass Micrometer added config is for Micrometer only. do think</technical_language>

Target:
public MessageMonitor<? extends Message<?>> registerComponent(Class<?> componentType, String componentName) { if (EventProcessor.class.isAssignableFrom(componentType)) { return registerEventProcessor(componentName); } if (CommandBus.class.isAssignableFrom(componentType)) { return registerCommandBus(componentName); } if (EventBus.class.isAssignableFrom(componentType)) { return registerEventBus(componentName); } if (QueryBus.class.isAssignableFrom(componentType)) { return registerQueryBus(componentName); } logger.warn("Cannot provide MessageMonitor for component of type [{}]. Returning No-Op instance.", componentName, componentType.getSimpleName()); return NoOpMessageMonitor.instance(); }
Source:
<code><START> public void testWatcherDisconnectOnClose() throws Exception { <END> ZooKeeper zk = null; try { final BlockingQueue<WatchedEvent> queue = new LinkedBlockingQueue<>(); MyWatcher connWatcher = new MyWatcher(); Watcher watcher = new Watcher() { @Override public void process(WatchedEvent event) { try { queue.put(event); } catch (InterruptedException e) { } } }; zk = createClient(connWatcher, hostPort); StatCallback scb = new StatCallback() { public void processResult(int rc, String path, Object ctx, Stat stat) { } }; zk.exists("/missing", watcher, scb, null); zk.close(); WatchedEvent event = queue.poll(10, TimeUnit.SECONDS); Assert.assertNotNull( "No watch event was received after closing the Zookeeper client. " + "A 'Closed' event should have occurred", event); Assert.assertEquals( "Closed events are not generated by the server, " + "and so should have a type of 'None'", Event.EventType.None, event.getType()); Assert.assertEquals( "A 'Closed' event was expected as the Zookeeper client was closed " + "without altering the node it was watching", Event.KeeperState.Closed, event.getState()); } finally { if (zk != null) { zk.close(); } } }</code><technical_language>Unnecessary exception type change</technical_language>

Target:
public void testWatcherDisconnectOnClose() throws IOException, InterruptedException, KeeperException { ZooKeeper zk = null; try { final BlockingQueue<WatchedEvent> queue = new LinkedBlockingQueue<>(); MyWatcher connWatcher = new MyWatcher(); Watcher watcher = new Watcher() { @Override public void process(WatchedEvent event) { try { queue.put(event); } catch (InterruptedException e) { } } }; zk = createClient(connWatcher, hostPort); StatCallback scb = new StatCallback() { public void processResult(int rc, String path, Object ctx, Stat stat) { } }; zk.exists("/missing", watcher, scb, null); zk.close(); WatchedEvent event = queue.poll(10, TimeUnit.SECONDS); assertNotNull("No watch event was received after closing the Zookeeper client. A 'Closed' event should have occurred", event); assertEquals("Closed events are not generated by the server, and so should have a type of 'None'", Event.EventType.None, event.getType()); assertEquals("A 'Closed' event was expected as the Zookeeper client was closed without altering the node it was watching", Event.KeeperState.Closed, event.getState()); } finally { if (zk != null) { zk.close(); } } }
Source:
<code>public static boolean checkVlanUriOverlap(final String vlanRange1, final String vlanRange2) { final List<Integer> vlans1 = expandVlanUri(vlanRange1); final List<Integer> vlans2 = expandVlanUri(vlanRange2); if (vlans1 == null || vlans2 == null) { return true; <START> } <END> for (final Integer vlan1: vlans1) { if (vlans2.contains(vlan1)) { return true; } } return false; }</code><technical_language>if of is null, result is true? This means overlap</technical_language>

Target:
public static boolean checkVlanUriOverlap(final String vlanRange1, final String vlanRange2) { final List<Integer> vlans1 = expandVlanUri(vlanRange1); final List<Integer> vlans2 = expandVlanUri(vlanRange2); if (vlans1 == null || vlans2 == null) { return true; } return !Collections.disjoint(vlans1, vlans2); }
Source:
<code>protected void onCreate(Bundle savedInstanceState) { Utilities.setActivityTheme(this, getApplicationContext()); super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_entry); mAmountView = (EditText) findViewById(R.id.entry_amount); mBudgetView = (Spinner) findViewById(R.id.spinner_budget); mDateView = (DatePicker) findViewById(R.id.entry_date_picker); mNotesView = (EditText) findViewById(R.id.entry_notes); mAddButtonView = (Button) findViewById(R.id.add_entry_button); addItemsToBudgetSpinner(); getIntent().setAction("Already created"); Bundle bundle = getIntent().getExtras(); <START> if (bundle.getBoolean("Add")) { <END> setTitle(MessageFormat.format(getTitle().toString(), getString(R.string.title_entry_add))); mAddButtonView.setText(getString(R.string.entry_activity_button_add)); } else { setTitle(MessageFormat.format(getTitle().toString(), getString(R.string.title_entry_edit))); mAddButtonView.setText(getString(R.string.entry_activity_button_edit)); Budget b = Budget.getBudgetById(bundle.getLong("BudgetId")); Entry e = b.getEntryById(bundle.getLong("EntryId")); mAmountView.setText(e.getAmount()); LocalDate date = e.getDate(); mDateView.updateDate(date.getYear(), date.getMonthOfYear(), date.getDayOfMonth()); mNotesView.setText(e.getNotes()); ArrayAdapter<String> editAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, new String[]{b.getName()}); mBudgetView.setAdapter(editAdapter); mBudgetView.setEnabled(false); } }</code><technical_language>I this if (bundle.getBoolean("Add", true)), want sort of default "Add" in case this activity setting Bundle</technical_language>

Target:
protected void onCreate(Bundle savedInstanceState) { Utilities.setActivityTheme(this, getApplicationContext()); super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_entry); mAmountView = (EditText) findViewById(R.id.entry_amount); mBudgetView = (Spinner) findViewById(R.id.spinner_budget); mDateView = (DatePicker) findViewById(R.id.entry_date_picker); mNotesView = (EditText) findViewById(R.id.entry_notes); mAddButtonView = (Button) findViewById(R.id.add_entry_button); addItemsToBudgetSpinner(); Bundle bundle = getIntent().getExtras(); addMode = bundle.getBoolean("Add", true); if (addMode) { setTitle(MessageFormat.format(getTitle().toString(), getString(R.string.title_entry_add))); mAddButtonView.setText(getString(R.string.entry_activity_button_add)); } else { setTitle(MessageFormat.format(getTitle().toString(), getString(R.string.title_entry_edit))); mAddButtonView.setText(getString(R.string.entry_activity_button_edit)); Budget b = Budget.getBudgetById(bundle.getLong("BudgetId")); Entry e = b.getEntryById(bundle.getLong("EntryId")); mAmountView.setText(e.getAmount()); LocalDate date = e.getDate(); mDateView.updateDate(date.getYear(), date.getMonthOfYear(), date.getDayOfMonth()); mNotesView.setText(e.getNotes()); ArrayAdapter<String> editAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, new String[]{b.getName()}); mBudgetView.setAdapter(editAdapter); mBudgetView.setEnabled(false); } getIntent().setAction("Already created"); }
Source:
<code>public void init() { MockitoAnnotations.initMocks(this); tasksSyncJob = Mockito.spy(GlusterTasksSyncJob.getInstance()); logUtil = Mockito.spy(GlusterAuditLogUtil.getInstance()); tasksSyncJob.setLogUtil(logUtil); doReturn(clusterDao).when(tasksSyncJob).getClusterDao(); doReturn(getClusters()).when(clusterDao).getAll(); doReturn(provider).when(tasksSyncJob).getProvider(); doReturn(stepDao).when(tasksSyncJob).getStepDao(); doReturn(volumeDao).when(tasksSyncJob).getVolumeDao(); doReturn(jobRepository).when(tasksSyncJob).getJobRepository(); doReturn(backend).when(tasksSyncJob).getBackend(); doNothing().when(tasksSyncJob).releaseLock(any(Guid.class)); doNothing().when(tasksSyncJob).endStepJob(any(Step.class)); <START> doNothing().when(tasksSyncJob).logMessage(any(Guid.class), any(GlusterVolumeEntity.class), any(String.class), any(String.class), any(AuditLogType.class)); <END> doNothing().when(logUtil).logAuditMessage(any(Guid.class), any(GlusterVolumeEntity.class), any(VDS.class), any(AuditLogType.class), any(Map.class)); }</code><technical_language>line is required</technical_language>

Target:
public void init() { MockitoAnnotations.initMocks(this); tasksSyncJob = Mockito.spy(GlusterTasksSyncJob.getInstance()); logUtil = Mockito.spy(GlusterAuditLogUtil.getInstance()); doNothing().when(logUtil).logClusterMessage(any(Guid.class), any(AuditLogType.class)); doReturn(clusterDao).when(tasksSyncJob).getClusterDao(); doReturn(getClusters()).when(clusterDao).getAll(); doReturn(provider).when(tasksSyncJob).getProvider(); doReturn(stepDao).when(tasksSyncJob).getStepDao(); doReturn(volumeDao).when(tasksSyncJob).getVolumeDao(); doReturn(jobRepository).when(tasksSyncJob).getJobRepository(); doReturn(backend).when(tasksSyncJob).getBackend(); doNothing().when(tasksSyncJob).releaseLock(any(Guid.class)); doNothing().when(tasksSyncJob).endStepJob(any(Step.class)); doNothing().when(tasksSyncJob).eventMessageLogger(any(GlusterAsyncTask.class), any(JobExecutionStatus.class), any(VDSGroup.class)); }
Source:
<code>public void end() { <START> if (mStarted) { <END> if (mOutcome == null) { mOutcome = Outcome.CANCEL; } Map<String, Object> properties = getCommonProperties(); properties.put(KEY_OUTCOME, mOutcome.toString().toLowerCase(Locale.ROOT)); AnalyticsTracker.track(Stat.EDITOR_SESSION_END, properties); } }</code><technical_language>Calling end() if started is error condition? If yes, wdyt logging a message if started</technical_language>

Target:
public void end() { if (mStarted) { if (mOutcome == null) { mOutcome = Outcome.CANCEL; } Map<String, Object> properties = getCommonProperties(); properties.put(KEY_OUTCOME, mOutcome.toString().toLowerCase(Locale.ROOT)); AnalyticsTracker.track(Stat.EDITOR_SESSION_END, properties); } else { AppLog.e(T.EDITOR, "A non-started editor session cannot be attempted to be ended"); } }
Source:
<code>private GestureDetector.SimpleOnGestureListener createTapListener(final int position) { return new GestureDetector.SimpleOnGestureListener() { @Override public void onLongPress(MotionEvent e) { <START> Log.d("plamenko", "onLongPress: " + position); <END> } }; }</code><technical_language>haha, replace tag :)</technical_language>

Target:
private GestureDetector.SimpleOnGestureListener createTapListener(final int position) { return new GestureDetector.SimpleOnGestureListener() { @Override public void onLongPress(MotionEvent e) { Log.d("MyPagerAdapter", "onLongPress: " + position); } }; }
Source:
<code>public static <Arg1, Arg2 extends Arg1> boolean nullSafeEquals(Arg1 d1, Arg2 d2) { if (d1 == null) { return d2 == null; } else if (d2 == null) { return false; } <START> return (d1 instanceof Timestamp || d2 instanceof Timestamp) ? compare((Date) d1, (Date) d2) == 0 : d1.equals(d2); <END> }</code><technical_language>better</technical_language>

Target:
public static <Arg1, Arg2 extends Arg1> boolean nullSafeEquals(Arg1 d1, Arg2 d2) { if (d1 == null) { return d2 == null; } else if (d2 == null) { return false; } return (d1 instanceof Date && d2 instanceof Date) ? compare((Date) d1, (Date) d2) == 0 : d1.equals(d2); }
Source:
<code>public static <T, F> void setPrivateField( T obj, Class<T> objClass, Class<F> fieldClass, F fieldValue) { Field targetField = null; Field[] classFields = objClass.getDeclaredFields(); for (Field f : classFields) { if (f.getType().equals(fieldClass)) { if (targetField != null) { throw new IllegalStateException("Class " + objClass + " has multiple fields of type " + fieldClass); } targetField = f; } } <START> <END> if (targetField == null) { throw new IllegalStateException("Class " + objClass + " has no fields of type " + fieldClass); } targetField.setAccessible(true); try { targetField.set(obj, fieldValue); } catch (IllegalAccessException e) { Log.w(TAG, "Error setting field", e); } }</code><technical_language>Nit: extra space & I name f "field" instead</technical_language>

Target:
public static <T, F> void setPrivateField( T obj, Class<T> objClass, Class<F> fieldClass, F fieldValue) { Field targetField = null; Field[] classFields = objClass.getDeclaredFields(); for (Field field : classFields) { if (field.getType().equals(fieldClass)) { if (targetField != null) { throw new IllegalStateException("Class " + objClass + " has multiple fields of type " + fieldClass); } targetField = field; } } if (targetField == null) { throw new IllegalStateException("Class " + objClass + " has no fields of type " + fieldClass); } targetField.setAccessible(true); try { targetField.set(obj, fieldValue); } catch (IllegalAccessException e) { Log.w(TAG, "Error setting field", e); } }
Source:
<code>private static void serializeMap(JsonObject root, String key, Map<String, ?> map) { final JsonObject jsonObject = new JsonObject(); for (Entry<String, ?> e : map.entrySet()) { <START> jsonObject.add(e.getKey(), ((JsonSerializable) e.getValue()).toJson()); <END> } root.add(key, jsonObject); }</code><technical_language>safe side, I add a type check here, want stat prevent others in case of a casting error</technical_language>

Target:
private static void serializeMap(JsonObject root, String key, Map<String, ?> map) { final JsonObject jsonObject = new JsonObject(); for (Entry<String, ?> e : map.entrySet()) { addJsonIfSerializable(jsonObject, e.getKey(), e.getValue()); } root.add(key, jsonObject); }
Source:
<code>public RepositoryFileAclDto getMetadataAcl( String domainId ) throws PentahoAccessControlException, FileNotFoundException { checkMetadataExists( domainId ); if ( aclMetadataHelper != null ) { final RepositoryFile domainRepositoryFile = aclMetadataHelper.getDomainRepositoryFile( domainId ); <START> final RepositoryFileAcl acl = aclMetadataHelper.getAclHelper().getAclFor( domainRepositoryFile ); <END> return acl == null ? null : repositoryFileAclAdapter.marshal( acl ); } return null; }</code><technical_language>A couple things. I getAclHelper(). methods ACL Aware interfaces directly. getAclFor( RepositoryFile): Move this ACLAware interface change domainId String if possible. I fetching RepositoryFile passing in, interface logical DomainID</technical_language>

Target:
public RepositoryFileAclDto getMetadataAcl( String domainId ) throws PentahoAccessControlException, FileNotFoundException { checkMetadataExists( domainId ); if ( aclAwarePentahoMetadataDomainRepositoryImporter != null ) { final RepositoryFileAcl acl = aclAwarePentahoMetadataDomainRepositoryImporter.getAclFor( domainId ); return acl == null ? null : repositoryFileAclAdapter.marshal( acl ); } return null; }
Source:
<code>public Optional<DMNIncludeModel> create(final Path path) { try { <START> final String fileName = path.getFileName(); <END> final String modelPackage = getPackage(path); final String pathURI = path.toURI(); final String namespace = getNamespace(path); return Optional.of(new DMNIncludeModel(fileName, modelPackage, pathURI, namespace)); } catch (final Exception e) { return Optional.empty(); } }</code><technical_language>Path Package in Submarine.. is this meta-data essential</technical_language>

Target:
public DMNIncludeModel create(final Path path) throws DMNIncludeModelCouldNotBeCreatedException { try { final String fileName = path.getFileName(); final String modelPackage = getPackage(path); final String pathURI = path.toURI(); final String namespace = getNamespace(path); return new DMNIncludeModel(fileName, modelPackage, pathURI, namespace); } catch (final Exception e) { throw new DMNIncludeModelCouldNotBeCreatedException(); } }
Source:
<code>protected void run(Server server, User user, String commandLabel, String[] args) throws Exception { final Trade charge = new Trade(this.getName(), ess); charge.isAffordableFor(user); RandomTeleport randomTeleport = ess.getRandomTeleport(); UserRandomTeleportEvent event = new UserRandomTeleportEvent(user, randomTeleport.getCenter(), randomTeleport.getMinRange(), randomTeleport.getMaxRange()); server.getPluginManager().callEvent(event); if (event.isCancelled()) { return; } <START> Location center = event.getCenter(); double minRange = event.getMinRange(); double maxRange = event.getMaxRange(); <END> getRandomLocation(randomTeleport, center, minRange, maxRange).thenAccept(location -> { CompletableFuture<Boolean> future = getNewExceptionFuture(user.getSource(), commandLabel); user.getAsyncTeleport().teleport(location, charge, PlayerTeleportEvent.TeleportCause.COMMAND, future); future.thenAccept(success -> { if (success) { user.sendMessage(tl("tprSuccess")); } }); }); }</code><technical_language>this inlined</technical_language>

Target:
protected void run(Server server, User user, String commandLabel, String[] args) throws Exception { final Trade charge = new Trade(this.getName(), ess); charge.isAffordableFor(user); RandomTeleport randomTeleport = ess.getRandomTeleport(); UserRandomTeleportEvent event = new UserRandomTeleportEvent(user, randomTeleport.getCenter(), randomTeleport.getMinRange(), randomTeleport.getMaxRange()); server.getPluginManager().callEvent(event); if (event.isCancelled()) { return; } randomTeleport.getRandomLocation(event.getCenter(), event.getMinRange(), event.getMaxRange()).thenAccept(location -> { CompletableFuture<Boolean> future = getNewExceptionFuture(user.getSource(), commandLabel); user.getAsyncTeleport().teleport(location, charge, PlayerTeleportEvent.TeleportCause.COMMAND, future); future.thenAccept(success -> { if (success) { user.sendMessage(tl("tprSuccess")); } }); }); }
Source:
<code>public List<MetricFamilySamples> collect() { List<MetricFamilySamples> mfs = new ArrayList<MetricFamilySamples>(); try { Long processCpuTime = callLongGetter("getProcessCpuTime", osBean); mfs.add(new CounterMetricFamily("process_cpu_seconds_total", "Total user and system CPU time spent in seconds.", processCpuTime / NANOSECONDS_PER_SECOND)); } catch (Exception e) { LOGGER.log(Level.FINE,"Could not access process cpu time", e); } mfs.add(new GaugeMetricFamily("process_start_time_seconds", "Start time of the process since unix epoch in seconds.", runtimeBean.getStartTime() / MILLISECONDS_PER_SECOND)); try { Long openFdCount = callLongGetter("getOpenFileDescriptorCount", osBean); mfs.add(new GaugeMetricFamily( "process_open_fds", "Number of open file descriptors.", openFdCount)); Long maxFdCount = callLongGetter("getMaxFileDescriptorCount", osBean); mfs.add(new GaugeMetricFamily( "process_max_fds", "Maximum number of open file descriptors.", maxFdCount)); } catch (Exception e) { <START> LOGGER.log(Level.FINE, "Could not access file descriptor metrics", e); <END> } if (linux) { try { collectMemoryMetricsLinux(mfs); } catch (Exception e) { LOGGER.warning(e.toString()); } } return mfs; }</code><technical_language>This is spammy non-unix systems</technical_language>

Target:
public List<MetricFamilySamples> collect() { List<MetricFamilySamples> mfs = new ArrayList<MetricFamilySamples>(); try { Long processCpuTime = callLongGetter("getProcessCpuTime", osBean); mfs.add(new CounterMetricFamily("process_cpu_seconds_total", "Total user and system CPU time spent in seconds.", processCpuTime / NANOSECONDS_PER_SECOND)); } catch (Exception e) { LOGGER.log(Level.FINE,"Could not access process cpu time", e); } mfs.add(new GaugeMetricFamily("process_start_time_seconds", "Start time of the process since unix epoch in seconds.", runtimeBean.getStartTime() / MILLISECONDS_PER_SECOND)); try { Long openFdCount = callLongGetter("getOpenFileDescriptorCount", osBean); mfs.add(new GaugeMetricFamily( "process_open_fds", "Number of open file descriptors.", openFdCount)); Long maxFdCount = callLongGetter("getMaxFileDescriptorCount", osBean); mfs.add(new GaugeMetricFamily( "process_max_fds", "Maximum number of open file descriptors.", maxFdCount)); } catch (Exception e) { } if (linux) { try { collectMemoryMetricsLinux(mfs); } catch (Exception e) { LOGGER.warning(e.toString()); } } return mfs; }
Source:
<code>public TemplateStore getCodeTemplateStore() { if (fCodeTemplateStore == null) { Promise<TemplateStore> p = getTemplateStoreInitializer().getTemplateStore(); try { fCodeTemplateStore = p.getValue(); } catch (InvocationTargetException e) { log(e); } catch (InterruptedException e) { log(e); } } return <START> fCodeTemplateStore; <END> }</code><technical_language>In error case, field remain initialized. I expect in case simply initialize "in place", promises etc</technical_language>

Target:
public TemplateStore getCodeTemplateStore() { if (fCodeTemplateStore == null) { Promise<TemplateStore> p= getTemplateStoreInitializer().getTemplateStore(); try { fCodeTemplateStore= p.getValue(); } catch (InvocationTargetException | InterruptedException e) { fCodeTemplateStore= getTemplateStoreInitializer().loadTemplateStore(); log(e); } } return fCodeTemplateStore; }
Source:
<code>public FileHeader createFileHeader(DiffEntry ent) throws IOException, CorruptObjectException, MissingObjectException { ByteArrayOutputStream buf = new ByteArrayOutputStream(); final EditList editList; writeDiffHeader(buf, ent); if (ent.getOldMode() == GITLINK || ent.getNewMode() == GITLINK) { writeGitLinkDiffText(buf, ent); editList = new EditList(); } else { byte[] aRaw = open(ent.getOldMode(), ent.getOldId()); byte[] bRaw = open(ent.getNewMode(), ent.getNewId()); if (RawText.isBinary(aRaw) || RawText.isBinary(bRaw)) { buf.write(encodeASCII("Binary files differ\n")); editList = new EditList(); } else { RawText a = rawTextFactory.create(aRaw); RawText b = rawTextFactory.create(bRaw); editList = new MyersDiff(a, b).getEdits(); } } <START> buf.flush(); <END> return new FileHeader(buf.toByteArray(), editList); }</code><technical_language>Flush necessary, a no-op a ByteArrayOutputStream</technical_language>

Target:
public FileHeader createFileHeader(DiffEntry ent) throws IOException, CorruptObjectException, MissingObjectException { ByteArrayOutputStream buf = new ByteArrayOutputStream(); final EditList editList; final FileHeader.PatchType type; writeDiffHeader(buf, ent); if (ent.getOldMode() == GITLINK || ent.getNewMode() == GITLINK) { writeGitLinkDiffText(buf, ent); editList = new EditList(); type = PatchType.UNIFIED; } else { byte[] aRaw = open(ent.getOldMode(), ent.getOldId()); byte[] bRaw = open(ent.getNewMode(), ent.getNewId()); if (RawText.isBinary(aRaw) || RawText.isBinary(bRaw)) { buf.write(encodeASCII("Binary files differ\n")); editList = new EditList(); type = PatchType.BINARY; } else { RawText a = rawTextFactory.create(aRaw); RawText b = rawTextFactory.create(bRaw); editList = new MyersDiff(a, b).getEdits(); type = PatchType.UNIFIED; } } return new FileHeader(buf.toByteArray(), editList, type); }
Source:
<code>public String getRyukImage() { <START> return (String) properties.getOrDefault("ryuk.container.image", "testcontainersofficial/ryuk:latest"); <END> }</code><technical_language>suggestion return (String) properties.getOrDefault("ryuk.container.image", "testcontainersofficial/ryuk:0.3.0");</technical_language>

Target:
public String getRyukImage() { return (String) properties.getOrDefault("ryuk.container.image", "testcontainersofficial/ryuk:0.3.0"); }
Source:
<code>private static void demonstrateTreasureChestIteratorForType(ItemType itemType) { LOGGER.info("------------------------"); LOGGER.info("Item Iterator for ItemType " + itemType + ": "); <START> Iterator itemIterator = TREASURE_CHEST.iterator(itemType); <END> while (itemIterator.hasNext()) { LOGGER.info(itemIterator.next().toString()); } }</code><technical_language>Raw type: Iterator<Item> returned TREASURE_CHEST.iterator()</technical_language>

Target:
private static void demonstrateTreasureChestIteratorForType(ItemType itemType) { LOGGER.info("------------------------"); LOGGER.info("Item Iterator for ItemType " + itemType + ": "); Iterator<Item> itemIterator = TREASURE_CHEST.iterator(itemType); while (itemIterator.hasNext()) { LOGGER.info(itemIterator.next().toString()); } }
Source:
<code>public List<String> getRecipientsTextDropdown(int qnNumber, int responseNumber) { Select selectElement = new Select(browser.driver.findElement( By.name(Const.ParamsNames.FEEDBACK_RESPONSE_RECIPIENT + "-" + qnNumber + "-" + responseNumber))); List<WebElement> optionElements = selectElement.getOptions(); <START> List<String> recipients = new ArrayList<String>(); <END> for (WebElement option : optionElements) { recipients.add(option.getText()); } return recipients; }</code><technical_language>new ArrayList<>()</technical_language>

Target:
public List<String> getRecipientsTextDropdown(int qnNumber, int responseNumber) { Select selectElement = new Select(browser.driver.findElement( By.name(Const.ParamsNames.FEEDBACK_RESPONSE_RECIPIENT + "-" + qnNumber + "-" + responseNumber))); List<WebElement> optionElements = selectElement.getOptions(); List<String> recipients = new ArrayList<>(); for (WebElement option : optionElements) { recipients.add(option.getText()); } return recipients; }
Source:
<code>public static DevelopersApi api() { <START> HOST = "https://localhost:8443"; END> ApiClient apiClient = new ApiClient(); apiClient.setBasePath(HOST); apiClient.setVerifyingSsl(false); apiClient.setDebugging(true); return new DevelopersApi(apiClient); }</code><technical_language>do need this line? SetupTest sets setupHosts method, ? methods cleaner: Tester.setHost(host); Tester.setOpHost(opHost); Test.setupHosts(host, opHost)</technical_language>

Target:
public static DevelopersApi api() { ApiClient apiClient = new ApiClient(); apiClient.setBasePath(HOST); apiClient.setVerifyingSsl(false); apiClient.setDebugging(true); return new DevelopersApi(apiClient); }
Source:
<code>private IPageChangingListener onPageChanging(IWizardHandle wizardHandle) { return new IPageChangingListener() { @Override public void handlePageChanging(PageChangingEvent event) { if (event.getCurrentPage() == getPage(wizardHandle)){ if (event.getTargetPage() == null || event.getTargetPage().equals(getPage(wizardHandle).getNextPage())) { <START> String blockedMsg = null; <END> try { if( selectedConnection != null && selectedConnection.canConnect()) { Job connectJob = chooseConnectionComposite.getConnectJob(); WizardUtils.runInWizard( connectJob, new DelegatingProgressMonitor(), getContainer(((WizardPage)handle))); boolean connected = JobUtils.isOk(connectJob.getResult()); if( !connected ) { blockedMsg = connectJob.getResult().getMessage(); } } } catch(Exception e) { blockedMsg = "Error while checking if we can connect to OpenShift Connection: " + e.getMessage(); } if(blockedMsg != null ) { event.doit = false; handle.setMessage(blockedMsg, IMessageProvider.ERROR); } else { handle.setMessage(null, IMessageProvider.NONE); } } if (selectedConnection instanceof Connection) { OpenShiftServerTaskModelAccessor.set((Connection) selectedConnection, getTaskModel()); } } } }; }</code><technical_language>![CRITICAL](<LINK_1> 'Severity: CRITICAL') Refactor this method reduce Cognitive Complexity 17 15 allowed. [![rule](<LINK_2>](<LINK_0></technical_language>

Target:
private IPageChangingListener onPageChanging(IWizardHandle wizardHandle) { return new IPageChangingListener() { @Override public void handlePageChanging(PageChangingEvent event) { if (event.getCurrentPage() == getPage(wizardHandle)){ if (event.getTargetPage() == null || event.getTargetPage().equals(getPage(wizardHandle).getNextPage())) { String blockedMsg = null; try { blockedMsg = runConnectionJob(); } catch(Exception e) { blockedMsg = "Error while checking if we can connect to OpenShift Connection: " + e.getMessage(); } event.doit = (blockedMsg == null); handle.setMessage(blockedMsg, (blockedMsg == null ? IMessageProvider.NONE : IMessageProvider.ERROR)); } if (selectedConnection instanceof Connection) { OpenShiftServerTaskModelAccessor.set((Connection) selectedConnection, getTaskModel()); } } } }; }
Source:
<code>public void hashCode_withoutAddress() throws Exception { <START> assertEquals(0, Address.parse("name only").length); <END> }</code><technical_language>try arrange, act, assert pattern empty line block. In this case "arrange" necessary. want separate "act" "assert"</technical_language>

Target:
public void hashCode_withoutAddress() throws Exception { Address[] addresses = Address.parse("name only"); assertEquals(0, addresses.length); }
Source:
<code>public Map<String, String> provide(Network network, String networkId, Collection<String> subnetIds) { Map<String, String> filter = new HashMap<>(); if (network.getAttributes() != null && network.getAttributes().getMap() != null) { Map<String, Object> attributes = network.getAttributes().getMap(); <START> String sharedProjectId = (String) attributes.get("sharedProjectId"); filter.put("sharedProjectId", sharedProjectId); <END> filter.put("networkId", networkId); buildSubnetIdFilter(subnetIds, filter); } return filter; }</code><technical_language>this constant refactored a field avoid duplication</technical_language>

Target:
public Map<String, String> provide(Network network, String networkId, Collection<String> subnetIds) { Map<String, String> filter = new HashMap<>(); if (network.getAttributes() != null && network.getAttributes().getMap() != null) { Map<String, Object> attributes = network.getAttributes().getMap(); String sharedProjectId = (String) attributes.get(SHARED_PROJECT_ID); if (!Strings.isNullOrEmpty(sharedProjectId)) { filter.put(SHARED_PROJECT_ID, sharedProjectId); } } filter.put("networkId", networkId); filter.putAll(buildSubnetIdFilter(subnetIds)); return filter; }
Source:
<code>public Boolean call() throws Exception { <START> return Files.toString(jmxTransAppStdOut, Charset.forName("UTF-8")).contains(value); <END> }</code><technical_language>Guava's Charsets.UTF_8 in place of literal "UTF-8" (note this code disappear if run jmxtrans in process)</technical_language>

Target:
public Boolean call() throws Exception { return Files.toString(jmxTransAppStdOut, Charsets.UTF_8).contains(value); }
Source:
<code>private void setLbToPendingUpdate(LoadBalancer lb) throws EntityNotFoundException, UnprocessableEntityException, ImmutableEntityException { if (!loadBalancerRepository.testAndSetStatus(lb.getAccountId(), lb.getId(), LoadBalancerStatus.PENDING_UPDATE, false)) { <START> String message = StringHelper.immutableLoadBalancer(lb); <END> LOG.warn(message); throw new ImmutableEntityException(message); } else { loadBalancerStatusHistoryService.save(lb.getAccountId(), lb.getId(), LoadBalancerStatus.PENDING_UPDATE); } }</code><technical_language>is a bug in String helper, LB is populated entirely. message returned 'null' status</technical_language>

Target:
private void setLbToPendingUpdate(LoadBalancer lb) throws EntityNotFoundException, UnprocessableEntityException, ImmutableEntityException { lb = loadBalancerRepository.getById(lb.getId()); if (!loadBalancerRepository.testAndSetStatus(lb.getAccountId(), lb.getId(), LoadBalancerStatus.PENDING_UPDATE, false)) { String message = StringHelper.immutableLoadBalancer(lb); LOG.warn(message); throw new ImmutableEntityException(message); } else { loadBalancerStatusHistoryService.save(lb.getAccountId(), lb.getId(), LoadBalancerStatus.PENDING_UPDATE); } }
Source:
<code>private List<Pair<Guid, Boolean>> disconnectOrConnectHostsInUpToDomainStorageServer(ActionType actionType) { List<VDS> hostsInStatusUp = getAllRunningVdssInPool(); List<Callable<Pair<Guid, Boolean>>> callables = new LinkedList<>(); for (final VDS vds : hostsInStatusUp) { callables.add(() -> { Pair<Guid, Boolean> toReturn = new Pair<>(vds.getId(), Boolean.FALSE); try { boolean connectResult = false; switch (actionType) { case CONNECT: connectResult = StorageHelperDirector.getInstance().getItem(getStorageDomain().getStorageType()) .connectStorageToDomainByVdsId(getStorageDomain(), vds.getId()); break; case DISCONNECT: <START> StorageHelperDirector.getInstance().getItem(getStorageDomain().getStorageType()) .disconnectStorageFromDomainByVdsId(getStorageDomain(), vds.getId()); <END> } toReturn.setSecond(connectResult); } catch (RuntimeException e) { log.error("Failed to host '{}' to storage domain (name '{}', id '{}'): {}", actionType.actionDescription, vds.getName(), getStorageDomain().getName(), getStorageDomain().getId(), e.getMessage()); log.debug("Exception", e); } return toReturn; }); } return ThreadPoolUtil.invokeAll(callables); }</code><technical_language>forgot assign connectResult</technical_language>

Target:
private List<Pair<Guid, Boolean>> disconnectOrConnectHostsInUpToDomainStorageServer(ActionType actionType) { List<VDS> hostsInStatusUp = getAllRunningVdssInPool(); List<Callable<Pair<Guid, Boolean>>> callables = new LinkedList<>(); for (final VDS vds : hostsInStatusUp) { callables.add(() -> { Pair<Guid, Boolean> toReturn = new Pair<>(vds.getId(), Boolean.FALSE); try { boolean connectResult = false; switch (actionType) { case CONNECT: connectResult = StorageHelperDirector.getInstance().getItem(getStorageDomain().getStorageType()) .connectStorageToDomainByVdsId(getStorageDomain(), vds.getId()); break; case DISCONNECT: connectResult = StorageHelperDirector.getInstance().getItem(getStorageDomain().getStorageType()) .disconnectStorageFromDomainByVdsId(getStorageDomain(), vds.getId()); } toReturn.setSecond(connectResult); } catch (RuntimeException e) { log.error("Failed to host '{}' to storage domain (name '{}', id '{}'): {}", actionType.actionDescription, vds.getName(), getStorageDomain().getName(), getStorageDomain().getId(), e.getMessage()); log.debug("Exception", e); } return toReturn; }); } return ThreadPoolUtil.invokeAll(callables); }
Source:
<code><START> ConditionalStreamListenerHandler(Expression condition, StreamListenerMessageHandler streamListenerMessageHandler) { <END> this.condition = condition; this.streamListenerMessageHandler = streamListenerMessageHandler; }</code><technical_language>ConditionalStreamListenerHandler non-null condition intermediate base class hold StreamListenerMessageHandler. way, instead of checking for conditiion == null for conditional stream listener handlers, type check ConditionalStreamListenerHandler</technical_language>

Target:
ConditionalStreamListenerHandler(Expression condition, StreamListenerMessageHandler streamListenerMessageHandler) { Assert.notNull(streamListenerMessageHandler, "the message handler cannot be null"); Assert.isTrue(condition == null || streamListenerMessageHandler.isVoid(), "cannot specify a condition and a return value at the same time"); this.condition = condition; this.streamListenerMessageHandler = streamListenerMessageHandler; }
Source:
<code>public void init() { <START> <END> infraProperties = getDeploymentProperties(); publisherURL = infraProperties.getProperty(PUBLISHER_URL); storeURL = infraProperties.getProperty(STORE_URL); if (publisherURL == null) { publisherURL = "https://localhost:9443/publisher"; } if (storeURL == null) { storeURL = "https://localhost:9443/store"; } setKeyStoreProperties(); apiPublisher = new APIPublisherRestClient(publisherURL); }</code><technical_language>do need logic, this is executed in parent constrcutor</technical_language>

Target:
public void init() { apiPublisher = new APIPublisherRestClient(publisherURL); }
Source:
<code>public String getPrivateLink(Context context, Account account) { <START> String parsedRemoteId = mRemoteId.substring(0, Math.min(mRemoteId.length(), 8)); <END> String fileId = Integer.valueOf(parsedRemoteId).toString(); String privateLink = null; try { String baseUrl = AccountUtils.getBaseUrlForAccount(context, account); if (baseUrl == null) throw new AccountUtils.AccountNotFoundException(account, "Account not found", null); privateLink = baseUrl + AccountUtils.INDEX_PATH + FILES_PATH + "/" + fileId; } catch (AccountUtils.AccountNotFoundException e) { Log_OC.d(TAG, e.toString()); } return privateLink; }</code><technical_language>Sorry, I understand conversion get string for private link</technical_language>

Target:
public String getPrivateLink(Context context, Account account) { String parsedRemoteId = mRemoteId.substring(0, FILE_ID_LENGTH); String fileId = Integer.valueOf(parsedRemoteId).toString(); String privateLink = null; try { String baseUrl = AccountUtils.getBaseUrlForAccount(context, account); if (baseUrl == null) throw new AccountUtils.AccountNotFoundException(account, "Account not found", null); privateLink = baseUrl + PRIVATE_LINK_PATH + fileId; } catch (AccountUtils.AccountNotFoundException e) { Log_OC.d(TAG, e.toString()); } return privateLink; }
Source:
<code>public void rollsBackTransaction() { final TestEntity testEntity = new TestEntity("description"); daoTestRule.inTransaction(() -> persist(testEntity)); testEntity.setDescription("newDescription"); try { daoTestRule.inTransaction(() -> { persist(testEntity); persist(new TestEntity(null)); }); <START> Assert.fail("Expected a constraint violation"); <END> } catch (ConstraintViolationException ignoredException) { final TestEntity sameTestEntity = get(testEntity.getId()); assertThat(sameTestEntity.getDescription()).isEqualTo("description"); } }</code><technical_language>want failBecauseExceptionWasNotThrown(ConstraintViolationException.class) instead</technical_language>

Target:
public void rollsBackTransaction() { final TestEntity testEntity = new TestEntity("description"); daoTestRule.inTransaction(() -> persist(testEntity)); testEntity.setDescription("newDescription"); try { daoTestRule.inTransaction(() -> { persist(testEntity); persist(new TestEntity(null)); }); failBecauseExceptionWasNotThrown(ConstraintViolationException.class); } catch (ConstraintViolationException ignoredException) { final TestEntity sameTestEntity = get(testEntity.getId()); assertThat(sameTestEntity.getDescription()).isEqualTo("description"); } }
Source:
<code>public boolean hasPathCapability(final Path path, final String capability) throws IOException { switch (validatePathCapabilityArgs(path, capability)) { case CommonPathCapabilities.FS_READ_ONLY_CONNECTOR: return true; default: <START> return false; <END> } }</code><technical_language>super.hasPathCapability(path, capability) here? delegate FileSystem's call, effectively difference (including supportAcls() call there), cleaner</technical_language>

Target:
public boolean hasPathCapability(final Path path, final String capability) throws IOException { switch (validatePathCapabilityArgs(path, capability)) { case CommonPathCapabilities.FS_READ_ONLY_CONNECTOR: return true; default: return super.hasPathCapability(path, capability); } }
Source:
<code>private void applyViewContext() { ViewContext viewContext = <START> fViewContext.get(fTrace); <END> applyExpandedStateContext(viewContext); if (fColumnComparators != null) { final Tree tree = fTimeGraphViewer.getTree(); final TreeColumn column = tree.getColumn(fCurrentSortColumn); tree.setSortDirection(fSortDirection); tree.setSortColumn(column); } fTimeGraphViewer.getControl().setFocus(); if ((viewContext != null) && (viewContext.getSelection() != null)) { fTimeGraphViewer.setSelection(viewContext.getSelection(), true); } fViewContext.remove(fTrace); }</code><technical_language>remove is equivalent get remove</technical_language>

Target:
private void applyViewContext() { ViewContext viewContext = fViewContext.remove(fTrace); applyExpandedStateContext(viewContext); if (fColumnComparators != null) { final Tree tree = fTimeGraphViewer.getTree(); final TreeColumn column = tree.getColumn(fCurrentSortColumn); tree.setSortDirection(fSortDirection); tree.setSortColumn(column); } fTimeGraphViewer.getControl().setFocus(); if ((viewContext != null) && (viewContext.getSelection() != null)) { fTimeGraphViewer.setSelection(viewContext.getSelection(), true); } }
Source:
<code>SupportLevel getEvidenceVerifySupport(Class<? extends Evidence> evidenceType, String algorithmName) throws RealmUnavailableException; boolean verifyEvidence(Evidence evidence) throws RealmUnavailableException; <START> default boolean checkEvidenceTrusted(Evidence evidence) throws RealmUnavailableException { <END> Assert.checkNotNullParam("evidence", evidence); if (! exists()) { return false; } if (evidence instanceof SecurityIdentityEvidence) { final SecurityIdentity evidenceIdentity = ((SecurityIdentityEvidence) evidence).getSecurityIdentity(); final RealmInfo evidenceRealmInfo = evidenceIdentity.getRealmInfo(); final SecurityRealm evidenceSecurityRealm = evidenceRealmInfo.getSecurityRealm(); return createdBySecurityRealm(evidenceSecurityRealm); } return false; }</code><technical_language>If do this realm level, worried this lead a lot of duplication and/or bizarre behavior. In discussions original concept I discussed ServerAuthenticationContext possibly determination of trust talking realm. Is a reason realm involved in this check</technical_language>

Target:
SupportLevel getEvidenceVerifySupport(Class<? extends Evidence> evidenceType, String algorithmName) throws RealmUnavailableException; boolean verifyEvidence(Evidence evidence) throws RealmUnavailableException; boolean exists() throws RealmUnavailableException; default void dispose() { }