auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void testStateHolderFailureRereadBehavior() throws ClassNotFoundException { StateHolder<Integer, ObjectStreamClass> stateHolder = spy(new TransientStateHolder<>()); StateRepository stateRepository = mock(StateRepository.class); when(stateRepository.getPersistentStateHolder(eq("CompactJavaSerializer-ObjectStreamClassIndex"), eq(Integer.class), eq(ObjectStreamClass.class), any(), any())).thenReturn(stateHolder); AtomicBoolean failing = new AtomicBoolean(); Answer<Object> optionalFailure = invocation -> { try { return invocation.callRealMethod(); } finally { if (failing.get()) { throw new RuntimeException(); } } }; doAnswer(optionalFailure).when(stateHolder).entrySet(); doAnswer(optionalFailure).when(stateHolder).get(any()); doAnswer(optionalFailure).when(stateHolder).putIfAbsent(any(), any()); CompactJavaSerializer<Object> serializerA = new CompactJavaSerializer<>(getClass().getClassLoader()); serializerA.init(stateRepository); Date object = new Date(); failing.set(true); try { serializerA.serialize(object); fail("Expected RuntimeException"); } catch (RuntimeException e) { } failing.set(false); ByteBuffer serialized = serializerA.serialize(object); assertThat(serializerA.read(serialized), is(object)); assertThat(stateHolder.entrySet(), hasSize(1)); <START> CompactJavaSerializer serializerB = new CompactJavaSerializer(getClass().getClassLoader()); <END> serializerB.init(stateRepository); assertThat(serializerB.read(serialized), is(object)); }</code><technical_language>Lack of generic types is causing a build failure here</technical_language>

Target:
public void testStateHolderFailureRereadBehavior() throws ClassNotFoundException { StateHolder<Integer, ObjectStreamClass> stateMap = spy(new TransientStateHolder<>()); StateRepository stateRepository = mock(StateRepository.class); when(stateRepository.getPersistentStateHolder(eq("CompactJavaSerializer-ObjectStreamClassIndex"), eq(Integer.class), eq(ObjectStreamClass.class), any(), any())).thenReturn(stateMap); AtomicBoolean failing = new AtomicBoolean(); Answer<Object> optionalFailure = invocation -> { try { return invocation.callRealMethod(); } finally { if (failing.get()) { throw new RuntimeException(); } } }; doAnswer(optionalFailure).when(stateMap).entrySet(); doAnswer(optionalFailure).when(stateMap).get(any()); doAnswer(optionalFailure).when(stateMap).putIfAbsent(any(), any()); CompactJavaSerializer<Date> serializerA = new CompactJavaSerializer<Date>(getClass().getClassLoader()); serializerA.init(stateRepository); Date object = new Date(); failing.set(true); try { serializerA.serialize(object); fail("Expected RuntimeException"); } catch (RuntimeException e) { } failing.set(false); ByteBuffer serialized = serializerA.serialize(object); assertThat(serializerA.read(serialized), is(object)); assertThat(stateMap.entrySet(), hasSize(1)); CompactJavaSerializer<Date> serializerB = new CompactJavaSerializer<Date>(getClass().getClassLoader()); serializerB.init(stateRepository); assertThat(serializerB.read(serialized), is(object)); }
Source:
<code><START> public ScheduledExecutorService resolveScheduledExecutorService() { <END> return resolveSchedulerBean(ScheduledExecutorService.class); }</code><technical_language>this package private instead</technical_language>

Target:
ScheduledExecutorService resolveScheduledExecutorService() { return resolveSchedulerBean(ScheduledExecutorService.class); }
Source:
<code>public RankedAdapterFactoryDescriptor.Registry createFilteredAdapterFactoryRegistry() { String disabledAdapterFactoriesString = getEMFComparePreferences().get( EMFComparePreferences.DISABLED_ADAPTER_FACTORY, ""); final List<String> disabledAdapterFactories = Lists.newArrayList(disabledAdapterFactoriesString .split(";")); Multimap<Collection<?>, RankedAdapterFactoryDescriptor> filteredRegistry = Multimaps <START> .unmodifiableListMultimap(ArrayListMultimap.create(Multimaps.filterValues( <END> adapterFactoryRegistry, new Predicate<RankedAdapterFactoryDescriptor>() { public boolean apply(RankedAdapterFactoryDescriptor input) { return !disabledAdapterFactories.contains(input.getId()); } }))); return new RankedAdapterFactoryDescriptorRegistryImpl( ComposedAdapterFactory.Descriptor.Registry.INSTANCE, filteredRegistry); }</code><technical_language>Here, excuse for ImmutableListMultimap, create a copy (with ArrayListMultimap.create(...)) this copy unmodifiable. ImmutableListMultimap.copyOf(Multimaps.filterValues(....))</technical_language>

Target:
public RankedAdapterFactoryDescriptor.Registry createFilteredAdapterFactoryRegistry() { String disabledAdapterFactoriesString = getEMFComparePreferences().get( EMFComparePreferences.DISABLED_ADAPTER_FACTORY, ""); final List<String> disabledAdapterFactories = Lists.newArrayList(disabledAdapterFactoriesString .split(";")); Multimap<Collection<?>, RankedAdapterFactoryDescriptor> filteredRegistry = ImmutableListMultimap .copyOf(Multimaps.filterValues(adapterFactoryRegistry, new Predicate<RankedAdapterFactoryDescriptor>() { public boolean apply(RankedAdapterFactoryDescriptor input) { return !disabledAdapterFactories.contains(input.getId()); } })); return new RankedAdapterFactoryDescriptorRegistryImpl( ComposedAdapterFactory.Descriptor.Registry.INSTANCE, filteredRegistry); }
Source:
<code>HighlightField highlight() throws IOException { if (shouldSkip()) { return null; } ensureWeigher(); scoreMatters = context.field.fieldOptions().scoreOrdered(); if (!scoreMatters) { Boolean topScoring = (Boolean) getOption("top_scoring"); scoreMatters = topScoring != null && topScoring; } defaultField = new FieldWrapper(this, context, weigher); int numberOfSnippets = context.field.fieldOptions().numberOfFragments(); if (numberOfSnippets == 0) { numberOfSnippets = 1; } segmenter = new DelayedSegmenter(defaultField); HitEnum hitEnum = buildHitEnum(); if(log.isTraceEnabled()) { GraphvizHitEnumGenerator visContext = new GraphvizHitEnumGenerator(hitEnum); GraphvizTermHitEnumWriters.register(visContext, weigher.termInfos()); <START> log.trace("HitEnum Graph : \n{}", visContext.generateGraph()); <END> } List<Snippet> snippets = buildChooser().choose(segmenter, hitEnum, numberOfSnippets); if (snippets.size() != 0) { cache.lastMatched = true; return new HighlightField(context.fieldName, formatSnippets(snippets)); } cache.lastMatched = false; int noMatchSize = context.field.fieldOptions().noMatchSize(); if (noMatchSize <= 0) { return null; } List<String> fieldValues = defaultField.getFieldValues(); if (fieldValues.isEmpty()) { return null; } Text fragment = new StringText(getSegmenterFactory() .extractNoMatchFragment(fieldValues.get(0), noMatchSize)); return new HighlightField(context.fieldName, new Text[] {fragment}); }</code><technical_language>pretty sweet if return graphs hits if user asks for it. cool</technical_language>

Target:
HighlightField highlight() throws IOException { if (shouldSkip()) { return null; } ensureWeigher(); scoreMatters = context.field.fieldOptions().scoreOrdered(); if (!scoreMatters) { Boolean topScoring = (Boolean) getOption("top_scoring"); scoreMatters = topScoring != null && topScoring; } defaultField = new FieldWrapper(this, context, weigher); int numberOfSnippets = context.field.fieldOptions().numberOfFragments(); if (numberOfSnippets == 0) { numberOfSnippets = 1; } segmenter = new DelayedSegmenter(defaultField); List<Snippet> snippets = buildChooser().choose(segmenter, buildHitEnum(), numberOfSnippets); if (snippets.size() != 0) { cache.lastMatched = true; return new HighlightField(context.fieldName, formatSnippets(snippets)); } cache.lastMatched = false; int noMatchSize = context.field.fieldOptions().noMatchSize(); if (noMatchSize <= 0) { return null; } List<String> fieldValues = defaultField.getFieldValues(); if (fieldValues.isEmpty()) { return null; } Text fragment = new StringText(getSegmenterFactory() .extractNoMatchFragment(fieldValues.get(0), noMatchSize)); return new HighlightField(context.fieldName, new Text[] {fragment}); }
Source:
<code>protected SiteMap processText(URL sitemapUrl, InputStream stream) throws IOException { LOG.debug("Processing textual Sitemap"); SiteMap textSiteMap = new SiteMap(sitemapUrl); textSiteMap.setType(SitemapType.TEXT); BOMInputStream bomIs = new BOMInputStream(stream); @SuppressWarnings("resource") BufferedReader reader = new BufferedReader(new InputStreamReader(bomIs, UTF_8)); String line; int i = 0; while ((line = reader.readLine()) != null && ++i <= MAX_URLS) { line = line.trim(); if (line.isEmpty()) <START> continue; <END> try { URL url = new URL(line); boolean valid = urlIsValid(textSiteMap.getBaseUrl(), url.toString()); if (valid || !strict) { SiteMapURL sUrl = new SiteMapURL(url, valid); textSiteMap.addSiteMapUrl(sUrl); LOG.debug(" {}. {}", i, sUrl); } else { LOG.debug("URL: is excluded from the sitemap as it is not a valid url = not under the base url: {}", url.toExternalForm(), textSiteMap.getBaseUrl()); } } catch (MalformedURLException e) { LOG.debug("Bad url: [{}]", line.substring(0, Math.min(1024, line.length()))); } } textSiteMap.setProcessed(true); return textSiteMap; }</code><technical_language>Minor - I want { } for single line elements</technical_language>

Target:
protected SiteMap processText(URL sitemapUrl, InputStream stream) throws IOException { LOG.debug("Processing textual Sitemap"); SiteMap textSiteMap = new SiteMap(sitemapUrl); textSiteMap.setType(SitemapType.TEXT); BOMInputStream bomIs = new BOMInputStream(stream); @SuppressWarnings("resource") BufferedReader reader = new BufferedReader(new InputStreamReader(bomIs, UTF_8)); String line; int i = 0; while ((line = reader.readLine()) != null && ++i <= MAX_URLS) { line = line.trim(); if (line.isEmpty()) { continue; } try { URL url = new URL(line); boolean valid = urlIsValid(textSiteMap.getBaseUrl(), url.toString()); if (valid || !strict) { SiteMapURL sUrl = new SiteMapURL(url, valid); textSiteMap.addSiteMapUrl(sUrl); LOG.debug(" {}. {}", i, sUrl); } else { LOG.debug("URL: is excluded from the sitemap as it is not a valid url = not under the base url: {}", url.toExternalForm(), textSiteMap.getBaseUrl()); } } catch (MalformedURLException e) { LOG.debug("Bad url: [{}]", line.substring(0, Math.min(1024, line.length()))); } } textSiteMap.setProcessed(true); return textSiteMap; }
Source:
<code>private static Stream<Tuple2<Long, Long>> primeFactorsAndResultingValTail(Tuple2<Long, Long> previousFactorAndResultingVal) { return Match .when(1L, p -> Stream.<Tuple2<Long, Long>>nil()) .otherwise(() -> { final long nextPrimeFactor = knownPrimes.filter(p -> previousFactorAndResultingVal._2 % p == 0).take(1).head(); return Stream.build( new Tuple2<>(nextPrimeFactor, previousFactorAndResultingVal._2 / nextPrimeFactor), <START> ProjectEulerTest::primeFactorsAndResultingValTail); <END> }) .apply(previousFactorAndResultingVal._2); }</code><technical_language>java // tuple is a good name... final Tuple2<...> tuple = new Tuple2<>(nextPrimeFactor, previousFactorAndResultingVal._2 / nextPrimeFactor); return Stream.gen(tuple, () -> primeFactorsAndResultingValTail(tuple));</technical_language>

Target:
private static Stream<Tuple2<Long, Long>> primeFactorsAndResultingValTail(Tuple2<Long, Long> previousFactorAndResultingVal) { return Match .when(1L, p -> Stream.<Tuple2<Long, Long>>nil()) .otherwise(() -> { final long nextPrimeFactor = knownPrimes.filter(p -> previousFactorAndResultingVal._2 % p == 0).take(1).head(); final Tuple2<Long, Long> head = new Tuple2<>(nextPrimeFactor, previousFactorAndResultingVal._2 / nextPrimeFactor); return Stream.gen(head, () -> primeFactorsAndResultingValTail(head)); }) .apply(previousFactorAndResultingVal._2); }
Source:
<code>public void setWorkflowGroup(Context context, Collection collection, int step, Group group) throws SQLException, AuthorizeException { Workflow workflow = null; try { workflow = workflowFactory.getWorkflow(collection); } catch (IOException | WorkflowConfigurationException e) { log.error(LogManager.getHeader(context, "setWorkflowGroup", "collection_id=" + collection.getID() + " " + e.getMessage()), e); } <START> if (!StringUtils.equals("default", workflow.getID())) { <END> throw new IllegalArgumentException( "setWorkflowGroup can be used only on collection with the default basic dspace workflow. " + "Instead, the collection: " + collection.getID() + " has the workflow: " + workflow.getID()); } String roleId; switch (step) { case 1: roleId = "reviewer"; break; case 2: roleId = "editor"; break; case 3: roleId = "finaleditor"; break; default: throw new IllegalArgumentException("Illegal step count: " + step); } CollectionRole colRole = collectionRoleService.find(context, collection, roleId); if (colRole == null) { if (group != null) { colRole = collectionRoleService.create(context, collection, roleId, group); } } else { if (group != null) { colRole.setGroup(group); collectionRoleService.update(context, colRole); } else { collectionRoleService.delete(context, colRole); } } collection.setModified(); }</code><technical_language>this hardcoded string a constant</technical_language>

Target:
public void setWorkflowGroup(Context context, Collection collection, int step, Group group) throws SQLException, AuthorizeException { Workflow workflow = null; try { workflow = workflowFactory.getWorkflow(collection); } catch (IOException | WorkflowConfigurationException e) { log.error(LogManager.getHeader(context, "setWorkflowGroup", "collection_id=" + collection.getID() + " " + e.getMessage()), e); } if (!StringUtils.equals(XmlWorkflowFactory.LEGACY_WORKFLOW_NAME, workflow.getID())) { throw new IllegalArgumentException( "setWorkflowGroup can be used only on collection with the default basic dspace workflow. " + "Instead, the collection: " + collection.getID() + " has the workflow: " + workflow.getID()); } String roleId; switch (step) { case 1: roleId = CollectionRoleService.LEGACY_WORKFLOW_STEP1_NAME; break; case 2: roleId = CollectionRoleService.LEGACY_WORKFLOW_STEP2_NAME; break; case 3: roleId = CollectionRoleService.LEGACY_WORKFLOW_STEP3_NAME; break; default: throw new IllegalArgumentException("Illegal step count: " + step); } CollectionRole colRole = collectionRoleService.find(context, collection, roleId); if (colRole == null) { if (group != null) { colRole = collectionRoleService.create(context, collection, roleId, group); } } else { if (group != null) { colRole.setGroup(group); collectionRoleService.update(context, colRole); } else { collectionRoleService.delete(context, colRole); } } collection.setModified(); }
Source:
<code>public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { AccessGroupSet principals = getAgentPrincipals().getPrincipals(); <START> if (globalPermissionEvaluator.hasGlobalPermission(principals, Permission.reindex)) { <END> throw new ResourceNotFoundException(); } try { LookupMappingsSettings.updateMappings(); } catch (Exception e) { response.getWriter().append("Failed to refresh mappings, check logs."); LOG.error("Failed to refresh mappings", e); } try { xslViewResolver.refreshViews(); } catch (Exception e) { response.getWriter().append("Failed to refresh transform mappings, check logs."); LOG.error("Failed to refresh transform mappings", e); } headerMenuSettings.init(); response.getWriter().append("Mappings refresh was successful."); }</code><technical_language>confused. throwing exception IS a global permission</technical_language>

Target:
public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { AccessGroupSet principals = getAgentPrincipals().getPrincipals(); if (!globalPermissionEvaluator.hasGlobalPermission(principals, Permission.reindex)) { throw new ResourceNotFoundException(); } try { LookupMappingsSettings.updateMappings(); } catch (Exception e) { response.getWriter().append("Failed to refresh mappings, check logs."); LOG.error("Failed to refresh mappings", e); } try { xslViewResolver.refreshViews(); } catch (Exception e) { response.getWriter().append("Failed to refresh transform mappings, check logs."); LOG.error("Failed to refresh transform mappings", e); } headerMenuSettings.init(); response.getWriter().append("Mappings refresh was successful."); }
Source:
<code>public void flush() { if (!_pendingCheckpoint) { return; } try { _sendFlushLock.writeLock().lock(); if (LOG.isDebugEnabled()) { LOG.debug(String.format("Staring transport flush, tasks = [%s].", _tasks)); } _transportProvider.flush(); if (LOG.isDebugEnabled()) { LOG.debug("Transport has been successfully flushed."); } if (_checkpointPolicy == CheckpointPolicy.DATASTREAM) { try { LOG.info(String.format("Start committing checkpoints = %s, tasks = [%s].", _latestCheckpoints, _tasks)); Map<DatastreamTask, String> committed = new HashMap<>(); _latestCheckpoints.forEach((task, cpMap) -> committed.put(task, JsonUtils.toJson(cpMap))); _checkpointProvider.commit(committed); _latestCheckpoints.forEach((task, cpMap) -> _safeCheckpoints.put(task, new HashMap<>(cpMap))); LOG.info("Checkpoints have been successfully committed: " + _safeCheckpoints); } catch (Throwable t) { String errorMessage = String.format("Checkpoint commit failed, tasks = [%s].", _tasks); LOG.error(errorMessage, t); <START> throw new DatastreamRuntimeException(errorMessage, t); <END> } } _pendingCheckpoint = false; } catch (Throwable t) { String errorMessage = String.format("Failed to flush transport, tasks = [%s].", _tasks); LOG.error(errorMessage, t); throw new DatastreamRuntimeException(errorMessage, t); } finally { _sendFlushLock.writeLock().unlock(); } }</code><technical_language>logAndThrow</technical_language>

Target:
public void flush() { if (!_pendingCheckpoint) { return; } try { _sendFlushLock.writeLock().lock(); if (LOG.isDebugEnabled()) { LOG.debug(String.format("Staring transport flush, tasks = [%s].", _tasks)); } _transportProvider.flush(); if (LOG.isDebugEnabled()) { LOG.debug("Transport has been successfully flushed."); } if (_checkpointPolicy == CheckpointPolicy.DATASTREAM) { try { LOG.info(String.format("Start committing checkpoints = %s, tasks = [%s].", _latestCheckpoints, _tasks)); Map<DatastreamTask, String> committed = new HashMap<>(); _latestCheckpoints.forEach((task, cpMap) -> committed.put(task, JsonUtils.toJson(cpMap))); _checkpointProvider.commit(committed); _latestCheckpoints.forEach((task, cpMap) -> _safeCheckpoints.put(task, new HashMap<>(cpMap))); LOG.info("Checkpoints have been successfully committed: " + _safeCheckpoints); } catch (Throwable t) { String errorMessage = String.format("Checkpoint commit failed, tasks = [%s].", _tasks); ErrorLogger.logAndThrowDatastreamRuntimeException(LOG, errorMessage, t); } } _pendingCheckpoint = false; } catch (Throwable t) { String errorMessage = String.format("Failed to flush transport, tasks = [%s].", _tasks); ErrorLogger.logAndThrowDatastreamRuntimeException(LOG, errorMessage, t); } finally { _sendFlushLock.writeLock().unlock(); } }
Source:
<code>public void run() { while (true) { try { rs.cleanNotificationEvents(ttl); rs.cleanWriteNotificationEvents(ttl); } catch (Exception ex) { LOG.warn("Exception received while cleaning notifications. More details can be found in debug mode", ex); } <START> <END> LOG.debug("Cleaner thread done"); try { Thread.sleep(sleepTime); } catch (InterruptedException e) { LOG.info("Cleaner thread sleep interrupted", e); } } }</code><technical_language>this debug log is removed? sure, if for security issues</technical_language>

Target:
public void run() { while (true) { try { rs.cleanNotificationEvents(ttl); rs.cleanWriteNotificationEvents(ttl); } catch (Exception ex) { LOG.warn("Exception received while cleaning notifications: ", ex); } LOG.debug("Cleaner thread done"); try { Thread.sleep(sleepTime); } catch (InterruptedException e) { LOG.info("Cleaner thread sleep interrupted", e); } } }
Source:
<code>private static void indexTweeterDocument(String indexType, int id, Date date) { try { client.prepareIndex(indexName, indexType).setSource(buildTweeterJson(id, date)) .setId("tweet_" + indexType + "_" + id).execute().actionGet(); } catch (Exception ex) { <START> System.out.println("Exception indexing documents!!!!!"); <END> } }</code><technical_language>a rethrow better</technical_language>

Target:
private static void indexTweeterDocument(String indexType, int id, Date date) { client.prepareIndex(indexName, indexType).setSource(buildTweeterJson(id, date)) .setId("tweet_" + indexType + "_" + id).execute().actionGet(); }
Source:
<code>protected CompletableFuture<Void> doResolve(ITextViewer viewer, IProgressMonitor monitor) { return CompletableFuture.runAsync(() -> { try { monitor.isCanceled(); refCount= countReferences(getElement(), monitor); monitor.isCanceled(); if (refCount == 0 && showReferencesAtLeastOne) { super.setLabel(""); } else { <START> super.setLabel(refCount + " references"); END> } } catch (JavaModelException e) { } catch (CoreException e) { } }); }</code><technical_language>If want "0 references" "1 reference", condition need replaced "==". way, strings need externalized in a .properties file</technical_language>

Target:
protected CompletableFuture<Void> doResolve(ITextViewer viewer, IProgressMonitor monitor) { return CompletableFuture.runAsync(() -> { try { monitor.isCanceled(); long refCount= countReferences(getElement(), monitor); monitor.isCanceled(); action= refCount > 0 ? e -> new FindReferencesAction(editor).run(super.getElement()) : null; if (refCount == 0 && showReferencesAtLeastOne) { super.setLabel(""); } else { super.setLabel(MessageFormat.format(JavaCodeMiningMessages.JavaReferenceCodeMining_label, refCount)); } } catch (JavaModelException e) { } catch (CoreException e) { } }); }
Source:
<code>public void testCustomProvider() { ResteasyProviderFactory provider = new ResteasyProviderFactoryImpl(null, true); provider.registerProvider(IIOImageProvider.class); <START> RestClientBuilderImpl.setProviderFactory(provider); <END> RestClientBuilderImpl builder = (RestClientBuilderImpl) RestClientBuilder.newBuilder(); Assert.assertTrue(builder.getBuilderDelegate().getProviderFactory().getProviderClasses().contains(IIOImageProvider.class)); Assert.assertFalse(builder.getBuilderDelegate().getProviderFactory().getProviderClasses().contains(DefaultTextPlain.class)); }</code><technical_language>This a side-effect of leaving RestClientBuilderImpl end of test in a state state test. This lead strange/unexpected failures in case of testsuite execution order changes, etc. restore original state a try-finally block? Thanks</technical_language>

Target:
public void testCustomProvider() { try { ResteasyProviderFactory provider = new ResteasyProviderFactoryImpl(null, true); provider.registerProvider(IIOImageProvider.class); RestClientBuilderImpl.setProviderFactory(provider); RestClientBuilderImpl builder = (RestClientBuilderImpl) RestClientBuilder.newBuilder(); Assert.assertTrue(builder.getBuilderDelegate().getProviderFactory().getProviderClasses().contains(IIOImageProvider.class)); Assert.assertFalse(builder.getBuilderDelegate().getProviderFactory().getProviderClasses().contains(DefaultTextPlain.class)); } finally { RestClientBuilderImpl.setProviderFactory(null); } }
Source:
<code>public EnumPluginBundle() { super(Arrays.asList( <START> (Class<? extends Plugin>) EnumFieldPlugin.class, <END> EnumViewPropertyPlugin.class, EnumInheritedPropertyPlugin.class)); }</code><technical_language>Json plugin</technical_language>

Target:
public EnumPluginBundle() { super(Arrays.<Class<? extends Plugin>>asList( EnumFieldPlugin.class, EnumViewPropertyPlugin.class, EnumInheritedPropertyPlugin.class)); }
Source:
<code>private void checkGroupByAliasFeature(String sql1, String sql2, boolean exact) { List<AbstractPlanNode> pns; String explainStr1; String explainStr2; pns = compileToFragments(sql1); explainStr1 = buildExplainPlan(pns); pns = compileToFragments(sql2); explainStr2 = buildExplainPlan(pns); if (! exact) { <START> explainStr1 = explainStr1.replaceAll("TEMP_TABLE_\\$\\$\\.column#[\\d]", <END> "TEMP_TABLE_\\$\\$.column#[Index]"); explainStr2 = explainStr2.replaceAll("TEMP_TABLE_\\$\\$\\.column#[\\d]", "TEMP_TABLE_\\$\\$.column#[Index]"); assertEquals(explainStr1, explainStr2); } assertEquals(explainStr1, explainStr2); }</code><technical_language>Is some constant TEMP_TABLE_NAME construct this string? nice if string "$$TEMP_TABLE_NAME$$" appeared in source, changed if necessary. this is final time change this, thought time this change</technical_language>

Target:
private void checkGroupByAliasFeature(String sql1, String sql2, boolean exact) { List<AbstractPlanNode> pns; String explainStr1; String explainStr2; pns = compileToFragments(sql1); explainStr1 = buildExplainPlan(pns); pns = compileToFragments(sql2); explainStr2 = buildExplainPlan(pns); if (! exact) { explainStr1 = explainStr1.replaceAll("\\$\\$_VOLT_TEMP_TABLE_\\$\\$\\.column#[\\d]", "\\$\\$_VOLT_TEMP_TABLE_\\$\\$\\.column#[Index]"); explainStr2 = explainStr2.replaceAll("\\$\\$_VOLT_TEMP_TABLE_\\$\\$\\.column#[\\d]", "\\$\\$_VOLT_TEMP_TABLE_\\$\\$\\.column#[Index]"); assertEquals(explainStr1, explainStr2); } assertEquals(explainStr1, explainStr2); }
Source:
<code>protected void onInitUI() { final FlowPanel me = (FlowPanel) getWidget(); me.add(header = new Grid(1, Cols.values().length)); me.add(body = new FlowPanel()); FlowPanel title = new FlowPanel(); title.add(headerText = new InlineLabel()); title.setStyleName(Gerrit.RESOURCES.css().screenHeader()); header.setWidget(0, Cols.Title.num, title); header.setStyleName(Gerrit.RESOURCES.css().screenHeader()); header.getCellFormatter().setHorizontalAlignment(0, Cols.FarEast.num, HasHorizontalAlignment.ALIGN_RIGHT); <START> header.getCellFormatter().setWidth(0, Cols.FarEast.num, "99%"); <END> }</code><technical_language>work I reason for 99% 100%? some CSS trick applying here</technical_language>

Target:
protected void onInitUI() { final FlowPanel me = (FlowPanel) getWidget(); me.add(header = new Grid(1, Cols.values().length)); me.add(body = new FlowPanel()); FlowPanel title = new FlowPanel(); title.add(headerText = new InlineLabel()); title.setStyleName(Gerrit.RESOURCES.css().screenHeader()); header.setWidget(0, Cols.Title.ordinal(), title); header.setStyleName(Gerrit.RESOURCES.css().screenHeader()); header.getCellFormatter().setHorizontalAlignment(0, Cols.FarEast.ordinal(), HasHorizontalAlignment.ALIGN_RIGHT); header.getCellFormatter().setWidth(0, Cols.FarEast.ordinal(), "100%"); }
Source:
<code>public String createEntityExtractUrl(DataStore store, String installPath, ImageFormat format, DataObject dataObject) { SwiftTO swiftTO = (SwiftTO)store.getTO(); String tempKey = UUID.randomUUID().toString(); boolean result = SwiftUtil.setTempKey(swiftTO, tempKey); if (!result) { s_logger.error("Unable to set Temp-Key: " + tempKey); <START> return ""; <END> } String containerName = SwiftUtil.getContainerName(dataObject.getType().toString(), dataObject.getId()); String objectName = installPath.split("\\/")[1]; int urlExpirationInterval = Integer.parseInt(_configDao.getValue(Config.ExtractURLExpirationInterval.toString())); URL swiftUrl = SwiftUtil.generateTempUrl(swiftTO, containerName, objectName, tempKey, urlExpirationInterval); if (swiftUrl != null) { s_logger.info("Swift temp-url: " + swiftUrl.toString()); return swiftUrl.toString(); } return null; }</code><technical_language>return empty here, null later</technical_language>

Target:
public String createEntityExtractUrl(DataStore store, String installPath, ImageFormat format, DataObject dataObject) { SwiftTO swiftTO = (SwiftTO)store.getTO(); String tempKey = UUID.randomUUID().toString(); boolean result = SwiftUtil.setTempKey(swiftTO, tempKey); if (!result) { String errMsg = "Unable to set Temp-Key: " + tempKey; s_logger.error(errMsg); throw new CloudRuntimeException(errMsg); } String containerName = SwiftUtil.getContainerName(dataObject.getType().toString(), dataObject.getId()); String objectName = installPath.split("\\/")[1]; int urlExpirationInterval = Integer.parseInt(_configDao.getValue(Config.ExtractURLExpirationInterval.toString())); URL swiftUrl = SwiftUtil.generateTempUrl(swiftTO, containerName, objectName, tempKey, urlExpirationInterval); if (swiftUrl != null) { s_logger.debug("Swift temp-url: " + swiftUrl.toString()); return swiftUrl.toString(); } throw new CloudRuntimeException("Unable to create extraction URL"); }
Source:
<code>public void emitRecord(ByteBuffer record, int targetSubpartition) throws IOException { BufferBuilder buffer = subpartitionBufferBuilders[targetSubpartition]; <START> if (buffer == null) { buffer = getNewEmptySubpartitionBufferBuilderForNewRecord(targetSubpartition); } buffer.appendAndCommit(record); <END> while (record.hasRemaining()) { finishSubpartitionBufferBuilder(targetSubpartition); buffer = getNewEmptySubpartitionBufferBuilderForRecordContinuation(record, targetSubpartition); } if (buffer.isFull()) { finishSubpartitionBufferBuilder(targetSubpartition); } }</code><technical_language>nit: names a bit lengthy, a bit confusing getNewEmptySubpartitionBufferBuilderForNewRecord is appending data, while getNewEmptySubpartitionBufferBuilderForRecordContinuation is. extract lines a method: BufferBuilder buffer = appendDataForSubpartitionNewRecord(record, targetSubpartition); for broadcast version BufferBuilder buffer = appendDataForBroadcastNewRecord(record, targetSubpartition); ..</technical_language>

Target:
public void emitRecord(ByteBuffer record, int targetSubpartition) throws IOException { BufferBuilder buffer = appendUnicastDataForNewRecord(record, targetSubpartition); while (record.hasRemaining()) { finishUnicastBufferBuilder(targetSubpartition); buffer = appendUnicastDataForRecordContinuation(record, targetSubpartition); } if (buffer.isFull()) { finishUnicastBufferBuilder(targetSubpartition); } }
Source:
<code>private void addUserLibrary(Element element, String entry) { Element pathElement = doc.createElement("path"); IClasspathContainer container = EclipseClasspath.resolveUserLibraryReference(entry); String name = ExportUtil.removePrefixAndSuffix(entry, "${", "}"); pathElement.setAttribute("refid", name); element.appendChild(pathElement); if (visited.add(entry)) { Element userElement = doc.createElement("path"); userElement.setAttribute("id", name); for (IClasspathEntry <START> entrie : <END> container.getClasspathEntries()) { String jarFile = entrie.getPath().toString(); if (EclipseClasspath.isLibraryReference(entry)) { IPath home = JavaCore.getClasspathVariable("ECLIPSE_HOME"); if (home != null && home.isPrefixOf(entrie.getPath())) { variable2valueMap.put("ECLIPSE_HOME", home.toString()); jarFile = "${ECLIPSE_HOME}" + jarFile.substring(home.toString().length()); } else if (!new File(jarFile).exists() && jarFile.startsWith('/' + projectName) && new File(projectRoot, jarFile.substring(('/' + projectName).length())).exists()) { jarFile = jarFile.substring(('/' + projectName).length() + 1); } } jarFile = ExportUtil.getRelativePath(jarFile, projectRoot); Element userPathElement = doc.createElement("pathelement"); userPathElement.setAttribute(IAntModelConstants.ATTR_LOCATION, jarFile); userElement.appendChild(userPathElement); } addToClasspathBlock(userElement); } }</code><technical_language>rename entry</technical_language>

Target:
private void addUserLibrary(Element element, String entry) { Element pathElement = doc.createElement("path"); IClasspathContainer container = EclipseClasspath.resolveUserLibraryReference(entry); String name = ExportUtil.removePrefixAndSuffix(entry, "${", "}"); pathElement.setAttribute("refid", name); element.appendChild(pathElement); if (visited.add(entry)) { Element userElement = doc.createElement("path"); userElement.setAttribute("id", name); for (IClasspathEntry cpentry : container.getClasspathEntries()) { String jarFile = cpentry.getPath().toString(); if (EclipseClasspath.isLibraryReference(entry)) { IPath home = JavaCore.getClasspathVariable("ECLIPSE_HOME"); if (home != null && home.isPrefixOf(cpentry.getPath())) { variable2valueMap.put("ECLIPSE_HOME", home.toString()); jarFile = "${ECLIPSE_HOME}" + jarFile.substring(home.toString().length()); } else if (!new File(jarFile).exists() && jarFile.startsWith('/' + projectName) && new File(projectRoot, jarFile.substring(('/' + projectName).length())).exists()) { jarFile = jarFile.substring(('/' + projectName).length() + 1); } } jarFile = ExportUtil.getRelativePath(jarFile, projectRoot); Element userPathElement = doc.createElement("pathelement"); userPathElement.setAttribute(IAntModelConstants.ATTR_LOCATION, jarFile); userElement.appendChild(userPathElement); } addToClasspathBlock(userElement); } }
Source:
<code>public void registerContribution(Object contribution, String extensionPoint, ComponentInstance contributor) { if (RENDITION_DEFINITIONS_EP.equals(extensionPoint)) { RenditionDefinition renditionDefinition = (RenditionDefinition) contribution; renditionDefinitionRegistry.addContribution(renditionDefinition); } else if (RENDITON_DEFINION_PROVIDERS_EP.equals(extensionPoint)) { renditionDefinitionProviderRegistry.addContribution((RenditionDefinitionProviderDescriptor) contribution); } else if (STORED_RENDITION_MANAGERS_EP.equals(extensionPoint)) { storedRenditionManagerDescriptors.add(((StoredRenditionManagerDescriptor) contribution)); } else if (DEFAULT_RENDITION_EP.equals(extensionPoint)) { defaultRenditionDescriptor = ((DefaultRenditionDescriptor) contribution); } <START> } <END></code><technical_language>need account descriptor unregistration. need a list of contributions, of one. in unregister remove list re-set defaultRenditionDescriptor one. for example redirectResolverContributions / redirectResolver in DownloadServiceImpl</technical_language>

Target:
public void registerContribution(Object contribution, String extensionPoint, ComponentInstance contributor) { if (RENDITION_DEFINITIONS_EP.equals(extensionPoint)) { RenditionDefinition renditionDefinition = (RenditionDefinition) contribution; renditionDefinitionRegistry.addContribution(renditionDefinition); } else if (RENDITON_DEFINION_PROVIDERS_EP.equals(extensionPoint)) { renditionDefinitionProviderRegistry.addContribution((RenditionDefinitionProviderDescriptor) contribution); } else if (STORED_RENDITION_MANAGERS_EP.equals(extensionPoint)) { storedRenditionManagerDescriptors.add(((StoredRenditionManagerDescriptor) contribution)); } else if (DEFAULT_RENDITION_EP.equals(extensionPoint)) { defaultRenditionDescriptor = ((DefaultRenditionDescriptor) contribution); defaultRenditionDescriptors.add((DefaultRenditionDescriptor) contribution); } }
Source:
<code>public List<PersonInterface> toMetadata() { List<PersonInterface> result = new ArrayList<>(1); <START> PersonInterface personInterface; <END> try { personInterface = UghImplementation.INSTANCE.createPerson(metadataType); } catch (MetadataTypeNotAllowedException e) { throw new NullPointerException(e.getMessage()); } String normdataRecord = getField(Field.NORMDATA_RECORD).getValue(); if (normdataRecord != null && normdataRecord.length() > 0 && !normdataRecord.equals(ConfigCore.getParameter(Parameters.AUTHORITY_DEFAULT, ""))) { String[] authorityFile = Metadaten.parseAuthorityFileArgs(normdataRecord); personInterface.setAutorityFile(authorityFile[0], authorityFile[1], authorityFile[2]); } personInterface.setFirstName(getField(Field.FIRSTNAME).getValue()); personInterface.setLastName(getField(Field.LASTNAME).getValue()); result.add(personInterface); return result; }</code><technical_language>Interface appended variable name</technical_language>

Target:
public List<PersonInterface> toMetadata() { List<PersonInterface> result = new ArrayList<>(1); PersonInterface person; try { person = UghImplementation.INSTANCE.createPerson(metadataType); } catch (MetadataTypeNotAllowedException e) { throw new NullPointerException(e.getMessage()); } String normdataRecord = getField(Field.NORMDATA_RECORD).getValue(); if (normdataRecord != null && normdataRecord.length() > 0 && !normdataRecord.equals(ConfigCore.getParameter(Parameters.AUTHORITY_DEFAULT, ""))) { String[] authorityFile = Metadaten.parseAuthorityFileArgs(normdataRecord); person.setAutorityFile(authorityFile[0], authorityFile[1], authorityFile[2]); } person.setFirstName(getField(Field.FIRSTNAME).getValue()); person.setLastName(getField(Field.LASTNAME).getValue()); result.add(person); return result; }
Source:
<code>public void testGuessTransformer() throws IOException, CatalogTransformerException { SortedServiceList mockSortedServiceList = mock(SortedServiceList.class); <START> InputTransformer mockInputTransformer = mock(InputTransformer.class); <END> when(mockInputTransformer.transform(mock(InputStream.class))) .thenThrow(new CatalogTransformerException()); when(mockSortedServiceList.stream()).thenReturn(Stream.of(mockInputTransformer)); transformer.setInputTransformers(mockSortedServiceList); Metacard metacard = transformer.transform(new ByteArrayInputStream(samplePointJsonText().getBytes())); assertEquals("ddf.metacard", metacard.getMetacardType().getName()); assertEquals("myTitle", metacard.getTitle()); }</code><technical_language>verify of mocks</technical_language>

Target:
public void testGuessTransformer() throws IOException, CatalogTransformerException { SortedServiceList mockSortedServiceList = mock(SortedServiceList.class); InputTransformer mockInputTransformer = mock(InputTransformer.class); when(mockInputTransformer.transform(mock(InputStream.class))) .thenThrow(new CatalogTransformerException()); when(mockSortedServiceList.stream()).thenReturn(Stream.of(mockInputTransformer)); transformer.setInputTransformers(mockSortedServiceList); Metacard metacard = transformer.transform(new ByteArrayInputStream(samplePointJsonText().getBytes())); ArgumentCaptor<ByteArrayInputStream> inputStreamCaptor = ArgumentCaptor.forClass(ByteArrayInputStream.class); verify(mockSortedServiceList).stream(); verify(mockInputTransformer).transform(inputStreamCaptor.capture()); assertThat(metacard.getMetacardType().getName(), is("ddf.metacard")); assertThat(metacard.getTitle(), is(DEFAULT_TITLE)); }
Source:
<code>void allocate(File destinationFile, long sizeInBytes) throws IOException { if (!poolInitialized) { <START> LOGGER.debug("Allocating segment before pool is fully initialized to " + destinationFile.getAbsolutePath()); <END> } File reserveFile = reserveFiles.remove(sizeInBytes); if (reserveFile == null) { LOGGER.info("Segment of size not found in pool; attempting to create a new preallocated file", sizeInBytes); reserveFile = createReserveFile(sizeInBytes); } if (destinationFile.exists() || !reserveFile.renameTo(destinationFile)) { reserveFiles.add(sizeInBytes, reserveFile); throw new IOException("Error while moving reserve file: " + reserveFile.getAbsolutePath() + " to location: " + destinationFile.getAbsolutePath()); } }</code><technical_language>I useful this info</technical_language>

Target:
void allocate(File destinationFile, long sizeInBytes) throws IOException { if (enablePooling && poolState != PoolState.INITIALIZED) { logger.info("Allocating segment of size to before pool is fully initialized", sizeInBytes, destinationFile.getAbsolutePath()); metrics.diskSpaceAllocatorAllocBeforeInitCount.inc(); } else { logger.debug("Allocating segment of size to {}", sizeInBytes, destinationFile.getAbsolutePath()); } if (destinationFile.exists()) { throw new IOException("Destination file already exists: " + destinationFile.getAbsolutePath()); } File reserveFile = null; if (poolState != PoolState.NOT_INVENTORIED) { reserveFile = reserveFiles.remove(sizeInBytes); } if (reserveFile == null) { if (enablePooling) { logger.info("Segment of size not found in pool; attempting to create a new preallocated file; poolState: {}", sizeInBytes, poolState); metrics.diskSpaceAllocatorSegmentNotFoundCount.inc(); } Utils.preAllocateFileIfNeeded(destinationFile, sizeInBytes); } else { try { Files.move(reserveFile.toPath(), destinationFile.toPath()); } catch (Exception e) { reserveFiles.add(sizeInBytes, reserveFile); throw e; } } }
Source:
<code>private CosmosException logAndWrapExceptionWithLastRetryWithException(Exception exception) { RetryWithException lastRetryWithException = this.request.getLastRetryWithException(); String exceptionType; if (exception instanceof GoneException) { exceptionType = "GoneException"; } else if (exception instanceof PartitionKeyRangeGoneException) { exceptionType = "PartitionKeyRangeGoneException"; } else if (exception instanceof InvalidPartitionException) { exceptionType = "InvalidPartitionException"; } else if (exception instanceof PartitionKeyRangeIsSplittingException) { exceptionType = "PartitionKeyRangeIsSplittingException"; } else if (exception instanceof CosmosException) { logger.warn("Received CosmosException after backoff/retry. Will fail the request.", <START> exception); <END> return (CosmosException)exception; } else { throw new IllegalStateException("Invalid exception type", exception); } if (lastRetryWithException != null) { logger.warn( "Received after backoff/retry including at least one RetryWithException. " + "Will fail the request with RetryWithException. {}: {}. RetryWithException: {}", exceptionType, exceptionType, exception, lastRetryWithException); return lastRetryWithException; } logger.warn( "Received after backoff/retry. Will fail the request. {}", exceptionType, exception); return BridgeInternal.createServiceUnavailableException(exception); }</code><technical_language>happen if code throws unrelated exception this retry policy? do log here? if exception get logged is truely handled. (e.g., 429). log unrelated exceptions this policy related other policy handle log exception</technical_language>

Target:
private CosmosException logAndWrapExceptionWithLastRetryWithException(Exception exception) { String exceptionType; if (exception instanceof GoneException) { exceptionType = "GoneException"; } else if (exception instanceof PartitionKeyRangeGoneException) { exceptionType = "PartitionKeyRangeGoneException"; } else if (exception instanceof InvalidPartitionException) { exceptionType = "InvalidPartitionException"; } else if (exception instanceof PartitionKeyRangeIsSplittingException) { exceptionType = "PartitionKeyRangeIsSplittingException"; } else if (exception instanceof CosmosException) { logger.warn("Received CosmosException after backoff/retry. Will fail the request.", exception); return (CosmosException)exception; } else { throw new IllegalStateException("Invalid exception type", exception); } RetryWithException lastRetryWithExceptionSnapshot = GoneAndRetryWithRetryPolicy.this.lastRetryWithException; if (lastRetryWithExceptionSnapshot != null) { logger.warn( "Received after backoff/retry including at least one RetryWithException. " + "Will fail the request with RetryWithException. {}: {}. RetryWithException: {}", exceptionType, exceptionType, exception, lastRetryWithExceptionSnapshot); return lastRetryWithExceptionSnapshot; } logger.warn( "Received after backoff/retry. Will fail the request. {}", exceptionType, exception); return BridgeInternal.createServiceUnavailableException(exception); }
Source:
<code>public CapabilityIndex(Iterator<IInstallableUnit> itor) { nameMap = new HashMap<>(300); namespaceMap = new HashMap<>(10); while (itor.hasNext()) { IInstallableUnit iu = itor.next(); Collection<IProvidedCapability> pcs = iu.getProvidedCapabilities(); for (IProvidedCapability pc : pcs) { namespaceMap.computeIfAbsent(pc.getNamespace(), n -> new HashSet<>()).add(iu); <START> nameMap.compute(pc.getName(), (n, v) -> { <END> if (v == null || v == iu) { return iu; } else if (v instanceof IInstallableUnit) { Collection<IInstallableUnit> list = new HashSet<>(); list.add((IInstallableUnit) v); list.add(iu); return list; } else { ((Collection<IInstallableUnit>) v).add(iu); return v; } }); } } }</code><technical_language>Please names (namespace, name, prev) reduce amount of change ease reading</technical_language>

Target:
public CapabilityIndex(Iterator<IInstallableUnit> itor) { nameMap = new HashMap<>(300); namespaceMap = new HashMap<>(10); while (itor.hasNext()) { IInstallableUnit iu = itor.next(); Collection<IProvidedCapability> pcs = iu.getProvidedCapabilities(); for (IProvidedCapability pc : pcs) { namespaceMap.computeIfAbsent(pc.getNamespace(), namespace -> new HashSet<>()).add(iu); nameMap.compute(pc.getName(), (name, prev) -> { if (prev == null || prev == iu) { return iu; } else if (prev instanceof IInstallableUnit) { Collection<IInstallableUnit> ius = new HashSet<>(); ius.add((IInstallableUnit) prev); ius.add(iu); return ius; } else { ((Collection<IInstallableUnit>) prev).add(iu); return prev; } }); } } }
Source:
<code>private void registerCleanupTimer( KeyedProcessFunction<K, RowData, RowData>.Context ctx, long timestamp) throws Exception { long cleanupTimestamp = timestamp + precedingOffset + 1; Long curCleanupTimestamp = cleanupTsState.value(); if (curCleanupTimestamp == null || curCleanupTimestamp < cleanupTimestamp) { <START> ctx.timerService().registerEventTimeTimer(cleanupTimestamp); <END> cleanupTsState.update(cleanupTimestamp); } }</code><technical_language>Yes. This is a tradeoff avoid timers. 1.5 times is discuss</technical_language>

Target:
private void registerCleanupTimer( KeyedProcessFunction<K, RowData, RowData>.Context ctx, long timestamp) throws Exception { long minCleanupTimestamp = timestamp + precedingOffset + 1; long maxCleanupTimestamp = timestamp + (long) (precedingOffset * 1.5) + 1; Long curCleanupTimestamp = cleanupTsState.value(); if (curCleanupTimestamp == null || curCleanupTimestamp < minCleanupTimestamp) { ctx.timerService().registerEventTimeTimer(maxCleanupTimestamp); cleanupTsState.update(maxCleanupTimestamp); } }
Source:
<code>public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) { if (verticalOffset > -appBarLayout.getTotalScrollRange() && showOverflowMenu) { showOverflowMenu = false; toolBarLayout.setTitle(""); getAppCompatActivity().supportInvalidateOptionsMenu(); toolbarExpanded = true; } else if (verticalOffset <= -appBarLayout.getTotalScrollRange() && !showOverflowMenu) { showOverflowMenu = true; toolBarLayout.setTitle(readingList != null ? readingList.title() : null); getAppCompatActivity().supportInvalidateOptionsMenu(); toolbarExpanded = false; } DeviceUtil.updateStatusBarTheme(requireActivity(), toolbar, <START> (appBarLayout.getTotalScrollRange() + verticalOffset) > appBarLayout.getTotalScrollRange() / 2); <END> swipeRefreshLayout.setEnabled(verticalOffset == 0); }</code><technical_language>add actionMode == null && logic list is scrollable multi-selecting items? ![Screenshot_1558380118](<LINK_0></technical_language>

Target:
public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) { if (verticalOffset > -appBarLayout.getTotalScrollRange() && showOverflowMenu) { showOverflowMenu = false; toolBarLayout.setTitle(""); getAppCompatActivity().supportInvalidateOptionsMenu(); toolbarExpanded = true; } else if (verticalOffset <= -appBarLayout.getTotalScrollRange() && !showOverflowMenu) { showOverflowMenu = true; toolBarLayout.setTitle(readingList != null ? readingList.title() : null); getAppCompatActivity().supportInvalidateOptionsMenu(); toolbarExpanded = false; } DeviceUtil.updateStatusBarTheme(requireActivity(), toolbar, actionMode == null && (appBarLayout.getTotalScrollRange() + verticalOffset) > appBarLayout.getTotalScrollRange() / 2); swipeRefreshLayout.setEnabled(verticalOffset == 0); }