auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code><START> protected void executeCommand() { <END> boolean hasConnectStorageSucceeded = connectToStorage(); VDSReturnValue returnValueUpdatedStorageDomain = updateStatsForDomain(); if (hasConnectStorageSucceeded && returnValueUpdatedStorageDomain.getSucceeded()) { final StorageDomain updatedStorageDomain = (StorageDomain) returnValueUpdatedStorageDomain.getReturnValue(); TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { getStorageConnDao().update(getParameters().getStorageServerConnection()); getStorageDomainDynamicDao().update(updatedStorageDomain.getStorageDynamicData()); return null; } }); setSucceeded(true); } }</code><technical_language>a reminder db lock for user experience more opinions</technical_language>

Target:
protected void executeCommand() { StoragePoolIsoMap map = getStoragePoolIsoMap(); changeStorageDomainStatusInTransaction(map,StorageDomainStatus.Locked); boolean hasConnectStorageSucceeded = connectToStorage(); VDSReturnValue returnValueUpdatedStorageDomain = null; if(!hasConnectStorageSucceeded) { setSucceeded(false); VdcFault f = new VdcFault(); f.setError(VdcBllErrors.StorageServerConnectionError); getReturnValue().setFault(f); changeStorageDomainStatusInTransaction(map,StorageDomainStatus.Maintenance); return; } returnValueUpdatedStorageDomain = updateStatsForDomain(); if (returnValueUpdatedStorageDomain.getSucceeded()) { final StorageDomain updatedStorageDomain = (StorageDomain) returnValueUpdatedStorageDomain.getReturnValue(); TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { getStorageConnDao().update(getParameters().getStorageServerConnection()); getStorageDomainDynamicDao().update(updatedStorageDomain.getStorageDynamicData()); return null; } }); setSucceeded(true); } changeStorageDomainStatusInTransaction(map,StorageDomainStatus.Maintenance); }
Source:
<code>protected void addHttpRequestEntities(HttpRequestBase request) throws BugzillaRestException { super.addHttpRequestEntities(request); try { <START> UserCredentials credentials = getClient().getLocation().getCredentials(AuthenticationType.REPOSITORY); <END> if (credentials == null) { throw new IllegalStateException("Authentication requested without valid credentials"); } Gson gson = new GsonBuilder() .registerTypeAdapter(OldAttributes.class, new TaskAttributeTypeAdapter(getClient().getLocation())) .create(); StringEntity requestEntity = new StringEntity(gson.toJson(oldAttributes)); ((HttpPut) request).setEntity(requestEntity); } catch (UnsupportedEncodingException e) { com.google.common.base.Throwables.propagate(new CoreException( new Status(IStatus.ERROR, BugzillaRestCore.ID_PLUGIN, "Can not build HttpRequest", e))); } }</code><technical_language>credentials in this method, checked</technical_language>

Target:
protected void addHttpRequestEntities(HttpRequestBase request) throws BugzillaRestException { super.addHttpRequestEntities(request); try { Gson gson = new GsonBuilder() .registerTypeAdapter(OldAttributes.class, new TaskAttributeTypeAdapter(getClient().getLocation())) .create(); StringEntity requestEntity = new StringEntity(gson.toJson(oldAttributes)); ((HttpPut) request).setEntity(requestEntity); } catch (UnsupportedEncodingException e) { Throwables.propagate(new CoreException( new Status(IStatus.ERROR, BugzillaRestCore.ID_PLUGIN, "Can not build HttpRequest", e))); } }
Source:
<code>public static Collection<ByteArrayWrapper> spop(Region<ByteArrayWrapper, RedisSet> region, ByteArrayWrapper key, int popCount) { RedisSet redisSet = region.get(key); if (redisSet != null) { return redisSet.doSpop(region, key, popCount); } else { <START> return null; <END> } }</code><technical_language>calling code differentiate null empty collection? If not, return empty collection get rid of upstream null checks</technical_language>

Target:
public static Collection<ByteArrayWrapper> spop(Region<ByteArrayWrapper, RedisSet> region, ByteArrayWrapper key, int popCount) { RedisSet redisSet = region.get(key); if (redisSet != null) { return redisSet.doSpop(region, key, popCount); } else { return emptyList(); } }
Source:
<code>private void moveProductsSideways() { $(allCarrouselDivs).addClass(stateTransitionStyleName); $(allCarrouselDivs).addClass(stateBesideStyleName); Scheduler.get().scheduleFixedPeriod(new Scheduler.RepeatingCommand() { public boolean execute() { removeProductClasses(); return false; } <START> }, 1250); <END> }</code><technical_language>Constant</technical_language>

Target:
private void moveProductsSideways() { toggleClass(true); Scheduler.get().scheduleFixedPeriod(new Scheduler.RepeatingCommand() { public boolean execute() { removeProductClasses(); return false; } }, animationSidewaysDuration); }
Source:
<code>public void createPartControl(Composite parent) { fPagebook = new PageBook(parent, SWT.NULL); createInfoPage(); createViewerPage(); getSite().setSelectionProvider(new AdaptingSelectionProvider(ICElement.class, fTreeViewer)); initDragAndDrop(); createActions(); createContextMenu(); bindingService = (IBindingService) PlatformUI.getWorkbench().getService(IBindingService.class); if (bindingService != null) { bindingManagerListener = new IBindingManagerListener() { @Override public void bindingManagerChanged(BindingManagerEvent event) { if (event.isActiveBindingsChanged()) { String keyBinding = bindingService.getBestActiveBindingFormattedFor(IWorkbenchCommandConstants.EDIT_DELETE); if (keyBinding != null) <START> fRemoveFromViewAction.setText(CHMessages.CHViewPart_RemoveFromView_label <END> + '\t'+ keyBinding); } } }; bindingService.addBindingManagerListener(bindingManagerListener); } setMessage(CHMessages.CHViewPart_emptyPageMessage); initializeActionStates(); IContextService ctxService = (IContextService) getSite().getService(IContextService.class); if (ctxService != null) { fContextActivation= ctxService.activateContext(CUIPlugin.CVIEWS_SCOPE); } PlatformUI.getWorkbench().getHelpSystem().setHelp(fPagebook, ICHelpContextIds.CALL_HIERARCHY_VIEW); addPartListener(); }</code><technical_language>Break lines</technical_language>

Target:
public void createPartControl(Composite parent) { fPagebook = new PageBook(parent, SWT.NULL); createInfoPage(); createViewerPage(); getSite().setSelectionProvider(new AdaptingSelectionProvider(ICElement.class, fTreeViewer)); initDragAndDrop(); createActions(); createContextMenu(); bindingService = (IBindingService) PlatformUI.getWorkbench().getService(IBindingService.class); if (bindingService != null) { bindingManagerListener = new IBindingManagerListener() { @Override public void bindingManagerChanged(BindingManagerEvent event) { if (event.isActiveBindingsChanged()) { String keyBinding = bindingService.getBestActiveBindingFormattedFor(IWorkbenchCommandConstants.EDIT_DELETE); if (keyBinding != null) { fRemoveFromViewAction.setText(CHMessages.CHViewPart_RemoveFromView_label + '\t'+ keyBinding); } } } }; bindingService.addBindingManagerListener(bindingManagerListener); } setMessage(CHMessages.CHViewPart_emptyPageMessage); initializeActionStates(); IContextService ctxService = (IContextService) getSite().getService(IContextService.class); if (ctxService != null) { fContextActivation= ctxService.activateContext(CUIPlugin.CVIEWS_SCOPE); } PlatformUI.getWorkbench().getHelpSystem().setHelp(fPagebook, ICHelpContextIds.CALL_HIERARCHY_VIEW); addPartListener(); }
Source:
<code>MouseNavigator(final StyledText styledText) { if (styledText == null) { SWT.error(SWT.ERROR_NULL_ARGUMENT); } if (styledText.isDisposed()) { SWT.error(SWT.ERROR_WIDGET_DISPOSED); } parent = styledText; <START> mouseDownListener = new Listener() { <END> @Override public void handleEvent(Event e) { onMouseDown(e); } }; parent.addListener(SWT.MouseDown, mouseDownListener); mouseUpListener = new Listener() { @Override public void handleEvent(Event e) { onMouseUpOrExit(e); } }; parent.addListener(SWT.MouseUp, mouseUpListener); paintListener = new Listener() { @Override public void handleEvent(Event e) { onPaint(e); } }; parent.addListener(SWT.Paint, paintListener); mouseMoveListener = new Listener() { @Override public void handleEvent(Event e) { onMouseMove(e); } }; parent.addListener(SWT.MouseMove, mouseMoveListener); mouseExitListener = new Listener() { @Override public void handleEvent(Event event) { onMouseUpOrExit(event); } }; parent.addListener(SWT.MouseExit, mouseExitListener); }</code><technical_language>Please convert listeners Lambdas, this performance benefits (bytecode saved + faster)</technical_language>

Target:
MouseNavigator(final StyledText styledText) { if (styledText == null) { SWT.error(SWT.ERROR_NULL_ARGUMENT); } if (styledText.isDisposed()) { SWT.error(SWT.ERROR_WIDGET_DISPOSED); } parent = styledText; mouseDownListener = (event) -> { onMouseDown(event); }; parent.addListener(SWT.MouseDown, mouseDownListener); mouseUpListener = (event) -> { onMouseUpOrExit(event); }; parent.addListener(SWT.MouseUp, mouseUpListener); paintListener = (event) -> { onPaint(event); }; parent.addListener(SWT.Paint, paintListener); mouseMoveListener = (event) -> { onMouseMove(event); }; parent.addListener(SWT.MouseMove, mouseMoveListener); mouseExitListener = (event) -> { onMouseUpOrExit(event); }; parent.addListener(SWT.MouseExit, mouseExitListener); }
Source:
<code>public CouchDBDocument saveDocument(CouchDBDocument document) { Response response = null; try { response = databaseClient.saveDocument( document, document.getId() ); if ( response.getStatus() == Response.Status.CREATED.getStatusCode() ) { CouchDBResponse entity = response.readEntity( CouchDBResponse.class ); updateDocumentRevision( document, entity.getRev() ); } else if ( response.getStatus() == Response.Status.CONFLICT.getStatusCode() ) { <START> throw new OptimisticLockException(); <END> } else { CouchDBResponse entity = response.readEntity( CouchDBResponse.class ); throw logger.errorCreatingDocument( response.getStatus(), entity.getError(), entity.getReason() ); } return document; } catch (ResteasyClientException e) { throw logger.couchDBConnectionProblem( e ); } finally { if ( response != null ) { response.close(); } } }</code><technical_language>add some error message this exception. user see. HibernateException in this case</technical_language>

Target:
public CouchDBDocument saveDocument(CouchDBDocument document) { return doSaveDocument( document, false ); }
Source:
<code>static String exportGnucashXML(SQLiteDatabase db) throws IOException { Log.i(LOG_TAG, "Exporting database to GnuCash XML"); ExportParams exportParams = new ExportParams(ExportFormat.GNC_XML); exportParams.setExportAllTransactions(true); exportParams.setExportTarget(ExportParams.ExportTarget.SD_CARD); exportParams.setDeleteTransactionsAfterExport(false); new File(Environment.getExternalStorageDirectory() + "/gnucash/").mkdirs(); exportParams.setTargetFilepath(Environment.getExternalStorageDirectory() + "/gnucash/" + Exporter.buildExportFilename(ExportFormat.GNC_XML)); <START> GncXmlExporter exporter = new GncXmlExporter(exportParams); <END> BufferedWriter writer = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(exportParams.getTargetFilepath()), "UTF-8")); try { String xml = exporter.generateXML(); writer.write(xml); } catch (ParserConfigurationException e) { e.printStackTrace(); } finally { writer.flush(); writer.close(); } return exportParams.getTargetFilepath(); }</code><technical_language>I Android opens database database migrations. If try open db yourself, is a conflict. migration takes database provided DatabaseHelper.onUpgrade() method. Granted I test opening db Application subclass, I wrong. tested a migration from, v1.3.3 this build</technical_language>

Target:
static String exportGnucashXML(SQLiteDatabase db) throws IOException { Log.i(LOG_TAG, "Exporting database to GnuCash XML"); ExportParams exportParams = new ExportParams(ExportFormat.GNC_XML); exportParams.setExportAllTransactions(true); exportParams.setExportTarget(ExportParams.ExportTarget.SD_CARD); exportParams.setDeleteTransactionsAfterExport(false); new File(Environment.getExternalStorageDirectory() + "/gnucash/").mkdirs(); exportParams.setTargetFilepath(Environment.getExternalStorageDirectory() + "/gnucash/" + Exporter.buildExportFilename(ExportFormat.GNC_XML)); GncXmlExporter exporter = new GncXmlExporter(exportParams, db); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(exportParams.getTargetFilepath()), "UTF-8")); try { String xml = exporter.generateXML(); writer.write(xml); } catch (ParserConfigurationException e) { e.printStackTrace(); } finally { writer.flush(); writer.close(); } return exportParams.getTargetFilepath(); }
Source:
<code>public double getWalkSpeed() { <START> return walkSpeed; <END> }</code><technical_language>this</technical_language>

Target:
public double getWalkSpeed() { return this.walkSpeed; }
Source:
<code>public void setSortOrder(@Nullable Comparator<?> comparator) { if (comparator == null) { return; } <START> fComparator = (Comparator<ISegment>) comparator; <END> final TableViewer tableViewer = fTableViewer; if (tableViewer == null) { return; } Arrays.sort(fSegmentArray, fComparator); tableViewer.refresh(); }</code><technical_language>Set comparator (potentially null) first, return if null. Is a is in fact ISegment comparator, avoid class cast exception</technical_language>

Target:
public void setSortOrder(@Nullable Comparator<?> comparator) { if (comparator == null) { return; } if (fSegmentArray == null) { return; } final TableViewer tableViewer = fTableViewer; if (tableViewer == null) { return; } fComparator = (Comparator<ISegment>) comparator; Arrays.sort(fSegmentArray, fComparator); tableViewer.refresh(); }
Source:
<code>public void setPortrait(AbstractIcon portrait) { <START> this.portrait = portrait; <END> }</code><technical_language>this null? If lets require non-null here</technical_language>

Target:
public void setPortrait(AbstractIcon portrait) { assert (portrait != null) : "Illegal assignment: cannot have a null AbstractIcon for a Portrait"; this.portrait = Objects.requireNonNull(portrait); }
Source:
<code>public <T> boolean register(T destroyableInstance, Binding<T> binding, Iterable<LifecycleAction> action) { try { return (running.get()) ? binding.acceptScopingVisitor(new ManagedInstanceScopingVisitor(destroyableInstance, binding.getSource(), action)) : false; } catch (Exception e) { LOGGER.warn("failed to register lifecycle actions for {}", destroyableInstance, e); <START> return false; <END> } }</code><technical_language>throwing here? conditions this throw exception fine ignoring</technical_language>

Target:
public <T> boolean register(T destroyableInstance, Binding<T> binding, Iterable<LifecycleAction> action) { return (running.get()) ? binding.acceptScopingVisitor(new ManagedInstanceScopingVisitor(destroyableInstance, binding.getSource(), action)) : false; }
Source:
<code>public String render(Double data) { int totalSeconds = data.intValue(); int days = totalSeconds / SECONDS_IN_A_DAY; int hours = (totalSeconds % SECONDS_IN_A_DAY) / SECONDS_IN_AN_HOUR; int minutes = (totalSeconds % SECONDS_IN_AN_HOUR) / SECONDS_IN_A_MINUTE; int seconds = totalSeconds % SECONDS_IN_A_MINUTE; String reply = ""; if (days > 0) { reply += days + (days == 1 ? " day " : " days "); } else if (hours > 0) { reply += hours + " h "; } else if (minutes > 0) { reply += minutes + " min "; <START> } else if (seconds >= 0) { <END> reply += seconds + " sec"; } return reply; }</code><technical_language>Remove this file this patch</technical_language>

Target:
public String render(Double data) { int totalSeconds = data.intValue(); int days = totalSeconds / SECONDS_IN_A_DAY; int hours = (totalSeconds % SECONDS_IN_A_DAY) / SECONDS_IN_AN_HOUR; int minutes = (totalSeconds % SECONDS_IN_AN_HOUR) / SECONDS_IN_A_MINUTE; int seconds = totalSeconds % SECONDS_IN_A_MINUTE; String reply = ""; if (days > 0) { reply += days + (days == 1 ? " day " : " days "); } else if (hours > 0) { reply += hours + " h "; } else if (minutes > 0) { reply += minutes + " min "; } else if (seconds > 0) { reply += seconds + " sec"; } return reply; }
Source:
<code>public void validateAllSupportedCiphers() throws IOException, DecoderException { final Iterator<SupportedCipherDetails> i = CIPHERS_TO_TEST.iterator(); <START> while (i.hasNext()) { <END> final SupportedCipherDetails cipherDetails = i.next(); validateEncryptedFileWithHeaderValues(cipherDetails); } }</code><technical_language>for : iterator directly</technical_language>

Target:
public void validateAllSupportedCiphers() throws IOException, DecoderException { for (final SupportedCipherDetails cipherDetails : CIPHERS_TO_TEST) { validateEncryptedFileWithHeaderValues(cipherDetails); } }
Source:
<code>void addLocationIdValues(final Map<Integer, List<ObservationUnitRow>> observationUnitRowMap) { final Map<Integer, String> instanceIdLocationIdMap = this.studyDataManager.getInstanceIdLocationIdMap(new ArrayList<>(observationUnitRowMap.keySet())); for(Integer instanceId: observationUnitRowMap.keySet()) { final List<ObservationUnitRow> observationUnitRows = observationUnitRowMap.get(instanceId); final ObservationUnitData locationIdData = new ObservationUnitData(); locationIdData.setValue(instanceIdLocationIdMap.get(instanceId)); <START> for(ObservationUnitRow row: observationUnitRows) { <END> row.getVariables().put(LOCATION_ID_VARIABLE_NAME, locationIdData); } } }</code><technical_language>Apply cleanup (eg. put final in for loop variables). Apply formatter</technical_language>

Target:
void addLocationIdValues(final Map<Integer, List<ObservationUnitRow>> observationUnitRowMap) { final Map<Integer, String> instanceIdLocationIdMap = this.studyDataManager.getInstanceIdLocationIdMap(new ArrayList<>(observationUnitRowMap.keySet())); for(final Integer instanceId: observationUnitRowMap.keySet()) { final ObservationUnitData locationIdData = new ObservationUnitData(); locationIdData.setValue(instanceIdLocationIdMap.get(instanceId)); observationUnitRowMap.get(instanceId).forEach(row -> { row.getVariables().put(LOCATION_ID_VARIABLE_NAME, locationIdData); }); } }
Source:
<code><START> private void collectMatchingIUs(Map<String, ?> indexToUse, String name, Collection<IInstallableUnit> collector) { <END> Object v = indexToUse.get(name); if (v == null) return; if (v instanceof IInstallableUnit) collector.add((IInstallableUnit) v); else collector.addAll((Collection<IInstallableUnit>) v); }</code><technical_language>this static? is actally necessary is move collections everywhere</technical_language>

Target:
private static void collectMatchingIUs(Map<String, ?> indexToUse, String name, Collection<IInstallableUnit> collector) { Object v = indexToUse.get(name); if (v == null) return; if (v instanceof IInstallableUnit) collector.add((IInstallableUnit) v); else collector.addAll((Collection<IInstallableUnit>) v); }
Source:
<code>public String intercept(ActionInvocation invocation) throws Exception { <START> HttpServletRequest servletRequest = invocation.getInvocationContext().getServletRequest(); <END> HttpSession httpSession = servletRequest.getSession(false); if (httpSession == null) { LOG.debug("Creating new HttpSession and new SessionMap in ServletActionContext"); servletRequest.getSession(true); invocation.getInvocationContext().setSession(new SessionMap<>(servletRequest)); } return invocation.invoke(); }</code><technical_language>candidate for explicit IllegalArgumentException if invocation is null</technical_language>

Target:
public String intercept(ActionInvocation invocation) throws Exception { HttpServletRequest servletRequest = invocation.getInvocationContext().getServletRequest(); HttpSession httpSession = servletRequest.getSession(false); if (httpSession == null) { LOG.debug("Creating new HttpSession and new SessionMap in ServletActionContext"); servletRequest.getSession(true); invocation.getInvocationContext().withSession(new SessionMap<>(servletRequest)); } return invocation.invoke(); }
Source:
<code>public void testList() { for (Location location : api().list()) { <START> assertTrue(!location.id().isEmpty()); <END> } assertTrue(!api().list().isEmpty()); }</code><technical_language>please add a "checkLocation(location);" assertNotNull fields of Location</technical_language>

Target:
public void testList() { assertTrue(!api().list().isEmpty()); for (Location location : api().list()) { assertTrue(!location.id().isEmpty()); checkLocation(location); } }
Source:
<code>public boolean isTrue(State state, String[] params) { if (!params[1].equalsIgnoreCase("")) { ObjectInstance container = state.getObject(params[1]); Set<String> contents = ContainerFactory.getContentNames(container); if (contents.isEmpty()) { return false; } ObjectInstance toPeel = null; <START> for (String name : contents) { <END> toPeel = state.getObject(name); break; } for (IngredientRecipe content : this.topLevelIngredient.getConstituentIngredients()) { if (content.getName().equals(toPeel.getName())) { return content.getPeeled(); } } AbstractMap<String, IngredientRecipe> necessaryTraits = this.topLevelIngredient.getNecessaryTraits(); Set<String> toMeltTraits = IngredientFactory.getTraits(toPeel); for (String trait : necessaryTraits.keySet()) { if (toMeltTraits.contains(trait)) { if (necessaryTraits.get(trait).getPeeled()) { return true; } } } return false; } else { for (IngredientRecipe content : topLevelIngredient.getConstituentIngredients()) { if (content.getPeeled()) { return true; } } AbstractMap<String, IngredientRecipe> traitMap = topLevelIngredient.getConstituentNecessaryTraits(); for (String trait : traitMap.keySet()) { if (traitMap.get(trait).getPeeled()) { return true; } } return false; } }</code><technical_language>check if ingredients in container peelable</technical_language>

Target:
public boolean isTrue(State state, String[] params) { if (!params[1].equalsIgnoreCase("")) { ObjectInstance container = state.getObject(params[1]); Set<String> contents = ContainerFactory.getContentNames(container); if (contents.isEmpty()) { return false; } ObjectInstance toPeel = null; for (String name : contents) { toPeel = state.getObject(name); boolean match = false; for (IngredientRecipe content : this.topLevelIngredient.getConstituentIngredients()) { if (content.getName().equals(toPeel.getName())) { if (!content.getPeeled()) { return false; } match = true; break; } } if (!match) { AbstractMap<String, IngredientRecipe> necessaryTraits = this.topLevelIngredient.getNecessaryTraits(); Set<String> toMeltTraits = IngredientFactory.getTraits(toPeel); for (String trait : necessaryTraits.keySet()) { if (toMeltTraits.contains(trait)) { if (necessaryTraits.get(trait).getPeeled()) { match = true; break; } } } if (!match) { return false; } } } return true; } else { for (IngredientRecipe content : topLevelIngredient.getConstituentIngredients()) { if (content.getPeeled()) { return true; } } AbstractMap<String, IngredientRecipe> traitMap = topLevelIngredient.getConstituentNecessaryTraits(); for (String trait : traitMap.keySet()) { if (traitMap.get(trait).getPeeled()) { return true; } } return false; } }
Source:
<code>Mono<DecryptResult> decryptAsync(EncryptionAlgorithm algorithm, byte[] cipherText, byte[] iv, byte[] authenticationData, byte[] authenticationTag, Context context, JsonWebKey key) { <START> throw new UnsupportedOperationException("Decrypt operaiton is not supported for EC key"); <END> }</code><technical_language>s/operaiton/operation</technical_language>

Target:
Mono<DecryptResult> decryptAsync(EncryptionAlgorithm algorithm, byte[] cipherText, byte[] iv, byte[] authenticationData, byte[] authenticationTag, Context context, JsonWebKey key) { throw new UnsupportedOperationException("Decrypt operation is not supported for EC key"); }
Source:
<code>public static void main(String[] args) throws Exception { if(args.length < 1) { usage(); return; } try (BufferedReader modelReader = new BufferedReader(new FileReader(args[0]))) { String chartTitle = modelReader.readLine(); String[] series = modelReader.readLine().split(","); List<String> listLanguages = new ArrayList<>(10); List<Double> listCountries = new ArrayList<>(10); List<Double> listSpeakers = new ArrayList<>(10); String ln; while((ln = modelReader.readLine()) != null) { String[] vals = ln.split(","); listCountries.add(Double.valueOf(vals[0])); listSpeakers.add(Double.valueOf(vals[1])); listLanguages.add(vals[2]); } String[] categories = listLanguages.toArray(new String[listLanguages.size()]); Double[] values1 = listCountries.toArray(new Double[listCountries.size()]); Double[] values2 = listSpeakers.toArray(new Double[listSpeakers.size()]); try { XMLSlideShow ppt = new XMLSlideShow(); XSLFSlide slide = ppt.createSlide(); XSLFChart chart = ppt.createChart(); Rectangle2D rect2D = new java.awt.Rectangle(XDDFChart.DEFAULT_X, XDDFChart.DEFAULT_Y, <START> 5000000, 5000000); <END> slide.addChart(chart, rect2D); setBarData(chart, chartTitle, series, categories, values1, values2); try (OutputStream out = new FileOutputStream("bar-chart-demo-output.pptx")) { ppt.write(out); } } catch(Exception e) { e.printStackTrace(); } } System.out.println("Done"); }</code><technical_language>Please XDDFChart.DEFAULT_WIDTH XDDFChart.DEFAULT_HEIGHT instead of magic numbers</technical_language>

Target:
public static void main(String[] args) throws Exception { if(args.length < 1) { usage(); return; } try (BufferedReader modelReader = new BufferedReader(new FileReader(args[0]))) { String chartTitle = modelReader.readLine(); String[] series = modelReader.readLine().split(","); List<String> listLanguages = new ArrayList<>(10); List<Double> listCountries = new ArrayList<>(10); List<Double> listSpeakers = new ArrayList<>(10); String ln; while((ln = modelReader.readLine()) != null) { String[] vals = ln.split(","); listCountries.add(Double.valueOf(vals[0])); listSpeakers.add(Double.valueOf(vals[1])); listLanguages.add(vals[2]); } String[] categories = listLanguages.toArray(new String[listLanguages.size()]); Double[] values1 = listCountries.toArray(new Double[listCountries.size()]); Double[] values2 = listSpeakers.toArray(new Double[listSpeakers.size()]); try { XMLSlideShow ppt = new XMLSlideShow(); XSLFSlide slide = ppt.createSlide(); XSLFChart chart = ppt.createChart(); Rectangle2D rect2D = new java.awt.Rectangle(XDDFChart.DEFAULT_X, XDDFChart.DEFAULT_Y, XDDFChart.DEFAULT_WIDTH, XDDFChart.DEFAULT_HEIGHT); slide.addChart(chart, rect2D); setBarData(chart, chartTitle, series, categories, values1, values2); try (OutputStream out = new FileOutputStream("bar-chart-demo-output.pptx")) { ppt.write(out); } } catch(Exception e) { e.printStackTrace(); } } System.out.println("Done"); }
Source:
<code>public boolean isValid(String value, ConstraintValidatorContext ctx) { if (value == null) { return true; } <START> for (String s:invalCategNames) { <END> if (value.equals(s)) { return false; } } return true; }</code><technical_language>Please put spaces :</technical_language>

Target:
public boolean isValid(String value, ConstraintValidatorContext ctx) { if (value == null) { return true; } for (String forbiddenValue : forbiddenValues) { if (value.equals(forbiddenValue)) { return false; } } return true; }
Source:
<code>private void triggerWindowProcess(long upperLimit, List<RowData> inputs) throws Exception { long lowerLimit = upperLimit - lowerBoundary; List<Long> outdatedTs = new LinkedList<>(); if (inputs != null) { for (Map.Entry<Long, List<RowData>> entry : inputState.entries()) { long dataTs = entry.getKey(); if (dataTs >= lowerLimit) { if (dataTs <= upperLimit) { List<RowData> dataList = entry.getValue(); if (dataList != null) { for (RowData data : dataList) { arrowSerializer.write(getFunctionInput(data)); currentBatchCount++; } } } } else { <START> outdatedTs.add(dataTs); <END> } } for (Long dateTs : outdatedTs) { inputState.remove(dateTs); } inputData.add(inputs); if (currentBatchCount > 0) { arrowSerializer.finishCurrentBatch(); pythonFunctionRunner.process(baos.toByteArray()); elementCount += currentBatchCount; checkInvokeFinishBundleByCount(); currentBatchCount = 0; baos.reset(); } } }</code><technical_language>clear state directly, is need store a list</technical_language>

Target:
private void triggerWindowProcess(long upperLimit, List<RowData> inputs) throws Exception { long lowerLimit = upperLimit - lowerBoundary; if (inputs != null) { Iterator<Map.Entry<Long, List<RowData>>> iter = inputState.iterator(); while (iter.hasNext()) { Map.Entry<Long, List<RowData>> entry = iter.next(); long dataTs = entry.getKey(); if (dataTs >= lowerLimit) { if (dataTs <= upperLimit) { List<RowData> dataList = entry.getValue(); for (RowData data : dataList) { arrowSerializer.write(getFunctionInput(data)); currentBatchCount++; } } } else { iter.remove(); } } inputData.add(inputs); invokeCurrentBatch(); } }
Source:
<code>public void startProcessInstanceCmdExecutorTest() { StartProcessInstanceCmd startProcessInstanceCmd = new StartProcessInstanceCmd("x"); ProcessInstance fakeProcessInstance = new ProcessInstance("fakeId", "name", "description", "processDefinitionId", "initiator", new Date(), "businessKey", "status"); given(processEngine.startProcess(any())).willReturn(fakeProcessInstance); <START> assertThat(startProcessInstanceCmdExecutor).isNotNull(); <END> assertThat(startProcessInstanceCmdExecutor.getHandledType()).isEqualTo(StartProcessInstanceCmd.class); startProcessInstanceCmdExecutor.execute(startProcessInstanceCmd); verify(processEngine).startProcess(startProcessInstanceCmd); verify(commandResults).send(ArgumentMatchers.<Message<StartProcessInstanceResults>>any()); }</code><technical_language>removed</technical_language>

Target:
public void startProcessInstanceCmdExecutorTest() { StartProcessInstanceCmd startProcessInstanceCmd = new StartProcessInstanceCmd("x"); ProcessInstance fakeProcessInstance = new ProcessInstance("fakeId", "name", "description", "processDefinitionId", "initiator", new Date(), "businessKey", "status"); given(processEngine.startProcess(any())).willReturn(fakeProcessInstance); assertThat(startProcessInstanceCmdExecutor.getHandledType()).isEqualTo(StartProcessInstanceCmd.class); startProcessInstanceCmdExecutor.execute(startProcessInstanceCmd); verify(processEngine).startProcess(startProcessInstanceCmd); verify(commandResults).send(ArgumentMatchers.<Message<StartProcessInstanceResults>>any()); }
Source:
<code>public static String methodWithTwoDuplicateStringLiterals() { <START> return String.format("%s%s", "test", "test"); <END> }</code><technical_language>@dskalenko - test confirming suppression is enough suppress - previously needed</technical_language>

Target:
public String methodWithTwoDuplicateStringLiterals() { return String.format("%s%s%s", "test", "test", this.toString()); }
Source:
<code>protected boolean validate() { Guid imageId = getParameters().getImageId(); <START> if (!Guid.isNullOrEmpty(imageId)) { return validateImageTransfer(imageId); } else { if (getParameters().getTransferType() != TransferType.Download) { return validateCreateImage(); } else { return failValidation(EngineMessage.ACTION_TYPE_FAILED_IMAGE_NOT_SPECIFIED_FOR_DOWNLOAD); } } <END> }</code><technical_language>Maybe: if (!Guid.isNullOrEmpty(imageId)) { return validateImageTransfer(imageId); } else if (getParameters().getTransferType() != TransferType.Download) { return validateCreateImage(); } return failValidation(EngineMessage.ACTION_TYPE_FAILED_IMAGE_NOT_SPECIFIED_FOR_DOWNLOAD);</technical_language>

Target:
protected boolean validate() { Guid imageId = getParameters().getImageId(); if (!Guid.isNullOrEmpty(imageId)) { return validateImageTransfer(imageId); } else if (getParameters().getTransferType() == TransferType.Download) { return failValidation(EngineMessage.ACTION_TYPE_FAILED_IMAGE_NOT_SPECIFIED_FOR_DOWNLOAD); } return validateCreateImage(); }
Source:
<code>public void run() { try { <START> cloudFile.upload(TestDataCreationHelper.createRandomInputStream(options.getSize()), <END> options.getSize()); } catch (StorageException | URISyntaxException | IOException e) { throw new RuntimeException(e); } }</code><technical_language>Cache input stream</technical_language>

Target:
public void run() { try { inputStream.reset(); cloudFile.upload(inputStream, options.getSize()); } catch (StorageException | URISyntaxException | IOException e) { throw new RuntimeException(e); } }
Source:
<code>public String getStoreClientConfigString(List<String> storeNames, String coordinatorUrl) { String result = null; try { <START> RestRequestBuilder requestBuilder = new RestRequestBuilder(new URI(coordinatorUrl <END> + URL_SEPARATOR + STORE_CLIENT_CONFIG_OPS + URL_SEPARATOR + Joiner.on(",") .join(storeNames))); String timeoutStr = Long.toString(this.config.getTimeoutConfig() .getOperationTimeout(VoldemortOpCode.GET_OP_CODE)); requestBuilder.setMethod(GET); requestBuilder.setHeader(RestMessageHeaders.X_VOLD_REQUEST_TIMEOUT_MS, timeoutStr); requestBuilder.setHeader(RestMessageHeaders.X_VOLD_REQUEST_ORIGIN_TIME_MS, String.valueOf(System.currentTimeMillis())); if(this.routingTypeCode != null) { requestBuilder.setHeader(RestMessageHeaders.X_VOLD_ROUTING_TYPE_CODE, this.routingTypeCode); } if(this.zoneId != INVALID_ZONE_ID) { requestBuilder.setHeader(RestMessageHeaders.X_VOLD_ZONE_ID, String.valueOf(this.zoneId)); } RestRequest request = requestBuilder.build(); Future<RestResponse> future = client.restRequest(request); RestResponse response = future.get(); ByteString entity = response.getEntity(); result = entity.asString("UTF-8"); } catch(ExecutionException e) { if(e.getCause() instanceof RestException) { RestException exception = (RestException) e.getCause(); if(logger.isDebugEnabled()) { logger.debug("REST EXCEPTION STATUS : " + exception.getResponse().getStatus()); } } else { throw new VoldemortException("Unknown HTTP request execution exception: " + e.getMessage(), e); } } catch(InterruptedException e) { if(logger.isDebugEnabled()) { logger.debug("Operation interrupted : " + e.getMessage(), e); } throw new VoldemortException("Operation interrupted exception: " + e.getMessage(), e); } catch(URISyntaxException e) { throw new VoldemortException("Illegal HTTP URL" + e.getMessage(), e); } return result; }</code><technical_language>StringBuilder build String for URI instead of multiple string concat</technical_language>

Target:
public String getStoreClientConfigString(List<String> storeNames, String coordinatorUrl) { try { StringBuilder URIStringBuilder = new StringBuilder().append(coordinatorUrl) .append(URL_SEPARATOR) .append(STORE_CLIENT_CONFIG_OPS) .append(URL_SEPARATOR) .append(Joiner.on(",") .join(storeNames)); RestRequestBuilder requestBuilder = new RestRequestBuilder(new URI(URIStringBuilder.toString())); String timeoutStr = Long.toString(this.config.getTimeoutConfig() .getOperationTimeout(VoldemortOpCode.GET_OP_CODE)); requestBuilder.setMethod(requestType.GET.toString()); requestBuilder.setHeader(RestMessageHeaders.X_VOLD_REQUEST_TIMEOUT_MS, timeoutStr); requestBuilder = setCommonRequestHeader(requestBuilder); RestRequest request = requestBuilder.build(); Future<RestResponse> future = client.restRequest(request); RestResponse response = future.get(); ByteString entity = response.getEntity(); return entity.asString("UTF-8"); } catch(Exception e) { if(e.getCause() instanceof RestException) { return ((RestException) e.getCause()).getResponse().getEntity().asString("UTF-8"); } handleRequestAndResponseException(e); } return null; }
Source:
<code>private List<VendorSupplierDiversity> buildVendorDiversitiesFromPmwFormDropDownLists(PaymentWorksVendor pmwVendor, Map<String, SupplierDiversity> paymentWorksToKfsDiversityMap, List<VendorSupplierDiversity> kfsVendorSupplierDiversities) { if (paymentWorksFormModeService.shouldUseLegacyFormProcessingMode()) { VendorSupplierDiversity minority = createVendorSupplierDiversityForDropDownData(pmwVendor.getMinorityStatus(), pmwVendor.getMbeCertificationExpirationDate(), paymentWorksToKfsDiversityMap); if (ObjectUtils.isNotNull(minority)) { kfsVendorSupplierDiversities.add(minority); } VendorSupplierDiversity womanOwned = createVendorSupplierDiversityForDropDownData(pmwVendor.getWomanOwned(), pmwVendor.getWbeCertificationExpirationDate(), paymentWorksToKfsDiversityMap); if (ObjectUtils.isNotNull(womanOwned)) { kfsVendorSupplierDiversities.add(womanOwned); } VendorSupplierDiversity veteran = createVendorSupplierDiversityForDropDownData(pmwVendor.getDisabledVeteran(), pmwVendor.getVeteranCertificationExpirationDate(), paymentWorksToKfsDiversityMap); if (ObjectUtils.isNotNull(veteran)) { kfsVendorSupplierDiversities.add(veteran); } } else if (paymentWorksFormModeService.shouldUseForeignFormProcessingMode()) { <START> LOG.info("buildVendorDiversitiesFromPmwFormDropDownLists, " + PaymentWorksConstants.FOREIGN_FORM_PROCESSING_NOT_IMPLEMENTED_LOG_MESSAGE); <END> } return kfsVendorSupplierDiversities; }</code><technical_language>sense empty stub method for processing in case of foreign form mode</technical_language>

Target:
private List<VendorSupplierDiversity> buildVendorDiversitiesFromPmwFormDropDownLists(PaymentWorksVendor pmwVendor, Map<String, SupplierDiversity> paymentWorksToKfsDiversityMap, List<VendorSupplierDiversity> kfsVendorSupplierDiversities) { VendorSupplierDiversity minority = createVendorSupplierDiversityForDropDownData(pmwVendor.getMinorityStatus(), pmwVendor.getMbeCertificationExpirationDate(), paymentWorksToKfsDiversityMap); if (ObjectUtils.isNotNull(minority)) { kfsVendorSupplierDiversities.add(minority); } VendorSupplierDiversity womanOwned = createVendorSupplierDiversityForDropDownData(pmwVendor.getWomanOwned(), pmwVendor.getWbeCertificationExpirationDate(), paymentWorksToKfsDiversityMap); if (ObjectUtils.isNotNull(womanOwned)) { kfsVendorSupplierDiversities.add(womanOwned); } VendorSupplierDiversity veteran = createVendorSupplierDiversityForDropDownData(pmwVendor.getDisabledVeteran(), pmwVendor.getVeteranCertificationExpirationDate(), paymentWorksToKfsDiversityMap); if (ObjectUtils.isNotNull(veteran)) { kfsVendorSupplierDiversities.add(veteran); } return kfsVendorSupplierDiversities; }
Source:
<code>public List<DMNIncludeModel> loadModels(final WorkspaceProject workspaceProject) { return getPaths(workspaceProject) .stream() .map(includeModelFactory::create) <START> .filter(Optional::isPresent) <END> .map(Optional::get) .collect(Collectors.toList()); }</code><technical_language>This filter lead factory ask why/where exception thrown! strange a factory return a concrete object</technical_language>

Target:
public List<DMNIncludeModel> loadModels(final WorkspaceProject workspaceProject) { return getPaths(workspaceProject) .stream() .map(getPathDMNIncludeModelFunction()) .filter(Objects::nonNull) .collect(Collectors.toList()); }
Source:
<code>public byte[] getBytesUnsafe() { <START> return getBytes(); <END> }</code><technical_language>If buffer reused, is safe cache a copy of bytes time unsafe is called copying time</technical_language>

Target:
public byte[] getBytesUnsafe() { return cachedBytes != null ? cachedBytes : getBytes(); }
Source:
<code>public void onCreate() { Log.d(TAG, "Service started"); <START> newEpisodesNotification = new NewEpisodesNotification(getApplicationContext()); <END> isRunning = true; handler = new Handler(Looper.getMainLooper()); notificationManager = new DownloadServiceNotification(this); IntentFilter cancelDownloadReceiverFilter = new IntentFilter(); cancelDownloadReceiverFilter.addAction(ACTION_CANCEL_ALL_DOWNLOADS); cancelDownloadReceiverFilter.addAction(ACTION_CANCEL_DOWNLOAD); registerReceiver(cancelDownloadReceiver, cancelDownloadReceiverFilter); downloadCompletionThread.start(); Notification notification = notificationManager.updateNotifications( requester.getNumberOfDownloads(), downloads); startForeground(R.id.notification_downloading, notification); }</code><technical_language>for forth. I noticed a problem this method. This executes database operations main thread, lead problems a big number of feeds. moving notification handling handleSuccessfulDownload? is executed in background. Also, FeedSyncTask called needs load feed anyway. task get another property shows if a new item</technical_language>

Target:
public void onCreate() { Log.d(TAG, "Service started"); isRunning = true; handler = new Handler(Looper.getMainLooper()); notificationManager = new DownloadServiceNotification(this); IntentFilter cancelDownloadReceiverFilter = new IntentFilter(); cancelDownloadReceiverFilter.addAction(ACTION_CANCEL_ALL_DOWNLOADS); cancelDownloadReceiverFilter.addAction(ACTION_CANCEL_DOWNLOAD); registerReceiver(cancelDownloadReceiver, cancelDownloadReceiverFilter); downloadCompletionThread.start(); Notification notification = notificationManager.updateNotifications( requester.getNumberOfDownloads(), downloads); startForeground(R.id.notification_downloading, notification); }
Source:
<code>public ByteBuf getCommandLineBytes() { final int dataItemsSize = dataItems == null ? macro.name().length() : dataItems.length(); final String changedSinceStr = changedSince == null ? "" : changedSince.toString(); final int vanishedSize = isVanished ? SP_VANISHED.length() : 0; <START> final int len = ImapClientConstants.PAD_LEN + changedSinceStr.length() + dataItemsSize + msgNumbers.length() + vanishedSize; <END> final ByteBuf sb = Unpooled.buffer(len); sb.writeBytes(isUid ? UID_FETCH_SP_B : FETCH_SP_B); sb.writeBytes(msgNumbers.getBytes(StandardCharsets.US_ASCII)); sb.writeByte(ImapClientConstants.SPACE); if (dataItems != null) { sb.writeByte(ImapClientConstants.L_PAREN); sb.writeBytes(dataItems.getBytes(StandardCharsets.US_ASCII)); sb.writeByte(ImapClientConstants.R_PAREN); } else { sb.writeBytes(macro.name().getBytes(StandardCharsets.US_ASCII)); } if (changedSince != null) { sb.writeByte(ImapClientConstants.SPACE); sb.writeByte(ImapClientConstants.L_PAREN); sb.writeBytes(CHANGEDSINCE_SP_B); sb.writeBytes(changedSinceStr.getBytes(StandardCharsets.US_ASCII)); if (isVanished) { sb.writeBytes(SP_VANISHED_B); } sb.writeByte(ImapClientConstants.R_PAREN); } sb.writeBytes(CRLF_B); return sb; }</code><technical_language>vanished size accounted for if changed is null</technical_language>

Target:
public ByteBuf getCommandLineBytes() { final int dataItemsSize = dataItems == null ? macro.name().length() : dataItems.length(); final String changedSinceStr = changedSince == null ? "" : changedSince.toString(); final int vanishedSize = isVanished ? SP_VANISHED.length() : 0; final int len = ImapClientConstants.PAD_LEN + dataItemsSize + msgNumbers.length() + vanishedSize; final ByteBuf sb = Unpooled.buffer(len); sb.writeBytes(isUid ? UID_FETCH_SP_B : FETCH_SP_B); sb.writeBytes(msgNumbers.getBytes(StandardCharsets.US_ASCII)); sb.writeByte(ImapClientConstants.SPACE); if (dataItems != null) { sb.writeByte(ImapClientConstants.L_PAREN); sb.writeBytes(dataItems.getBytes(StandardCharsets.US_ASCII)); sb.writeByte(ImapClientConstants.R_PAREN); } else { sb.writeBytes(macro.name().getBytes(StandardCharsets.US_ASCII)); } if (changedSince != null) { sb.writeByte(ImapClientConstants.SPACE); sb.writeByte(ImapClientConstants.L_PAREN); sb.writeBytes(CHANGEDSINCE_SP_B); sb.writeBytes(changedSinceStr.getBytes(StandardCharsets.US_ASCII)); if (isVanished) { sb.writeBytes(SP_VANISHED_B); } sb.writeByte(ImapClientConstants.R_PAREN); } sb.writeBytes(CRLF_B); return sb; }
Source:
<code>public void testGenerateTaskManagerResourceIDWithRemoteRpcService() throws Exception { final Configuration configuration = createConfiguration(); final String rpcAddress = "flink"; final int rpcPort = 9090; final String taskManagerResourceID = TaskManagerRunner.getTaskManagerResourceID(configuration, rpcAddress, rpcPort); assertThat(taskManagerResourceID, notNullValue()); <START> assertThat(taskManagerResourceID.substring(0, taskManagerResourceID.length() - 7), <END> equalTo(rpcAddress + ":" + rpcPort)); }</code><technical_language>containsString matcher</technical_language>

Target:
public void testGenerateTaskManagerResourceIDWithRemoteRpcService() throws Exception { final Configuration configuration = createConfiguration(); final String rpcAddress = "flink"; final int rpcPort = 9090; final String taskManagerResourceID = TaskManagerRunner.getTaskManagerResourceID(configuration, rpcAddress, rpcPort); assertThat(taskManagerResourceID, notNullValue()); assertThat(taskManagerResourceID, containsString(rpcAddress + ":" + rpcPort)); }
Source:
<code>public @NonNull TmfModelResponse<TmfTreeModel<TimeGraphEntryModel>> fetchTree(Map<String, Object> fetchParameters, @Nullable IProgressMonitor monitor) { fetchTreeIsComplete = true; long rootId = ENTRY_ID.getAndIncrement(); TraceEntryModel traceEntry = new TraceEntryModel(getTrace(), rootId); entryList = new ArrayList<>(); entryList.add(traceEntry); for (ITmfAnalysisModuleWithStateSystems module : fmodules) { synchronized (fStartedAnalysis) { if (monitor != null) { if (monitor.isCanceled()) { return new TmfModelResponse<>(null, Status.CANCELLED, CommonStatusMessage.TASK_CANCELLED); } } } waitForInitialization(getTrace(), module); long id = ENTRY_ID.getAndIncrement(); entryList.add(new ModuleEntryModel(id, rootId, module, traceEntry.getStartTime())); for (ITmfStateSystem ss : module.getStateSystems()) { addStateSystem(ss, id); } } Status status = fetchTreeIsComplete ? Status.COMPLETED : Status.RUNNING; String msg = fetchTreeIsComplete ? CommonStatusMessage.COMPLETED : CommonStatusMessage.RUNNING; return new TmfModelResponse<>(new <START> TmfTreeModel<>(Collections.emptyList(), entryList), <END> status, msg); }</code><technical_language>new API, is for data providers column headers, parameter pass TmfTreeModel constructor is list of column headers. is yet, eventually, add column headers for future</technical_language>

Target:
public @NonNull TmfModelResponse<TmfTreeModel<TimeGraphEntryModel>> fetchTree(Map<String, Object> fetchParameters, @Nullable IProgressMonitor monitor) { fetchTreeIsComplete = true; long rootId = ENTRY_ID.getAndIncrement(); ITmfTrace trace = getTrace(); TraceEntryModel.Builder traceEntry = new TraceEntryModel.Builder(rootId, trace.getName(), trace.getStartTime().toNanos(), trace); entryList = new ArrayList<>(); moduleEntryModelList = new ArrayList<>(); long traceEnd = traceEntry.getStartTime(); for (ITmfAnalysisModuleWithStateSystems module : fModules) { synchronized (fStartedAnalysis) { if (monitor != null) { if (monitor.isCanceled()) { return new TmfModelResponse<>(null, Status.CANCELLED, CommonStatusMessage.TASK_CANCELLED); } } } waitForInitialization(getTrace(), module); long id = ENTRY_ID.getAndIncrement(); ModuleEntryModel.Builder moduleEntry = new ModuleEntryModel.Builder(id, module.getName(), traceEntry.getStartTime(), module); long moduleEnd = traceEntry.getStartTime(); for (ITmfStateSystem ss : module.getStateSystems()) { addStateSystem(ss, id); moduleEnd = Long.max(moduleEnd, ss.getCurrentEndTime()); } moduleEntry.setEndTime(moduleEnd); traceEnd = Long.max(traceEnd, moduleEnd); ModuleEntryModel finalModuleEntry = moduleEntry.build(rootId); entryList.add(finalModuleEntry); moduleEntryModelList.add(finalModuleEntry); } traceEntry.setEndTime(traceEnd); TraceEntryModel finalTraceEntry = traceEntry.build(-1); entryList.add(finalTraceEntry); Collections.reverse(entryList); Status status = fetchTreeIsComplete ? Status.COMPLETED : Status.RUNNING; String msg = fetchTreeIsComplete ? CommonStatusMessage.COMPLETED : CommonStatusMessage.RUNNING; return new TmfModelResponse<>(new TmfTreeModel<>(Collections.emptyList(), entryList), status, msg); }
Source:
<code>protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == ACTIVITY_RESULT_SELECT_CELLTOWERS) { if (resultCode == RESULT_OK) { log.debug("Chosen file: " + data.getDataString()); try { String type = getContentResolver().getType(data.getData()); boolean isGzip = type != null && type.equals("application/octet-stream") && data.getDataString().endsWith(".gz"); <START> InputStream importFile = getContentResolver().openInputStream(data.getData()); <END> importCellTowersData(importFile, isGzip); } catch (FileNotFoundException e) { e.printStackTrace(); log.error("Cannot open file " + data.getDataString(), e); Helpers.msgShort(this, getString(R.string.error_importing_celltowers_data)); } } } }</code><technical_language>Im if this is right place open InputStream check type. prefer pass data.getData() instead of open InputStream</technical_language>

Target:
protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == ACTIVITY_RESULT_SELECT_CELLTOWERS) { if (resultCode == RESULT_OK) { log.debug("Chosen file: " + data.getDataString()); importCellTowersData(data.getData()); } } }