auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void verify_put_invoked_one_time_when_invoke_get_default_state_in_multithreaded_environment() { final int numberOfEntities = 1000; <START> final Collection<Callable<Object>> tasks = new ArrayList<>(); <END> for (int i = 0; i < numberOfEntities; i++) { tasks.add(Executors.callable(new Runnable() { @Override public void run() { final TestEntity testEntity = TestEntity.newInstance(newUuid()); testEntity.getDefaultState(); } })); } executeInMultithreadedEnvironment(tasks); final int expected = 1; verify(spyMap, times(expected)).put(any(), any()); assertEquals(expected, spyMap.size()); }</code><technical_language>I a express intention Guava's API: java ... = Lists.newArrayListWithExpectedSize(numberOfEntities); (and static import for this method). Also, a collection of Callable<Void> better. though</technical_language>

Target:
public void verify_put_invoked_one_time_when_invoke_get_default_state_in_multithreaded_environment() { final int numberOfEntities = 1000; final Collection<Callable<Object>> tasks = newArrayListWithExpectedSize(numberOfEntities); for (int i = 0; i < numberOfEntities; i++) { tasks.add(Executors.callable(new Runnable() { @Override public void run() { final TestEntity testEntity = TestEntity.newInstance(newUuid()); testEntity.getDefaultState(); } })); } executeInMultithreadedEnvironment(tasks); final int expected = 1; verify(spyMap, times(expected)).put(any(), any()); assertEquals(expected, spyMap.size()); }
Source:
<code>public void invoke(@NotNull final Project project, final Editor editor, PsiFile file, DataContext dataContext) { if (!CommonRefactoringUtil.checkReadOnlyStatus(file)) return; if (editor.getSettings().isVariableInplaceRenameEnabled()) { final TemplateState templateState = TemplateManagerImpl.getTemplateState(editor); if (templateState != null && !templateState.isFinished()) return; } SelectionModel selectionModel = editor.getSelectionModel(); List<GoExpression> expressions = selectionModel.hasSelection() ? collectExpressionsInSelection(file, selectionModel) : collectExpressionsAtOffset(file, editor.getDocument(), editor.getCaretModel().getOffset()); if (expressions.size() > 1) { smartIntroduce(project, editor, expressions); } else if (expressions.size() == 1) { GoExpression expression = ContainerUtil.getFirstItem(expressions); <START> if (expression == null) { <END> showCannotPerform(project, editor); return; } performOnElement(project, editor, expression); } else { showCannotPerform(project, editor); } }</code><technical_language>chance a list of null values here</technical_language>

Target:
public void invoke(@NotNull final Project project, final Editor editor, PsiFile file, DataContext dataContext) { if (!CommonRefactoringUtil.checkReadOnlyStatus(file)) return; performAction(new GoIntroduceOperation(project, editor, file)); }
Source:
<code>public SearchRequestBuilder buildScrollSearchRequest() { String indices = index != null && !index.isEmpty() ? index : "_all"; List<String> fields = columns.stream() <START> .map(column -> column.getColumnName()) <END> .collect(toList()); SearchRequestBuilder searchRequestBuilder = client.prepareSearch(indices) .setTypes(type) .setSearchType(QUERY_THEN_FETCH) .setScroll(new TimeValue(scrollTimeout.toMillis())) .setFetchSource(fields.toArray(new String[fields.size()]), null) .setQuery(buildSearchQuery()) .setPreference("_shards:" + shard) .setSize(scrollSize); LOG.debug("ElasticSearch Request: %s", searchRequestBuilder); return searchRequestBuilder; }</code><technical_language>map(ElasticsearchColumnHandle::getColumnName)</technical_language>

Target:
public SearchRequestBuilder buildScrollSearchRequest() { String indices = index != null && !index.isEmpty() ? index : "_all"; List<String> fields = columns.stream() .map(ElasticsearchColumnHandle::getColumnName) .collect(toList()); SearchRequestBuilder searchRequestBuilder = client.prepareSearch(indices) .setTypes(type) .setSearchType(QUERY_THEN_FETCH) .setScroll(new TimeValue(scrollTimeout.toMillis())) .setFetchSource(fields.toArray(new String[0]), null) .setQuery(buildSearchQuery()) .setPreference("_shards:" + shard) .setSize(scrollSize); LOG.debug("Elasticsearch Request: %s", searchRequestBuilder); return searchRequestBuilder; }
Source:
<code>public void setHits(long accessHit) { <START> this.accessHit = accessHit > Integer.MAX_VALUE <END> ? Integer.MAX_VALUE : (int) accessHit; }</code><technical_language>do pretend long of interface methods while in fact int? I is for IMap</technical_language>

Target:
public void setHits(long accessHit) { this.hits = accessHit > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) accessHit; }
Source:
<code>private List<Item> items(ActivityFormDTO schema, List<LocationDTO> locations, SiteDTO site, List<SiteHistoryDTO> histories) { List<Item> items = new ArrayList<>(); Map<String, Object> baselineState = histories.get(0).getJsonMap(); RenderContext ctx = new RenderContext(schema, locations, site, baselineState); boolean first = true; for (SiteHistoryDTO history : histories) { <START> if (isAttachmentHistoryEntry(history.getEntityName())) { <END> continue; } ctx.setHistory(history); Item item = new Item(); if (first) { if (history.isInitial()) { item.setMsg(I18N.MESSAGES.siteHistoryCreated(history.getDateCreated(), history.getUserName(), history.getUserEmail())); } first = false; } else { item.setMsg(I18N.MESSAGES.siteHistoryUpdated(history.getDateCreated(), history.getUserName(), history.getUserEmail())); item.setDetails(details(ctx)); } items.add(item); } Collections.reverse(items); return items; }</code><technical_language>this skipping _all_ fields in update if update contains attachment? If for example, I update a site, changing a quantity field _and_ attachment, skip changes here? checking indicator type of field</technical_language>

Target:
private List<Item> items(ActivityFormDTO schema, List<LocationDTO> locations, SiteDTO site, List<SiteHistoryDTO> histories) { List<Item> items = new ArrayList<>(); Map<String, Object> baselineState = histories.get(0).getJsonMap(); RenderContext ctx = new RenderContext(schema, locations, site, baselineState); boolean first = true; for (SiteHistoryDTO history : histories) { ctx.setHistory(history); Item item = new Item(); if (first) { if (history.isInitial()) { item.setMsg(I18N.MESSAGES.siteHistoryCreated(history.getDateCreated(), history.getUserName(), history.getUserEmail())); } first = false; } else { item.setMsg(I18N.MESSAGES.siteHistoryUpdated(history.getDateCreated(), history.getUserName(), history.getUserEmail())); item.setDetails(details(ctx)); } items.add(item); } Collections.reverse(items); return items; }
Source:
<code>public void testLoadCatalogFromExternalFile() throws CatalogApiException, IOException, URISyntaxException { URL originURL = Resources.getResource("SpyCarBasic.xml"); File originFile = new File(originURL.toURI()); <START> File destinationFile = new File("/var/tmp/SpyCarBasic.xml"); <END> destinationFile.deleteOnExit(); Files.copy(originFile, destinationFile); final VersionedCatalog c = loader.loadDefaultCatalog(destinationFile.toURI().toString()); Assert.assertEquals(c.getCatalogName(), "SpyCarBasic"); }</code><technical_language>a temporary directory (/var/tmp exist), File.createTempFile for instance</technical_language>

Target:
public void testLoadCatalogFromExternalFile() throws CatalogApiException, IOException, URISyntaxException { File originFile = new File(Resources.getResource("SpyCarBasic.xml").toURI()); File destinationFile = new File(Files.createTempDir().toString() + "/SpyCarBasicRelocated.xml"); destinationFile.deleteOnExit(); Files.copy(originFile, destinationFile); final VersionedCatalog c = loader.loadDefaultCatalog(destinationFile.toURI().toString()); Assert.assertEquals(c.getCatalogName(), "SpyCarBasic"); }
Source:
<code>public void presentAnnotationIsAvailable() throws Exception { Method method = ClassWithDummyMethod.class.getMethod("annotatedDummyMethod"); FrameworkMethod frameworkMethod = new FrameworkMethod(method); Annotation annotation = frameworkMethod.getAnnotation(Rule.class); <START> assertThat(annotation, isA((Class)Rule.class)); <END> }</code><technical_language>style-nit: space cast operator (or previous suggestion)</technical_language>

Target:
public void presentAnnotationIsAvailable() throws Exception { Method method = ClassWithDummyMethod.class.getMethod("annotatedDummyMethod"); FrameworkMethod frameworkMethod = new FrameworkMethod(method); Annotation annotation = frameworkMethod.getAnnotation(Rule.class); assertTrue(Rule.class.isAssignableFrom(annotation.getClass())); }
Source:
<code>public void createSubscriptions(Long userId, String[] vocabularyCodes) { for (String vocabularyCode : vocabularyCodes) { <START> if (!notificationRepository.findByUserIdAndVocabularyCode(userId, vocabularyCode).isPresent()) { <END> final VocabularyV5 vocabulary = vocabularyRepository.findOne(vocabularyCode); if (vocabulary != null) { final VocabularyConversion vocabularyConversion = vocabularyConversionRepository.findByIdV5(vocabularyCode); final Notification newNotification = new Notification(userId, vocabularyConversion, vocabularyCode, vocabulary.getVersion()); notificationRepository.save(newNotification); } } } }</code><technical_language>propose select user's subscriptions filter out requested vocabularyCodes N queries time vocabulary is downloading</technical_language>

Target:
public void createSubscriptions(Long userId, String[] vocabularyCodes) { final List<String> subscribedVocabularies = notificationRepository.findByUserId(userId).stream() .map(Notification::getVocabularyCode).collect(Collectors.toList()); final String[] newVocabulariesToSubscribe = Stream.of(vocabularyCodes) .filter(code -> !subscribedVocabularies.contains(code)).toArray(String[]::new); vocabularyRepository.findByIdIn(newVocabulariesToSubscribe).forEach(vocabulary -> { final VocabularyConversion vocabularyConversion = vocabularyConversionRepository.findByIdV5(vocabulary.getId()); final Notification newNotification = new Notification(userId, vocabularyConversion, vocabulary.getId(), vocabulary.getVersion()); notificationRepository.save(newNotification); }); }
Source:
<code>public Map<UUID, Set<UUID>> createPhysicalLocatorSet(UUID locatorId) throws Exception { Insert<GenericTableSchema> op = plSetTable.insert(locatorId); try { <START> UUID newId = modify(client, plSetTable, op) .result(Duration.Inf()); <END> if (newId == null) throw new VtepException( endPoint, "cannot create locator set for locator: " + locatorId); Map<UUID, Set<UUID>> locatorSet = retrievePhysicalLocatorSet( plSetTable.getUuidMatcher(newId)); if (locatorSet.isEmpty()) throw new VtepException( endPoint, "cannot retrieve locator set for locator: " + locatorId); return locatorSet; } catch (TimeoutException tOut) { throw new VtepException(endPoint, tOut); } }</code><technical_language>unnecessary wrapping</technical_language>

Target:
public Map<UUID, Set<UUID>> createPhysicalLocatorSet(UUID locatorId) throws Exception { Insert<GenericTableSchema> op = plSetTable.insert(locatorId); try { UUID newId = modify(client, plSetTable, op).result(Duration.Inf()); if (newId == null) throw new VtepException( endPoint, "cannot create locator set for locator: " + locatorId); Map<UUID, Set<UUID>> locatorSet = retrievePhysicalLocatorSet( plSetTable.getUuidMatcher(newId)); if (locatorSet.isEmpty()) throw new VtepRetrievalException( "locator set for locator " + locatorId); return locatorSet; } catch (TimeoutException tOut) { throw new VtepException(endPoint, tOut); } }
Source:
<code>protected void decode(ChannelHandlerContext ctx, Object msg, List<Object> out) throws Exception { <START> if (LOG.isDebugEnabled()) { <END> LOG.debug("Received request from channel to decode.", msg, ctx.channel()); } if (!(msg instanceof ByteBuf)) { out.add(msg); return; } ByteBuf buffer = (ByteBuf) msg; buffer.markReaderIndex(); if (usingV3Protocol) { try { out.add(reqV3.decode(buffer)); } catch (InvalidProtocolBufferException e) { usingV3Protocol = false; buffer.resetReaderIndex(); out.add(reqPreV3.decode(buffer)); } } else { out.add(reqPreV3.decode(buffer)); } }</code><technical_language>bad merge in this file</technical_language>

Target:
protected void decode(ChannelHandlerContext ctx, Object msg, List<Object> out) throws Exception { if (LOG.isTraceEnabled()) { LOG.trace("Received request from channel to decode.", msg, ctx.channel()); } if (!(msg instanceof ByteBuf)) { out.add(msg); return; } ByteBuf buffer = (ByteBuf) msg; buffer.markReaderIndex(); if (usingV3Protocol) { try { out.add(reqV3.decode(buffer)); } catch (InvalidProtocolBufferException e) { usingV3Protocol = false; buffer.resetReaderIndex(); out.add(reqPreV3.decode(buffer)); } } else { out.add(reqPreV3.decode(buffer)); } }
Source:
<code>private boolean azureSingleResourceGroupDeploymentEnabled() { String userCrn = ThreadBasedUserCrnProvider.getUserCrn(); boolean azureSingleResourceGroupDeploymentEnabled = <START> entitlementService.azureSingleResourceGroupDeploymentEnabled(userCrn, Crn.safeFromString(userCrn).getAccountId()); <END> LOGGER.debug("Azure Single Resource Group deployment model is {}, generating default value accordingly!", azureSingleResourceGroupDeploymentEnabled ? "enabled" : "disabled"); return azureSingleResourceGroupDeploymentEnabled; }</code><technical_language>I internal crn here</technical_language>

Target:
private boolean azureSingleResourceGroupDeploymentEnabled() { String accountId = ThreadBasedUserCrnProvider.getAccountId(); boolean azureSingleResourceGroupDeploymentEnabled = entitlementService.azureSingleResourceGroupDeploymentEnabled(INTERNAL_ACTOR_CRN, accountId); LOGGER.debug("Azure Single Resource Group deployment model is {}, generating default value accordingly!", azureSingleResourceGroupDeploymentEnabled ? "enabled" : "disabled"); return azureSingleResourceGroupDeploymentEnabled; }
Source:
<code>public void testAmILeader() { BooleanResult isLeader1 = new BooleanResult(); BooleanResult isLeader2 = new BooleanResult(); ZkLeaderElector leaderElector1 = new ZkLeaderElector( "1", getZkUtilsWithNewClient(), new ZkLeaderElector.ZkLeaderElectorListener() { @Override public void onBecomingLeader() { isLeader1.res = true; } }); ZkLeaderElector leaderElector2 = new ZkLeaderElector( "2", getZkUtilsWithNewClient(), new ZkLeaderElector.ZkLeaderElectorListener() { @Override public void onBecomingLeader() { isLeader2.res = true; } }); <START> leaderElector1.amILeader(); <END> leaderElector2.amILeader(); Assert.assertFalse(TestZkUtils.testWithDelayBackOff(()->isLeader1.res, 2, 100)); Assert.assertFalse(TestZkUtils.testWithDelayBackOff(()->isLeader2.res, 2, 100)); leaderElector1.tryBecomeLeader(); leaderElector2.tryBecomeLeader(); Assert.assertTrue(leaderElector1.amILeader()); Assert.assertFalse(leaderElector2.amILeader()); }</code><technical_language>Do result check for Line 490-491</technical_language>

Target:
public void testAmILeader() { BooleanResult isLeader1 = new BooleanResult(); BooleanResult isLeader2 = new BooleanResult(); ZkLeaderElector leaderElector1 = new ZkLeaderElector( "1", getZkUtilsWithNewClient(), new ZkLeaderElector.ZkLeaderElectorListener() { @Override public void onBecomingLeader() { isLeader1.res = true; } }); ZkLeaderElector leaderElector2 = new ZkLeaderElector( "2", getZkUtilsWithNewClient(), new ZkLeaderElector.ZkLeaderElectorListener() { @Override public void onBecomingLeader() { isLeader2.res = true; } }); Assert.assertFalse(leaderElector1.amILeader()); Assert.assertFalse(leaderElector2.amILeader()); leaderElector1.tryBecomeLeader(); leaderElector2.tryBecomeLeader(); Assert.assertTrue(leaderElector1.amILeader()); Assert.assertFalse(leaderElector2.amILeader()); }
Source:
<code><START> @Deprecated @Override public ChunkBiomeContainer getBiomes() { throw new UnsupportedOperationException("Chunk method called on a cube"); } <END></code><technical_language>Redirect BigCube.getBiomes() throw</technical_language>

Target:
@Deprecated @Override public ChunkBiomeContainer getBiomes() { return this.cube.getBiomes(); }
Source:
<code>public RelNode convert(RelNode relNode) { FlinkLogicalAggregate agg = (FlinkLogicalAggregate) relNode; RelNode input = agg.getInput(); int[] groupSet = agg.getGroupSet().toArray(); RelTraitSet traitSet = relNode.getTraitSet().replace(FlinkConventions.BATCH_PHYSICAL()); Tuple2<int[], Seq<AggregateCall>> auxGroupSetAndCallsTuple = AggregateUtil.checkAndSplitAggCalls(agg); int[] auxGroupSet = auxGroupSetAndCallsTuple._1; Seq<AggregateCall> aggCallsWithoutAuxGroupCalls = auxGroupSetAndCallsTuple._2; Tuple3<int[][], DataType[][], UserDefinedFunction[]> aggBufferTypesAndFunctions = AggregateUtil.transformToBatchAggregateFunctions( aggCallsWithoutAuxGroupCalls, input.getRowType(), null); UserDefinedFunction[] aggFunctions = aggBufferTypesAndFunctions._3(); RelTraitSet requiredTraitSet = input.getTraitSet() .replace(FlinkConventions.BATCH_PHYSICAL()); if (groupSet.length != 0) { FlinkRelDistribution requiredDistribution = FlinkRelDistribution.hash(groupSet, false); requiredTraitSet = requiredTraitSet.replace(requiredDistribution); RelCollation sortCollation = createRelCollation(groupSet); requiredTraitSet = requiredTraitSet.replace(sortCollation); } else { requiredTraitSet = requiredTraitSet.replace(FlinkRelDistribution.SINGLETON()); } RelNode convInput = RelOptRule.convert(input, requiredTraitSet); return new BatchExecPythonGroupAggregate( relNode.getCluster(), <START> null, <END> traitSet, convInput, agg.getRowType(), convInput.getRowType(), convInput.getRowType(), groupSet, auxGroupSet, aggCallsWithoutAuxGroupCalls, aggFunctions); }</code><technical_language>set RelBuilder null</technical_language>

Target:
public RelNode convert(RelNode relNode) { FlinkLogicalAggregate agg = (FlinkLogicalAggregate) relNode; RelNode input = agg.getInput(); int[] groupSet = agg.getGroupSet().toArray(); RelTraitSet traitSet = relNode.getTraitSet().replace(FlinkConventions.BATCH_PHYSICAL()); Tuple2<int[], Seq<AggregateCall>> auxGroupSetAndCallsTuple = AggregateUtil.checkAndSplitAggCalls(agg); int[] auxGroupSet = auxGroupSetAndCallsTuple._1; Seq<AggregateCall> aggCallsWithoutAuxGroupCalls = auxGroupSetAndCallsTuple._2; Tuple3<int[][], DataType[][], UserDefinedFunction[]> aggBufferTypesAndFunctions = AggregateUtil.transformToBatchAggregateFunctions( aggCallsWithoutAuxGroupCalls, input.getRowType(), null); UserDefinedFunction[] aggFunctions = aggBufferTypesAndFunctions._3(); RelTraitSet requiredTraitSet = input.getTraitSet() .replace(FlinkConventions.BATCH_PHYSICAL()); if (groupSet.length != 0) { FlinkRelDistribution requiredDistribution = FlinkRelDistribution.hash(groupSet, false); requiredTraitSet = requiredTraitSet.replace(requiredDistribution); RelCollation sortCollation = createRelCollation(groupSet); requiredTraitSet = requiredTraitSet.replace(sortCollation); } else { requiredTraitSet = requiredTraitSet.replace(FlinkRelDistribution.SINGLETON()); } RelNode convInput = RelOptRule.convert(input, requiredTraitSet); return new BatchExecPythonGroupAggregate( relNode.getCluster(), traitSet, convInput, agg.getRowType(), convInput.getRowType(), convInput.getRowType(), groupSet, auxGroupSet, aggCallsWithoutAuxGroupCalls, aggFunctions); }
Source:
<code>public List<Todo> getTodoList() { ImmutableList<RowResult<byte[]>> results = transactionManager.runTaskWithRetry((transaction) -> { BatchingVisitable<RowResult<byte[]>> rowResultBatchingVisitable = transaction.getRange( TodoSchema.todoTable(), RangeRequest.all()); ImmutableList.Builder<RowResult<byte[]>> rowResults = ImmutableList.builder(); <START> rowResultBatchingVisitable.batchAccept(10, items -> { <END> rowResults.addAll(items); return true; }); return rowResults.build(); }); return results.stream() .map(RowResult::getOnlyColumnValue) .map(ValueType.STRING::convertToString) .map(ImmutableTodo::of) .collect(Collectors.toList()); }</code><technical_language>parameters this tests brittle; batch sizes explicitly defined tests (another reason txn manager directly)</technical_language>

Target:
public List<Todo> getTodoList() { ImmutableList<RowResult<byte[]>> results = transactionManager.runTaskWithRetry((transaction) -> { BatchingVisitable<RowResult<byte[]>> rowResultBatchingVisitable = transaction.getRange( TodoSchema.todoTable(), RangeRequest.all()); ImmutableList.Builder<RowResult<byte[]>> rowResults = ImmutableList.builder(); rowResultBatchingVisitable.batchAccept(1000, items -> { rowResults.addAll(items); return true; }); return rowResults.build(); }); return results.stream() .map(RowResult::getOnlyColumnValue) .map(ValueType.STRING::convertToString) .map(ImmutableTodo::of) .collect(Collectors.toList()); }
Source:
<code>private void shutdown() { Fuseki.serverLog.info("Shutting down dataset") ; dataset.close() ; if ( dataset instanceof DatasetGraphTransaction ) { DatasetGraphTransaction dsgtxn = (DatasetGraphTransaction)dataset ; <START> StoreConnection.release(dsgtxn.getLocation()) ; <END> } dataset = null ; }</code><technical_language>remove unused #checkShutdown requestCounter</technical_language>

Target:
public synchronized void shutdown() { if ( state == CLOSING ) return; Fuseki.serverLog.info(format("Shutting down data service for %s", endpoints.keySet())); expel(dataset); dataset = null; state = CLOSED; }
Source:
<code>public CreativeTabs toNative(Category category, ItemStack item) { if (category.name.startsWith("nova:")) { switch (category.name) { case Category.BUILDING_BLOCKS_NAME: return CreativeTabs.tabBlock; case Category.DECORATIONS_NAME: return CreativeTabs.tabDecorations; case Category.TECHNOLOGY_NAME: return CreativeTabs.tabRedstone; case Category.TRANSPORTATION_NAME: return CreativeTabs.tabTransport; case Category.FOOD_NAME: return CreativeTabs.tabFood; case Category.TOOLS_NAME: return CreativeTabs.tabTools; case Category.COMBAT_NAME: return CreativeTabs.tabCombat; case Category.ALCHEMY_NAME: return CreativeTabs.tabBrewing; case Category.MATERIALS_NAME: return CreativeTabs.tabMaterials; case Category.MISCELLANEOUS_NAME: return CreativeTabs.tabMisc; } } Optional<CreativeTabs> first = Arrays.stream(CreativeTabs.creativeTabArray) .filter(tab -> tab.getTabLabel().equals(category.name)) .findFirst(); if (first.isPresent()) { return first.get(); } else { Optional<Item> categoryItem = category.item; <START> ModCreativeTab tab = new ModCreativeTab(category.name, categoryItem.isPresent() ? Game.natives().toNative(categoryItem.get()) : item); <END> return tab; } }</code><technical_language>Refactor categoryItem.isPresent() ? Game.natives().toNative(categoryItem.get()) : item out a local var. This written category.item.map(Game.natives()::toNative).orElse(item)</technical_language>

Target:
public CreativeTabs toNative(Category category, ItemStack item) { if (category.name.startsWith("nova:")) { switch (category.name) { case Category.BUILDING_BLOCKS_NAME: return CreativeTabs.tabBlock; case Category.DECORATIONS_NAME: return CreativeTabs.tabDecorations; case Category.TECHNOLOGY_NAME: return CreativeTabs.tabRedstone; case Category.TRANSPORTATION_NAME: return CreativeTabs.tabTransport; case Category.FOOD_NAME: return CreativeTabs.tabFood; case Category.TOOLS_NAME: return CreativeTabs.tabTools; case Category.COMBAT_NAME: return CreativeTabs.tabCombat; case Category.ALCHEMY_NAME: return CreativeTabs.tabBrewing; case Category.MATERIALS_NAME: return CreativeTabs.tabMaterials; case Category.MISCELLANEOUS_NAME: return CreativeTabs.tabMisc; } } return Arrays.stream(CreativeTabs.creativeTabArray) .filter(tab -> tab.getTabLabel().equals(category.name)) .findFirst() .orElseGet(() -> new ModCreativeTab(category.name, category.item.map(ItemConverter.instance()::toNative).orElse(item))); }
Source:
<code>public TemplateEngineFreemarkerAuthenticityFormDirective(Context context) { <START> this.authenticityToken = context.getSession().getAuthenticityToken(); <END> }</code><technical_language>please do this in execute method. adding __AT session - if is needed..</technical_language>

Target:
public TemplateEngineFreemarkerAuthenticityFormDirective(Context context) { this.context = context; }
Source:
<code>public void test() throws InterruptedException { Thread.sleep(5000L); verify(eventListener, atLeast(4)).handleEvent("testSchedulerMultipleExecutions"); verify(eventListener, atLeast(2)).handleEvent("testSchedulerSingleExecution"); <START> verify(eventListener, atMost(3)).handleEvent("testSchedulerSingleExecution"); <END> }</code><technical_language>Generally tests sleep slows run - for a scheduler test other ways do testing. In a perfect world tests ok, slow machines time-based tests reliable. I prefer tests do explicit waits releases of job based CountDownLatch. If entails please try update PR for that. push is need carefully watch for failures if case disable test</technical_language>

Target:
public void test() throws ReflectiveOperationException, SchedulerException { Field schedulerField = SchedulerServiceImpl.class.getDeclaredField("scheduler"); schedulerField.setAccessible(true); Scheduler scheduler = (Scheduler) schedulerField.get(schedulerService); JobKey jobKey = new JobKey("testSchedulerMultipleExecutions", "nuxeo"); JobDetail jobDetail = scheduler.getJobDetail(jobKey); assertThat(jobDetail).isNotNull(); assertThat(jobDetail.isConcurrentExectionDisallowed()).isFalse(); jobKey = new JobKey("testSchedulerSingleExecution", "nuxeo"); jobDetail = scheduler.getJobDetail(jobKey); assertThat(jobDetail).isNotNull(); assertThat(jobDetail.isConcurrentExectionDisallowed()).isTrue(); }
Source:
<code>private void decrementLatchAndHandle(int count) { if (latch.addAndGet(-count) > 0) { return; } Map<Integer, Object> result = createHashMap(partitionResults.length()); <START> for (int partitionId = 0; partitionId < partitionResults.length(); partitionId++) { <END> Object partitionResult = partitionResults.get(partitionId); if (partitionResult instanceof Throwable) { future.setResult(partitionResult); if (callback != null) { callback.onFailure((Throwable) partitionResult); } return; } if (partitionResult != null) { result.put(partitionId, partitionResult); } } future.setResult(result); if (callback != null) { callback.onResponse(result); } }</code><technical_language>if invoked partitions [5, 10, 5000]</technical_language>

Target:
private void decrementLatchAndHandle(int count) { if (latch.addAndGet(-count) > 0) { return; } Map<Integer, Object> result = createHashMap(partitionResults.length()); for (int partitionId = 0; partitionId < partitionResults.length(); partitionId++) { Object partitionResult = partitionResults.get(partitionId); if (partitionResult instanceof Throwable) { future.setResult(partitionResult); if (callback != null) { callback.onFailure((Throwable) partitionResult); } return; } if (partitionResult != null) { result.put(partitionId, partitionResult == NULL_RESULT ? null : partitionResult); } } future.setResult(result); if (callback != null) { callback.onResponse(result); } }
Source:
<code><START> public NoVotePresenter( <END> EventBus eventBus, MyView view, MyProxy proxy) { super(eventBus, view, proxy, ApplicationPresenter.SLOT_MAIN); }</code><technical_language>rm public</technical_language>

Target:
NoVotePresenter( EventBus eventBus, MyView view, MyProxy proxy) { super(eventBus, view, proxy, ApplicationPresenter.SLOT_MAIN); }
Source:
<code>public void testRuleDirExpansion() throws Exception { scratch.file( "foo/BUILD", "genrule(name = 'bar',", " srcs = ['bar_in.txt'],", " cmd = 'touch $(RULEDIR)',", " outs = ['bar/bar_out.txt'])", "genrule(name = 'baz',", " srcs = ['bar/bar_out.txt'],", " cmd = 'touch $(RULEDIR)',", " outs = ['logs/baz_out.txt', 'logs/baz.log'])"); <START> getConfiguredTarget(" END> FileConfiguredTarget bazOutTarget = getFileConfiguredTarget(" SpawnAction bazAction = (SpawnAction) getGeneratingAction(bazOutTarget.getArtifact()); String fooExpected = "touch " + bazOutTarget .getArtifact() .getExecPath() .getParentDirectory() .getParentDirectory() .getPathString(); getConfiguredTarget(" Artifact barOut = bazAction.getInputs().iterator().next(); assertThat(barOut.getExecPath().endsWith(PathFragment.create("foo/bar/bar_out.txt"))).isTrue(); SpawnAction barAction = (SpawnAction) getGeneratingAction(barOut); String barExpected = "touch " + barOut.getExecPath().getParentDirectory().getPathString(); assertCommandEquals(fooExpected, barAction.getArguments().get(2)); assertCommandEquals(fooExpected, bazAction.getArguments().get(2)); assertThat(fooExpected.equals(barExpected)).isFalse(); }</code><technical_language>nit: getCommand("//foo:bar") do exact (except a lines shorter)</technical_language>

Target:
public void testRuleDirExpansion() throws Exception { scratch.file( "foo/BUILD", "genrule(name = 'bar',", " srcs = ['bar_in.txt'],", " cmd = 'touch $(RULEDIR)',", " outs = ['bar/bar_out.txt'])", "genrule(name = 'baz',", " srcs = ['bar/bar_out.txt'],", " cmd = 'touch $(RULEDIR)',", " outs = ['baz/baz_out.txt', 'logs/baz.log'])"); String expectedRegex = "touch bazel-out.*foo"; assertThat(getCommand(" assertThat(getCommand(" }
Source:
<code>protected boolean canDoAction() { GlusterVolumeEntity volume = getGlusterVolume(); if (!super.canDoAction()) { return false; } <START> if (volume.getAsyncTask() == null || volume.getAsyncTask().getType() != GlusterTaskType.REMOVE_BRICK <END> || volume.getAsyncTask().getStatus() != JobExecutionStatus.STARTED) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_GLUSTER_VOLUME_REMOVE_BRICKS_NOT_STARTED); } return true; }</code><technical_language>Out of curiosity - I assume guys gluster tasks in some commands, a GlusterTaskUtils helper class a method check if a gluster task is of a type checking null equals a type , simply negate result of this method</technical_language>

Target:
protected boolean canDoAction() { GlusterVolumeEntity volume = getGlusterVolume(); if (!super.canDoAction()) { return false; } if (!(GlusterTaskUtils.isTaskOfType(volume, GlusterTaskType.REMOVE_BRICK)) || !(GlusterTaskUtils.isTaskStatus(volume, JobExecutionStatus.STARTED))) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_GLUSTER_VOLUME_REMOVE_BRICKS_NOT_STARTED); } return true; }
Source:
<code>public final void run() { try (FlowScopeLog log = new FlowScopeLogBuilder(LOGGER, Level.FINE, "TimeGraphView:ZoomThread", "start", fZoomStartTime, "end", fZoomEndTime).setCategoryAndId(getViewId(), fScopeId).build()) { doRun(); } finally { <START> fDirty.updateAndGet(i -> i > 0 ? i - 1 : i); <END> } }</code><technical_language>I suspect exceptions is is causing problem adding 'finally' blocks is helps. If is incorrect dirty count is another design problem fixed. wary of hiding problem in this way. I suggest detect error log it, this: if (fDirty.getAndUpdate(...) <= 0) { Activator.logError(...); }</technical_language>

Target:
public final void run() { try (FlowScopeLog log = new FlowScopeLogBuilder(LOGGER, Level.FINE, "TimeGraphView:ZoomThread", "start", fZoomStartTime, "end", fZoomEndTime).setCategoryAndId(getViewId(), fScopeId).build()) { doRun(); } finally { fDirty.incrementAndGet(); } }
Source:
<code>private void populateInheritance(Table table, Set<Table> processed) { <START> if (table.hasParent() && !processed.contains(table)) { <END> Table parent = table.getParent(this.elideTableConfig); if (parent.hasParent()) { populateInheritance(parent, processed); } Map<String, Measure> measures = getInheritedMeasures(table, new HashMap<String, Measure>()); table.setMeasures(new ArrayList<Measure>(measures.values())); Map<String, Dimension> dimensions = getInheritedDimensions(table, new HashMap<String, Dimension>()); table.setDimensions(new ArrayList<Dimension>(dimensions.values())); Map<String, Join> joins = getInheritedJoins(table, new HashMap<String, Join>()); table.setJoins(new ArrayList<Join>(joins.values())); String schema = getInheritedSchema(table); table.setSchema(schema); String dbConnectionName = (String) getInheritedConnection(table); table.setDbConnectionName(dbConnectionName); String sql = (String) getInheritedSql(table); table.setSql(sql); String tableName = (String) getInheritedTable(table); table.setTable(tableName); } processed.add(table); }</code><technical_language>Nitpick - I invert this if condition return early if is true. entire function nested this if block (it helps line length readability)</technical_language>

Target:
private void populateInheritance(Table table, Set<Table> processed) { if (processed.contains(table)) { return; } processed.add(table); if (!table.hasParent()) { return; } Table parent = table.getParent(this.elideTableConfig); if (!processed.contains(parent)) { populateInheritance(parent, processed); } Map<String, Measure> measures = getInheritedMeasures(parent, attributesListToMap(table.getMeasures())); table.setMeasures(new ArrayList<Measure>(measures.values())); Map<String, Dimension> dimensions = getInheritedDimensions(parent, attributesListToMap(table.getDimensions())); table.setDimensions(new ArrayList<Dimension>(dimensions.values())); Map<String, Join> joins = getInheritedJoins(parent, attributesListToMap(table.getJoins())); table.setJoins(new ArrayList<Join>(joins.values())); String schema = getInheritedSchema(parent, table.getSchema()); table.setSchema(schema); String dbConnectionName = (String) getInheritedConnection(parent, table.getDbConnectionName()); table.setDbConnectionName(dbConnectionName); String sql = (String) getInheritedSql(parent, table.getSql()); table.setSql(sql); String tableName = (String) getInheritedTable(parent, table.getTable()); table.setTable(tableName); }
Source:
<code>protected boolean handle(Op op, int framelen) throws IOException { assert Thread.currentThread() instanceof EitherSide.Reader; switch (op) { case EXIT: onExit(dis.readInt()); return true; case STDOUT: onStdout(readChunk(framelen)); return true; case STDERR: onStderr(readChunk(framelen)); return true; default: <START> return false; <END> } }</code><technical_language>assert</technical_language>

Target:
protected boolean handle(Op op, int framelen) throws IOException { assert Thread.currentThread() instanceof EitherSide.Reader; assert !op.clientSide; switch (op) { case EXIT: onExit(dis.readInt()); return true; case STDOUT: onStdout(readChunk(framelen)); return true; case STDERR: onStderr(readChunk(framelen)); return true; default: return false; } }
Source:
<code><START> public void persist(CatalogItem<?, ?> catalogItem) { <END> checkArgument(getCatalogItem(catalogItem.getSymbolicName(), catalogItem.getVersion()) != null, "Unknown catalog item %s", catalogItem); mgmt.getRebindManager().getChangeListener().onUnmanaged(catalogItem); }</code><technical_language>this interface BrooklynCatalog</technical_language>

Target:
public void persist(CatalogItem<?, ?> catalogItem) { checkArgument(getCatalogItem(catalogItem.getSymbolicName(), catalogItem.getVersion()) != null, "Unknown catalog item %s", catalogItem); mgmt.getRebindManager().getChangeListener().onChanged(catalogItem); }
Source:
<code>protected Void visitIntegerLiteral(IntegerLiteral node, Integer indent) { <START> builder.append(String.format(Locale.ENGLISH, "%d", node.getValue())); <END> return null; }</code><technical_language>suggestion builder.append(Integer.toString(node.getValue())); Cheaper String.format</technical_language>

Target:
protected Void visitIntegerLiteral(IntegerLiteral node, Integer indent) { builder.append(node.getValue()); return null; }
Source:
<code>public void setParams(Collection<?> set) { if (set != null) { this.set = set; elements = set.toArray(); this.hasS = true; prob = set.isEmpty() ? 1 : 1.0 / set.size(); logprob = set.isEmpty() ? 0 : (-Math.log(set.size())); <START> finiteSupport = elements.clone(); <END> } }</code><technical_language>clone</technical_language>

Target:
public void setParams(Collection<?> set) { if (set != null) { this.set = set; elements = set.toArray(); this.hasS = true; prob = set.isEmpty() ? 1 : 1.0 / set.size(); logprob = set.isEmpty() ? 0 : (-Math.log(set.size())); } }
Source:
<code><START> public void mouseUp(MouseEvent e) { <END> if (DRAG_NONE != _dragState) { setCapture(false); if (e.button == 1 && DRAG_TRACE_ITEM == _dragState) { _timeProvider.notifyStartFinishTime(); if (_dragX == _dragX0) { long time = getTimeAtX(e.x); _timeProvider.setSelectedTimeNotify(time, false); } _dragState = DRAG_NONE; } else if (e.button == 1 && DRAG_SPLIT_LINE == _dragState) { redraw(); _dragState = DRAG_NONE; } else if (e.button == 3 && DRAG_ZOOM == _dragState) { Point size = getCtrlSize(); int nameWidth = _timeProvider.getNameSpace(); int x = e.x - nameWidth; if (Math.max(_dragX, _dragX0) > nameWidth && _dragX != _dragX0) { long time0 = getTimeAtX(_dragX0); long time1 = getTimeAtX(_dragX); if (time0 < time1) { _timeProvider.setStartFinishTimeNotify(time0, time1); } else { _timeProvider.setStartFinishTimeNotify(time1, time0); } } else { redraw(); } _dragState = DRAG_NONE; } } }</code><technical_language>if (fPendingMenuDetectEvent != null && e.button == 3) { menuDetected(fPendingMenuDetectEvent); }</technical_language>

Target:
public void mouseUp(MouseEvent e) { if (fPendingMenuDetectEvent != null && e.button == 3 && _dragX == _dragX0) { setCapture(false); _dragState = DRAG_NONE; menuDetectedImpl(fPendingMenuDetectEvent); } if (DRAG_NONE != _dragState) { setCapture(false); if (e.button == 1 && DRAG_TRACE_ITEM == _dragState) { _timeProvider.notifyStartFinishTime(); if (_dragX == _dragX0) { long time = getTimeAtX(e.x); _timeProvider.setSelectedTimeNotify(time, false); } _dragState = DRAG_NONE; } else if (e.button == 1 && DRAG_SPLIT_LINE == _dragState) { redraw(); _dragState = DRAG_NONE; } else if (e.button == 3 && DRAG_ZOOM == _dragState) { Point size = getCtrlSize(); int nameWidth = _timeProvider.getNameSpace(); int x = e.x - nameWidth; if (Math.max(_dragX, _dragX0) > nameWidth && _dragX != _dragX0) { long time0 = getTimeAtX(_dragX0); long time1 = getTimeAtX(_dragX); if (time0 < time1) { _timeProvider.setStartFinishTimeNotify(time0, time1); } else { _timeProvider.setStartFinishTimeNotify(time1, time0); } } else { redraw(); } _dragState = DRAG_NONE; } } }
Source:
<code>public static BodyBuilder method(HttpMethod method, String uri) { <START> return new DefaultBodyBuilder(method, new UriTemplate(uri)); <END> }</code><technical_language>UriTemplate here, String in end in getUrl()? is benefit reason create a UriTemplate point in this class</technical_language>

Target:
public static BodyBuilder method(HttpMethod method, String uri) { return new DefaultBodyBuilder(method, uri); }
Source:
<code>private List<String> getAllProcessedFiles(BatchSourceContext batchSourceContext) { KeyValueTable table = batchSourceContext.getDataset(excelInputreaderConfig.memoryTableName); List<String> processedFiles = new ArrayList<>(); try (CloseableIterator<KeyValue<byte[], byte[]>> filesIterable = table.scan(null, null)) { <START> while (filesIterable.hasNext()) { <END> KeyValue<byte[], byte[]> file = filesIterable.next(); processedFiles.add(new String(file.getKey(), Charsets.UTF_8)); } } return processedFiles; }</code><technical_language>key table growing is a TTL set this. a while this table large a long time return. need able set TTL ask for this configuration user right</technical_language>

Target:
private List<String> getAllProcessedFiles(BatchSourceContext batchSourceContext) { List<String> processedFiles = new ArrayList<>(); if (!excelInputreaderConfig.reprocess) { KeyValueTable table = batchSourceContext.getDataset(excelInputreaderConfig.memoryTableName); processedFiles = new ArrayList<>(); Calendar cal = Calendar.getInstance(); cal.add(Calendar.DATE, -Integer.valueOf(excelInputreaderConfig.tableExpiryPeriod)); Date expiryDate = cal.getTime(); try (CloseableIterator<KeyValue<byte[], byte[]>> filesIterable = table.scan(null, null)) { while (filesIterable.hasNext()) { KeyValue<byte[], byte[]> file = filesIterable.next(); Long time = Bytes.toLong(file.getValue()); Date processedDate = new Date(time); if (processedDate.before(expiryDate)) { table.delete(file.getKey()); } else { processedFiles.add(new String(file.getKey(), Charsets.UTF_8)); } } } } return processedFiles; }
Source:
<code>Mono<PartitionPublishingProperties> getPartitionPublishingProperties(String partitionId) { PartitionPublishingState publishingState = getClientPartitionPublishingState(partitionId); if (publishingState.isFromLink()) { <START> return Mono.just(publishingState.toPartitionPublishingProperties()); <END> } else { return withRetry(this.getSendLink(partitionId).flatMap(amqpSendLink -> Mono.just(this.getClientPartitionPublishingState(partitionId))), retryOptions.getTryTimeout(), retryPolicy).map( PartitionPublishingState::toPartitionPublishingProperties); } }</code><technical_language>Mono.defer() instead wait user subscribes call publishingState.toPartitionPublishingProperties()</technical_language>

Target:
Mono<PartitionPublishingProperties> getPartitionPublishingProperties(String partitionId) { PartitionPublishingState publishingState = getClientPartitionPublishingState(partitionId); if (publishingState.isFromLink()) { return Mono.defer(() -> Mono.just(publishingState.toPartitionPublishingProperties())); } else { return withRetry(getSendLink(partitionId).flatMap(amqpSendLink -> Mono.just(getClientPartitionPublishingState(partitionId))), retryOptions.getTryTimeout(), retryPolicy).map( PartitionPublishingState::toPartitionPublishingProperties); } }
Source:
<code>private void stopJobExecution(final Exception cause) throws Exception { validateRunsInMainThread(); <START> Exception resultingException = null; <END> stopScheduling(cause); disconnectTaskManagerResourceManagerConnections(cause); try { stopJobMasterServices(); } catch (Exception e) { resultingException = e; } ExceptionUtils.tryRethrowException(resultingException); }</code><technical_language>Move this closer try block</technical_language>

Target:
private void stopJobExecution(final Exception cause) throws Exception { validateRunsInMainThread(); stopScheduling(cause); disconnectTaskManagerResourceManagerConnections(cause); Exception resultingException = null; try { stopJobMasterServices(); } catch (Exception e) { resultingException = e; } ExceptionUtils.tryRethrowException(resultingException); }
Source:
<code>public void testWithNullArrays() { final KeySet keySetOriginal = new KeySet(); final byte[] authenticationKey = null; keySetOriginal.setAuthenticationKey(authenticationKey); final byte[] encryptionKey = null; keySetOriginal.setEncryptionKey(encryptionKey); <START> final com.alliander.osgp.domain.core.valueobjects.smartmetering.KeySet keySetMapped = this.mapperFactory <END> .getMapperFacade().map(keySetOriginal, com.alliander.osgp.domain.core.valueobjects.smartmetering.KeySet.class); assertNotNull(keySetMapped); assertNull(keySetMapped.getAuthenticationKey()); assertNull(keySetMapped.getEncryptionKey()); }</code><technical_language>original mapper</technical_language>

Target:
public void testWithNullArrays() { final KeySet keySetOriginal = new KeySet(); final byte[] authenticationKey = null; keySetOriginal.setAuthenticationKey(authenticationKey); final byte[] encryptionKey = null; keySetOriginal.setEncryptionKey(encryptionKey); final com.alliander.osgp.domain.core.valueobjects.smartmetering.KeySet keySetMapped = this.configurationMapper .map(keySetOriginal, com.alliander.osgp.domain.core.valueobjects.smartmetering.KeySet.class); assertNotNull(keySetMapped); assertNull(keySetMapped.getAuthenticationKey()); assertNull(keySetMapped.getEncryptionKey()); }
Source:
<code>public static void main(String... args) throws Exception { <START> Thread.setDefaultUncaughtExceptionHandler((t, e) -> LOGGER.log(Level.SEVERE, "Unhandled exception in thread " + t, e)); <END> Launcher launcher = new Launcher(); CmdLineParser parser = new CmdLineParser(launcher); try { parser.parseArgument(args); launcher.run(); } catch (CmdLineException e) { System.err.println(e.getMessage()); System.err.println("java -jar slave.jar [options...]"); parser.printUsage(System.err); System.err.println(); } }</code><technical_language>approach logging initialized Master side</technical_language>

Target:
public static void main(String... args) throws Exception { Launcher launcher = new Launcher(); CmdLineParser parser = new CmdLineParser(launcher); try { parser.parseArgument(args); launcher.run(); } catch (CmdLineException e) { System.err.println(e.getMessage()); System.err.println("java -jar slave.jar [options...]"); parser.printUsage(System.err); System.err.println(); } }
Source:
<code>public JdbcOptions build() { checkNotNull(dbURL, "No dbURL supplied."); checkNotNull(tableName, "No tableName supplied."); if (this.dialect == null) { Optional<JdbcDialect> optional = JdbcDialects.get(dbURL); this.dialect = optional.orElseGet(() -> { throw new NullPointerException("Unknown dbURL,can not find proper dialect."); }); } if (this.driverName == null) { Optional<String> optional = dialect.defaultDriverName(); this.driverName = optional.orElseGet(() -> { throw new NullPointerException("No driverName supplied."); }); } <START> return new JdbcOptions(dbURL, tableName, driverName, username, password, dialect,connectionCheckTimeoutSeconds); <END> }</code><technical_language>Add space connectionCheckTimeoutSeconds</technical_language>

Target:
public JdbcOptions build() { checkNotNull(dbURL, "No dbURL supplied."); checkNotNull(tableName, "No tableName supplied."); if (this.dialect == null) { Optional<JdbcDialect> optional = JdbcDialects.get(dbURL); this.dialect = optional.orElseGet(() -> { throw new NullPointerException("Unknown dbURL,can not find proper dialect."); }); } if (this.driverName == null) { Optional<String> optional = dialect.defaultDriverName(); this.driverName = optional.orElseGet(() -> { throw new NullPointerException("No driverName supplied."); }); } return new JdbcOptions(dbURL, tableName, driverName, username, password, dialect, parallelism, connectionCheckTimeoutSeconds); }
Source:
<code>public void testOtherSoundsSettings_touchVibration() throws Exception { Vibrator mVibrator = (Vibrator) getInstrumentation().getTargetContext().getSystemService(Context.VIBRATOR_SERVICE); if <START> (mVibrator.hasVibrator() == false) return; <END> int originalValue = Settings.System.getInt( mContentResolver, Settings.System.HAPTIC_FEEDBACK_ENABLED, -1); assertTrue("Touch vibration does not exist.", originalValue != -1); mBackupUtils.backupNowAndAssertSuccess(SETTINGS_PACKAGE_NAME); boolean ret = Settings.System.putInt( mContentResolver, Settings.System.HAPTIC_FEEDBACK_ENABLED, 1 - originalValue); assertTrue("Toggle Touch vibration fail.", ret); mBackupUtils.restoreAndAssertSuccess(LOCAL_TRANSPORT_TOKEN, SETTINGS_PACKAGE_NAME); int restoreValue = Settings.System.getInt( mContentResolver, Settings.System.HAPTIC_FEEDBACK_ENABLED, -1); assertTrue("Touch vibration restore fail.", originalValue == restoreValue); }</code><technical_language>nit: change "!Vibrator.hasVibrator()"</technical_language>

Target:
public void testOtherSoundsSettings_touchVibration() throws Exception { Vibrator mVibrator = (Vibrator) getInstrumentation().getTargetContext().getSystemService(Context.VIBRATOR_SERVICE); if (!mVibrator.hasVibrator()) return; int originalValue = Settings.System.getInt( mContentResolver, Settings.System.HAPTIC_FEEDBACK_ENABLED, -1); assertTrue("Touch vibration does not exist.", originalValue != -1); mBackupUtils.backupNowAndAssertSuccess(SETTINGS_PACKAGE_NAME); boolean ret = Settings.System.putInt( mContentResolver, Settings.System.HAPTIC_FEEDBACK_ENABLED, 1 - originalValue); assertTrue("Toggle Touch vibration fail.", ret); mBackupUtils.restoreAndAssertSuccess(LOCAL_TRANSPORT_TOKEN, SETTINGS_PACKAGE_NAME); int restoreValue = Settings.System.getInt( mContentResolver, Settings.System.HAPTIC_FEEDBACK_ENABLED, -1); assertTrue("Touch vibration restore fail.", originalValue == restoreValue); }