auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void setAlarms() { reminders = db.getReminders(); <START> enableBootReceiver(db.areRemindersActive()); <END> for (int i = 0; i < reminders.size(); i++) { Reminder reminder = reminders.get(i); Intent intent = new Intent(context, GlucosioBroadcastReceiver.class); intent.putExtra("metric", reminder.getMetric()); PendingIntent alarmIntent = PendingIntent.getBroadcast(context, (int) reminder.getId(), intent, 0); if (reminder.isActive()) { Calendar cal = Calendar.getInstance(); cal.setTime(reminder.getAlarmTime()); alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), AlarmManager.INTERVAL_DAY, alarmIntent); } else { alarmMgr.cancel(alarmIntent); } } }</code><technical_language>reading DB times? DB operations UI thread</technical_language>

Target:
public void setAlarms() { List<Reminder> reminders = db.getReminders(); int activeRemindersCount = 0; for (int i = 0; i < reminders.size(); i++) { Reminder reminder = reminders.get(i); Intent intent = new Intent(context, GlucosioBroadcastReceiver.class); intent.putExtra("metric", reminder.getMetric()); intent.putExtra("glucosio_reminder", true); PendingIntent alarmIntent = PendingIntent.getBroadcast(context, (int) reminder.getId(), intent, 0); if (reminder.isActive()) { activeRemindersCount++; Calendar calNow = Calendar.getInstance(); Calendar calAlarm = Calendar.getInstance(); calAlarm.setTime(reminder.getAlarmTime()); calAlarm.set(Calendar.SECOND, 0); DateTime now = new DateTime(calNow.getTime()); DateTime reminderDate = new DateTime(calAlarm); if (reminderDate.isBefore(now)) { calAlarm.set(Calendar.DATE, calNow.get(Calendar.DATE)); calAlarm.add(Calendar.DATE, 1); } Log.d("Glucosio", "Added reminder on " + calAlarm.get(Calendar.DAY_OF_MONTH) + " at " + calAlarm.get(Calendar.HOUR) + ":" + calAlarm.get(Calendar.MINUTE)); alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, calAlarm.getTimeInMillis(), AlarmManager.INTERVAL_DAY, alarmIntent); } else { alarmMgr.cancel(alarmIntent); } } enableBootReceiver(activeRemindersCount > 0); }
Source:
<code>public Map<String,Project> getProjects() { Map<String,Project> projects = (Map<String,Project>)getConfigurationValue("projects"); <START> return projects; <END> }</code><technical_language>simplify return</technical_language>

Target:
public Map<String,Project> getProjects() { return (Map<String,Project>)getConfigurationValue("projects"); }
Source:
<code>public void setBinaryData(Object answer, PendingCalloutInterface pendingCalloutInterface) { FormIndex questionFormIndex = pendingCalloutInterface.getPendingCalloutFormIndex(); if (questionFormIndex == null) { <START> Logger.log(LogTypes.TYPE_ERROR_ASSERTION, <END> "Unable to find question widget to attach pending data to."); return; } for (QuestionWidget q : widgets) { if (questionFormIndex.equals(q.getFormId())) { q.setBinaryData(answer); return; } } Logger.log(LogTypes.TYPE_ERROR_ASSERTION, "Unable to find question widget to attach pending data to."); }</code><technical_language>Wondering reasoning for TYPE_ERROR_ASSERTION SOFT_ASSERT . serving purpose if well, remove of simplify things</technical_language>

Target:
public void setBinaryData(Object answer, PendingCalloutInterface pendingCalloutInterface) { FormIndex questionFormIndex = pendingCalloutInterface.getPendingCalloutFormIndex(); if (questionFormIndex == null) { Logger.log(LogTypes.SOFT_ASSERT, "No pending callout index was set when trying to attach pending data."); return; } for (QuestionWidget q : widgets) { if (questionFormIndex.equals(q.getFormId())) { q.setBinaryData(answer); return; } } Logger.log(LogTypes.SOFT_ASSERT, "Unable to find question widget to attach pending data to."); }
Source:
<code>public synchronized void addAddressToTunnelInterface( int tunnelResourceId, LinkAddress localAddr) { UserRecord userRecord = mUserResourceTracker.getUserRecord(Binder.getCallingUid()); <START> <END> TunnelInterfaceRecord tunnelInterfaceInfo = userRecord.mTunnelInterfaceRecords.getResourceOrThrow(tunnelResourceId); try { mSrvConfig .getNetdInstance() .interfaceAddAddress( tunnelInterfaceInfo.mInterfaceName, localAddr.getAddress().getHostAddress(), localAddr.getPrefixLength()); } catch (RemoteException e) { throw e.rethrowFromSystemServer(); } catch (ServiceSpecificException e) { rethrowFromServiceSpecificException(e); } }</code><technical_language>This enforce permissions model applying for tunnel mode. Currently, this is NETWORK_STACK</technical_language>

Target:
public synchronized void addAddressToTunnelInterface( int tunnelResourceId, LinkAddress localAddr) { enforceNetworkStackPermission(); UserRecord userRecord = mUserResourceTracker.getUserRecord(Binder.getCallingUid()); TunnelInterfaceRecord tunnelInterfaceInfo = userRecord.mTunnelInterfaceRecords.getResourceOrThrow(tunnelResourceId); try { mSrvConfig .getNetdInstance() .interfaceAddAddress( tunnelInterfaceInfo.mInterfaceName, localAddr.getAddress().getHostAddress(), localAddr.getPrefixLength()); } catch (RemoteException e) { throw e.rethrowFromSystemServer(); } catch (ServiceSpecificException e) { throw new IllegalArgumentException(e); } }
Source:
<code>public static Boolean notExists( EvaluationContext ctx, List tests, Object target) { for (Object test : tests) { Boolean r = applyUnaryTest(ctx, test, target); <START> if (r != null && r) return false; <END> } return true; }</code><technical_language>double checking this is intent? change odd.</technical_language>

Target:
public static Boolean notExists( EvaluationContext ctx, List tests, Object target) { for (Object test : tests) { Boolean r = applyUnaryTest(ctx, test, target); if (r == null || r) return false; } return true; }
Source:
<code>public WorkflowState getState(String state) { for (WorkflowState s : getStates()) { <START> if (state.equals(s.name())) { <END> return s; } } throw new IllegalStateException("No state '" + state + "' in workflow definiton " + getType()); }</code><technical_language>s.name().equals(state)</technical_language>

Target:
public WorkflowState getState(String state) { for (WorkflowState s : getStates()) { if (Objects.equals(s.name(), state)) { return s; } } throw new IllegalStateException("No state '" + state + "' in workflow definiton " + getType()); }
Source:
<code>private void setSessionUser(Session session) { try { User user = getUserResource().getUserByNameAndDomain(session.getUser().getUserName(), session.getUser().getDomain().getName()); if (user != null) { session.getUser().setId(user.getId()); session.getUser().setHref(user.getHref()); session.getUser().getDomain().setId(user.getDomain().getId()); session.getUser().getDomain().setHref(user.getDomain().getHref()); } } catch (WebApplicationException ex) { <START> } <END> }</code><technical_language>I BackendUserResource.getUserByNameAndDomain method is called here. check if is reasonable move code this class? then, instead of implementing 'performGet' implement 'getEntity', check if result is nil instead of generating ignoring exception</technical_language>

Target:
private void setSessionUser(Session session) { User user = getUserResource().getUserByNameAndDomain(session.getUser().getUserName(), session.getUser().getDomain().getName()); if (user != null) { session.getUser().setId(user.getId()); session.getUser().setHref(user.getHref()); session.getUser().getDomain().setId(user.getDomain().getId()); session.getUser().getDomain().setHref(user.getDomain().getHref()); } }
Source:
<code>private void generateMissingColumnsCheck(MethodSpec.Builder methodBuilder) { methodBuilder.addStatement( "$1T<$2T> missingTableCqlNames = findMissingColumnsCql(expectedCqlNames, (($3T) tableMetadata.get()).getColumns().keySet())", List.class, CqlIdentifier.class, DefaultTableMetadata.class); CodeBlock missingCqlColumnExceptionMessage = CodeBlock.of( <START> "String.format(\"The CQL ks.table: %s.%s has missing columns: %s that are defined in the entity class: %s\", " <END> + "keyspaceId, tableId, missingTableCqlNames, entityClassName)"); methodBuilder.beginControlFlow("if (!missingTableCqlNames.isEmpty())"); methodBuilder.addStatement( "throw new $1T($2L)", IllegalArgumentException.class, missingCqlColumnExceptionMessage); methodBuilder.endControlFlow(); }</code><technical_language>suggestion "String.format(\"The CQL table: %s.%s missing columns: %s defined in entity class: %s\", " ? occurs a couple of other times below</technical_language>

Target:
private void generateMissingColumnsCheck(MethodSpec.Builder methodBuilder) { methodBuilder.addComment("validation of all columns"); methodBuilder.addStatement( "$1T<$2T> missingTableCqlNames = findMissingCqlIdentifiers(expectedCqlNames, tableMetadata.get().getColumns().keySet())", List.class, CqlIdentifier.class); CodeBlock missingCqlColumnExceptionMessage = CodeBlock.of( "String.format(\"The CQL ks.table: %s.%s has missing columns: %s that are defined in the entity class: %s\", " + "keyspaceId, tableId, missingTableCqlNames, entityClassName)"); methodBuilder.beginControlFlow("if (!missingTableCqlNames.isEmpty())"); methodBuilder.addStatement( "throw new $1T($2L)", IllegalArgumentException.class, missingCqlColumnExceptionMessage); methodBuilder.endControlFlow(); }
Source:
<code>private String getKeyTrustStoreAttribute(String sysPropName, KeyOrTrustStoreType store, String valueType, boolean throwForNull) { String sysProp = System.getProperty(sysPropName); if (StringUtils.isNotBlank(sysProp)) { return sysProp.trim(); } else { String value = null; if (store!=null) { <START> value = valueType.equals("path") ? store.getPath() : store.getPassword(); <END> } if (StringUtils.isBlank(value) && throwForNull) { throw new RuntimeException( "To enable HTTPS, keystore must be configured with password in deployment file or using system property"); } else { return (value!=null) ? value.trim() : value; } } }</code><technical_language>"path".equals(valueType)</technical_language>

Target:
private String getKeyTrustStoreAttribute(String sysPropName, KeyOrTrustStoreType store, String valueType, boolean throwForNull) { String sysProp = System.getProperty(sysPropName); if (StringUtils.isNotBlank(sysProp)) { return sysProp.trim(); } else { String value = null; if (store!=null) { value = "path".equals(valueType) ? store.getPath() : store.getPassword(); } if (StringUtils.isBlank(value) && throwForNull) { throw new IllegalArgumentException( "To enable HTTPS, keystore must be configured with password in deployment file or using system property. " + sysPropName); } else { return value; } } }
Source:
<code>public Set<BlockType> getCategorisedByName(String category) { <START> return CLIWorldEdit.inst.getFileRegistries().getDataFile().blocktags.getOrDefault(category, new ArrayList<>()).stream() <END> .map(BlockType.REGISTRY::get) .collect(Collectors.toSet()); }</code><technical_language>I prefer ImmutableList.of Collections.emptyList, re-allocated time. important here, more of a general habit</technical_language>

Target:
public Set<BlockType> getCategorisedByName(String category) { return CLIWorldEdit.inst.getFileRegistries().getDataFile().blocktags.getOrDefault(category, Collections.emptyList()).stream() .map(BlockType.REGISTRY::get) .collect(Collectors.toSet()); }
Source:
<code><START> private List<Object> getInputFields(IndexedRecord inputRecord, String columnName) { <END> if (!columnName.startsWith(".")) columnName = "." + columnName; Try<scala.collection.immutable.List<Evaluator.Ctx>> result = wandou.avpath.package$.MODULE$.select(inputRecord, columnName); List<Object> values = new ArrayList<Object>(); if (result.isSuccess()) { for (Evaluator.Ctx ctx : JavaConversions.asJavaCollection(result.get())) { values.add(ctx.value()); } } else { throw TalendRuntimeException.createUnexpectedException(result.failed().get()); } return values; }</code><technical_language>extract this method in a common place</technical_language>

Target:
private List<Object> getInputFields(IndexedRecord inputRecord, String columnName) { if (!columnName.startsWith(".")) columnName = "." + columnName; Try<scala.collection.immutable.List<Evaluator.Ctx>> result = wandou.avpath.package$.MODULE$.select(inputRecord, columnName); List<Object> values = new ArrayList<Object>(); if (result.isSuccess()) { for (Evaluator.Ctx ctx : JavaConversions.asJavaCollection(result.get())) { values.add(ctx.value()); } } else { Throwable t = result.failed().get(); throw ProcessingErrorCode.createAvpathSyntaxError(t, columnName, -1); } return values; }
Source:
<code>public void setUp() throws Exception { SqlTestUtils.deleteDatabase(username); sandbox = SqlSandboxUtils.getStaticStorage(username); <START> ParseUtils.parseIntoSandbox(this.getClass().getClassLoader().getResourceAsStream("ipm_restore.xml"), sandbox); <END> sandbox = null; }</code><technical_language>This statement is printing a lot of stack traces in test suite. I those, a bug</technical_language>

Target:
public void setUp() throws Exception { sandbox = SqlSandboxUtils.getStaticStorage(username); PrototypeFactory.setStaticHasher(new ClassNameHasher()); ParseUtils.parseIntoSandbox(this.getClass().getClassLoader().getResourceAsStream("ipm_restore.xml"), sandbox); sandbox = null; }
Source:
<code>private void handleUtterance(Session session, String query, Response response) { session.updateContext(); Example.Builder b = new Example.Builder(); b.setId("session:" + session.id); b.setUtterance(query); b.setContext(session.context); Example ex = b.createExample(); ex.preprocess(); ParserState state; <START> state = builder.parser.parse(builder.params, ex, false); <END> response.ex = ex; ex.logWithoutContext(); if (ex.predDerivations.size() > 0) { response.candidateIndex = 0; printDerivation(response.getDerivation()); } session.updateContext(ex, opts.contextMaxExchanges); }</code><technical_language>Why? state</technical_language>

Target:
private void handleUtterance(Session session, String query, Response response) { session.updateContext(); Example.Builder b = new Example.Builder(); b.setId("session:" + session.id); b.setUtterance(query); b.setContext(session.context); Example ex = b.createExample(); ex.preprocess(); builder.parser.parse(builder.params, ex, false); response.ex = ex; ex.logWithoutContext(); if (ex.predDerivations.size() > 0) { response.candidateIndex = 0; printDerivation(response.getDerivation()); } session.updateContext(ex, opts.contextMaxExchanges); }
Source:
<code>public void addEvent(ITimeEvent event) { if (!(event instanceof TimeLineEvent)) { <START> throw new IllegalArgumentException("Needs to be a TimeLineEvent"); END> } super.addEvent(event); }</code><technical_language>a bit worried gaps handled, this implementation dummy event is added for gaps. NullTimeEvent allowed. is OK? ignore them</technical_language>

Target:
public void addEvent(ITimeEvent event) { isValidEvent(event); super.addEvent(event); }
Source:
<code>private void addSuggestion(Map map, Account account, AccountInfo info, Boolean active) { <START> if(active != null) { <END> if(active.booleanValue() != account.isActive()) { return; } } map.put(account.getId(), info); }</code><technical_language>Style-nit: Space if. I write code more cleanly: if (active == null || active == account.isActive()) { map.put(account.getId(), info); }</technical_language>

Target:
private void addSuggestion(Map map, Account account, AccountInfo info, Boolean active) { if (active == null || active == account.isActive()) { map.put(account.getId(), info); } }
Source:
<code>static ImmutableHolidayCalendar generateSydney() { <START> List<LocalDate> holidays = new ArrayList<>(0); END> return ImmutableHolidayCalendar.of(HolidayCalendarId.of("AUSY"), holidays, SATURDAY, SUNDAY); }</code><technical_language>this merged a holiday calendar</technical_language>

Target:
static ImmutableHolidayCalendar generateSydney() { List<LocalDate> holidays = new ArrayList<>(2000); for (int year = 1950; year <= 2099; year++) { holidays.add(bumpToMon(date(year, 1, 1))); holidays.add(bumpToMon(date(year, 1, 26))); holidays.add(easter(year).minusDays(2)); holidays.add(easter(year).plusDays(1)); holidays.add(date(year, 4, 25)); holidays.add(first(year, 6).with(dayOfWeekInMonth(2, MONDAY))); holidays.add(first(year, 8).with(dayOfWeekInMonth(1, MONDAY))); holidays.add(first(year, 10).with(dayOfWeekInMonth(1, MONDAY))); holidays.add(christmas(year)); holidays.add(boxingDay(year)); } removeSatSun(holidays); return ImmutableHolidayCalendar.of(HolidayCalendarId.of("AUSY"), holidays, SATURDAY, SUNDAY); }
Source:
<code>public Expression visitLeave(JsonPathAsTextParseNode node, List<Expression> children) throws SQLException { if(!(PJson.INSTANCE.isComparableTo(children.get(0).getDataType()))){ throw TypeMismatchException.newException(children.get(0).getDataType(), children.get(1).getDataType()); } <START> if(!(PVarchar.INSTANCE.isComparableTo(children.get(1).getDataType()))){ <END> throw TypeMismatchException.newException(children.get(0).getDataType(), children.get(1).getDataType()); } LiteralExpression rhs=(LiteralExpression)children.get(1); String v=(String)rhs.getValue(); if(!v.startsWith("{")||!v.endsWith("}")){ throw new SQLExceptionInfo.Builder(SQLExceptionCode.JSON_PATH_ERROR).build().buildException(); } Expression expression = new JsonPathAsTextExpression(children); return wrapGroupByExpression(expression); }</code><technical_language>change this a PVarcharArray consistent ?| ?&</technical_language>

Target:
public Expression visitLeave(JsonPathAsTextParseNode node, List<Expression> children) throws SQLException { if(!(PJson.INSTANCE.isComparableTo(children.get(0).getDataType()))){ throw TypeMismatchException.newException(children.get(0).getDataType(), children.get(1).getDataType()); } if(children.get(1).getDataType()!=PVarcharArray.INSTANCE){ throw TypeMismatchException.newException(children.get(0).getDataType(), children.get(1).getDataType()); } Expression expression = new JsonPathAsTextExpression(children); return wrapGroupByExpression(expression); }
Source:
<code>@Deprecated @Restricted(DoNotUse.class) @RestrictedSince("2.0") public String getInstallation() { for (SCMSourceTrait t: traits) { <START> if (t instanceof MercurialInstallationSCMSourceTrait) { <END> return ((MercurialInstallationSCMSourceTrait) t).getInstallation(); } } return null; }</code><technical_language>useful a java <T extends SCMSourceTrait> public List<? extends T> getTraits(Class<T> type);</technical_language>

Target:
@Deprecated @Restricted(DoNotUse.class) @RestrictedSince("2.0") public String getInstallation() { MercurialInstallationSCMSourceTrait t = getTrait(MercurialInstallationSCMSourceTrait.class); return t != null ? t.getInstallation() : null; }
Source:
<code>public void getApexDFSRootDirScheme() throws Exception { Configuration conf = new Configuration(false); conf.set(StramClientUtils.APEX_APP_DFS_ROOT_DIR, "file:/p/q/r"); conf.setBoolean(StramUserLogin.DT_APP_PATH_IMPERSONATED, false); UserGroupInformation testUser = UserGroupInformation.createUserForTesting("testUser1", new String[]{""}); <START> spy(UserGroupInformation.class); <END> doReturn(testUser).when(UserGroupInformation.class, "getLoginUser"); FileSystem fs = FileSystem.newInstance(conf); Path path = StramClientUtils.getApexDFSRootDir(fs, conf); Assert.assertEquals(fs.getHomeDirectory() + "/datatorrent", path.toString()); Assert.assertNull(conf.get(StramClientUtils.DT_DFS_ROOT_DIR)); Assert.assertEquals("file:/p/q/r", conf.get(StramClientUtils.APEX_APP_DFS_ROOT_DIR)); }</code><technical_language>moved @Before @BeforeClass</technical_language>

Target:
public void getApexDFSRootDirScheme() throws Exception { Configuration conf = new Configuration(false); conf.set(StramClientUtils.APEX_APP_DFS_ROOT_DIR, "file:/p/q/r"); conf.setBoolean(StramUserLogin.DT_APP_PATH_IMPERSONATED, false); setupLoginTestUser(); FileSystem fs = FileSystem.newInstance(conf); Path path = StramClientUtils.getApexDFSRootDir(fs, conf); Assert.assertEquals(fs.getHomeDirectory() + "/datatorrent", path.toString()); Assert.assertNull(conf.get(StramClientUtils.DT_DFS_ROOT_DIR)); Assert.assertEquals("file:/p/q/r", conf.get(StramClientUtils.APEX_APP_DFS_ROOT_DIR)); }
Source:
<code>public AdvancedJoystickButton getifAvailable(int buttonNumber) { if (buttonNumber < 1 || buttonNumber > maxButtons) { <START> String message = "button " + buttonNumber + " is out of range!"; <END> return getMockButton(message); } if (buttonMap.containsKey(buttonNumber)) { return buttonMap.remove(buttonNumber); } else { String message = "button " + buttonNumber + " is already used! Cannot be used twice!"; return getMockButton(message); } }</code><technical_language>I streamline this line -- easier read</technical_language>

Target:
public AdvancedJoystickButton getifAvailable(int buttonNumber) { if (buttonNumber < 1 || buttonNumber > maxButtons) { return handleInvalidButton("button " + buttonNumber + " is out of range!"); } if (buttonMap.containsKey(buttonNumber)) { return buttonMap.remove(buttonNumber); } else { return handleInvalidButton("button " + buttonNumber + " is already used! Cannot be used twice!"); } }
Source:
<code>private boolean isBaseSnapshotDisk() { return getNewDisk().isDiskSnapshot() && ((DiskImage) <START> getNewDisk()).getImage().getVolumeFormat() == VolumeFormat.RAW; <END> }</code><technical_language>I safer check if getImage().getVolumeFormat() != VolumeFormat.COW</technical_language>

Target:
private boolean isBaseSnapshotDisk() { return getNewDisk().isDiskSnapshot() && ((DiskImage) getNewDisk()).getImage().getVolumeFormat() != VolumeFormat.COW; }
Source:
<code>public void checkWebNodejsSimpleProjectCommands() { consoles.executeCommandFromProjectExplorer( WEB_NODEJS_SIMPLE, BUILD_GOAL, INSTALL_DEPENDENCIES_COMMAND_ITEM.getItem(WEB_NODEJS_SIMPLE), "bower_components/angular"); <START> consoles.executeCommandFromProjectExplorer( <END> WEB_NODEJS_SIMPLE, RUN_GOAL, RUN_COMMAND_ITEM.getItem(WEB_NODEJS_SIMPLE), "Started connect web server"); consoles.checkWebElementVisibilityAtPreviewPage( By.xpath(" consoles.closeProcessTabWithAskDialog(RUN_COMMAND_ITEM.getItem(WEB_NODEJS_SIMPLE)); }</code><technical_language>Empty row commands improve readability of code here</technical_language>

Target:
public void checkWebNodejsSimpleProjectCommands() { By textOnPreviewPage = By.xpath(" consoles.executeCommandFromProjectExplorer( WEB_NODE_JS_PROJECT, BUILD_GOAL, INSTALL_DEPENDENCIES_COMMAND_ITEM.getItem(WEB_NODE_JS_PROJECT), "bower_components/angular"); consoles.executeCommandFromProjectExplorer( WEB_NODE_JS_PROJECT, RUN_GOAL, RUN_COMMAND_ITEM.getItem(WEB_NODE_JS_PROJECT), "Started connect web server"); consoles.checkWebElementVisibilityAtPreviewPage(textOnPreviewPage); consoles.closeProcessTabWithAskDialog(RUN_COMMAND_ITEM.getItem(WEB_NODE_JS_PROJECT)); }
Source:
<code>private void createProject() throws RepositoryNotFoundException, OrmException, IOException, Failure { final PerformCreateProject perfCreateProject = <START> performCreateProject.create(projectName, ownerIds, newParent, <END> projectDescription, submitType, contributorAgreements, signedOffBy, permissionsOnly, branch); final StringBuilder err = perfCreateProject.createProject(); if (err.length() > 0) { throw new Failure(1, err.toString()); } }</code><technical_language>This is a huge number of args. cleaner if setters a CreateProjectBuilder object</technical_language>

Target:
private void createProject() throws RepositoryNotFoundException, OrmException, IOException, Failure { final CreateProjectArgs args = new CreateProjectArgs(); args.setProjectName(projectName); args.setOwnerIds(ownerIds); args.setNewParent(newParent); args.setProjectDescription(projectDescription); args.setSubmitType(submitType); args.setContributorAgreements(contributorAgreements); args.setSignedOffBy(signedOffBy); args.setPermissionsOnly(permissionsOnly); args.setBranch(branch); args.setContentMerge(contentMerge); args.setChangeIdRequired(requireChangeID); final PerformCreateProject perfCreateProject = performCreateProject.create(args); try { perfCreateProject.createProject(); } catch (CreateProjectParamsException e) { throw new Failure(1, e.getMessage()); } }
Source:
<code>public void sanitizeForSaving() { <START> this.commentText = Sanitizer.sanitizeTextField(this.commentText); <END> this.commentText = Sanitizer.sanitizeForRichText(this.commentText); }</code><technical_language>function for this purpose, all. if this function differs newly defined sanitizeForRichText, if decommission of (i.e function for purposes)</technical_language>

Target:
public void sanitizeForSaving() { this.commentText = Sanitizer.sanitizeForRichText(this.commentText); }
Source:
<code><START> public ReceivePacket( XBee64BitAddress sourceAddress64, XBee16BitAddress sourceAddress16, int receiveOptions, byte[] receivedData){ <END> super(XBeeAPIType.RECEIVE_PACKET); this.sourceAddress64 = sourceAddress64; this.sourceAddress16 = sourceAddress16; this.receiveOptions = receiveOptions; this.receivedData = receivedData; }</code><technical_language>Throw proper exception if is supported: - NullPointerException if sourceAddress64 == null sourceAddress16 == null. - receiveOptions valid values</technical_language>

Target:
public ReceivePacket(XBee64BitAddress sourceAddress64, XBee16BitAddress sourceAddress16, int receiveOptions, byte[] receivedData){ super(APIFrameType.RECEIVE_PACKET); if (sourceAddress64 == null) throw new NullPointerException("64-bit source address cannot be null."); if (sourceAddress16 == null) throw new NullPointerException("16-bit source address cannot be null."); if (receiveOptions < 0 || receiveOptions > 255) throw new IllegalArgumentException("Receive options value must be between 0 and 255."); this.sourceAddress64 = sourceAddress64; this.sourceAddress16 = sourceAddress16; this.receiveOptions = receiveOptions; this.receivedData = receivedData; }
Source:
<code>public void testPutJsonQueryEntity() throws Exception { String cacheName = "person"; Person simple = new Person(100, "John", "Doe", 10000); putObject(cacheName, "300", simple); String ret = content(cacheName, GridRestCommand.CACHE_GET, "keyType", "int", "key", "300" ); info("Get command result: " + ret); checkJson(ret, simple); JsonNode val = queryObject( cacheName, "type", Person.class.getSimpleName(), "pageSize", "1", "qry", "orgId = ?", "arg1", String.valueOf(simple.getOrganizationId()) ); assertEquals(simple.getOrganizationId().intValue(), val.get("orgId").intValue()); assertEquals(simple.getSalary(), val.get("salary").doubleValue()); assertEquals(simple.getFirstName(), val.get("firstName").textValue()); assertEquals(simple.getLastName(), val.get("lastName").textValue()); <START> initCache(); <END> }</code><technical_language>remove inserted entry (perhaps adding "finally" block)</technical_language>

Target:
public void testPutJsonQueryEntity() throws Exception { String cacheName = "person"; Person simple = new Person(100, "John", "Doe", 10000); try { putObject(cacheName, "300", simple); String ret = content(cacheName, GridRestCommand.CACHE_GET, "keyType", "int", "key", "300"); info("Get command result: " + ret); checkJson(ret, simple); JsonNode val = queryObject( cacheName, GridRestCommand.EXECUTE_SQL_QUERY, "type", Person.class.getSimpleName(), "pageSize", "1", "qry", "orgId = ?", "arg1", String.valueOf(simple.getOrganizationId()) ); assertEquals(simple.getOrganizationId().intValue(), val.get("orgId").intValue()); assertEquals(simple.getSalary(), val.get("salary").doubleValue()); assertEquals(simple.getFirstName(), val.get("firstName").textValue()); assertEquals(simple.getLastName(), val.get("lastName").textValue()); } finally { grid(0).cache(cacheName).remove(300); } }
Source:
<code>public synchronized void start() { super.start(); try { createStreamClient(); <START> } catch (Exception e) { <END> LOG.error("Unable to create Stream client by name: for host: {}, port: {}. Reason: ", new Object[]{streamName, host, port, e.getMessage(), e}); closeWriterQuietly(); closeClientQuietly(); } LOG.info("StreamSink started.", getName()); }</code><technical_language>this catch (Throwable t)</technical_language>

Target:
public synchronized void start() { try { createStreamClient(); } catch (Throwable t) { LOG.error("Unable to create Stream client by name: for host: {}, port: {}. Reason: ", new Object[]{streamName, host, port, t.getMessage(), t}); closeWriterQuietly(); closeClientQuietly(); return; } super.start(); LOG.info("StreamSink started.", getName()); }
Source:
<code>public Mono<Void> inspect(HealthMonitoringRecord record) { return Mono.fromRunnable(() -> { if (record.getSeverity() == HealthMonitoringRecord.HealthSeverity.ERROR) { <START> logger.error("Unhealthiness detected in the operation %s for %s.", record.operation.name(), record.lease.getId(), record.throwable); <END> } }); }</code><technical_language>this give intend. slf4j place holder %s please fix everywhere. slf4j print out %s is substitution. <LINK_0></technical_language>

Target:
public Mono<Void> inspect(HealthMonitoringRecord record) { return Mono.fromRunnable(() -> { if (record.getSeverity() == HealthMonitoringRecord.HealthSeverity.ERROR) { logger.error("Unhealthiness detected in the operation for {}.", record.operation.name(), record.lease.getId(), record.throwable); } }); }
Source:
<code>public void testUpdateQuotaRecords() { UsageVO usageVO = new UsageVO(); usageVO.setId(100L); usageVO.setQuotaCalculated(0); usageVO.setUsageType(UsageTypes.NETWORK_BYTES_SENT); usageVO.setRawUsage(9000000000.0); usageVO.setSize(1010101010L); QuotaTariffVO tariffVO = new QuotaTariffVO(); tariffVO.setCurrencyValue(new BigDecimal(1)); Mockito.when(quotaTariffDao.findTariffPlanByUsageType(Mockito.anyInt(), Mockito.any(Date.class))).thenReturn(tariffVO); quotaManager.updateQuotaNetwork(usageVO, UsageTypes.NETWORK_BYTES_SENT); quotaManager.updateQuotaAllocatedVMUsage(usageVO, new BigDecimal(0.5)); quotaManager.updateQuotaDiskUsage(usageVO, new BigDecimal(0.5), UsageTypes.VOLUME); quotaManager.updateQuotaRaw(usageVO, new BigDecimal(0.5), UsageTypes.VPN_USERS); Mockito.verify(quotaUsageDao, Mockito.times(4)).persistQuotaUsage(Mockito.any(QuotaUsageVO.class)); <START> Mockito.verify(usageDao, Mockito.times(4)).persistUsage(Mockito.any(UsageVO.class)); <END> }</code><technical_language>This test method contains asserts. do verify update of quota records is correct simply throwing exception</technical_language>

Target:
public void testUpdateQuotaRecords() { UsageVO usageVO = new UsageVO(); usageVO.setId(100L); usageVO.setQuotaCalculated(0); usageVO.setUsageType(UsageTypes.NETWORK_BYTES_SENT); usageVO.setRawUsage(9000000000.0); usageVO.setSize(1010101010L); QuotaTariffVO tariffVO = new QuotaTariffVO(); tariffVO.setCurrencyValue(new BigDecimal(1)); Mockito.when(quotaTariffDao.findTariffPlanByUsageType(Mockito.anyInt(), Mockito.any(Date.class))).thenReturn(tariffVO); QuotaUsageVO qu = quotaManager.updateQuotaNetwork(usageVO, UsageTypes.NETWORK_BYTES_SENT); assertTrue(qu.getQuotaUsed().compareTo(BigDecimal.ZERO) > 0); qu = quotaManager.updateQuotaAllocatedVMUsage(usageVO, new BigDecimal(0.5)); assertTrue(qu.getQuotaUsed().compareTo(BigDecimal.ZERO) > 0); qu = quotaManager.updateQuotaDiskUsage(usageVO, new BigDecimal(0.5), UsageTypes.VOLUME); assertTrue(qu.getQuotaUsed().compareTo(BigDecimal.ZERO) > 0); qu = quotaManager.updateQuotaRaw(usageVO, new BigDecimal(0.5), UsageTypes.VPN_USERS); assertTrue(qu.getQuotaUsed().compareTo(BigDecimal.ZERO) > 0); Mockito.verify(quotaUsageDao, Mockito.times(4)).persistQuotaUsage(Mockito.any(QuotaUsageVO.class)); Mockito.verify(usageDao, Mockito.times(4)).persistUsage(Mockito.any(UsageVO.class)); }
Source:
<code><START> public boolean containsAll(Collection<?> c) { <END> return fInnerElements.values().containsAll(c); }</code><technical_language>Do need special case for nulls in c</technical_language>

Target:
public boolean containsAll(Collection<?> c) { Collection<?> nonNullCollection = c; if (nonNullCollection.contains(null)) { if(!contains(null)) { return false; } nonNullCollection = c.stream().filter(Objects::nonNull).collect(Collectors.toList()); } return fInnerElements.values().containsAll(nonNullCollection); }
Source:
<code><START> static FilePath secretsDir(FilePath workspace) { <END> Computer computer = workspace.toComputer(); Node node = computer == null ? null : computer.getNode(); FilePath root = node == null ? workspace : node.getRootPath(); return root.child("secretFiles"); }</code><technical_language>Needs merge master</technical_language>

Target:
static FilePath secretsDir(FilePath workspace) { return tempDir(workspace).child("secretFiles"); }
Source:
<code>public String getTaskForm(String containerId, Long taskId, String language) { if( config.isRest() ) { Map<String, Object> valuesMap = new HashMap<String, Object>(); valuesMap.put(RestURI.CONTAINER_ID, containerId); valuesMap.put(RestURI.TASK_INSTANCE_ID, taskId); return makeHttpGetRequestAndCreateRawResponse( <START> build(loadBalancer.getUrl(), FORM_URI + "/" + TASK_FORM_GET_URI, valuesMap) + "?lang=" + language); <END> } else { CommandScript script = new CommandScript( Collections.singletonList( (KieServerCommand) new DescriptorCommand( "FormService", "getFormDisplayTask", new Object[]{taskId, language, true} )) ); ServiceResponse<String> response = (ServiceResponse<String>) executeJmsCommand( script, DescriptorCommand.class.getName(), "BPM-UI", containerId ).getResponses().get(0); throwExceptionOnFailure(response); return response.getResult(); } }</code><technical_language>here, is missing "filter" parameter</technical_language>

Target:
public String getTaskForm(String containerId, Long taskId, String language) { if( config.isRest() ) { Map<String, Object> valuesMap = new HashMap<String, Object>(); valuesMap.put(RestURI.CONTAINER_ID, containerId); valuesMap.put(RestURI.TASK_INSTANCE_ID, taskId); return makeHttpGetRequestAndCreateRawResponse( build(loadBalancer.getUrl(), FORM_URI + "/" + TASK_FORM_GET_URI, valuesMap) + "?lang=" + language + "&filter=true"); } else { CommandScript script = new CommandScript( Collections.singletonList( (KieServerCommand) new DescriptorCommand( "FormService", "getFormDisplayTask", new Object[]{taskId, language, true} )) ); ServiceResponse<String> response = (ServiceResponse<String>) executeJmsCommand( script, DescriptorCommand.class.getName(), "BPM-UI", containerId ).getResponses().get(0); throwExceptionOnFailure(response); return response.getResult(); } }
Source:
<code>public Response putCredentials(String message) throws IOException { Map<String, String> messageMap = gson.fromJson(message, new TypeToken<Map<String, String>>(){}.getType()); String entity = messageMap.get("entity"); String username = messageMap.get("username"); String password = messageMap.get("password"); if (entity == null || username == null || password == null) { <START> return new JsonResponse(Status.INTERNAL_SERVER_ERROR, "", "").build(); <END> } String user = SecurityUtils.getPrincipal(); logger.info("Update credentials for user entity {}", user, entity); UserCredentials uc = credentials.getUserCredentials(user); uc.putUsernamePassword(entity, new UsernamePassword(username, password)); credentials.putUserCredentials(user, uc); return new JsonResponse(Status.OK, "", "").build(); }</code><technical_language>Status.BAD_REQUEST more adequate here</technical_language>

Target:
public Response putCredentials(String message) throws IOException { Map<String, String> messageMap = gson.fromJson(message, new TypeToken<Map<String, String>>(){}.getType()); String entity = messageMap.get("entity"); String username = messageMap.get("username"); String password = messageMap.get("password"); if (entity == null || username == null || password == null) { return new JsonResponse(Status.BAD_REQUEST, "", "").build(); } String user = SecurityUtils.getPrincipal(); logger.info("Update credentials for user entity {}", user, entity); UserCredentials uc = credentials.getUserCredentials(user); uc.putUsernamePassword(entity, new UsernamePassword(username, password)); credentials.putUserCredentials(user, uc); return new JsonResponse(Status.OK, "", "").build(); }
Source:
<code><START> public View getView(int index, View view, ViewGroup arg2) { <END> MKOLUpdateElement e = (MKOLUpdateElement) getItem(index); if (currentView == null) { currentView = View.inflate(BaiduMapOfflineMapPreference.this.getContext(), R.layout.list_baidumap_offline_localmap_item, null); } view = currentView; initViewItem(view, e); return view; }</code><technical_language>@droneboost I meant. A ListView recycles views visible avoids creating new views user is scrolling up/down list. recycling View view parameter in getView(int index, View view, ViewGroup args) method. If view recycle, parameter is null, parameter null, reuse it. A typical example is follow: public View getView(int index, View view, ViewGroup args){ if (view == null){ view = View.inflate(...); } // else 'view' parameter is null, reuse inflation. initViewItem(view, ....); return view; } class field, overwriting view successive data, entries in listview identical</technical_language>

Target:
public View getView(int index, View view, ViewGroup arg2) { MKOLUpdateElement e = (MKOLUpdateElement) getItem(index); if (view == null) { view = View.inflate(BaiduMapOfflineMapPreference.this.getContext(), R.layout.list_baidumap_offline_localmap_item, null); } initViewItem(view, e); return view; }
Source:
<code>private void run() { logger.info("Creating presenter started..."); createPackageHierachyIndex(); createNameTokensPackage(); try { createNametokensClass(); <START> } catch (Exception e) { <END> failedStep = true; e.printStackTrace(); } try { fetchPresenterTemplates(); } catch (Exception e) { e.printStackTrace(); return; } createNameTokensFieldAndMethods(); createPresenterPackage(); createPresenterModule(); createPresenter(); createPresenterUiHandlers(); createPresenterView(); createPresenterViewUi(); createPresenterModuleLinkForGin(); logger.info("...Creating presenter finished."); }</code><technical_language>catch a more precise Exception subclass</technical_language>

Target:
private void run() { logger.info("Creating presenter started..."); createPackageHierachyIndex(); createNameTokensPackage(); try { createNametokensClass(); } catch (Exception e) { error("Could not create or find the name tokens file 'NameTokens.java': Error: " + e.toString()); failedStep = true; e.printStackTrace(); } try { fetchPresenterTemplates(); } catch (Exception e) { error("Could not fetch the nested presenter templates: Error: " + e.toString()); e.printStackTrace(); return; } createNameTokensFieldAndMethods(); createPresenterPackage(); createPresenterModule(); createPresenter(); createPresenterUiHandlers(); createPresenterView(); createPresenterViewUi(); createPresenterModuleLinkForGin(); logger.info("...Creating presenter finished."); }
Source:
<code>public void close() { if (containerContext != null) { containerContext.close(); if (moduleDeployer != null) { ConfigurableApplicationContext moduleCommon = moduleDeployer.getCommonContext(); if (moduleCommon != null) { <START> moduleCommon.close(); <END> } } } if (adminContext != null) { adminContext.close(); ApplicationContext parent = adminContext.getParent(); if (parent instanceof ConfigurableApplicationContext) { ((ConfigurableApplicationContext) parent).close(); } } }</code><technical_language>this is handled in SingleNode case, in distributed case, I correct? Moreover, launcher contexts a bit ugly me. I guess I expect more transparent (maybe listening for some kind of close event whatever?)</technical_language>

Target:
public void close() { if (containerContext != null) { containerContext.close(); } if (adminContext != null) { adminContext.close(); ApplicationContext parent = adminContext.getParent(); if (parent instanceof ConfigurableApplicationContext) { ((ConfigurableApplicationContext) parent).close(); } } }
Source:
<code>protected Scope visitUnion(Union node, Optional<Scope> scope) { if (!node.isDistinct().isPresent()) { <START> warningCollector.add(new PrestoWarning(PARSER_WARNING, "UNION specified without ALL or DISTINCT")); <END> } return visitSetOperation(node, scope); }</code><technical_language>give a more instructive message here. For example, "UNION DISTINCT keyword is equivalent UNION DISTINCT, is computationally expensive. Consider UNION possible, specifically add keyword DISTINCT stop this warning"</technical_language>

Target:
protected Scope visitUnion(Union node, Optional<Scope> scope) { if (!node.isDistinct().isPresent()) { warningCollector.add(new PrestoWarning(PARSER_WARNING, "UNION specified without ALL or DISTINCT" + " keyword is equivalent to UNION DISTINCT, which is computationally expensive. " + "Consider using UNION ALL when possible, or specifically add keyword DISTINCT to stop " + "getting this warning")); } return visitSetOperation(node, scope); }
Source:
<code>protected void initVm() { VmHandler.updateDisksFromDb(getVm()); getVm().setKvmEnable(getParameters().getKvmEnable()); getVm().setRunAndPause(getParameters().getRunAndPause() == null ? getVm().isRunAndPause() : getParameters().getRunAndPause()); getVm().setAcpiEnable(getParameters().getAcpiEnable()); getVm().setConsoleUserId(null); getParameters().setRunAsStateless(getParameters().getRunAsStateless() != null ? getParameters().getRunAsStateless() : getVm().isStateless()); getVm().setDisplayType(getParameters().getUseVnc() == null ? getVm().getDefaultDisplayType() : (getParameters().getUseVnc() ? DisplayType.vnc : DisplayType.qxl)); if (getParameters().getVncKeyboardLayout() == null) { getVm().setVncKeyboardLayout(getVm().getDefaultVncKeyboardLayout()); } else { getVm().setVncKeyboardLayout(getParameters().getVncKeyboardLayout()); <START> } <END> if (getParameters().getInitializationType() == null) { if (!getVm().isInitialized()) { getVm().setInitializationType(osRepository.isWindows(getVm().getVmOsId()) ? InitializationType.Sysprep : InitializationType.None); } } else { getVm().setInitializationType(getParameters().getInitializationType()); } if (!StringUtils.isEmpty(getParameters().getFloppyPath())) { getVmStaticDAO().update(getVm().getStaticData()); } getVm().setVdsGroupCpuFlagsData( CpuFlagsManagerHandler.GetVDSVerbDataByCpuName(getVm().getVdsGroupCpuName(), getVm() .getVdsGroupCompatibilityVersion())); }</code><technical_language>handled in runVmOnceCommand</technical_language>

Target:
protected void initVm() { VmHandler.updateDisksFromDb(getVm()); getVm().setKvmEnable(getParameters().getKvmEnable()); getVm().setRunAndPause(getParameters().getRunAndPause() == null ? getVm().isRunAndPause() : getParameters().getRunAndPause()); getVm().setAcpiEnable(getParameters().getAcpiEnable()); getVm().setConsoleUserId(null); getParameters().setRunAsStateless(getParameters().getRunAsStateless() != null ? getParameters().getRunAsStateless() : getVm().isStateless()); getVm().setDisplayType(getParameters().getUseVnc() == null ? getVm().getDefaultDisplayType() : (getParameters().getUseVnc() ? DisplayType.vnc : DisplayType.qxl)); if (getParameters().getInitializationType() == null) { if (!getVm().isInitialized()) { getVm().setInitializationType(osRepository.isWindows(getVm().getVmOsId()) ? InitializationType.Sysprep : InitializationType.None); } } else { getVm().setInitializationType(getParameters().getInitializationType()); } if (!StringUtils.isEmpty(getParameters().getFloppyPath())) { getVmStaticDAO().update(getVm().getStaticData()); } getVm().setVdsGroupCpuFlagsData( CpuFlagsManagerHandler.GetVDSVerbDataByCpuName(getVm().getVdsGroupCpuName(), getVm() .getVdsGroupCompatibilityVersion())); }
Source:
<code>public void testStartScannerNotExistingContainer() { ServerTemplate serverTemplate = createServerTemplate(); ContainerSpec container = new ContainerSpec("not-existing", "not-existing", serverTemplate, RELEASE_ID, KieContainerStatus.STARTED, null); try { controllerClient.startScanner(container, 1000L); fail("Should throw exception about container not found."); } catch (KieServerControllerClientException e) { assertNotFoundException((T) e); <START> assertEquals("No container spec found for id not-existing", <END> e.getMessage()); } }</code><technical_language>In this test class is imported org.assertj.core.api.Assertions.assertThat is need import JUnit asserts. Please replace assertEquals(epxpected, actual) assertThat(actual).isEqualTo(Expected)</technical_language>

Target:
public void testStartScannerNotExistingContainer() { ServerTemplate serverTemplate = createServerTemplate(); ContainerSpec container = new ContainerSpec("not-existing", "not-existing", serverTemplate, RELEASE_ID, KieContainerStatus.STARTED, null); try { controllerClient.startScanner(container, 1000L); fail("Should throw exception about container not found."); } catch (KieServerControllerClientException e) { assertNotFoundException((T) e); assertThat(e.getMessage()).endsWith("No container spec found for id not-existing"); } }
Source:
<code>private static int confirmLfsInstall() { MessageDialog dialog = new MessageDialog(null, UIText.ConfigurationChecker_installLfsTitle, null, UIText.ConfigurationChecker_installLfsMessage, MessageDialog.QUESTION, 0, UIText.ConfigurationChecker_installLfsYes, UIText.ConfigurationChecker_installLfsNo, UIText.ConfigurationChecker_installLfsDontAsk); <START> return dialog.open(); <END> }</code><technical_language>This API is new. work Eclipses >= Neon. baseline is Luna. Please other constructor String[]</technical_language>

Target:
private static int confirmLfsInstall() { MessageDialog dialog = new MessageDialog(null, UIText.ConfigurationChecker_installLfsTitle, null, UIText.ConfigurationChecker_installLfsMessage, MessageDialog.QUESTION, new String[] { UIText.ConfigurationChecker_installLfsYes, UIText.ConfigurationChecker_installLfsNo, UIText.ConfigurationChecker_installLfsDontAsk }, 0); return dialog.open(); }
Source:
<code>private void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { String sessionId = (String) request.getAttribute(SessionConstants.HTTP_SESSION_ENGINE_SESSION_ID_KEY); if (sessionId == null) { throw new ServletException("Engine session missing"); } Current current = new Current(); current.setSessionId(sessionId); current.setApplicationMode(findApplicationMode(sessionId)); current.setUser(findPrincipal(sessionId)); current.setRoot(getRoot(request)); current.setPrefix(getPrefix(request)); current.setPath(getPath(request)); current.setBackend(backend); <START> fromRequest(request, response, current); <END> CurrentManager.put(current); try { chain.doFilter(request, response); } finally { CurrentManager.remove(); } }</code><technical_language>put call current.getParameters().setParameter() here? String correlationId = getCorrelationId(request); if (correlationId != null) { current.getParameters().setParameter(CORRELATION_ID_PARAM, correlationId); }</technical_language>

Target:
private void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { String sessionId = (String) request.getAttribute(SessionConstants.HTTP_SESSION_ENGINE_SESSION_ID_KEY); if (sessionId == null) { throw new ServletException("Engine session missing"); } Current current = new Current(); current.setSessionId(sessionId); current.setApplicationMode(findApplicationMode(sessionId)); current.setUser(findPrincipal(sessionId)); current.setRoot(getRoot(request)); current.setPrefix(getPrefix(request)); current.setPath(getPath(request)); current.setBackend(backend); String correlationId = getCorrelationId(request); current.getParameters().put(CORRELATION_ID_PARAM, correlationId); response.setHeader(CORRELATION_ID_HEADER, correlationId); CurrentManager.put(current); try { chain.doFilter(request, response); } finally { CurrentManager.remove(); } }