auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void dispose() { fCurrentEntries = <START> checkNotNull(Collections.emptyList()); <END> fTableViewer = null; fComparator = null; }</code><technical_language>remove checkNotNull, external @NonNull annotation Collections.emptyList()</technical_language>

Target:
public void dispose() { fCurrentEntries = Collections.emptyList(); fTableViewer = null; fComparator = null; }
Source:
<code>private void setOperationObjectFromApiOperationAnnotation(Operation operation, io.swagger.oas.annotations.Operation apiOperation) { if (StringUtils.isNotBlank(apiOperation.summary())) { operation.setSummary(apiOperation.summary()); } if (StringUtils.isNotBlank(apiOperation.description())) { operation.setDescription(apiOperation.description()); } if (StringUtils.isNotBlank(apiOperation.operationId())) { operation.setOperationId(getOperationId(apiOperation.operationId())); } if (apiOperation.deprecated()) { operation.setDeprecated(apiOperation.deprecated()); } ReaderUtils.getStringListFromStringArray(apiOperation.tags()).ifPresent(operation::setTags); OperationParser.getTags(apiOperation.tags()).ifPresent(tag -> openApiTags.addAll(tag)); OperationParser.getExternalDocumentation(apiOperation.externalDocs()).ifPresent(operation::setExternalDocs); OperationParser.getRequestBody(apiOperation.requestBody()).ifPresent(operation::setRequestBody); <START> OperationParser.getApiResponses(apiOperation.responses()).ifPresent(operation::setResponses); <END> OperationParser.getServers(apiOperation.servers()).ifPresent(operation::setServers); OperationParser.getParametersList(apiOperation.parameters()).ifPresent(operation::setParameters); }</code><technical_language>Do a check if responses.size() is > 0 not. apiOperation.responses() is Empty empty map. avoid this: "responses": { "default": } want</technical_language>

Target:
private void setOperationObjectFromApiOperationAnnotation(Operation operation, io.swagger.oas.annotations.Operation apiOperation) { if (StringUtils.isNotBlank(apiOperation.summary())) { operation.setSummary(apiOperation.summary()); } if (StringUtils.isNotBlank(apiOperation.description())) { operation.setDescription(apiOperation.description()); } if (StringUtils.isNotBlank(apiOperation.operationId())) { operation.setOperationId(getOperationId(apiOperation.operationId())); } if (apiOperation.deprecated()) { operation.setDeprecated(apiOperation.deprecated()); } ReaderUtils.getStringListFromStringArray(apiOperation.tags()).ifPresent(operation::setTags); OperationParser.getTags(apiOperation.tags()).ifPresent(tag -> openApiTags.addAll(tag)); OperationParser.getExternalDocumentation(apiOperation.externalDocs()).ifPresent(operation::setExternalDocs); OperationParser.getRequestBody(apiOperation.requestBody(), components).ifPresent(operation::setRequestBody); OperationParser.getApiResponses(apiOperation.responses(), components).ifPresent(operation::setResponses); OperationParser.getServers(apiOperation.servers()).ifPresent(operation::setServers); OperationParser.getParametersList(apiOperation.parameters(), components).ifPresent(operation::setParameters); }
Source:
<code>public void deleteAll(){ for (Subject subject : subjectDataService.retrieveAll()){ <START> delete(subject); <END> } }</code><technical_language>subjectDataService.deleteAll() instead of this loop</technical_language>

Target:
public void deleteAll(){ subjectDataService.deleteAll(); }
Source:
<code>public Object readResolve() throws ObjectStreamException { try { Constructor<? extends SerializableObject> constructor = this.getClass().getConstructor(this.getClass()); try { constructor.setAccessible(true); } catch (SecurityException ex) { logger.warn("Accessing copy constructor failed.", constructor, ex); } try { return constructor.newInstance(this); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) { throw new RuntimeException("Instantiation using copy constructor failed!", ex); } } catch (NoSuchMethodException snme) { logger.debug("No copy constructor detected for class {}, trying default constructor.", this.getClass() <START> .getSimpleName()); <END> try { SerializableObject newInstance = this.getClass().newInstance(); transferStateTo(newInstance); return newInstance; } catch (IllegalAccessException | InstantiationException ex) { throw new RuntimeException("Deserialization using default constructor failed!", ex); } } }</code><technical_language>wrapped space dot</technical_language>

Target:
public Object readResolve() throws ObjectStreamException { try { Constructor<? extends SerializableObject> constructor = this.getClass().getConstructor(this.getClass()); try { constructor.setAccessible(true); } catch (SecurityException ex) { logger.warn("Accessing copy constructor failed.", constructor, ex); } try { return constructor.newInstance(this); } catch (ReflectiveOperationException ex) { throw new RuntimeException("Instantiation using copy constructor failed!", ex); } } catch (NoSuchMethodException snme) { logger.debug("No copy constructor detected for class {}, trying default constructor.", this.getClass().getSimpleName()); try { SerializableObject newInstance = this.getClass().newInstance(); transferStateTo(newInstance); return newInstance; } catch (IllegalAccessException | InstantiationException ex) { throw new RuntimeException("Deserialization using default constructor failed!", ex); } } }
Source:
<code>public ToolBar createControl(Composite parent, int orientation) { if (parent != null) { if (toolBarExist() && (parent != toolBar.getParent() || (orientation & toolBar.getStyle()) == 0)) { <START> dispose(); <END> } if (!toolBarExist()) { int style = itemStyle; if ((style & orientation) == 0) { style &= ~SWT.HORIZONTAL & ~SWT.VERTICAL; style |= orientation; } toolBar = new ToolBar(parent, style); toolBar.setMenu(getContextMenuControl()); update(true); toolBar.getAccessible().addAccessibleListener(getAccessibleListener()); } } return toolBar; }</code><technical_language>change semantics of createControl(*) dispose toolbar</technical_language>

Target:
public ToolBar createControl(Composite parent, int orientation) { if (parent != null) { boolean orientationChanged = (itemStyle & orientation) == 0; if (toolBarExist() && (parent != toolBar.getParent() || orientationChanged)) { dispose(); } if (!toolBarExist()) { if (orientationChanged) { itemStyle &= ~SWT.HORIZONTAL & ~SWT.VERTICAL; itemStyle |= orientation; } toolBar = new ToolBar(parent, itemStyle); toolBar.setMenu(getContextMenuControl()); update(true); toolBar.getAccessible().addAccessibleListener(getAccessibleListener()); } } return toolBar; }
Source:
<code>public Response undeployApiPost(String apiName, String version , String tenantDomain, MessageContext messageContext) { InMemoryAPIDeployer inMemoryApiDeployer = new InMemoryAPIDeployer(); if (tenantDomain == null){ <START> tenantDomain =SUPER_TENAT_DOMAIN; <END> } Map<String, String> apiAttributes = inMemoryApiDeployer.getGatewayAPIAttributes(apiName, version, tenantDomain); String apiId = apiAttributes.get(APIConstants.GatewayArtifactSynchronizer.API_ID); String label = apiAttributes.get(APIConstants.GatewayArtifactSynchronizer.LABEL); boolean status = inMemoryApiDeployer.unDeployAPI(apiId, label); JSONObject responseObj = new JSONObject(); if (status) { responseObj.put("Message", "Success"); String responseStringObj = String.valueOf(responseObj); return Response.ok().entity(responseStringObj).build(); } else { responseObj.put("Message", "Error"); String responseStringObj = String.valueOf(responseObj); return Response.serverError().entity(responseStringObj).build(); } }</code><technical_language>Formatting error</technical_language>

Target:
public Response undeployApiPost(String apiName, String version , String tenantDomain, MessageContext messageContext) { InMemoryAPIDeployer inMemoryApiDeployer = new InMemoryAPIDeployer(); if (tenantDomain == null) { tenantDomain = APIConstants.SUPER_TENANT_DOMAIN; } Map<String, String> apiAttributes = inMemoryApiDeployer.getGatewayAPIAttributes(apiName, version, tenantDomain); String apiId = apiAttributes.get(APIConstants.GatewayArtifactSynchronizer.API_ID); String label = apiAttributes.get(APIConstants.GatewayArtifactSynchronizer.LABEL); boolean status = inMemoryApiDeployer.unDeployAPI(apiId, label); JSONObject responseObj = new JSONObject(); if (status) { responseObj.put("Message", "Success"); String responseStringObj = String.valueOf(responseObj); return Response.ok().entity(responseStringObj).build(); } else { responseObj.put("Message", "Error"); String responseStringObj = String.valueOf(responseObj); return Response.serverError().entity(responseStringObj).build(); } }
Source:
<code>public void placeVisually() { AppCompatActivity activity = UiUtils.getActivityFromView(view); if (!(activity instanceof SpriteActivity)) { return; } Sprite currentSprite = ProjectManager.getInstance().getCurrentSprite(); Formula formulax = getFormulaWithBrickField(BrickField.X_POSITION); Formula formulay = getFormulaWithBrickField(BrickField.Y_POSITION); Intent intent = new Intent(view.getContext(), VisualPlacementActivity.class); intent.putExtra(EXTRA_BRICK_HASH, hashCode()); try { <START> intent.putExtra("X", formulax.interpretInteger(currentSprite)); <END> intent.putExtra("Y", formulay.interpretInteger(currentSprite)); } catch (InterpretationException interpretationException) { intent.putExtra("X", 0); intent.putExtra("Y", 0); } activity.startActivityForResult(intent, REQUEST_CODE_VISUAL_PLACEMENT); }</code><technical_language>id prefer interpretInteger portions in a try catch block, saving temporary variables putting intent extra of try / catch</technical_language>

Target:
public void placeVisually() { AppCompatActivity activity = UiUtils.getActivityFromView(view); if (!(activity instanceof SpriteActivity)) { return; } Sprite currentSprite = ProjectManager.getInstance().getCurrentSprite(); Formula formulax = getFormulaWithBrickField(BrickField.X_POSITION); Formula formulay = getFormulaWithBrickField(BrickField.Y_POSITION); Intent intent = new Intent(view.getContext(), VisualPlacementActivity.class); intent.putExtra(EXTRA_BRICK_HASH, hashCode()); int xValue; int yValue; try { xValue = formulax.interpretInteger(currentSprite); yValue = formulay.interpretInteger(currentSprite); } catch (InterpretationException interpretationException) { xValue = 0; yValue = 0; } intent.putExtra(EXTRA_X_TRANSFORM, xValue); intent.putExtra(EXTRA_Y_TRANSFORM, yValue); activity.startActivityForResult(intent, REQUEST_CODE_VISUAL_PLACEMENT); }
Source:
<code>public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.setLockingEnabled(false); if (oldVersion == 1) { SmartStore.createLongOperationsStatusTable(db); <START> } <END> }</code><technical_language>If rid of this block, get rid of (line 261)</technical_language>

Target:
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.setLockingEnabled(false); }
Source:
<code>public void testScalarFunctionConcat() throws Exception { MockDataContext dc = new MockDataContext("sch", "tab", "1"); Table table = dc.getDefaultSchema().getTables()[0]; MutableColumn col = new MutableColumn("foo").setTable(table); MutableColumn col2 = new MutableColumn("bar").setTable(table); Object[] functionParams = new Object[3]; functionParams[0] = col; functionParams[1] = "$"; functionParams[2] = col2; Query query = dc.query() .from(table) <START> .select(col, FunctionType.CONCAT, functionParams) <END> .where("bar") .eq("hello") .toQuery(); assertEquals("SELECT CONCAT(tab.foo,'$',tab.bar) FROM sch.tab WHERE tab.bar = 'hello'", query.toSql()); DataSet ds = dc.executeQuery(query); assertTrue(ds.next()); assertEquals("Row[values=[1$hello]]", ds.getRow().toString()); assertFalse(ds.next()); }</code><technical_language>I realize function is created "only" functionParams parameters - col a true parameter. of exceptions I in code. I introduce a new SelectItem constructor (and builder methods etc) initial column select item a function parameters</technical_language>

Target:
public void testScalarFunctionConcat() throws Exception { MockDataContext dc = new MockDataContext("sch", "tab", "1"); Table table = dc.getDefaultSchema().getTables()[0]; MutableColumn col = new MutableColumn("foo").setTable(table); MutableColumn col2 = new MutableColumn("bar").setTable(table); Object[] functionParams = new Object[3]; functionParams[0] = col; functionParams[1] = "$"; functionParams[2] = col2; Query query = dc.query() .from(table) .select(FunctionType.CONCAT, col, functionParams) .where("bar") .eq("hello") .toQuery(); assertEquals("SELECT CONCAT(tab.foo,'$',tab.bar) FROM sch.tab WHERE tab.bar = 'hello'", query.toSql()); DataSet ds = dc.executeQuery(query); assertTrue(ds.next()); assertEquals("Row[values=[1$hello]]", ds.getRow().toString()); assertFalse(ds.next()); }
Source:
<code>public void register(SystemStreamPartition systemStreamPartition, String offset) { if (started.get()) { <START> String msg = <END> String.format("Trying to register partition after consumer has been started. sn=%s, ssp=%s", systemName, systemStreamPartition); LOG.error(msg); throw new SamzaException(msg); } if (!systemStreamPartition.getSystem().equals(systemName)) { LOG.warn("ignoring SSP " + systemStreamPartition + ", because this consumer's system is " + systemName); return; } super.register(systemStreamPartition, offset); TopicPartition tp = toTopicPartition(systemStreamPartition); topicPartitions2SSP.put(tp, systemStreamPartition); LOG.info("Registering ssp = " + systemStreamPartition + " with offset " + offset); String existingOffset = topicPartitions2Offset.get(tp); if (existingOffset == null || compareOffsets(existingOffset, offset) > 0) { topicPartitions2Offset.put(tp, offset); } samzaConsumerMetrics.registerTopicAndPartition(toTopicAndPartition(tp)); }</code><technical_language>do log message throw up. codeflow triggers register(ssp, offset) logs exception. Please delete if redundant</technical_language>

Target:
public void register(SystemStreamPartition systemStreamPartition, String offset) { if (started.get()) { String msg = String.format("%s: Trying to register partition after consumer has been started. ssp=%s", this, systemStreamPartition); throw new SamzaException(msg); } if (!systemStreamPartition.getSystem().equals(systemName)) { LOG.warn("{}: ignoring SSP {}, because this consumer's system doesn't match.", this, systemStreamPartition); return; } LOG.info("{}: Registering ssp = with offset {}", this, systemStreamPartition, offset); super.register(systemStreamPartition, offset); TopicPartition tp = toTopicPartition(systemStreamPartition); topicPartitionsToSSP.put(tp, systemStreamPartition); String existingOffset = topicPartitionsToOffset.get(tp); if (existingOffset == null || compareOffsets(existingOffset, offset) > 0) { topicPartitionsToOffset.put(tp, offset); } metrics.registerTopicAndPartition(toTopicAndPartition(tp)); }
Source:
<code>protected void closeChannel() { final Callable<Void> callable = new Callable<Void>() { @Override public Void call() throws Exception { if (lock.tryLock()) { try { if (channel != null) { channel.close(); } } catch (IOException e) { } finally { channel = null; lock.unlock(); } } else { scheduleTask(this); } return null; } }; try { callable.call(); } catch (Exception e) { <START> log.warn("Closing channel faild ", e); <END> } }</code><technical_language>log.warn("Closing channel failed", e);</technical_language>

Target:
protected void closeChannel() { final Callable<Void> callable = new Callable<Void>() { @Override public Void call() throws Exception { if (lock.tryLock()) { try { if (channel != null) { channel.close(); } } catch (IOException e) { } finally { channel = null; lock.unlock(); } } else { scheduleTask(this); } return null; } }; try { callable.call(); } catch (Exception e) { log.warn("Closing channel failed", e); } }
Source:
<code><START> public boolean isCoercibleTo(PDataType targetType, Object value) { <END> return true; }</code><technical_language>want this: if (!isCoercibleTo(targetType)) { return false; } // Loop element in call thisElementType.isCoercibleTo(targetElementType, element)</technical_language>

Target:
public boolean isCoercibleTo(PDataType targetType, Object value) { return targetType.isCoercibleTo(targetType, value); }
Source:
<code>protected ICommand getSetCommand(SetRequest req) { ICommand cmd = super.getSetCommand(req); if <START> (req.getElementToEdit() <END> instanceof Interaction && req.getValue() instanceof List<?>) { if (UMLPackage.eINSTANCE.getInteraction_Fragment() == req.getFeature()) { Interaction interaction = ((Interaction) req.getElementToEdit()); EList<InteractionFragment> currentList = interaction.getFragments(); List<InteractionFragment> newList = (List<InteractionFragment>) req.getValue(); if (hasNewFragment(currentList, newList)) { InteractionFragment newFragment = getNewFragment(currentList, newList); if (newFragment instanceof MessageOccurrenceSpecification) { cmd = UnexecutableCommand.INSTANCE; } } } } return cmd; }</code><technical_language>check null for req</technical_language>

Target:
protected ICommand getSetCommand(SetRequest req) { ICommand cmd = super.getSetCommand(req); if (null != req && req.getElementToEdit() instanceof Interaction && req.getValue() instanceof List<?>) { if (UMLPackage.eINSTANCE.getInteraction_Fragment() == req.getFeature()) { Interaction interaction = ((Interaction) req.getElementToEdit()); EList<InteractionFragment> currentList = interaction.getFragments(); List<InteractionFragment> newList = (List<InteractionFragment>) req.getValue(); if (hasNewFragment(currentList, newList)) { InteractionFragment newFragment = getNewFragment(currentList, newList); if (newFragment instanceof MessageOccurrenceSpecification) { cmd = UnexecutableCommand.INSTANCE; } } } } return cmd; }
Source:
<code><START> public void start() { <END> scheduler = Schedulers.newElastic("EventProcessorAsyncClient"); disposable = scheduler.schedule(this::run); }</code><technical_language>if I invoke start() multiple times</technical_language>

Target:
public synchronized void start() { if (!started.compareAndSet(false, true)) { logger.info("Event processor is already running"); return; } logger.info("Starting a new event processor instance with id {}", this.identifier); scheduler = Schedulers.newElastic("EventProcessorAsyncClient"); runner = scheduler.schedulePeriodically(this::run, INITIAL_DELAY, INTERVAL_IN_SECONDS, TimeUnit.SECONDS); }
Source:
<code>public boolean updateAccounts(Collection<Account> accounts) { Objects.requireNonNull(accounts, "accounts cannot be null"); if (accounts.isEmpty()) { logger.debug("Empty account collection to update."); return false; } if (mySqlAccountStore == null) { logger.info("MySql Account DB store is not accessible"); return false; } if (config.updateDisabled) { logger.info("Updates has been disabled"); return false; } if (hasDuplicateAccountIdOrName(accounts)) { logger.error("Duplicate account id or name exist in the accounts to update"); return false; } rwLock.readLock().lock(); try { if (accountInfoMap.hasConflictingAccount(accounts)) { logger.error("Accounts={} conflict with the accounts in local cache. Cancel the update operation.", accounts); <START> return false; <END> } } finally { rwLock.readLock().unlock(); } try { updateAccountsWithMySqlStore(accounts); } catch (SQLException e) { logger.error("Failed updating accounts={} in MySql DB", accounts, e); return false; } rwLock.writeLock().lock(); try { accountInfoMap.updateAccounts(accounts); } finally { rwLock.writeLock().unlock(); } return true; }</code><technical_language>I wish interface method threw exception. caller if failed due bad input system error. revisit this later</technical_language>

Target:
public boolean updateAccounts(Collection<Account> accounts) { Objects.requireNonNull(accounts, "accounts cannot be null"); if (accounts.isEmpty()) { logger.debug("Empty account collection to update."); return false; } if (mySqlAccountStore == null) { logger.warn("MySql Account DB store is not accessible"); return false; } if (config.updateDisabled) { logger.info("Updates have been disabled"); return false; } if (hasDuplicateAccountIdOrName(accounts)) { logger.error("Duplicate account id or name exist in the accounts to update"); accountServiceMetrics.updateAccountErrorCount.inc(); return false; } infoMapLock.readLock().lock(); try { if (accountInfoMap.hasConflictingAccount(accounts)) { logger.error("Accounts={} conflict with the accounts in local cache. Cancel the update operation.", accounts); accountServiceMetrics.updateAccountErrorCount.inc(); return false; } for (Account account : accounts) { if (accountInfoMap.hasConflictingContainer(account.getAllContainers(), account.getId())) { logger.error( "Containers={} under Account={} conflict with the containers in local cache. Cancel the update operation.", account.getAllContainers(), account.getId()); accountServiceMetrics.updateAccountErrorCount.inc(); return false; } } } finally { infoMapLock.readLock().unlock(); } try { updateAccountsWithMySqlStore(accounts); } catch (SQLException e) { logger.error("Failed updating accounts={} in MySql DB", accounts, e); accountServiceMetrics.updateAccountErrorCount.inc(); return false; } infoMapLock.writeLock().lock(); try { accountInfoMap.updateAccounts(accounts); } finally { infoMapLock.writeLock().unlock(); } return true; }
Source:
<code><START> private void mockValidateCustomProperties() { <END> doReturn(Collections.EMPTY_LIST).when(command).validateCustomProperties(any(VmStatic.class)); }</code><technical_language>generics - Collections.<ValidationErrors>emptyList()</technical_language>

Target:
private void mockValidateCustomProperties() { doReturn(Collections.<ValidationError>emptyList()).when(command).validateCustomProperties(any(VmStatic.class)); }
Source:
<code>public void onCompletion(Void result, Exception exception) { long processingStartTimeMs = SystemTime.getInstance().milliseconds(); metrics.getPeersSecurityRequestTimeInMs.update(processingStartTimeMs - operationStartTimeMs); <START> ReadableStreamChannel channel = null; <END> try { if (exception == null) { securityService.postProcessRequest(restRequest, new SecurityPostProcessRequestCallback(restRequest, restResponseChannel, callback)); } } catch (Exception e) { exception = e; } finally { metrics.getPeersSecurityRequestCallbackProcessingTimeInMs.update( SystemTime.getInstance().milliseconds() - processingStartTimeMs); if (exception != null) { callback.onCompletion(null, exception); } } }</code><technical_language>used</technical_language>

Target:
public void onCompletion(Void result, Exception exception) { long processingStartTimeMs = SystemTime.getInstance().milliseconds(); metrics.getPeersSecurityRequestTimeInMs.update(processingStartTimeMs - operationStartTimeMs); try { if (exception == null) { securityService.postProcessRequest(restRequest, new SecurityPostProcessRequestCallback(restRequest, restResponseChannel, callback)); } } catch (Exception e) { exception = e; } finally { metrics.getPeersSecurityRequestCallbackProcessingTimeInMs.update( SystemTime.getInstance().milliseconds() - processingStartTimeMs); if (exception != null) { callback.onCompletion(null, exception); } } }
Source:
<code><START> int getDayOfMonth() { <END> if (isYearDay() || isLeapDay()) { return 0; } int doy = getDayOfYearAdjusted() - 1; return 1 + (doy % InternationalFixedChronology.DAYS_IN_MONTH); }</code><technical_language>for month(). I recommend -1 for leap-day 0 for year-day again</technical_language>

Target:
int getDayOfMonth() { return this.day; }
Source:
<code>public synchronized IAntClasspathEntry[] getDefaultAntHomeEntries() { if (defaultAntHomeEntries == null) { ServiceTracker<?, ?> tracker = new ServiceTracker<>(AntCorePlugin.getPlugin().getBundle().getBundleContext(), PackageAdmin.class.getName(), null); tracker.open(); try { List<AntClasspathEntry> result = new ArrayList<>(29); PackageAdmin packageAdmin = (PackageAdmin) tracker.getService(); if (packageAdmin != null) { ExportedPackage[] packages = packageAdmin.getExportedPackages("org.apache.tools.ant"); Bundle bundle = findHighestAntVersion(packages); if (bundle == null) { for (ExportedPackage <START> package1 : <END> packages) { bundle = package1.getExportingBundle(); if (bundle == null) { continue; } try { addLibraries(bundle, result); if (result.size() > 0) { break; } } catch (IOException ioe) { AntCorePlugin.log(ioe); result.clear(); } } } else { try { addLibraries(bundle, result); } catch (IOException ioe) { AntCorePlugin.log(ioe); } } } defaultAntHomeEntries = result.toArray(new IAntClasspathEntry[result.size()]); } finally { tracker.close(); } } return defaultAntHomeEntries; }</code><technical_language>rename pckg</technical_language>

Target:
public synchronized IAntClasspathEntry[] getDefaultAntHomeEntries() { if (defaultAntHomeEntries == null) { ServiceTracker<?, ?> tracker = new ServiceTracker<>(AntCorePlugin.getPlugin().getBundle().getBundleContext(), PackageAdmin.class.getName(), null); tracker.open(); try { List<AntClasspathEntry> result = new ArrayList<>(29); PackageAdmin packageAdmin = (PackageAdmin) tracker.getService(); if (packageAdmin != null) { ExportedPackage[] packages = packageAdmin.getExportedPackages("org.apache.tools.ant"); Bundle bundle = findHighestAntVersion(packages); if (bundle == null) { for (ExportedPackage pckg : packages) { bundle = pckg.getExportingBundle(); if (bundle == null) { continue; } try { addLibraries(bundle, result); if (result.size() > 0) { break; } } catch (IOException ioe) { AntCorePlugin.log(ioe); result.clear(); } } } else { try { addLibraries(bundle, result); } catch (IOException ioe) { AntCorePlugin.log(ioe); } } } defaultAntHomeEntries = result.toArray(new IAntClasspathEntry[result.size()]); } finally { tracker.close(); } } return defaultAntHomeEntries; }
Source:
<code>private void deleteOldSchemas(Long currentSchemaId) throws SQLException { <START> Long toDelete = currentSchemaId - SCHEMAS_TO_KEEP; <END> while ( toDelete > 0 && schemaExists(toDelete) ) { new SchemaStore(connection, toDelete).destroy(); } }</code><technical_language>is this a valid assumption? (That ids incrementing properly). deleting older</technical_language>

Target:
private void deleteOldSchemas(Long currentSchemaId) throws SQLException { Long toDelete = currentSchemaId - SCHEMAS_TO_KEEP; while ( toDelete > 0 && schemaExists(toDelete) ) { new SchemaStore(connection, toDelete).destroy(); toDelete--; } }
Source:
<code>protected void onPostExecute(String s) { super.onPostExecute(s); if(onFinishRequest_callback != null){ onFinishRequest_callback.then(s); } try { if ((progress != null) && progress.isShowing()) { progress.dismiss(); } } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (final Exception e) { <START> e.printStackTrace(); <END> } finally { progress = null; } output_result = s; new MaterialDialog.Builder(context) .content(s) .title(R.string.result) .neutralText(R.string.OK) .positiveText(R.string.copy_text) .onPositive(new MaterialDialog.SingleButtonCallback() { @Override public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) { copyToClipboard(context, output_result); Api.toast(context, context.getString(R.string.result_copied_to_clipboard)); } }) .show(); }</code><technical_language>logs instead of e.printStackTrace()</technical_language>

Target:
protected void onPostExecute(String s) { super.onPostExecute(s); if(onFinishRequest_callback != null){ onFinishRequest_callback.then(s); } try { if ((progress != null) && progress.isShowing()) { progress.dismiss(); } } catch (IllegalArgumentException e) { Log.e(TAG, e.getMessage()); } catch (final Exception e) { Log.e(TAG, e.getMessage()); } finally { progress = null; } output_result = s; new MaterialDialog.Builder(context) .content(s) .title(R.string.result) .neutralText(R.string.OK) .positiveText(R.string.copy_text) .onPositive(new MaterialDialog.SingleButtonCallback() { @Override public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) { copyToClipboard(context, output_result); Api.toast(context, context.getString(R.string.result_copied_to_clipboard)); } }) .show(); }
Source:
<code>public boolean run() { final List<DataSegment> segments = IndexGeneratorJob.getPublishedSegments(config); <START> for (final DataSegment segment : segments) { <END> dbi.withHandle( new HandleCallback<Void>() { @Override public Void withHandle(Handle handle) throws Exception { handle.createStatement( String.format( "INSERT INTO %s (id, dataSource, created_date, start, end, partitioned, version, used, payload) " + "VALUES (:id, :dataSource, :created_date, :start, :end, :partitioned, :version, :used, :payload)", spec.getSegmentTable() ) ) .bind("id", segment.getIdentifier()) .bind("dataSource", segment.getDataSource()) .bind("created_date", new DateTime().toString()) .bind("start", segment.getInterval().getStart().toString()) .bind("end", segment.getInterval().getEnd().toString()) .bind("partitioned", segment.getShardSpec().getPartitionNum()) .bind("version", segment.getVersion()) .bind("used", true) .bind("payload", jsonMapper.writeValueAsString(segment)) .execute(); return null; } } ); log.info("Published %s", segment.getIdentifier()); } return true; }</code><technical_language>This a batch. IIRC, able call prepareBatch() handle, iterate segments adding bindings call executeBatch() run together. Batches committed transactionally put in a transaction, decrease amount of interaction do DB, a good thing</technical_language>

Target:
public boolean run() { final List<DataSegment> segments = IndexGeneratorJob.getPublishedSegments(config); dbi.withHandle( new HandleCallback<Void>() { @Override public Void withHandle(Handle handle) throws Exception { final PreparedBatch batch = handle.prepareBatch( String.format( "INSERT INTO %s (id, dataSource, created_date, start, end, partitioned, version, used, payload) " + "VALUES (:id, :dataSource, :created_date, :start, :end, :partitioned, :version, :used, :payload)", spec.getSegmentTable() ) ); for (final DataSegment segment : segments) { batch.add( new ImmutableMap.Builder() .put("id", segment.getIdentifier()) .put("dataSource", segment.getDataSource()) .put("created_date", new DateTime().toString()) .put("start", segment.getInterval().getStart().toString()) .put("end", segment.getInterval().getEnd().toString()) .put("partitioned", segment.getShardSpec().getPartitionNum()) .put("version", segment.getVersion()) .put("used", true) .put("payload", jsonMapper.writeValueAsString(segment)) .build() ); log.info("Published %s", segment.getIdentifier()); } batch.execute(); return null; } } ); return true; }
Source:
<code>public void testClearBranchTokenTypes() throws Exception { final DetailAST parent = new DetailAST(); final DetailAST child = new DetailAST(); parent.setFirstChild(child); final List<Consumer<DetailAST>> clearBranchTokenTypesMethods = Arrays.asList( ast -> child.setFirstChild(ast), ast -> child.setNextSibling(ast), ast -> child.addPreviousSibling(ast), ast -> child.addNextSibling(ast), ast -> child.addChild(ast), ast -> { try { Whitebox.invokeMethod(child, "setParent", ast); } catch (Exception exception) { throw new IllegalStateException(exception); } } ); for (Consumer<DetailAST> method : clearBranchTokenTypesMethods) { final BitSet branchTokenTypes = Whitebox.invokeMethod(parent, "getBranchTokenTypes"); method.accept(null); final BitSet branchTokenTypes2 = Whitebox.invokeMethod(parent, "getBranchTokenTypes"); assertNotSame(branchTokenTypes, branchTokenTypes2); <START> } <END> }</code><technical_language>do more notSame? this a vague test</technical_language>

Target:
public void testClearBranchTokenTypes() throws Exception { final DetailAST parent = new DetailAST(); final DetailAST child = new DetailAST(); parent.setFirstChild(child); final List<Consumer<DetailAST>> clearBranchTokenTypesMethods = Arrays.asList( ast -> child.setFirstChild(ast), ast -> child.setNextSibling(ast), ast -> child.addPreviousSibling(ast), ast -> child.addNextSibling(ast), ast -> child.addChild(ast), ast -> { try { Whitebox.invokeMethod(child, "setParent", ast); } catch (Exception exception) { throw new IllegalStateException(exception); } } ); for (Consumer<DetailAST> method : clearBranchTokenTypesMethods) { final BitSet branchTokenTypes = Whitebox.invokeMethod(parent, "getBranchTokenTypes"); method.accept(null); final BitSet branchTokenTypes2 = Whitebox.invokeMethod(parent, "getBranchTokenTypes"); assertEquals(branchTokenTypes, branchTokenTypes2); assertNotSame(branchTokenTypes, branchTokenTypes2); } }
Source:
<code>public void testExecuteSolver() throws Exception { SolverInstance instance = new SolverInstance(); instance.setSolverConfigFile( SOLVER_1_CONFIG ); assertSuccess( client.createContainer( CONTAINER_1_ID, new KieContainerResource( CONTAINER_1_ID, kjar1 ) ) ); ServiceResponse<SolverInstance> response = solverClient.createSolver( CONTAINER_1_ID, SOLVER_1_ID, instance ); assertSuccess( response ); assertEquals( SolverInstance.SolverStatus.NOT_SOLVING, response.getResult().getStatus() ); instance.setStatus( SolverInstance.SolverStatus.SOLVING ); instance.setPlanningProblem( loadPlanningProblem( 5, 10 ) ); <START> response = solverClient.updateSolverState( CONTAINER_1_ID, SOLVER_1_ID, instance ); <END> assertSuccess( response ); for( int i = 0; i < 5 && response.getResult().getStatus() == SolverInstance.SolverStatus.SOLVING; i++ ) { Thread.currentThread().sleep( 3000 ); response = solverClient.getSolverState( CONTAINER_1_ID, SOLVER_1_ID ); assertSuccess( response ); } assertEquals( SolverInstance.SolverStatus.NOT_SOLVING, response.getResult().getStatus() ); assertSuccess( solverClient.disposeSolver( CONTAINER_1_ID, SOLVER_1_ID ) ); }</code><technical_language>creating separate methods in client for starting solver terminating it? more intuitive user friendly point of view. show parameters mandatory for action</technical_language>

Target:
public void testExecuteSolver() throws Exception { SolverInstance instance = new SolverInstance(); instance.setSolverConfigFile( SOLVER_1_CONFIG ); assertSuccess( client.createContainer( CONTAINER_1_ID, new KieContainerResource( CONTAINER_1_ID, kjar1 ) ) ); ServiceResponse<SolverInstance> response = solverClient.createSolver( CONTAINER_1_ID, SOLVER_1_ID, instance ); assertSuccess( response ); assertEquals( SolverInstance.SolverStatus.NOT_SOLVING, response.getResult().getStatus() ); instance.setStatus( SolverInstance.SolverStatus.SOLVING ); instance.setPlanningProblem( loadPlanningProblem( 5, 10 ) ); response = solverClient.updateSolverState( CONTAINER_1_ID, SOLVER_1_ID, instance ); assertSuccess( response ); for( int i = 0; i < 5 && response.getResult().getStatus() == SolverInstance.SolverStatus.SOLVING; i++ ) { Thread.sleep( 3000 ); response = solverClient.getSolverState( CONTAINER_1_ID, SOLVER_1_ID ); assertSuccess( response ); } assertEquals( SolverInstance.SolverStatus.NOT_SOLVING, response.getResult().getStatus() ); assertSuccess( solverClient.disposeSolver( CONTAINER_1_ID, SOLVER_1_ID ) ); }
Source:
<code>public String getOS() { FormField field = getField("os"); if (field == null) { return null; } <START> return field.getValuesAsString().get(0); <END> }</code><technical_language>want FormField.getFirstValue() below</technical_language>

Target:
public String getOS() { return readFirstValue(OS); }
Source:
<code>protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { CloudbreakUser cbUser = authenticatedUserService.getCbUser(); <START> Long workspaceId = UNINITIALIZED_WORKSPACE_ID; <END> if (cbUser != null) { ClusterPertain cbSyncedUser = clusterPertainService.getOrCreateUser(cbUser.getUserId(), cbUser.getUserCrn(), cbUser.getTenant()); workspaceId = cbSyncedUser.getWorkspaceId(); } restRequestThreadLocalService.setCloudbreakUser(cbUser, workspaceId); filterChain.doFilter(request, response); restRequestThreadLocalService.removeCloudbreakUser(); }</code><technical_language>familiar UNINITIALIZED_WORKSPACE_ID -1. if wish call a CB API directly, workspaceID 0. default tenant default workspace existing</technical_language>

Target:
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { CloudbreakUser cloudbreakUser = authenticatedUserService.getCbUser(); restRequestThreadLocalService.setCloudbreakUser(cloudbreakUser); filterChain.doFilter(request, response); restRequestThreadLocalService.removeCloudbreakUser(); }
Source:
<code>protected File findManagedResourcesFolder( Bundle blueprintBundle ) { File root = blueprintBundle.getDataFile( "" ); while ( root != null && !root.getAbsolutePath().endsWith( ROOT_SYSTEM_DIR ) ) { root = root.getParentFile(); } <START> return new File( root.getAbsolutePath() + MANAGED_RESOURCES_DIR ); <END> }</code><technical_language>Paths.get more</technical_language>

Target:
protected File findManagedResourcesFolder( Bundle blueprintBundle ) { File root = blueprintBundle.getDataFile( "" ); while ( root != null && !root.getAbsolutePath().endsWith( ROOT_SYSTEM_DIR ) ) { root = root.getParentFile(); } return Paths.get( root.getAbsolutePath(), MANAGED_RESOURCES_DIR ).toFile(); }
Source:
<code>public Mail(Email from, String subject, Email to, Content content) { this.setFrom(from); this.setSubject(subject); Personalization personalization = new Personalization(); personalization.addTo(to); this.addPersonalization(personalization); <START> this.addPersonalization(content); <END> }</code><technical_language>This is correct, please change this back</technical_language>

Target:
public Mail(Email from, String subject, Email to, Content content) { this.setFrom(from); this.setSubject(subject); Personalization personalization = new Personalization(); personalization.addTo(to); this.addPersonalization(personalization); this.addContent(content); }
Source:
<code>protected void onCloseStream() { super.onCloseStream(); if (LAT_LON.size() > 0 && latLonChanged) { ObjectOutputStream oos = null; try { oos = new ObjectOutputStream(new FileOutputStream(LAT_LON_FILENAME)); oos.writeObject(LAT_LON); } catch (IOException e) { LOG.error(e.getMessage(), e); } finally { <START> IOUtils.closeQuietly(oos); <END> } } }</code><technical_language>switch Guava Apache Commons here? change in Guava 15</technical_language>

Target:
protected void onCloseStream() { super.onCloseStream(); if (LAT_LON.size() > 0 && latLonChanged) { ObjectOutputStream oos = null; try { oos = new ObjectOutputStream(new FileOutputStream(LAT_LON_FILENAME)); oos.writeObject(LAT_LON); } catch (IOException e) { LOG.error(e.getMessage(), e); } finally { Closeables.closeQuietly(oos); } } }
Source:
<code>public void testCreateFail() { <START> PluginDescriptor pluginDescriptor = mock(DefaultPluginDescriptor.class); <END> when(pluginDescriptor.getPluginClass()).thenReturn(FailTestPlugin.class.getName()); PluginWrapper pluginWrapper = mock(PluginWrapper.class); when(pluginWrapper.getDescriptor()).thenReturn(pluginDescriptor); when(pluginWrapper.getPluginClassLoader()).thenReturn(getClass().getClassLoader()); DefaultPluginFactory instance = new DefaultPluginFactory(); Plugin result = instance.create(pluginWrapper); assertNull(result); }</code><technical_language>need change. I feel refactoring action</technical_language>

Target:
public void testCreateFail() { PluginDescriptor pluginDescriptor = mock(PluginDescriptor.class); when(pluginDescriptor.getPluginClass()).thenReturn(FailTestPlugin.class.getName()); PluginWrapper pluginWrapper = mock(PluginWrapper.class); when(pluginWrapper.getDescriptor()).thenReturn(pluginDescriptor); when(pluginWrapper.getPluginClassLoader()).thenReturn(getClass().getClassLoader()); DefaultPluginFactory instance = new DefaultPluginFactory(); Plugin result = instance.create(pluginWrapper); assertNull(result); }
Source:
<code>public void testVisibilityForCreatorInPublisher() throws Exception { apiIdentifier = new APIIdentifier(providerName, API_NAME, API_VERSION_1_0_0); APICreationRequestBean apiCreationRequestBean = new APICreationRequestBean(API_NAME, API_CONTEXT, API_VERSION_1_0_0, providerName, new URL(apiEndPointUrl)); apiCreationRequestBean.setTags(API_TAGS); apiCreationRequestBean.setDescription(API_DESCRIPTION); apiCreationRequestBean.setVisibility(APIDTO.VisibilityEnum.PUBLIC.getValue()); APIDTO apidto = apiPublisherClientUser2.addAPI(apiCreationRequestBean); apiID = apidto.getId(); publishAPI(apiID, apiPublisherClientUser2, false); int retry = 0; while (retry < 15) { List<APIIdentifier> apiStoreAPIIdentifierList = APIMTestCaseUtils.getAPIIdentifierListFromHttpResponse(apiStoreClientUser2.getAllAPIs()); if (APIMTestCaseUtils.isAPIAvailable(apiIdentifier, apiStoreAPIIdentifierList)) { log.info("API '" + API_NAME + "' is available on store."); break; } log.info("Waiting for API '" + API_NAME + "' is available on store."); <START> Thread.sleep(3000); <END> retry++; } List<APIIdentifier> apiPublisherAPIIdentifierList = APIMTestCaseUtils.getAPIIdentifierListFromHttpResponse(apiPublisherClientUser2.getAllAPIs()); assertTrue(APIMTestCaseUtils.isAPIAvailable(this.apiIdentifier, apiPublisherAPIIdentifierList), "API is not visible to creator in APi Publisher. When Visibility is public. " + getAPIIdentifierString( this.apiIdentifier)); }</code><technical_language>do a loop check here</technical_language>

Target:
public void testVisibilityForCreatorInPublisher() throws Exception { apiIdentifier = new APIIdentifier(providerName, API_NAME, API_VERSION_1_0_0); APICreationRequestBean apiCreationRequestBean = new APICreationRequestBean(API_NAME, API_CONTEXT, API_VERSION_1_0_0, providerName, new URL(apiEndPointUrl)); apiCreationRequestBean.setTags(API_TAGS); apiCreationRequestBean.setDescription(API_DESCRIPTION); apiCreationRequestBean.setVisibility(APIDTO.VisibilityEnum.PUBLIC.getValue()); APIDTO apidto = apiPublisherClientUser2.addAPI(apiCreationRequestBean); apiID = apidto.getId(); publishAPI(apiID, apiPublisherClientUser2, false); int retry = 0; while (retry < 15) { List<APIIdentifier> apiStoreAPIIdentifierList = APIMTestCaseUtils.getAPIIdentifierListFromHttpResponse(apiStoreClientUser2.getAllAPIs()); if (APIMTestCaseUtils.isAPIAvailable(apiIdentifier, apiStoreAPIIdentifierList)) { log.info("API '" + API_NAME + "' is available on store."); break; } log.info("Waiting for API '" + API_NAME + "' is available on store."); Thread.sleep(1000); retry++; } List<APIIdentifier> apiPublisherAPIIdentifierList = APIMTestCaseUtils.getAPIIdentifierListFromHttpResponse(apiPublisherClientUser2.getAllAPIs()); assertTrue(APIMTestCaseUtils.isAPIAvailable(this.apiIdentifier, apiPublisherAPIIdentifierList), "API is not visible to creator in APi Publisher. When Visibility is public. " + getAPIIdentifierString( this.apiIdentifier)); }
Source:
<code>public Supplier<ManagedTimestampService> createTimestampService(String client, LeaderConfig unused) { PaxosAcceptor ourAcceptor = paxosResource.getPaxosAcceptor(client); Map<PaxosAcceptor, ExecutorService> acceptors = ImmutableMap.<PaxosAcceptor, ExecutorService>builder() .put(ourAcceptor, executorService) .putAll(paxosAcceptorsForClient.apply(client)) .build(); PaxosLearner ourLearner = paxosResource.getPaxosLearner(client); Map<PaxosLearner, ExecutorService> learners = ImmutableMap.<PaxosLearner, ExecutorService>builder() .put(ourLearner, executorService) .putAll(paxosLearnersForClient.apply(client)) .build(); PaxosProposer proposer = instrument(PaxosProposer.class, PaxosProposerImpl.newProposer( ourLearner, acceptors, learners, PaxosRemotingUtils.getQuorumSize(acceptors.keySet()), <START> uuid), <END> client); return () -> createManagedPaxosTimestampService(proposer, client, acceptors, learners); }</code><technical_language>This is technically a change in behaviour (previously node for timestamp service propose a UUID, while UUID). issue, want check this intentional</technical_language>

Target:
public Supplier<ManagedTimestampService> createTimestampService(String client, LeaderConfig unused) { PaxosAcceptor ourAcceptor = paxosResource.getPaxosAcceptor(client); List<PaxosAcceptor> acceptors = Stream.concat( paxosAcceptorsForClient.apply(client).stream(), Stream.of(ourAcceptor)) .collect(Collectors.toList()); PaxosLearner ourLearner = paxosResource.getPaxosLearner(client); List<PaxosLearner> learners = Stream.concat( paxosLearnersForClient.apply(client).stream(), Stream.of(ourLearner)) .collect(Collectors.toList()); PaxosProposer proposer = instrument(PaxosProposer.class, PaxosProposerImpl.newProposer( ourLearner, acceptors, learners, PaxosRemotingUtils.getQuorumSize(acceptors), UUID.randomUUID(), executor), client); return () -> createManagedPaxosTimestampService(proposer, client, acceptors, learners); }
Source:
<code>public static io.sphere.sdk.shoppinglists.commands.updateactions.ChangeName of(final LocalizedString name) { <START> return new io.sphere.sdk.shoppinglists.commands.updateactions.ChangeName(name); <END> }</code><technical_language>This imported here, I conflicts</technical_language>

Target:
public static ChangeName of(final LocalizedString name) { return new ChangeName(name); }
Source:
<code>public static String generateValueFileName(String fileNameBase, int fileNum) { <START> return StringUtils.safeFormat("%s_value_%d", fileNameBase, fileNum); <END> }</code><technical_language>crash if bad format string</technical_language>

Target:
public static String generateValueFileName(String fileNameBase, int fileNum) { return StringUtils.format("%s_value_%d", fileNameBase, fileNum); }
Source:
<code>protected boolean isSubtypeWithElements( AnnotationMirror subAnno, QualifierKind subKind, AnnotationMirror superAnno, QualifierKind superKind) { <START> if (REGEX_KIND == subKind && REGEX_KIND == superKind) { <END> int rhsValue = getRegexValue(subAnno); int lhsValue = getRegexValue(superAnno); return lhsValue <= rhsValue; } else if (PARTIALREGEX_KIND == subKind && PARTIALREGEX_KIND == superKind) { return AnnotationUtils.areSame(subAnno, superAnno); } throw new BugInCF("Unexpected qualifiers: %s %s", subAnno, superAnno); }</code><technical_language>I find comparison style puts a constant lhs a variable rhs funny. is, I dislike "if (4 == x || 5 == x)" I prefer "if (x == 4 || x == 5)". I a great reason for preference, is speak in English. Is a reason chose this order of arguments ==</technical_language>

Target:
protected boolean isSubtypeWithElements( AnnotationMirror subAnno, QualifierKind subKind, AnnotationMirror superAnno, QualifierKind superKind) { if (subKind == REGEX_KIND && superKind == REGEX_KIND) { int rhsValue = getRegexValue(subAnno); int lhsValue = getRegexValue(superAnno); return lhsValue <= rhsValue; } else if (subKind == PARTIALREGEX_KIND && superKind == PARTIALREGEX_KIND) { return AnnotationUtils.areSame(subAnno, superAnno); } throw new BugInCF("Unexpected qualifiers: %s %s", subAnno, superAnno); }
Source:
<code>public void closeBodyEvenWhenExceptionHappens() throws IOException { final IOException exception = new IOException("Smth went wrong"); final FailOutputStream output = new FailOutputStream(exception); final FakeInput input = new FakeInput(new InputStreamOf("abc")); try { new RsPrint(new RsText(input)) .printBody(output); } catch (final IOException ex) { <START> if (!ex.equals(exception)) { <END> throw ex; } } MatcherAssert.assertThat( input.haveClosed(), new IsEqual<>(true) ); }</code><technical_language>@olenagerasimova assertions in tests instead of exception throwing: java MatcherAssert.assertThat("wrong exception", ex, new IsEquals(exception));</technical_language>

Target:
public void closeBodyEvenWhenExceptionHappens() throws IOException { final IOException exception = new IOException("Smth went wrong"); final FailOutputStream output = new FailOutputStream(exception); final FakeInput input = new FakeInput(new InputStreamOf("abc")); try { new RsPrint(new RsText(input)) .printBody(output); } catch (final IOException ex) { if (!ex.equals(exception)) { throw ex; } } MatcherAssert.assertThat( "Input body was not closed", input.isClosed(), new IsEqual<>(true) ); }