auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public static String loadPrivateKeys(JSch jsch, String current_pkeys){ Preferences preferences=JSchCorePlugin.getPlugin().getPluginPreferences(); String ssh_home=preferences.getString(IConstants.KEY_SSH2HOME); String pkeys=preferences.getString(IConstants.KEY_PRIVATEKEY); if(ssh_home.length()==0) ssh_home=PreferenceInitializer.SSH_HOME_DEFAULT; java.io.File file; String[] pkey=pkeys.split(","); String[] _pkey=current_pkeys.split(","); String result=""; <START> for (String p : pkey) { <END> file = new java.io.File(p); if (!file.isAbsolute()) { file = new java.io.File(ssh_home, p); } if (file.exists()) { boolean notyet=true; for (String _pkey1 : _pkey) { if (p.equals(_pkey1)) { notyet=false; break;} } try { if(notyet) jsch.addIdentity(file.getPath()); if (result.length()==0) { result = p; } else { result += ("," + p); } }catch(JSchException e){ JSchCorePlugin.log(IStatus.ERROR, "An error occurred loading the SSH2 private keys", e); } } } return result; }</code><technical_language>jsch.core formatting</technical_language>

Target:
public static String loadPrivateKeys(JSch jsch, String current_pkeys){ Preferences preferences=JSchCorePlugin.getPlugin().getPluginPreferences(); String ssh_home=preferences.getString(IConstants.KEY_SSH2HOME); String pkeys=preferences.getString(IConstants.KEY_PRIVATEKEY); if(ssh_home.length()==0) ssh_home=PreferenceInitializer.SSH_HOME_DEFAULT; java.io.File file; String[] pkey=pkeys.split(","); String[] _pkey=current_pkeys.split(","); String result=""; for(String p : pkey){ file=new java.io.File(p); if(!file.isAbsolute()){ file=new java.io.File(ssh_home, p); } if(file.exists()){ boolean notyet=true; for(String _p : _pkey){ if(p.equals(_p)){ notyet=false; break; } } try{ if(notyet) jsch.addIdentity(file.getPath()); if(result.length()==0){ result=p; } else{ result+=(","+p); } } catch(JSchException e){ JSchCorePlugin.log(IStatus.ERROR, "An error occurred loading the SSH2 private keys", e); } } } return result; }
Source:
<code>private ObjectId createNoteContent(String reason, ObjectInserter inserter) throws UnsupportedEncodingException, IOException { String noteContent = reason != null ? reason : ""; <START> if (!noteContent.endsWith("\n")) { <END> noteContent = noteContent + "\n"; } return inserter.insert(Constants.OBJ_BLOB, noteContent.getBytes("UTF-8")); }</code><technical_language>new line appended if noteContent is empty reason specified</technical_language>

Target:
private ObjectId createNoteContent(String reason, ObjectInserter inserter) throws UnsupportedEncodingException, IOException { String noteContent = reason != null ? reason : ""; if (noteContent.length() > 0 && !noteContent.endsWith("\n")) { noteContent = noteContent + "\n"; } return inserter.insert(Constants.OBJ_BLOB, noteContent.getBytes("UTF-8")); }
Source:
<code>public Object getData(String name) { Object result = this.data.get(name); <START> if (result == null && name != null && name.equalsIgnoreCase("caseid")) { <END> result = getCaseId(); } return result; }</code><technical_language>I change name != null && name.equalsIgnoreCase("caseid") for "caseid".equalsIgnoreCase(name) . easier read</technical_language>

Target:
public Object getData(String name) { Object result = this.data.get(name); if (result == null && "caseid".equalsIgnoreCase(name)) { result = getCaseId(); } return result; }
Source:
<code>private static int getDefaultDataChannelCount() { int availableProcessors = Runtime.getRuntime().availableProcessors(); <START> return Math.min(250, Math.max(1, availableProcessors * 2)); <END> }</code><technical_language>Lets set default min 4</technical_language>

Target:
private static int getDefaultDataChannelCount() { int availableProcessors = Runtime.getRuntime().availableProcessors(); return Math.min(250, Math.max(1, availableProcessors * 4)); }
Source:
<code>public void listDirectoriesAndFilesAsyncMaxOverload() { DirectoryAsyncClient directoryAsyncClient = createAsyncClientWithSASToken(); <START> directoryAsyncClient.listFilesAndDirectories("subdir", 10, Duration.ofSeconds(1)).subscribe( <END> fileRef -> System.out.printf("Is the resource a directory? %b. The resource name is: %s.", fileRef.isDirectory(), fileRef.name()), error -> System.err.println(error.toString()), () -> System.out.println("Completed listing the directories and files.") ); END: com.azure.storage.file.directoryAsyncClient.listFilesAndDirectories#string-integer-duration }</code><technical_language>a timeout variable class level for code snippets pass instead, want leave vague. a Duration.ofSeconds(30) feels a more reasonable timeout</technical_language>

Target:
public void listDirectoriesAndFilesAsyncMaxOverload() { DirectoryAsyncClient directoryAsyncClient = createAsyncClientWithSASToken(); directoryAsyncClient.listFilesAndDirectories("subdir", 10).subscribe( fileRef -> System.out.printf("Is the resource a directory? %b. The resource name is: %s.", fileRef.isDirectory(), fileRef.name()), error -> System.err.println(error.toString()), () -> System.out.println("Completed listing the directories and files.") ); END: com.azure.storage.file.directoryAsyncClient.listFilesAndDirectories#string-integer }
Source:
<code>public PagedFlux<ConfigurationSetting> listSettings(SettingSelector selector) { try { return new PagedFlux<>(() -> withContext(context -> listFirstPageSettings(selector, context)), continuationToken -> withContext(context -> listNextPageSettings(context, continuationToken))); } catch (RuntimeException ex) { <START> return new PagedFlux<>(() -> Mono.error(logger.logExceptionAsError(Exceptions.propagate(ex)))); <END> } }</code><technical_language>a monoError too</technical_language>

Target:
public PagedFlux<ConfigurationSetting> listSettings(SettingSelector selector) { try { return new PagedFlux<>(() -> withContext(context -> listFirstPageSettings(selector, context)), continuationToken -> withContext(context -> listNextPageSettings(context, continuationToken))); } catch (RuntimeException ex) { return new PagedFlux<>(() -> monoError(logger, ex)); } }
Source:
<code>public InputStream openStream() throws IOException { <START> payload = objectApi.get(path).getPayload(); <END> try { return payload.openStream(); } catch (IOException e) { if (CloudFilesUtils.CLOUDFILESRETRY.apply(e)) { throw new IOException("Recoverable exception", e); } throw Throwables.propagate(e); } }</code><technical_language>this needs do a null check for payload assigning a new reference</technical_language>

Target:
public InputStream openStream() throws IOException { payload = (payload == null) ? objectApi.get(path).getPayload() : payload; try { return payload.openStream(); } catch (IOException e) { if (CloudFilesUtils.CLOUDFILESRETRY.apply(e)) { throw new IOException("Recoverable exception", e); } throw Throwables.propagate(e); } }
Source:
<code>public void testTypeConflictInPublicSchema() throws Exception { <START> node.createCache(new CacheConfiguration<PersonKey, Person>() <END> .setName(CACHE_PERSON) .setIndexedTypes(PersonKey.class, Person.class) .setSqlSchema(QueryUtils.DFLT_SCHEMA)); GridTestUtils.assertThrows(log, (Callable<Void>) () -> { node.createCache(new CacheConfiguration<PersonKey, Person>() .setName(CACHE_PERSON_2) .setIndexedTypes(PersonKey.class, Person.class) .setSqlSchema(QueryUtils.DFLT_SCHEMA)); return null; }, CacheException.class, "Table already exists: PERSON"); }</code><technical_language>4 spaces instead of tabs</technical_language>

Target:
public void testTypeConflictInPublicSchema() throws Exception { node.createCache(new CacheConfiguration<PersonKey, Person>() .setName(CACHE_PERSON) .setIndexedTypes(PersonKey.class, Person.class) .setSqlSchema(QueryUtils.DFLT_SCHEMA)); Throwable th = GridTestUtils.assertThrows(log, (Callable<Void>) () -> { node.createCache(new CacheConfiguration<PersonKey, Person>() .setName(CACHE_PERSON_2) .setIndexedTypes(PersonKey.class, Person.class) .setSqlSchema(QueryUtils.DFLT_SCHEMA)); return null; }, CacheException.class, null); SchemaOperationException e = X.cause(th, SchemaOperationException.class); assertEquals(SchemaOperationException.CODE_TABLE_EXISTS, e.code()); }
Source:
<code>private Plugin loadPlugin(File jarFile) throws IOException, ClassNotFoundException { Manifest jarManifest = new JarFile(jarFile).getManifest(); ClassLoader parentLoader = PluginLoader.class.getClassLoader(); ClassLoader jarClassLoader = new URLClassLoader(getPluginURLs(jarFile), parentLoader); Attributes attrs = jarManifest.getMainAttributes(); String pluginName = attrs.getValue("Gerrit-Plugin"); <START> String moduleName = attrs.getValue("Gerrit-SshModule"); <END> Class<?> moduleClass = Class.forName(moduleName, false, jarClassLoader); if (!AbstractModule.class.isAssignableFrom(moduleClass)) { throw new ClassNotFoundException("ModuleClass " + moduleClass.getName() + " is not a Guice AbstractModule"); } return new Plugin(pluginName, (Class<? extends AbstractModule>) moduleClass); }</code><technical_language>handle missing more gracefully NPE</technical_language>

Target:
private Plugin loadPlugin(File jarFile) throws IOException, ClassNotFoundException { Manifest jarManifest = new JarFile(jarFile).getManifest(); ClassLoader parentLoader = PluginLoader.class.getClassLoader(); ClassLoader jarClassLoader = new URLClassLoader(getPluginURLs(jarFile), parentLoader); String pluginName = getMandatoryAttribute(jarManifest, "Gerrit-Plugin"); String moduleName = getMandatoryAttribute(jarManifest, "Gerrit-SshModule"); Class<?> moduleClass = Class.forName(moduleName, false, jarClassLoader); if (!Module.class.isAssignableFrom(moduleClass)) { throw new ClassNotFoundException("Class " + moduleClass.getName() + " is not a Guice Module"); } return new Plugin(pluginName, (Class<? extends Module>) moduleClass); }
Source:
<code>public void testMetricOutputWithTimestamp() throws IOException { final Long now = System.currentTimeMillis(); class CustomCollector extends Collector { public List<MetricFamilySamples> collect() { List<MetricFamilySamples> mfs = new ArrayList<MetricFamilySamples>(); ArrayList<String> labelNames = new ArrayList<String>(); ArrayList<String> labelValues = new ArrayList<String>(); ArrayList<MetricFamilySamples.Sample> samples = new ArrayList<Collector.MetricFamilySamples.Sample>(); MetricFamilySamples.Sample sample = new MetricFamilySamples.Sample("nolabels", labelNames, labelValues, 1.0, now); samples.add(sample); mfs.add(new MetricFamilySamples("nolabels", Collector.Type.UNTYPED, "help", samples)); return mfs; } } new CustomCollector().register(registry); TextFormat.write004(writer, registry.metricFamilySamples()); assertEquals("# HELP nolabels help\n" + "# TYPE nolabels untyped\n" <START> + "nolabels 1.0 "+ now +"\n", writer.toString()); <END> }</code><technical_language>prefer this a literal string dynamic, output depends Java's implicit conversion string</technical_language>

Target:
public void testMetricOutputWithTimestamp() throws IOException { class CustomCollector extends Collector { public List<MetricFamilySamples> collect() { List<MetricFamilySamples> mfs = new ArrayList<MetricFamilySamples>(); ArrayList<String> labelNames = new ArrayList<String>(); ArrayList<String> labelValues = new ArrayList<String>(); ArrayList<MetricFamilySamples.Sample> samples = new ArrayList<Collector.MetricFamilySamples.Sample>(); MetricFamilySamples.Sample sample = new MetricFamilySamples.Sample("nolabels", labelNames, labelValues, 1.0, 1518123456L); samples.add(sample); mfs.add(new MetricFamilySamples("nolabels", Collector.Type.UNTYPED, "help", samples)); return mfs; } } new CustomCollector().register(registry); TextFormat.write004(writer, registry.metricFamilySamples()); assertEquals("# HELP nolabels help\n" + "# TYPE nolabels untyped\n" + "nolabels 1.0 1518123456\n", writer.toString()); }
Source:
<code>void setUp() { <START> final boolean multitenant = true; <END> builder = BoundedContext.newBuilder() .setMultitenant(multitenant); }</code><technical_language>inline</technical_language>

Target:
void setUp() { builder = BoundedContext.newBuilder() .setMultitenant(true); }
Source:
<code>private void autoComplete(int slashPosition, String input) { System.out.println(input); autoCompletePopup.getItems().clear(); XPathSuggestions xPathSuggestions = new XPathSuggestions(parent.getLanguageVersion().getLanguage()); List<String> suggestions = xPathSuggestions.getXPathSuggestions(input.trim()); List<MenuItem> resultToDisplay = suggestions.stream().map(m -> new MenuItem(m)).limit(5).collect(Collectors .toList()); autoCompletePopup.getItems().addAll(resultToDisplay); if (xpathExpressionArea.getText().length() > 0) { xpathExpressionArea.addEventHandler(KeyEvent.KEY_PRESSED, t -> { if (t.isControlDown() && (t.getCode() == KeyCode.SPACE)) { autoCompletePopup.show(xpathExpressionArea, 500, 500); <START> autoCompletePopup.setOnAction(e -> { <END> xpathExpressionArea.getText().replace(input, ""); xpathExpressionArea.replaceText(slashPosition + 1, xpathExpressionArea.getText().length() - 1, ((MenuItem) e.getTarget()).getText()); autoCompletePopup.hide(); }); } }); xpathExpressionArea.addEventHandler(KeyEvent.KEY_PRESSED, t -> { if (t.getCode() == KeyCode.ESCAPE) { autoCompletePopup.hide(); } }); } }</code><technical_language>set a specific action handler MenuItem, menu. Also, do eventhandler</technical_language>

Target:
private void autoComplete(int slashPosition, String input) { XPathSuggestions xPathSuggestions = new XPathSuggestions(parent.getLanguageVersion().getLanguage()); List<String> suggestions = xPathSuggestions.getXPathSuggestions(input.trim()); List<CustomMenuItem> resultToDisplay = new ArrayList<>(); if (!suggestions.isEmpty()) { for (int i = 0; i < suggestions.size() && i < 5; i++) { final String searchResult = suggestions.get(i); Label entryLabel = new Label(); entryLabel.setGraphic(Style.highlight(suggestions.get(i), input)); entryLabel.setPrefHeight(5); CustomMenuItem item = new CustomMenuItem(entryLabel, true); resultToDisplay.add(item); item.setOnAction(e -> { xpathExpressionArea.replaceText(slashPosition, slashPosition + input.length(), searchResult); autoCompletePopup.hide(); }); } } autoCompletePopup.getItems().setAll(resultToDisplay); if (autoCompletePopup.isAutoFix()) { xpathExpressionArea.getCharacterBoundsOnScreen(slashPosition, slashPosition + input.length()) .ifPresent(bounds -> autoCompletePopup.show(xpathExpressionArea, bounds.getMinX(), bounds.getMaxY())); } }
Source:
<code>private void createTimeEventContextMenu() { fEventMenuManager.setRemoveAllWhenShown(true); TimeGraphControl timeGraphControl = fTimeGraphViewer.getTimeGraphControl(); final Menu timeEventMenu = fEventMenuManager.createContextMenu(timeGraphControl); timeGraphControl.addTimeEventMenuListener(new MenuDetectListener() { @Override public void menuDetected(MenuDetectEvent event) { Menu menu = timeEventMenu; <START> if (isOnNamespace(event, timeGraphControl) || !(event.data instanceof FlamegraphEvent)) { <END> timeGraphControl.setMenu(null); event.doit = false; return; } timeGraphControl.setMenu(menu); } }); timeGraphControl.addTimeGraphEntryMenuListener(new MenuDetectListener() { @Override public void menuDetected(MenuDetectEvent event) { if (isOnNamespace(event, timeGraphControl)) { timeGraphControl.setMenu(null); event.doit = false; } } }); fEventMenuManager.addMenuListener(new IMenuListener() { @Override public void menuAboutToShow(IMenuManager manager) { fillTimeEventContextMenu(fEventMenuManager); fEventMenuManager.add(new GroupMarker(IWorkbenchActionConstants.MB_ADDITIONS)); } }); getSite().registerContextMenu(fEventMenuManager, fTimeGraphViewer.getSelectionProvider()); }</code><technical_language>If namespace, this listener get called Utils.findEvent() in TimeGraphControl.menuDetected() returns null. I need method isOnNamespace(). way, in method findEvent parameter '2', listener get called previous event if clicking blank space right of (I'm should, '0', is context menu for tick events?). menu is set, items selection a FlameGraphEvent in fillTimeEventContextMenu()</technical_language>

Target:
private void createTimeEventContextMenu() { fEventMenuManager.setRemoveAllWhenShown(true); TimeGraphControl timeGraphControl = fTimeGraphViewer.getTimeGraphControl(); final Menu timeEventMenu = fEventMenuManager.createContextMenu(timeGraphControl); timeGraphControl.addTimeGraphEntryMenuListener(new MenuDetectListener() { @Override public void menuDetected(MenuDetectEvent event) { timeGraphControl.setMenu(null); event.doit = false; } }); timeGraphControl.addTimeEventMenuListener(new MenuDetectListener() { @Override public void menuDetected(MenuDetectEvent event) { Menu menu = timeEventMenu; if (event.data instanceof FlamegraphEvent) { timeGraphControl.setMenu(menu); return; } timeGraphControl.setMenu(null); event.doit = false; } }); fEventMenuManager.addMenuListener(new IMenuListener() { @Override public void menuAboutToShow(IMenuManager manager) { fillTimeEventContextMenu(fEventMenuManager); fEventMenuManager.add(new GroupMarker(IWorkbenchActionConstants.MB_ADDITIONS)); } }); getSite().registerContextMenu(fEventMenuManager, fTimeGraphViewer.getSelectionProvider()); }
Source:
<code>public void testPostWithUnsupportedRetryAndFailureWhileHeadersAreSent() throws IOException { AtomicInteger count = new AtomicInteger(1); m_client.setRequestInterceptor( (request, conn, context, superCall) -> { System.out.println("POST write request; try " + count); if (count.getAndIncrement() < 2) { throw new SocketException("TEST:cannot write"); } return superCall.call(); }); HttpRequestFactory reqFactory = m_client.getHttpRequestFactory(); HttpRequest req = reqFactory.buildPostRequest(new GenericUrl(m_server.getContextUrl() + "retry"), new HttpContent() { @Override public void writeTo(OutputStream out) throws IOException { out.write("bar".getBytes()); } @Override public boolean retrySupported() { return false; } @Override public String getType() { return "text/plain;charset=UTF-8"; } @Override public long getLength() throws IOException { return 3; } }); req.setThrowExceptionOnExecuteError(false); req.execute(); <START> } <END></code><technical_language>assertions result</technical_language>

Target:
public void testPostWithUnsupportedRetryAndFailureWhileHeadersAreSent() throws IOException { AtomicInteger count = new AtomicInteger(1); m_client.setRequestInterceptor( (request, conn, context, superCall) -> { if (count.getAndIncrement() < 2) { conn.close(); } return superCall.call(); }); HttpRequestFactory reqFactory = m_client.getHttpRequestFactory(); HttpRequest req = reqFactory.buildPostRequest(new GenericUrl(m_server.getContextUrl() + "retry"), new HttpContent() { @Override public void writeTo(OutputStream out) throws IOException { out.write("bar".getBytes()); } @Override public boolean retrySupported() { return false; } @Override public String getType() { return "text/plain;charset=UTF-8"; } @Override public long getLength() throws IOException { return 3; } }); req.getHeaders().set(CORRELATION_ID, "02"); HttpResponse resp = req.execute(); byte[] bytes = IOUtility.readBytes(resp.getContent(), ObjectUtility.nvl(resp.getHeaders().getContentLength(), -1L).intValue()); String text = new String(bytes, StandardCharsets.UTF_8).trim(); assertEquals(text, "Post bar"); assertEquals(StandardCharsets.UTF_8, resp.getContentCharset()); assertEquals(new String(bytes), 10, bytes.length); assertEquals(Arrays.asList("02"), Servlet.doPostLog); assertNull(Servlet.doPostError); }
Source:
<code>String determineBranch() throws IOException { String branch = null; <START> String url = getInfoPart("URL:"); <END> int idx; final String branchesStr = "branches/"; if ((idx = url.indexOf(branchesStr)) > 0) { branch = url.substring(idx + branchesStr.length()); } return branch; }</code><technical_language>"URL:" a constant</technical_language>

Target:
String determineBranch() throws IOException { String branch = null; String url = getInfoPart(URLprefix); int idx; final String branchesStr = "branches/"; if ((idx = url.indexOf(branchesStr)) > 0) { branch = url.substring(idx + branchesStr.length()); } return branch; }
Source:
<code>protected void acquire(TransactionLocks locks) throws IOException { if (inodeIdentifiers != null && !inodeIdentifiers.isEmpty()) { List<INode> inodes; if(lockType == TransactionLockTypes.INodeLockType.READ_COMMITTED){ inodes = batchRead(); } else{ <START> inodes = orderedReadWithLock(); <END> } for (INode inode : inodes) { if (inode != null) { List<INode> pathInodes = readUpInodes(inode); addPathINodesAndUpdateResolvingCache(INodeUtil.constructPath(pathInodes), pathInodes); } } addIndividualINodes(inodes); } else { throw new StorageException( "INodeIdentifier object is not properly initialized "); } }</code><technical_language>I if create a new lock object a name for this. batched name a batch operation (fast) while is a sequential operation (slow) difference of performance important I marked more called batched other called else</technical_language>

Target:
protected void acquire(TransactionLocks locks) throws IOException { if (inodeIdentifiers != null && !inodeIdentifiers.isEmpty()) { List<INode> inodes = batchRead(); for (INode inode : inodes) { if (inode != null) { List<INode> pathInodes = readUpInodes(inode); addPathINodesAndUpdateResolvingCache(INodeUtil.constructPath(pathInodes), pathInodes); } } addIndividualINodes(inodes); } else { throw new StorageException( "INodeIdentifier object is not properly initialized "); } }
Source:
<code>public void testFormatRequest() throws Exception { Position position = new Position("123456789012345", new Location("gps"), 0); position.setTime(new Date(0)); <START> String url = ProtocolFormatter.formatRequest("http://localhost:5055/path", position); <END> assertEquals("http://localhost:5055/path?id=123456789012345&timestamp=0&lat=0.0&lon=0.0&speed=0.0&bearing=0.0&altitude=0.0&batt=0.0", url); }</code><technical_language>test path Traccar Client default</technical_language>

Target:
public void testFormatRequest() throws Exception { Position position = new Position("123456789012345", new Location("gps"), 0); position.setTime(new Date(0)); String url = ProtocolFormatter.formatRequest("http://localhost:5055", position); assertEquals("http://localhost:5055?id=123456789012345&timestamp=0&lat=0.0&lon=0.0&speed=0.0&bearing=0.0&altitude=0.0&batt=0.0", url); }
Source:
<code>public void init(ExternalComponentEditor presenter) { <START> componentEditorPropertiesColumn.innerHTML = ""; componentEditorPreviewColumn.innerHTML = ""; <END> domUtil.appendWidgetToElement(componentEditorPropertiesColumn, presenter.getPropertiesEditor().asWidget()); domUtil.appendWidgetToElement(componentEditorPreviewColumn, presenter.getExternalComponentPresenter().getView().asWidget()); }</code><technical_language>I lines unnecessary elements empty initialization</technical_language>

Target:
public void init(ExternalComponentEditor presenter) { domUtil.appendWidgetToElement(componentEditorPropertiesColumn, presenter.getPropertiesEditor().asWidget()); domUtil.appendWidgetToElement(componentEditorPreviewColumn, presenter.getExternalComponentPresenter().getView().asWidget()); }
Source:
<code>public void getPoints( final BackendlessGeoQuery geoQuery, final AsyncCallback<BackendlessCollection<GeoPoint>> responder ) { try { checkGeoQuery( geoQuery ); CollectionAdaptingPolicy<GeoPoint> adaptingPolicy = new CollectionAdaptingPolicy<GeoPoint>(); if( geoQuery.getDpp() != null && geoQuery.getDpp() > 0 ) { <START> Backendless.Cache.put( Messaging.DEVICE_ID + "." + BackendlessGeoQuery.class.getSimpleName(), geoQuery ); <END> } Invoker.invokeAsync( GEO_MANAGER_SERVER_ALIAS, "getPoints", new Object[] { Backendless.getApplicationId(), Backendless.getVersion(), geoQuery }, new AsyncCallback<BackendlessCollection<GeoPoint>>() { @Override public void handleResponse( BackendlessCollection<GeoPoint> response ) { response.setQuery( geoQuery ); response.setType( GeoPoint.class ); if( responder != null ) responder.handleResponse( response ); } @Override public void handleFault( BackendlessFault fault ) { responder.handleFault( fault ); } }, new AdaptingResponder<GeoPoint>( GeoPoint.class, adaptingPolicy ) ); } catch( Throwable e ) { if( responder != null ) responder.handleFault( new BackendlessFault( e ) ); } }</code><technical_language>This is wrong. Geo query cached server</technical_language>

Target:
public void getPoints( final BackendlessGeoQuery geoQuery, final AsyncCallback<BackendlessCollection<GeoPoint>> responder ) { try { checkGeoQuery( geoQuery ); CollectionAdaptingPolicy<GeoPoint> adaptingPolicy = new CollectionAdaptingPolicy<GeoPoint>(); Invoker.invokeAsync( GEO_MANAGER_SERVER_ALIAS, "getPoints", new Object[] { Backendless.getApplicationId(), Backendless.getVersion(), geoQuery }, new AsyncCallback<BackendlessCollection<GeoPoint>>() { @Override public void handleResponse( BackendlessCollection<GeoPoint> response ) { response.setQuery( geoQuery ); response.setType( GeoPoint.class ); if( geoQuery.getDpp() != null && geoQuery.getDpp() > 0 ) { setReferenceToCluster( response ); } if( responder != null ) responder.handleResponse( response ); } @Override public void handleFault( BackendlessFault fault ) { responder.handleFault( fault ); } }, new AdaptingResponder<GeoPoint>( GeoPoint.class, adaptingPolicy ) ); } catch( Throwable e ) { if( responder != null ) responder.handleFault( new BackendlessFault( e ) ); } }
Source:
<code><START> public InDimFilter optimizeLookup() { <END> if (extractionFn instanceof LookupExtractionFn && ((LookupExtractionFn) extractionFn).isOptimize()) { LookupExtractionFn exFn = (LookupExtractionFn) extractionFn; LookupExtractor lookup = exFn.getLookup(); final List<String> keys = new ArrayList<>(); for (String value : values) { final String convertedValue = Strings.emptyToNull(value); if (!exFn.isRetainMissingValue() && Objects.equals(convertedValue, exFn.getReplaceMissingValueWith())) { return this; } keys.addAll(lookup.unapply(convertedValue)); if (exFn.isRetainMissingValue() && lookup.apply(convertedValue) == null) { keys.add(convertedValue); } } if (keys.isEmpty()) { return this; } else { return new InDimFilter(dimension, keys, null); } } return this; }</code><technical_language>minor : this private users of this class optmize instead of calling optimizeLookup()</technical_language>

Target:
private InDimFilter optimizeLookup() { if (extractionFn instanceof LookupExtractionFn && ((LookupExtractionFn) extractionFn).isOptimize()) { LookupExtractionFn exFn = (LookupExtractionFn) extractionFn; LookupExtractor lookup = exFn.getLookup(); final List<String> keys = new ArrayList<>(); for (String value : values) { final String convertedValue = Strings.emptyToNull(value); if (!exFn.isRetainMissingValue() && Objects.equals(convertedValue, exFn.getReplaceMissingValueWith())) { return this; } keys.addAll(lookup.unapply(convertedValue)); if (exFn.isRetainMissingValue() && lookup.apply(convertedValue) == null) { keys.add(convertedValue); } } if (keys.isEmpty()) { return this; } else { return new InDimFilter(dimension, keys, null); } } return this; }
Source:
<code>private void fetchPopupPresenterTemplate(PresenterOptions presenterOptions) throws Exception { PopupPresenterOptions presenterWidgetOptions = new PopupPresenterOptions(); presenterWidgetOptions.setSingleton(presenterConfigModel.isUseSingleton()); presenterWidgetOptions.setCustom(presenterConfigModel.isUseOverrideDefaultPopup()); try { createdPopupPresenterTemplates = CreatePopupPresenter.run(presenterOptions, presenterWidgetOptions, true); } catch (Exception e) { <START> throw e; <END> } }</code><technical_language>do catch it</technical_language>

Target:
private void fetchPopupPresenterTemplate(PresenterOptions presenterOptions) throws Exception { PopupPresenterOptions presenterWidgetOptions = new PopupPresenterOptions(); presenterWidgetOptions.setSingleton(presenterConfigModel.isUseSingleton2()); presenterWidgetOptions.setCustom(presenterConfigModel.isUseOverrideDefaultPopup()); createdPopupPresenterTemplates = CreatePopupPresenter.run(presenterOptions, presenterWidgetOptions, true); }
Source:
<code>protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (StringUtils.isEmpty(request.getParameter(SSOUtils.POST_ACTION_URL))) { throw new RuntimeException("No post action url found in request."); } boolean acceptBasicAuth = (boolean) request.getSession().getServletContext().getAttribute(SSOUtils.ACCEPT_BASIC_AUTH_HEADERS); request.getSession(true).setAttribute(SSOUtils.PARAMS_MAP, new HashMap<>(request.getParameterMap())); if (acceptBasicAuth) { <START> response.sendRedirect(request.getContextPath() + SSOUtils.LOGIN_EXTERNAL_URI); <END> } else { response.sendRedirect(request.getContextPath() + SSOUtils.LOGIN_PHASE2_URI); } }</code><technical_language>redirect external done if external auth is enabled, this flag. if redirect other url is monitored apache</technical_language>

Target:
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (StringUtils.isEmpty(request.getParameter(SSOUtils.POST_ACTION_URL))) { throw new RuntimeException("No post action url found in request."); } boolean enableExternalAuth = (boolean) request.getSession().getServletContext().getAttribute(SSOUtils.ENABLE_EXTERNAL_AUTH); boolean acceptBasicAuth = (boolean) request.getSession().getServletContext().getAttribute(SSOUtils.ACCEPT_BASIC_AUTH_HEADERS); request.getSession(true).setAttribute(SSOUtils.PARAMS_MAP, new HashMap<>(request.getParameterMap())); if (enableExternalAuth) { response.sendRedirect(request.getContextPath() + SSOUtils.LOGIN_EXTERNAL_URI); } else if (acceptBasicAuth) { response.sendRedirect(request.getContextPath() + SSOUtils.LOGIN_BASIC_URI); } else { response.sendRedirect(request.getContextPath() + SSOUtils.LOGIN_PHASE2_URI); } }
Source:
<code>public boolean onTouch(View view, MotionEvent motionEvent) { if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) { startTime = motionEvent.getEventTime(); contextMenuShown = false; return true; } if(isDragging) { return true; } long holdTime = motionEvent.getEventTime() - startTime; if (holdTime < LONG_PRESS_DELAY && motionEvent.getAction() == MotionEvent.ACTION_UP) { this.onClick(view); return true; } if(!contextMenuShown && holdTime > LONG_PRESS_DELAY) { contextMenuShown = true; this.onLongClick(view); return true; } int intCurrentY = Math.round(motionEvent.getY()); int intCurrentX = Math.round(motionEvent.getX()); int intStartY = motionEvent.getHistorySize() > 0 ? Math.round(motionEvent.getHistoricalY(0)) : intCurrentY; int intStartX = motionEvent.getHistorySize() > 0 ? Math.round(motionEvent.getHistoricalX(0)) : intCurrentX; boolean hasMoved = (Math.abs(intCurrentX - intStartX) > MOVE_SENSITIVITY) || (Math.abs(intCurrentY - intStartY) > MOVE_SENSITIVITY); <START> int favSize = KissApplication.getApplication(mainActivity).getDataHandler().getFavorites(3).size(); <END> if (hasMoved && favSize > 1) { mainActivity.dismissPopup(); mainActivity.closeContextMenu(); View.DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(view); view.startDrag(null, shadowBuilder, view, 0); view.setVisibility(View.INVISIBLE); return true; } return false; }</code><technical_language>Do need get this onTouch()? do SQL query for tick dragging. instead disable drag completely is item? (just asking, I merge as-is too)</technical_language>

Target:
public boolean onTouch(View view, MotionEvent motionEvent) { if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) { startTime = motionEvent.getEventTime(); contextMenuShown = false; return true; } if(isDragging) { return true; } long holdTime = motionEvent.getEventTime() - startTime; if (holdTime < LONG_PRESS_DELAY && motionEvent.getAction() == MotionEvent.ACTION_UP) { this.onClick(view); return true; } if(!contextMenuShown && holdTime > LONG_PRESS_DELAY) { contextMenuShown = true; this.onLongClick(view); return true; } int intCurrentY = Math.round(motionEvent.getY()); int intCurrentX = Math.round(motionEvent.getX()); int intStartY = motionEvent.getHistorySize() > 0 ? Math.round(motionEvent.getHistoricalY(0)) : intCurrentY; int intStartX = motionEvent.getHistorySize() > 0 ? Math.round(motionEvent.getHistoricalX(0)) : intCurrentX; boolean hasMoved = (Math.abs(intCurrentX - intStartX) > MOVE_SENSITIVITY) || (Math.abs(intCurrentY - intStartY) > MOVE_SENSITIVITY); if (hasMoved && mDragEnabled) { mainActivity.dismissPopup(); mainActivity.closeContextMenu(); View.DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(view); view.startDrag(null, shadowBuilder, view, 0); view.setVisibility(View.INVISIBLE); return true; } return false; }
Source:
<code>public void testRowDataWriteReadWithCompatibleSchema() throws Exception { testRowDataWriteReadWithSchema(ADDRESS_SCHEMA_COMPATIBLE); <START> assertThat(client.getAllVersions("address-value").size(), is(1)); <END> }</code><technical_language>nit: SUBJECT</technical_language>

Target:
public void testRowDataWriteReadWithCompatibleSchema() throws Exception { testRowDataWriteReadWithSchema(ADDRESS_SCHEMA_COMPATIBLE); assertThat(client.getAllVersions(SUBJECT).size(), is(1)); }
Source:
<code>public String getName() { <START> return "External Components"; <END> }</code><technical_language>Consider i18n instead of hardcoding string External Components</technical_language>

Target:
public String getName() { return i18n.externalComponents(); }
Source:
<code>public void updateFirmwareShouldNotCallExecutorWhenFirmwareFileNotInCache() throws ProtocolAdapterException { final String firmwareIdentification = "fw"; when(this.firmwareFileCachingRepository.retrieve(firmwareIdentification)).thenReturn(null); try { this.firmwareService.updateFirmware(this.dlmsConnectionHolderMock, this.dlmsDeviceMock, firmwareIdentification); } catch (final ProtocolAdapterException e) { e.printStackTrace(); <START> ; <END> } verify(this.updateFirmwareCommandExecutor, times(0)).execute(this.dlmsConnectionHolderMock, this.dlmsDeviceMock, firmwareIdentification); }</code><technical_language>remove this line</technical_language>

Target:
public void updateFirmwareShouldNotCallExecutorWhenFirmwareFileNotInCache() throws ProtocolAdapterException { final String firmwareIdentification = "fw"; when(this.firmwareFileCachingRepository.retrieve(firmwareIdentification)).thenReturn(null); try { this.firmwareService.updateFirmware(this.dlmsConnectionHolderMock, this.dlmsDeviceMock, firmwareIdentification); } catch (final ProtocolAdapterException e) { e.printStackTrace(); } verify(this.updateFirmwareCommandExecutor, never()).execute(this.dlmsConnectionHolderMock, this.dlmsDeviceMock, firmwareIdentification); }
Source:
<code>public int kafkaPartition(RowMap r, int numPartitions) { if ( this.provider instanceof HashStringColumn ) return Math.abs(hashFunc.hashCode(((HashStringColumn) provider).getHashString(r, this.partitionColumns)) % numPartitions); else <START> return Math.abs(hashFunc.hashCode(provider.getHashString(r)) % numPartitions); <END> }</code><technical_language>this code cleaner; I preferable put partitionColumns in initializers for MaxwellKafkaPartitioner HashStringColumn</technical_language>

Target:
public int kafkaPartition(RowMap r, int numPartitions) { return Math.abs(hashFunc.hashCode(provider.getHashString(r, this.partitionColumns, this.partitionKeyFallback)) % numPartitions); }
Source:
<code>public Flux<NumericResponse<BitCountCommand, Long>> bitCount(Publisher<BitCountCommand> commands) { return connection.execute(cmd -> Flux.from(commands).concatMap(command -> { Assert.notNull(command.getKey(), "Key must not be null!"); Range<Long> range = command.getRange(); return (!Range.unbounded().equals(range) ? cmd.bitcount(command.getKey(), <START> range.getLowerBound().getValue().orElse(Long.MIN_VALUE), range.getUpperBound().getValue().orElse(Long.MAX_VALUE)) <END> : cmd.bitcount(command.getKey())).map(responseValue -> new NumericResponse<>(command, responseValue)); })); }</code><technical_language>starting index (unbounded) 0L -2<sup>63</sup></technical_language>

Target:
public Flux<NumericResponse<BitCountCommand, Long>> bitCount(Publisher<BitCountCommand> commands) { return connection.execute(cmd -> Flux.from(commands).concatMap(command -> { Assert.notNull(command.getKey(), "Key must not be null!"); Range<Long> range = command.getRange(); return (!Range.unbounded().equals(range) ? cmd.bitcount(command.getKey(), range.getLowerBound().getValue().orElse(0L), range.getUpperBound().getValue().orElse(Long.MAX_VALUE)) : cmd.bitcount(command.getKey())).map(responseValue -> new NumericResponse<>(command, responseValue)); })); }
Source:
<code>public List<String> getSessionIdsForUserName(String userName,String tenantDomain,String userStoreDomain) { List<String> sessionIdList = null; if (!enablePersist) { return sessionIdList; } Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { sessionIdList = new ArrayList<String>();; connection = jdbcPersistenceManager.getDBConnection(); connection.setAutoCommit(false); preparedStatement = connection.prepareStatement(SQL_SELECT_SESSION_IDS_MAPPED_TO_USER_NAME); preparedStatement.setString(1, userName); preparedStatement.setString(2, userStoreDomain); preparedStatement.setString(3, tenantDomain); resultSet = preparedStatement.executeQuery(); while (resultSet.next()) { sessionIdList.add(resultSet.getString(1)); } if (preparedStatement != null) { <START> preparedStatement.close(); <END> } } catch (IdentityException e) { log.error("Error while getting session data", e); } catch (SQLException e) { log.error("Error while getting session data", e); } finally { try { if (preparedStatement != null) { preparedStatement.close(); } if (connection != null) { connection.close(); } } catch (SQLException e) { log.error("Error while closing the stream", e); } } return sessionIdList; }</code><technical_language>duplicate ? closed in finally block</technical_language>

Target:
public List<String> getSessionIdsForUserName(String userName, String tenantDomain, String userStoreDomain) { List<String> sessionIdsList = null; if (!enablePersist) { return sessionIdsList; } Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { sessionIdsList = new ArrayList<String>(); connection = jdbcPersistenceManager.getDBConnection(); connection.setAutoCommit(false); preparedStatement = connection.prepareStatement(SQL_SELECT_SESSION_IDS_MAPPED_TO_USER_NAME); preparedStatement.setString(1, userName); preparedStatement.setString(2, userStoreDomain); preparedStatement.setString(3, tenantDomain); resultSet = preparedStatement.executeQuery(); while (resultSet.next()) { sessionIdsList.add(resultSet.getString(1)); } } catch (IdentityException e) { log.error("Error while getting session data", e); } catch (SQLException e) { log.error("Error while getting session data", e); } finally { try { if (preparedStatement != null) { preparedStatement.close(); } if (connection != null) { connection.close(); } } catch (SQLException e) { log.error("Error while closing the stream", e); } } return sessionIdsList; }
Source:
<code>public void testPreSplitCompositeFixedKey() throws Exception { Connection conn = DriverManager.getConnection(getUrl()); try { <START> conn.createStatement().execute("create table test2(key_1 char(3) not null, key_2 char(4) not null, v varchar(8) CONSTRAINT pk PRIMARY KEY (key_1,key_2)) split on('000','100','200')"); <END> conn.setAutoCommit(true); conn.createStatement().execute("upsert into test2 values('000','aaaa','value_1')"); conn.createStatement().execute("upsert into test2 values('000','aabb','value_2')"); conn.createStatement().execute("upsert into test2 values('100','aacc','value_3')"); conn.createStatement().execute("upsert into test2 values('100','aadd','value_4')"); conn.createStatement().execute("upsert into test2 values('200','aaee','value_5')"); conn.createStatement().execute("upsert into test2 values('201','aaff','value_6')"); ResultSet rs = conn.createStatement().executeQuery("select * from test2 where key_1>='000' and key_1<'200' and key_2>='aabb' and key_2<'aadd'"); assertTrue(rs.next()); assertEquals("000", rs.getString(1)); assertEquals("aabb", rs.getString(2)); assertEquals("value_2", rs.getString(3)); assertTrue(rs.next()); assertEquals("100", rs.getString(1)); assertEquals("aacc", rs.getString(2)); assertEquals("value_3", rs.getString(3)); assertFalse(rs.next()); } finally { conn.close(); } }</code><technical_language>Is a reason table name generated randomly</technical_language>

Target:
public void testPreSplitCompositeFixedKey() throws Exception { String tableName = generateRandomString(); Connection conn = DriverManager.getConnection(getUrl()); try { conn.createStatement().execute("create table " + tableName + "(key_1 char(3) not null, key_2 char(4) not null, v varchar(8) CONSTRAINT pk PRIMARY KEY (key_1,key_2)) split on('000','100','200')"); conn.setAutoCommit(true); conn.createStatement().execute("upsert into " + tableName + " values('000','aaaa','value_1')"); conn.createStatement().execute("upsert into " + tableName + " values('000','aabb','value_2')"); conn.createStatement().execute("upsert into " + tableName + " values('100','aacc','value_3')"); conn.createStatement().execute("upsert into " + tableName + " values('100','aadd','value_4')"); conn.createStatement().execute("upsert into " + tableName + " values('200','aaee','value_5')"); conn.createStatement().execute("upsert into " + tableName + " values('201','aaff','value_6')"); ResultSet rs = conn.createStatement().executeQuery("select * from " + tableName + " where key_1>='000' and key_1<'200' and key_2>='aabb' and key_2<'aadd'"); assertTrue(rs.next()); assertEquals("000", rs.getString(1)); assertEquals("aabb", rs.getString(2)); assertEquals("value_2", rs.getString(3)); assertTrue(rs.next()); assertEquals("100", rs.getString(1)); assertEquals("aacc", rs.getString(2)); assertEquals("value_3", rs.getString(3)); assertFalse(rs.next()); } finally { conn.close(); } }
Source:
<code><START> public static LanguageServerWrapper getLSWrapperForConnection(@NonNull IProject project, <END> @NonNull LanguageServerDefinition serverDefinition, @Nullable IPath initialPath) throws IOException { LanguageServerWrapper wrapper = null; synchronized(startedServers) { for (LanguageServerWrapper startedWrapper : getStartedLSWrappers(project)) { if (startedWrapper.serverDefinition.equals(serverDefinition)) { wrapper = startedWrapper; break; } } if (wrapper == null) { wrapper = project != null ? new LanguageServerWrapper(project, serverDefinition) : new LanguageServerWrapper(serverDefinition, initialPath); wrapper.start(); } startedServers.add(wrapper); } return wrapper; }</code><technical_language>similarly LanguageServerWrapper constructor, this private</technical_language>

Target:
private static LanguageServerWrapper getLSWrapperForConnection(@NonNull IProject project, @NonNull LanguageServerDefinition serverDefinition, @Nullable IPath initialPath) throws IOException { LanguageServerWrapper wrapper = null; synchronized(startedServers) { for (LanguageServerWrapper startedWrapper : getStartedLSWrappers(project)) { if (startedWrapper.serverDefinition.equals(serverDefinition)) { wrapper = startedWrapper; break; } } if (wrapper == null) { wrapper = project != null ? new LanguageServerWrapper(project, serverDefinition) : new LanguageServerWrapper(serverDefinition, initialPath); wrapper.start(); } startedServers.add(wrapper); } return wrapper; }
Source:
<code><START> public CosmosContinuablePagedIterable(ContinuablePagedFlux<String, T, FeedResponse<T>> pagedFlux) { <END> super(pagedFlux); }</code><technical_language>constructor public. end user need instantiate this. If public instantiated other packages, please BridgeInternal technique instead</technical_language>

Target:
CosmosContinuablePagedIterable(ContinuablePagedFlux<String, T, FeedResponse<T>> pagedFlux) { super(pagedFlux); }
Source:
<code>public Object read() { try { if (!forward()) { return null; } String tag = getLocalName(); Method <START> m = <END> readers.get(tag); if (m == null) { throw new RuntimeException( String.format("Can't find a reader for tag '%s'", tag) ); } return m.invoke(null, this); } catch (IllegalAccessException | InvocationTargetException e) { throw new RuntimeException("Failed to invoke read method."); } finally { close(); } }</code><technical_language>"method" a name</technical_language>

Target:
public Object read() { String tag = getLocalName(); Method method = readers.get(tag); try { if (!forward()) { return null; } if (method == null) { throw new RuntimeException( String.format("Can't find a reader for tag '%s'", tag) ); } return method.invoke(null, this); } catch (IllegalAccessException | InvocationTargetException exception) { throw new RuntimeException( String.format("Failed to invoke method '%1$s' to read element for tag '%2$s'", method, tag), exception ); } finally { close(); } }
Source:
<code>private void initialize() { log.info("Start initializing {}", getClass().getSimpleName()); Integer backupCheckPeriodInHours = Config.<Integer>getValue(ConfigValues.BackupCheckPeriodInHours); if (backupCheckPeriodInHours > 0) { schedulerUtil.scheduleAFixedDelayJob(this, "backupCheck", new Class[] {}, new Object[] {}, backupCheckPeriodInHours, backupCheckPeriodInHours, TimeUnit.HOURS); log.info("Finished initializing {}", getClass().getSimpleName()); } <START> lock = new ReentrantLock(); <END> }</code><technical_language>this is error prone: if schedule start process this line is executed, face NPE in line 82. Please initialize lock in c'tor is declared (line 52)</technical_language>

Target:
private void initialize() { log.info("Start initializing {}", getClass().getSimpleName()); Integer backupCheckPeriodInHours = Config.<Integer>getValue(ConfigValues.BackupCheckPeriodInHours); if (backupCheckPeriodInHours > 0) { schedulerUtil.scheduleAFixedDelayJob(this, "backupCheck", new Class[] {}, new Object[] {}, backupCheckPeriodInHours, backupCheckPeriodInHours, TimeUnit.HOURS); log.info("Finished initializing {}", getClass().getSimpleName()); } }
Source:
<code>public static Map<String, List<Long>> getTermPositions(IndexReader reader, String docid) throws IOException, NotStoredException { int ldocid = convertDocidToLuceneDocid(reader, docid); if (ldocid == -1) { return null; } Terms terms = reader.getTermVector(ldocid, IndexArgs.CONTENTS); if (terms == null) { throw new NotStoredException("Document vector not stored!"); } TermsEnum termIter = terms.iterator(); if (termIter == null) { throw new NotStoredException("Document vector not stored!"); } <START> Map<String, List<Long>> termPosition = new HashMap<>(); <END> PostingsEnum positionIter = null; while ((termIter.next()) != null) { List<Long> positions = new ArrayList<>(); Long termFreq = termIter.totalTermFreq(); positionIter = termIter.postings(positionIter, PostingsEnum.POSITIONS); positionIter.nextDoc(); for ( int i = 0; i < termFreq; i++ ) { positions.add(Long.valueOf(positionIter.nextPosition())); } termPosition.put(termIter.term().utf8ToString(), positions); } return termPosition; }</code><technical_language>yes, autoboxing is inefficient, List<Integer>, convert object anyway..</technical_language>

Target:
public static Map<String, List<Integer>> getTermPositions(IndexReader reader, String docid) throws IOException, NotStoredException { int ldocid = convertDocidToLuceneDocid(reader, docid); if (ldocid == -1) { return null; } Terms terms = reader.getTermVector(ldocid, IndexArgs.CONTENTS); if (terms == null) { throw new NotStoredException("Document vector not stored!"); } TermsEnum termIter = terms.iterator(); if (termIter == null) { throw new NotStoredException("Document vector not stored!"); } Map<String, List<Integer>> termPosition = new HashMap<>(); PostingsEnum positionIter = null; while ((termIter.next()) != null) { List<Integer> positions = new ArrayList<>(); long termFreq = termIter.totalTermFreq(); positionIter = termIter.postings(positionIter, PostingsEnum.POSITIONS); positionIter.nextDoc(); for ( int i = 0; i < termFreq; i++ ) { positions.add(positionIter.nextPosition()); } termPosition.put(termIter.term().utf8ToString(), positions); } return termPosition; }