auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>@Override protected void finalize() throws Throwable { try { <START> close(); <END> if (mCookie != null) { throw new AssertionError("Failed to close dex file in finalizer."); } mCookie = null; } finally { super.finalize(); } }</code><technical_language>This scares a theoretical long wait other processes handling cookie</technical_language>

Target:
@Override protected void finalize() throws Throwable { try { close(); synchronized (this) { if (mCookie != null) { throw new AssertionError("Failed to close dex file in finalizer."); } mCookie = null; } } finally { super.finalize(); } }
Source:
<code>private int getBlockFromCompletedQueue(final AbfsInputStream stream, final long position, final int length, final byte[] buffer) throws IOException { ReadBuffer buf = getBufferFromCompletedQueue(stream, position); if (buf == null) { return 0; } if (buf.getStatus() == ReadBufferStatus.READ_FAILED) { <START> if ((currentTimeMillis() - (buf.getTimeStamp()) < THRESHOLD_AGE_MILLISECONDS)) { <END> throw buf.getErrException(); } else { return 0; } } if ((buf.getStatus() != ReadBufferStatus.AVAILABLE) || (position >= buf.getOffset() + buf.getLength())) { return 0; } int cursor = (int) (position - buf.getOffset()); int availableLengthInBuffer = buf.getLength() - cursor; int lengthToCopy = Math.min(length, availableLengthInBuffer); System.arraycopy(buf.getBuffer(), cursor, buffer, 0, lengthToCopy); if (cursor == 0) { buf.setFirstByteConsumed(true); } if (cursor + lengthToCopy == buf.getLength()) { buf.setLastByteConsumed(true); } buf.setAnyByteConsumed(true); return lengthToCopy; }</code><technical_language>parenthesis confusing</technical_language>

Target:
private int getBlockFromCompletedQueue(final AbfsInputStream stream, final long position, final int length, final byte[] buffer) throws IOException { ReadBuffer buf = getBufferFromCompletedQueue(stream, position); if (buf == null) { return 0; } if (buf.getStatus() == ReadBufferStatus.READ_FAILED) { if ((currentTimeMillis() - (buf.getTimeStamp()) < thresholdAgeMilliseconds)) { throw buf.getErrException(); } else { return 0; } } if ((buf.getStatus() != ReadBufferStatus.AVAILABLE) || (position >= buf.getOffset() + buf.getLength())) { return 0; } int cursor = (int) (position - buf.getOffset()); int availableLengthInBuffer = buf.getLength() - cursor; int lengthToCopy = Math.min(length, availableLengthInBuffer); System.arraycopy(buf.getBuffer(), cursor, buffer, 0, lengthToCopy); if (cursor == 0) { buf.setFirstByteConsumed(true); } if (cursor + lengthToCopy == buf.getLength()) { buf.setLastByteConsumed(true); } buf.setAnyByteConsumed(true); return lengthToCopy; }
Source:
<code>public Object execute(ExecutionEvent event) throws ExecutionException { ISelection selection = HandlerUtil.getCurrentSelection(event); if (!(selection instanceof IStructuredSelection)) { return null; } final Iterator<Object> iterator = ((IStructuredSelection) selection).iterator(); if (!selection.isEmpty()) { while (iterator.hasNext()) { Object element = iterator.next(); if (element instanceof TmfTraceElement) { TmfTraceElement trace = (TmfTraceElement) element; refreshTrace(trace); <START> } else if (element instanceof TmfTraceFolder) { <END> TmfTraceFolder tmfTraceFolder = (TmfTraceFolder) element; for (TmfTraceElement e : tmfTraceFolder.getTraces()) { refreshTrace(e); } } else if (element instanceof ITmfEvent) { ITmfEvent iTmfEvent = (ITmfEvent) element; refreshTrace(iTmfEvent.getTrace()); } } } else { IEditorPart activeEditor = HandlerUtil.getActiveEditorChecked(event); if (activeEditor instanceof ITmfTraceEditor) { ITmfTrace trace = ((ITmfTraceEditor) activeEditor).getTrace(); refreshTrace(trace); } } return null; }</code><technical_language>This is supported handler activation rule in plugin.xml..</technical_language>

Target:
public Object execute(ExecutionEvent event) throws ExecutionException { ISelection selection = HandlerUtil.getCurrentSelection(event); if (!(selection instanceof IStructuredSelection)) { return null; } final Iterator<Object> iterator = ((IStructuredSelection) selection).iterator(); boolean refreshed = false; while (iterator.hasNext()) { Object element = iterator.next(); if (element instanceof TmfTraceElement) { TmfTraceElement trace = (TmfTraceElement) element; refreshTrace(trace); refreshed = true; } } if (refreshed) { return null; } IEditorPart activeEditor = HandlerUtil.getActiveEditorChecked(event); if (activeEditor instanceof ITmfTraceEditor) { ITmfTrace trace = ((ITmfTraceEditor) activeEditor).getTrace(); refreshTrace(trace); } return null; }
Source:
<code>public Stream<P> streamByPage() { <START> return pagedFluxBase.byPage().toStream(1); <END> }</code><technical_language>nit: define a constant instead</technical_language>

Target:
public Stream<P> streamByPage() { return pagedFluxBase.byPage().toStream(DEFAULT_BATCH_SIZE); }
Source:
<code>protected void setupEventRouting(EventRouting<String> routing) { super.setupEventRouting(routing); <START> routing.route(NumberAdded.class, (EventRoute<String, NumberAdded>) (message, context) -> <END> ImmutableSet.of(message.getCalculatorId())); }</code><technical_language>I suggest: java routing.route(NumberAdded.class, (message, context) -> withId(message.getCalculatorId()));</technical_language>

Target:
protected void setupEventRouting(EventRouting<String> routing) { super.setupEventRouting(routing); routing.route(NumberAdded.class, (message, context) -> withId(message.getCalculatorId())); }
Source:
<code>public void operationComplete(final ChannelFuture future) { final ImapCommandEntry entry = requestsQueue.peek(); if (entry != null) { <START> entry.setState(ImapCommandEntry.CommandState.SENT); <END> } if (!future.isSuccess()) { handleChannelException(new ImapAsyncClientException(FailureType.WRITE_TO_SERVER_FAILED, future.cause())); } }</code><technical_language>this get called for continuation</technical_language>

Target:
public void operationComplete(final ChannelFuture future) { final ImapCommandEntry entry = requestsQueue.peek(); if (entry != null) { entry.setState(ImapCommandEntry.CommandState.REQUEST_SENT); } if (!future.isSuccess()) { handleChannelException(new ImapAsyncClientException(FailureType.WRITE_TO_SERVER_FAILED, future.cause())); } }
Source:
<code><START> public synchronized boolean isRegistered() { <END> return boundedContextName != null; }</code><technical_language>overkill methods synchronized. discuss a per-case basis</technical_language>

Target:
public boolean isRegistered() { return boundedContextName != null; }
Source:
<code>public static void getThreadsFromLabel(final String label, final OnThreadsReady listener){ new AsyncTask<Void, Void, List<MailThread>>() { @Override protected List<MailThread> doInBackground(Void... params) { List<MailThread> threads = getAllThreads(); List<MailThread> res = new ArrayList<>(); for (MailThread thread : threads) { <START> String[] labels = thread.labels.split(";"); <END> if (thread.getLastMailFromLabel(label.toUpperCase())!=null) { res.add(thread); } } return res; } @Override protected void onPostExecute(List<MailThread> mailThreads) { super.onPostExecute(mailThreads); listener.threads(mailThreads); } }.execute(); }</code><technical_language>This variable is anymore</technical_language>

Target:
public static void getThreadsFromLabel(final String label, final OnThreadsReady listener){ new AsyncTask<Void, Void, List<MailThread>>() { @Override protected List<MailThread> doInBackground(Void... params) { List<MailThread> threads = getAllThreads(); List<MailThread> res = new ArrayList<>(); for (MailThread thread : threads) { if (thread.getLastMailFromLabel(label.toUpperCase())!=null) { res.add(thread); } } return res; } @Override protected void onPostExecute(List<MailThread> mailThreads) { super.onPostExecute(mailThreads); listener.threads(mailThreads); } }.execute(); }
Source:
<code>public void afterFailure(Throwable t) { <START> processors.forEach(sp -> { <END> if (sp.getLeft().equals(processor)) { if (sp.getRight() != null) { sp.getRight().close(); } processors.remove(sp); } }); if (failure.compareAndSet(null, t)) { processors.forEach(sp -> { sp.getLeft().stop(); if (sp.getRight() != null) { sp.getRight().close(); } }); } handleProcessorShutdown(t); }</code><technical_language>this current processor stopped? Do need stop metadata store in afterStop()</technical_language>

Target:
public void afterFailure(Throwable t) { closeAndRemoveProcessor(); if (failure.compareAndSet(null, t)) { processors.forEach(sp -> { sp.getLeft().stop(); if (sp.getRight() != null) { sp.getRight().close(); } }); } handleProcessorShutdown(t); }
Source:
<code>public void testBug243422() { IMetadataRepositoryManager repoMan = getAgent().getService(IMetadataRepositoryManager.class); assertNotNull(repoMan); File site = getTestData("Update site", "/testData/updatesite/UpdateSite243422/"); IMetadataRepository metadataRepo = null; try { metadataRepo = repoMan.loadRepository(site.toURI(), null); } catch (ProvisionException e) { fail("Can't load repository UpdateSite243422"); } IQuery<IInstallableUnit> query = QueryUtil.createIUQuery("org.eclipse.jdt.astview.feature.feature.group", Version.create("1.0.1")); IQueryResult<IInstallableUnit> result = metadataRepo.query(query, null); assertEquals("1.0", 1, queryResultSize(result)); IInstallableUnit featureIU = result.iterator().next(); Collection<IRequirement> required = featureIU.getRequirements(); for (IRequirement <START> iRequirement : <END> required) { IRequiredCapability req = (IRequiredCapability) iRequirement; if (req.getName().equals("org.eclipse.ui.ide")) { assertEquals("2.0", VersionRange.emptyRange, req.getRange()); } } }</code><technical_language>rename requirement</technical_language>

Target:
public void testBug243422() { IMetadataRepositoryManager repoMan = getAgent().getService(IMetadataRepositoryManager.class); assertNotNull(repoMan); File site = getTestData("Update site", "/testData/updatesite/UpdateSite243422/"); IMetadataRepository metadataRepo = null; try { metadataRepo = repoMan.loadRepository(site.toURI(), null); } catch (ProvisionException e) { fail("Can't load repository UpdateSite243422"); } IQuery<IInstallableUnit> query = QueryUtil.createIUQuery("org.eclipse.jdt.astview.feature.feature.group", Version.create("1.0.1")); IQueryResult<IInstallableUnit> result = metadataRepo.query(query, null); assertEquals("1.0", 1, queryResultSize(result)); IInstallableUnit featureIU = result.iterator().next(); for (IRequirement requirement : featureIU.getRequirements()) { IRequiredCapability req = (IRequiredCapability) requirement; if (req.getName().equals("org.eclipse.ui.ide")) { assertEquals("2.0", VersionRange.emptyRange, req.getRange()); } } }
Source:
<code><START> private void addMandatoryGoals(User userEntity) <END> { for (ActivityCategoryDTO activityCategory : activityCategoryService.getAllActivityCategories()) { if (activityCategory.isMandatoryNoGo()) { userEntity.getAnonymized().addGoal( BudgetGoal.createNoGoInstance(ActivityCategory.getRepository().findOne(activityCategory.getID()))); } } }</code><technical_language>A simpler write this be: private void addMandatoryGoals(User userEntity) { activityCategoryService.getAllActivityCategories().stream().filter(c -> c.isMandatoryNoGo()) .forEach(c -> addGoal(userEntity, c)); } private void addGoal(User userEntity, ActivityCategoryDTO category) { userEntity.getAnonymized() .addGoal(BudgetGoal.createNoGoInstance(ActivityCategory.getRepository().findOne(category.getID()))); }</technical_language>

Target:
private void addMandatoryGoals(User userEntity) { activityCategoryService.getAllActivityCategories().stream().filter(c -> c.isMandatoryNoGo()) .forEach(c -> addGoal(userEntity, c)); }
Source:
<code>static CaseMetadata getCaseMetadataFromCaseDirectoryPath(Path caseDirectoryPath) throws CaseMetadata.CaseMetadataException { CaseMetadata caseMetadata = null; File directory = new File(caseDirectoryPath.toString()); if (directory.isDirectory()) { String fileNamePrefix = directory.getName(); if (TimeStampUtils.endsWithTimeStamp(fileNamePrefix)) { fileNamePrefix = fileNamePrefix.substring(0, fileNamePrefix.length() - TimeStampUtils.getTimeStampLength()); <START> } <END> File file = new File(directory + "/" + fileNamePrefix + CaseMetadata.getFileExtension()); if(file.isFile()) { caseMetadata = new CaseMetadata(Paths.get(file.getAbsolutePath())); } } return caseMetadata; }</code><technical_language>profiled isDirectory call, regular expression pattern matching, string concatenation, File object construction, File.isFile calls if is a time savings? This premature optimization cost of greater code complexity, complexity of code led a NPE bug (See below). simple do file listing. consider inlining this code. If a performance problem, profile consider options time</technical_language>

Target:
private static CaseMetadata getCaseMetadataFromCaseDirectoryPath(Path caseDirectoryPath) throws CaseMetadata.CaseMetadataException, MultiUserCaseException { CaseMetadata caseMetadata = null; File directory = new File(caseDirectoryPath.toString()); if (directory.isDirectory()) { String fileNamePrefix = directory.getName(); if (TimeStampUtils.endsWithTimeStamp(fileNamePrefix)) { fileNamePrefix = fileNamePrefix.substring(0, fileNamePrefix.length() - TimeStampUtils.getTimeStampLength()); } File autFile = null; for (File file : directory.listFiles()) { if (file.getName().toLowerCase().endsWith(CaseMetadata.getFileExtension()) && file.isFile()) { autFile = file; break; } } if(autFile == null || !autFile.isFile()) { throw new MultiUserCaseException(String.format("No case metadata (.aut) file found in the case directory '%s'.", caseDirectoryPath.toString())); } caseMetadata = new CaseMetadata(Paths.get(autFile.getAbsolutePath())); } return caseMetadata; }
Source:
<code>public Attribute fillAttribute(PerunSessionImpl perunSession, User user, AttributeDefinition attribute) throws InternalErrorException, WrongAttributeAssignmentException { Attribute filledAttribute = new Attribute(attribute); if (generatedNamespaces.contains(attribute.getFriendlyNameParameter())) { ModulesUtilsBlImpl.LoginGenerator generator = new ModulesUtilsBlImpl.LoginGenerator(); String login = generator.generateLogin(user, new ModulesUtilsBlImpl.LoginGenerator.LoginGeneratorFunction() { @Override public String generateLogin(String firstName, String lastName) { String login = firstName+ "." + lastName; if (login.length()>20) { login = login.substring(0, 20); } return login; } <START> }); <END> if (login == null) return filledAttribute; int iterator = 0; while (iterator >= 0) { if (iterator > 0) { int iteratorLength = String.valueOf(iterator).length(); if (login.length() + iteratorLength > 20) { login = login.substring(0, login.length()-1); iterator = 0; filledAttribute.setValue(login); } else { filledAttribute.setValue(login + iterator); } } else { filledAttribute.setValue(login); } try { checkAttributeValue(perunSession, user, filledAttribute); return filledAttribute; } catch (WrongAttributeValueException ex) { iterator++; } } return filledAttribute; } else { return filledAttribute; } }</code><technical_language>CEITEC, added logic handle empty names input (since a-Z chars removed input). replaces names fixed string "External customer". want similar "Chineese" input, is ok registration form, fail this module logic</technical_language>

Target:
public Attribute fillAttribute(PerunSessionImpl perunSession, User user, AttributeDefinition attribute) throws InternalErrorException, WrongAttributeAssignmentException { Attribute filledAttribute = new Attribute(attribute); if (generatedNamespaces.contains(attribute.getFriendlyNameParameter())) { ModulesUtilsBlImpl.LoginGenerator generator = new ModulesUtilsBlImpl.LoginGenerator(); String login = generator.generateLogin(user, new ModulesUtilsBlImpl.LoginGenerator.LoginGeneratorFunction() { @Override public String generateLogin(String firstName, String lastName) { if (firstName == null || firstName.isEmpty() || lastName == null || lastName.isEmpty()) { return "eduteams-user"; } String login = firstName+ "." + lastName; if (login.length()>20) { login = login.substring(0, 20); } return login; } }); if (login == null) return filledAttribute; int iterator = 0; while (iterator >= 0) { if (iterator > 0) { int iteratorLength = String.valueOf(iterator).length(); if (login.length() + iteratorLength > 20) { login = login.substring(0, login.length()-1); iterator = 0; filledAttribute.setValue(login); } else { filledAttribute.setValue(login + iterator); } } else { filledAttribute.setValue(login); } try { checkAttributeValue(perunSession, user, filledAttribute); return filledAttribute; } catch (WrongAttributeValueException ex) { iterator++; } } return filledAttribute; } else { return filledAttribute; } }
Source:
<code>public void start() throws InstantiationException { long startupBeginTime = System.currentTimeMillis(); idConverter = idConverterFactory.getIdConverter(); securityService = securityServiceFactory.getSecurityService(); getPeersHandler = new GetPeersHandler(clusterMap, securityService, frontendMetrics); getSignedUrlHandler = new GetSignedUrlHandler(urlSigningService, securityService, idConverter, accountAndContainerInjector, frontendMetrics, clusterMap, clusterName, frontendConfig); postBlobHandler = <START> new PostBlobHandler(securityService, idConverter, idSigningService, router, accountAndContainerInjector, <END> SystemTime.getInstance(), frontendConfig, frontendMetrics); ttlUpdateHandler = new TtlUpdateHandler(router, securityService, idConverter, accountAndContainerInjector, frontendMetrics, clusterMap, clusterName, frontendConfig); getClusterMapSnapshotHandler = new GetClusterMapSnapshotHandler(securityService, frontendMetrics, clusterMap); getAccountsHandler = new GetAccountsHandler(securityService, accountService, frontendMetrics); postAccountsHandler = new PostAccountsHandler(securityService, accountService, frontendConfig, frontendMetrics); isUp = true; logger.info("AmbryBlobStorageService has started"); frontendMetrics.blobStorageServiceStartupTimeInMs.update(System.currentTimeMillis() - startupBeginTime); }</code><technical_language>Unfortunately, I is issue stitchBlob needs fixed in PostBlobHandler. for (String signedChunkId : signedChunkIds) { signedChunkId = RequestPath.parse(signedChunkId, Collections.emptyMap(), frontendConfig.pathPrefixesToRemove, clusterName).getOperationOrBlobId(false);</technical_language>

Target:
public void start() throws InstantiationException { long startupBeginTime = System.currentTimeMillis(); idConverter = idConverterFactory.getIdConverter(); securityService = securityServiceFactory.getSecurityService(); getPeersHandler = new GetPeersHandler(clusterMap, securityService, frontendMetrics); getSignedUrlHandler = new GetSignedUrlHandler(urlSigningService, securityService, idConverter, accountAndContainerInjector, frontendMetrics, clusterMap); postBlobHandler = new PostBlobHandler(securityService, idConverter, idSigningService, router, accountAndContainerInjector, SystemTime.getInstance(), frontendConfig, frontendMetrics, clusterName); ttlUpdateHandler = new TtlUpdateHandler(router, securityService, idConverter, accountAndContainerInjector, frontendMetrics, clusterMap); getClusterMapSnapshotHandler = new GetClusterMapSnapshotHandler(securityService, frontendMetrics, clusterMap); getAccountsHandler = new GetAccountsHandler(securityService, accountService, frontendMetrics); postAccountsHandler = new PostAccountsHandler(securityService, accountService, frontendConfig, frontendMetrics); isUp = true; logger.info("AmbryBlobStorageService has started"); frontendMetrics.blobStorageServiceStartupTimeInMs.update(System.currentTimeMillis() - startupBeginTime); }
Source:
<code>public void processDir(String contentDirectory) throws Exception { log.info("Checking for a META-INF directory in {}", contentDirectory); String metaDir = new File(contentDirectory, "META-INF").getAbsoluteFile().getAbsolutePath(); if(metaDir != null) { if(processors != null) { boolean failed = false; log.info("Running processor[s] for directory", processors.size(), metaDir); for(ConfigProcessor processor : processors) { try { log.info("Running {}", processor.getClass().getName()); processor.processFromDirectory(metaDir); <START> } catch(IOException e) { <END> throw e; } catch(Exception e) { throw e; } } } else { log.warn("No config processors exist in this context"); } } }</code><technical_language>catching exception rethrowing exception . Line: 50 52 needed</technical_language>

Target:
public void processDir(String contentDirectory) throws Exception { log.info("Checking for a META-INF directory in {}", contentDirectory); String metaDir = new File(contentDirectory, "META-INF").getAbsoluteFile().getAbsolutePath(); if(metaDir != null) { if(processors != null) { log.info("Running processor[s] for directory", processors.size(), metaDir); for(ConfigProcessor processor : processors) { log.info("Running {}", processor.getClass().getName()); processor.processFromDirectory(metaDir); } } else { log.warn("No config processors exist in this context"); } } }
Source:
<code><START> private void applyFlatPresentation() { <END> ITmfTrace parentTrace = getTrace(); synchronized (fFlatTraces) { fFlatTraces.add(parentTrace); for (ITmfTrace trace : TmfTraceManager.getTraceSet(parentTrace)) { final ITmfStateSystem ss = TmfStateSystemAnalysisModule.getStateSystem(trace, KernelAnalysisModule.ID); List<@NonNull TimeGraphEntry> entryList = getEntryList(ss); if (entryList != null) { for (TimeGraphEntry traceEntry : entryList) { hierarchicalToFlatTree(traceEntry); } } } } }</code><technical_language>nice, this sense easier understand</technical_language>

Target:
private void applyFlatPresentation() { ITmfTrace parentTrace = getTrace(); synchronized (fFlatTraces) { fFlatTraces.add(parentTrace); List<@NonNull TimeGraphEntry> entryList = getEntryList(parentTrace); if (entryList != null) { for (TimeGraphEntry traceEntry : entryList) { hierarchicalToFlatTree(traceEntry); } } } }
Source:
<code>public void run() { BufferedSource in = null; try { <START> in = Okio.buffer(Okio.source(mClient.getInputStream())); <END> final String request = in.readUtf8Line(); String command; String parameters; int index = request.indexOf(' '); if (index == -1) { command = request; parameters = ""; } else { command = request.substring(0, index); parameters = request.substring(index + 1); } boolean result; if (COMMAND_PROTOCOL_VERSION.equalsIgnoreCase(command)) { result = writeValue(mClient, VALUE_PROTOCOL_VERSION); } else if (COMMAND_SERVER_VERSION.equalsIgnoreCase(command)) { result = writeValue(mClient, VALUE_SERVER_VERSION); } else if (COMMAND_WINDOW_MANAGER_LIST.equalsIgnoreCase(command)) { result = listWindows(mClient); } else if (COMMAND_WINDOW_MANAGER_GET_FOCUS.equalsIgnoreCase(command)) { result = getFocusedWindow(mClient); } else if (COMMAND_WINDOW_MANAGER_AUTOLIST.equalsIgnoreCase(command)) { result = windowManagerAutolistLoop(); } else { result = windowCommand(mClient, command, parameters); } if (!result) { Log.w(LOG_TAG, "An error occurred with the command: " + command); } } catch (IOException e) { Log.w(LOG_TAG, "Connection error: ", e); } finally { if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } if (mClient != null) { try { mClient.close(); } catch (IOException e) { e.printStackTrace(); } } } }</code><technical_language>Similar, need for getInputSteam()</technical_language>

Target:
public void run() { BufferedSource in = null; try { in = Okio.buffer(Okio.source(mClient)); final String request = in.readUtf8Line(); String command; String parameters; int index = request.indexOf(' '); if (index == -1) { command = request; parameters = ""; } else { command = request.substring(0, index); parameters = request.substring(index + 1); } boolean result; if (COMMAND_PROTOCOL_VERSION.equalsIgnoreCase(command)) { result = writeValue(mClient, VALUE_PROTOCOL_VERSION); } else if (COMMAND_SERVER_VERSION.equalsIgnoreCase(command)) { result = writeValue(mClient, VALUE_SERVER_VERSION); } else if (COMMAND_WINDOW_MANAGER_LIST.equalsIgnoreCase(command)) { result = listWindows(mClient); } else if (COMMAND_WINDOW_MANAGER_GET_FOCUS.equalsIgnoreCase(command)) { result = getFocusedWindow(mClient); } else if (COMMAND_WINDOW_MANAGER_AUTOLIST.equalsIgnoreCase(command)) { result = windowManagerAutolistLoop(); } else { result = windowCommand(mClient, command, parameters); } if (!result) { Log.w(LOG_TAG, "An error occurred with the command: " + command); } } catch (IOException e) { Log.w(LOG_TAG, "Connection error: ", e); } finally { if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } if (mClient != null) { try { mClient.close(); } catch (IOException e) { e.printStackTrace(); } } } }
Source:
<code>public void obtainsCreationDate() throws Exception { final User user = NbRule.get(); final Alias alias = user.aliases().iterate().iterator().next(); final Inbox inbox = alias.inbox(); final Bout bout = inbox.bout(inbox.start()); <START> final Attachments attachments = bout.attachments(); <END> final long before = System.currentTimeMillis(); final String name = "attach-name"; attachments.create(name); final Attachment attachment = attachments.get(name); MatcherAssert.assertThat( attachment.date().getTime(), Matchers.greaterThan(before) ); final long after = System.currentTimeMillis(); MatcherAssert.assertThat( attachment.date().getTime(), Matchers.lessThan(after) ); attachments.delete(name); }</code><technical_language>@CarlosGines try inlining</technical_language>

Target:
public void obtainsCreationDate() throws Exception { final Alias alias = NbRule.get().aliases().iterate().iterator().next(); final Inbox inbox = alias.inbox(); final Attachments attachments = inbox.bout(inbox.start()).attachments(); final long before = System.currentTimeMillis(); final String name = "attach-name"; attachments.create(name); final Attachment attachment = attachments.get(name); MatcherAssert.assertThat( attachment.date().getTime(), Matchers.greaterThanOrEqualTo(before) ); final long after = System.currentTimeMillis(); MatcherAssert.assertThat( attachment.date().getTime(), Matchers.lessThanOrEqualTo(after) ); attachments.delete(name); }
Source:
<code>public boolean savePageFor(@NonNull ReadingListPageDiskRow row) { final PageTitle title = makeTitleFrom(row); if (title == null) { return false; } Page page = getApiService(title).pageCombo(title.getPrefixedText(), !WikipediaApp.getInstance().isImageDownloadEnabled()).toPage(title); try { <START> SavedPage savedPage = new SavedPage(page.getTitle()); <END> savedPage.writeToFileSystem(page); final ImageUrlMap imageUrlMap = new ImageUrlMap.Builder(savedPage.getBaseDir()) .extractUrls(page).build(); downloadImages(imageUrlMap); savedPage.writeUrlMap(imageUrlMap.toJSON()); L.i("Page " + title.getDisplayText() + " saved!"); return true; } catch (IOException e) { L.e("Failed to save page " + title.getDisplayText(), e); return false; } }</code><technical_language>wondering if code moved this try block clarify throw IOException can't</technical_language>

Target:
public boolean savePageFor(@NonNull ReadingListPageDiskRow row) { final PageTitle title = makeTitleFrom(row); if (title == null) { return false; } final Page page = getApiService(title).pageCombo(title.getPrefixedText(), !WikipediaApp.getInstance().isImageDownloadEnabled()).toPage(title); final SavedPage savedPage = new SavedPage(page.getTitle()); final ImageUrlMap imageUrlMap = new ImageUrlMap.Builder(savedPage.getBaseDir()) .extractUrls(page).build(); try { savedPage.writeToFileSystem(page); downloadImages(imageUrlMap); savedPage.writeUrlMap(imageUrlMap.toJSON()); L.i("Page " + title.getDisplayText() + " saved!"); return true; } catch (IOException e) { L.e("Failed to save page " + title.getDisplayText(), e); return false; } }
Source:
<code>public IkeSaPayload( boolean isResp, boolean isIkeSa, byte spiSize, long[] spis, SaProposal[] saProposals) { super(IkePayload.PAYLOAD_TYPE_SA, false); if (saProposals.length < 1 || isResp && (saProposals.length > 1) || saProposals.length != spis.length) { throw new IllegalArgumentException("Invalid SA payload."); } isSaResponse = isResp; proposalList = new <START> LinkedList<Proposal>(); <END> int protocolId = isIkeSa ? PROTOCOL_ID_IKE : PROTOCOL_ID_ESP; for (int i = 0; i < saProposals.length; i++) { Proposal proposal = new Proposal( (byte) (i + 1), protocolId, spiSize, spis[i], saProposals[i], false ); proposalList.add(proposal); } }</code><technical_language>ArrayList<> here. length saProposals.length, penalty it. LinkedList is common... ArrayList avoids questions</technical_language>

Target:
public IkeSaPayload( boolean isResp, boolean isIkeSa, byte spiSize, long[] spis, SaProposal[] saProposals) { super(IkePayload.PAYLOAD_TYPE_SA, false); if (saProposals.length < 1 || isResp && (saProposals.length > 1) || saProposals.length != spis.length) { throw new IllegalArgumentException("Invalid SA payload."); } isSaResponse = isResp; proposalList = new ArrayList<Proposal>(saProposals.length); int protocolId = isIkeSa ? PROTOCOL_ID_IKE : PROTOCOL_ID_ESP; for (int i = 0; i < saProposals.length; i++) { Proposal proposal = new Proposal( (byte) (i + 1) , protocolId, spiSize, spis[i], saProposals[i], false ); proposalList.add(proposal); } }
Source:
<code>public String toString(Object value) { if (value == null) { return null; } if (!value.getClass().isArray()) { throw new RuntimeException(Messages.MESSAGES.expectedArray(value.getClass().getName())); } <START> Object[] values = new Object[Array.getLength(value)]; <END> if (values.length == 0) { return ""; } if (rawType.getComponentType().isPrimitive()) { copyPrimitiveArray(values, value); } else { values = (Object[]) value; } return stringify(values); }</code><technical_language>reading answer time I understand point well. clearer understand this class extends ParamConverter<Object> instead of ParamConverter<Object[]>. I forgot this java distiction primitive array object array. Thanks :+1:</technical_language>

Target:
public String toString(Object value) { if (value == null) { return null; } if (!value.getClass().isArray()) { throw new RuntimeException(Messages.MESSAGES.expectedArray(value.getClass().getName())); } Object[] values = new Object[Array.getLength(value)]; if (values.length == 0) { return ""; } if (rawType.getComponentType().isPrimitive()) { copyPrimitiveArray(values, value); } else { values = (Object[]) value; } return stringify(Arrays.asList(values)); }
Source:
<code>public void initialize(URI uri, Configuration configuration) throws IOException { uri = ensureAuthority(uri, configuration); super.initialize(uri, configuration); setConf(configuration); LOG.debug("Initializing AzureBlobFileSystem for {}", uri); this.uri = URI.create(uri.getScheme() + "://" + uri.getAuthority()); this.abfsStore = new AzureBlobFileSystemStore(uri, this.isSecureScheme(), configuration); final AbfsConfiguration abfsConfiguration = abfsStore.getAbfsConfiguration(); this.setWorkingDirectory(this.getHomeDirectory()); if (abfsConfiguration.getCreateRemoteFileSystemDuringInitialization()) { <START> if (this.tryGetFileStatus(new Path("/")) == null) { <END> try { this.createFileSystem(); } catch (AzureBlobFileSystemException ex) { checkException(null, ex, AzureServiceErrorCode.FILE_SYSTEM_ALREADY_EXISTS); } } } if (UserGroupInformation.isSecurityEnabled()) { this.delegationTokenEnabled = abfsConfiguration.isDelegationTokenManagerEnabled(); if (this.delegationTokenEnabled) { LOG.debug("Initializing DelegationTokenManager for {}", uri); this.delegationTokenManager = abfsConfiguration.getDelegationTokenManager(); delegationTokenManager.bind(getUri(), configuration); LOG.debug("Created DelegationTokenManager {}", delegationTokenManager); } } AbfsClientThrottlingIntercept.initializeSingleton(abfsConfiguration.isAutoThrottlingEnabled()); this.authorizer = abfsConfiguration.getAbfsAuthorizer(); }</code><technical_language>replace "/" AbfsHttpConstants.ROOT_PATH</technical_language>

Target:
public void initialize(URI uri, Configuration configuration) throws IOException { uri = ensureAuthority(uri, configuration); super.initialize(uri, configuration); setConf(configuration); LOG.debug("Initializing AzureBlobFileSystem for {}", uri); this.uri = URI.create(uri.getScheme() + "://" + uri.getAuthority()); this.abfsStore = new AzureBlobFileSystemStore(uri, this.isSecureScheme(), configuration); final AbfsConfiguration abfsConfiguration = abfsStore.getAbfsConfiguration(); this.setWorkingDirectory(this.getHomeDirectory()); if (abfsConfiguration.getCreateRemoteFileSystemDuringInitialization()) { if (this.tryGetFileStatus(new Path(AbfsHttpConstants.ROOT_PATH)) == null) { try { this.createFileSystem(); } catch (AzureBlobFileSystemException ex) { checkException(null, ex, AzureServiceErrorCode.FILE_SYSTEM_ALREADY_EXISTS); } } } if (UserGroupInformation.isSecurityEnabled()) { this.delegationTokenEnabled = abfsConfiguration.isDelegationTokenManagerEnabled(); if (this.delegationTokenEnabled) { LOG.debug("Initializing DelegationTokenManager for {}", uri); this.delegationTokenManager = abfsConfiguration.getDelegationTokenManager(); delegationTokenManager.bind(getUri(), configuration); LOG.debug("Created DelegationTokenManager {}", delegationTokenManager); } } AbfsClientThrottlingIntercept.initializeSingleton(abfsConfiguration.isAutoThrottlingEnabled()); this.authorizer = abfsConfiguration.getAbfsAuthorizer(); }
Source:
<code>public String readString(ByteBuffer in) throws IOException { final int length = in.getInt(); <START> return new String(readBytes(in, length), UTF8); <END> }</code><technical_language>StringUtils.fromUtf8 used</technical_language>

Target:
public String readString(ByteBuffer in) throws IOException { final int length = in.getInt(); return StringUtils.fromUtf8(readBytes(in, length)); }
Source:
<code>protected void executeCommand() { if (getDiskImage() != null) { try { VDSReturnValue vdsReturnValue = performImageVdsmOperation(); getReturnValue().getInternalTaskIdList().add( createTask(vdsReturnValue.getCreationInfo(), getParameters().getParentCommand(), VdcObjectType.Storage, getParameters().getStorageDomainId())); } catch (VdcBLLException e) { if (e.getErrorCode() != VdcBllErrors.ImageDoesNotExistInDomainError) { throw e; } <START> log.debugFormat("The image group with id {0} wasn't actually deleted from the storage domain {1} because it didn't exist in it", <END> getDiskImage().getId(), getStorageDomainId()); } if (getParameters().getParentCommand() != VdcActionType.RemoveVmFromImportExport && getParameters().getParentCommand() != VdcActionType.RemoveVmTemplateFromImportExport) { performImageDbOperations(); } } else { log.warn("DiskImage is null, nothing to remove"); } setSucceeded(true); }</code><technical_language>I do warn, obligation</technical_language>

Target:
protected void executeCommand() { if (getDiskImage() != null) { try { VDSReturnValue vdsReturnValue = performImageVdsmOperation(); getReturnValue().getInternalTaskIdList().add( createTask(vdsReturnValue.getCreationInfo(), getParameters().getParentCommand(), VdcObjectType.Storage, getParameters().getStorageDomainId())); } catch (VdcBLLException e) { if (e.getErrorCode() != VdcBllErrors.ImageDoesNotExistInDomainError) { throw e; } log.warnFormat("The image group with id {0} wasn't actually deleted from the storage domain {1} because it didn't exist in it", getDiskImage().getId(), getStorageDomainId()); } if (getParameters().getParentCommand() != VdcActionType.RemoveVmFromImportExport && getParameters().getParentCommand() != VdcActionType.RemoveVmTemplateFromImportExport) { performImageDbOperations(); } } else { log.warn("DiskImage is null, nothing to remove"); } setSucceeded(true); }
Source:
<code><START> public static ADALError fromCommon(final BaseException exception) { <END> return exceptionMap.get(exception.getErrorCode()); }</code><technical_language>RE: > do do if errorCode is null? if, instead of a function converts String -> ADALError, behaved a constructor turn String -> AuthenticationException If Map returns ADALError, do do (only _this_ method creates AuthenticationException, possibly some other more class). If returns null, set a special ADALError set parameter of AuthenticationContext constructor (details) common</technical_language>

Target:
public static AuthenticationException fromCommon(final BaseException exception) { final ADALError adalError = exceptionMap.get(exception.getErrorCode()); if (adalError == null) { return new AuthenticationException(ADALError.MAPPING_FAILURE, exception.getMessage(), exception); } return new AuthenticationException(adalError, exception.getMessage(), exception); }
Source:
<code>public void onBootstrap() { ArrayList<LoadApi.LoadLibrary> libraries = new ArrayList<>(); <START> libraries.add(LoadApi.LoadLibrary.ADSENSE); <END> libraries.add(LoadApi.LoadLibrary.DRAWING); LoadApi.go(new Runnable() { @Override public void run() { GwtMapsLoadedEvent.fire(BootstrapperImpl.this); } }, libraries, true); placeManager.revealCurrentPlace(); }</code><technical_language>I need ADSENSE. Do need DRAWING</technical_language>

Target:
public void onBootstrap() { ArrayList<LoadApi.LoadLibrary> libraries = new ArrayList<>(); LoadApi.go(new Runnable() { @Override public void run() { GwtMapsLoadedEvent.fire(BootstrapperImpl.this); } }, libraries, true); placeManager.revealCurrentPlace(); }
Source:
<code>private ParameterizedTypeName(ParameterizedTypeName enclosingType, ClassName rawType, List<TypeName> typeArguments, List<AnnotationSpec> annotations) { super(annotations); <START> this.rawType = Objects.requireNonNull(rawType, "rawType == null"); <END> this.enclosingType = enclosingType; this.typeArguments = Util.immutableList(typeArguments); checkArgument(!this.typeArguments.isEmpty() || enclosingType != null, () -> "no type arguments: " + rawType); for (TypeName typeArgument : this.typeArguments) { checkArgument(!typeArgument.isPrimitive() && typeArgument != VOID, () -> "invalid type parameter: " + typeArgument); } }</code><technical_language>Import</technical_language>

Target:
private ParameterizedTypeName(ParameterizedTypeName enclosingType, ClassName rawType, List<TypeName> typeArguments, List<AnnotationSpec> annotations) { super(annotations); this.rawType = requireNonNull(rawType, "rawType == null"); this.enclosingType = enclosingType; this.typeArguments = Util.immutableList(typeArguments); checkArgument(!this.typeArguments.isEmpty() || enclosingType != null, () -> "no type arguments: " + rawType); for (TypeName typeArgument : this.typeArguments) { checkArgument(!typeArgument.isPrimitive() && typeArgument != VOID, () -> "invalid type parameter: " + typeArgument); } }
Source:
<code>public void onMessageBuildSuccess(MimeMessage message, boolean isDraft) { if (isDraft) { draftNeedsSaving = false; currentMessageBuilder = null; if (mAction == Action.EDIT_DRAFT && mMessageReference != null) { message.setUid(mMessageReference.getUid()); } boolean saveRemotely = recipientPresenter.isAllowSavingDraftRemotely(); new SaveMessageTask(getApplicationContext(), mAccount, mContacts, mHandler, message, mDraftId, saveRemotely).execute(); if (mFinishAfterDraftSaved) { finish(); } else { setProgressBarIndeterminateVisibility(false); } } else { currentMessageBuilder = null; <START> if (mAction == Action.REDIRECT) { <END> LocalMessage referenceMessage = mMessageReference.restoreToLocalMessage(getApplicationContext()); message = referenceMessage.cloneAsSuper(true); message.setResentDate(new Date(), K9.hideTimeZone()); message.setRecipients(RecipientType.RESENT_TO, toArray(recipientPresenter.getToAddresses())); message.setRecipients(RecipientType.RESENT_CC, toArray(recipientPresenter.getCcAddresses())); message.setRecipients(RecipientType.RESENT_BCC, toArray(recipientPresenter.getBccAddresses())); message.setResentFrom(new Address(mIdentity.getEmail(), mIdentity.getName())); message.setBody(mRedirectBody); } new SendMessageTask(getApplicationContext(), mAccount, mContacts, message, mDraftId != INVALID_DRAFT_ID ? mDraftId : null, mMessageReference).execute(); finish(); } }</code><technical_language>This piece of logic is misplaced here, redirected messages built a MessageBuilder</technical_language>

Target:
public void onMessageBuildSuccess(MimeMessage message, boolean isDraft) { if (isDraft) { draftNeedsSaving = false; currentMessageBuilder = null; if (mAction == Action.EDIT_DRAFT && mMessageReference != null) { message.setUid(mMessageReference.getUid()); } boolean saveRemotely = recipientPresenter.isAllowSavingDraftRemotely(); new SaveMessageTask(getApplicationContext(), mAccount, mContacts, mHandler, message, mDraftId, saveRemotely).execute(); if (mFinishAfterDraftSaved) { finish(); } else { setProgressBarIndeterminateVisibility(false); } } else { currentMessageBuilder = null; new SendMessageTask(getApplicationContext(), mAccount, mContacts, message, mDraftId != INVALID_DRAFT_ID ? mDraftId : null, mMessageReference).execute(); finish(); } }
Source:
<code>private void initStreamLogDirectory() { if (logDir.toFile().exists()) { <START> return; <END> } try { Files.createDirectories(logDir); } catch (IOException e) { throw new UnrecoverableCorfuError("Can't create stream log directory", e); } }</code><technical_language>log fact existed</technical_language>

Target:
private void initStreamLogDirectory() { if (logDir.toFile().exists()) { log.info("Log directory already exists: {}", logDir); return; } try { Files.createDirectories(logDir); } catch (IOException e) { throw new UnrecoverableCorfuError("Can't create stream log directory", e); } }
Source:
<code>public void missingItemMappings(RegistryEvent.MissingMappings<Item> event) { for (RegistryEvent.MissingMappings.Mapping<Item> entry : event.getAllMappings()) { for (SlimeBlock.SlimeType slime : SlimeBlock.SlimeType.values()) { <START> if (entry.key.getNamespace().equals(TConstruct.modID) && entry.key.getPath().equals("slime_sling_" + slime.getName())) { <END> entry.remap(GadgetItems.slime_sling.get(slime)); } if (entry.key.getNamespace().equals(TConstruct.modID) && entry.key.getPath().equals("slime_boots_" + slime.getName())) { entry.remap(GadgetItems.slime_boots.get(slime)); } if (entry.key.getNamespace().equals(TConstruct.modID) && entry.key.getPath().equals(String.format("congealed_%s_slime", slime.getName()))) { entry.remap(WorldBlocks.congealed_slime.get(slime).asItem()); } } } }</code><technical_language>Add a single mod ID filter top, save effort of loop if mod</technical_language>

Target:
public void missingItemMappings(RegistryEvent.MissingMappings<Item> event) { for (RegistryEvent.MissingMappings.Mapping<Item> entry : event.getAllMappings()) { if (entry.key.getNamespace().equals(TConstruct.modID)) { for (SlimeBlock.SlimeType slime : SlimeBlock.SlimeType.values()) { if (entry.key.getPath().equals("slime_sling_" + slime.getName())) { entry.remap(GadgetItems.slime_sling.get(slime)); } if (entry.key.getPath().equals("slime_boots_" + slime.getName())) { entry.remap(GadgetItems.slime_boots.get(slime)); } if (entry.key.getNamespace().equals(TConstruct.modID) && entry.key.getPath().equals(String.format("congealed_%s_slime", slime.getName()))) { entry.remap(WorldBlocks.congealed_slime.get(slime).asItem()); } } } } }
Source:
<code>DefaultCompactionPolicy(StoreConfig storeConfig, Time time) { this.storeConfig = storeConfig; this.time = time; <START> this.messageRetentionTimeInMs = (long) storeConfig.storeDeletedMessageRetentionDays * Time.SecsPerDay * Time.MsPerSec; <END> }</code><technical_language>here. This is fixed part of [this](<LINK_0></technical_language>

Target:
DefaultCompactionPolicy(StoreConfig storeConfig, Time time) { this.storeConfig = storeConfig; this.time = time; this.messageRetentionTimeInMs = storeConfig.storeDeletedMessageRetentionDays * Time.SecsPerDay * Time.MsPerSec; }
Source:
<code>public Response renew(String token) { Response resp; long expiration = 0; String error = ""; Response.Status errorStatus = Response.Status.BAD_REQUEST; if (tokenStateService == null) { error = "Token renewal support is not configured"; } else { String renewer = SubjectUtils.getCurrentEffectivePrincipalName(); if (allowedRenewers.contains(renewer)) { try { JWTToken jwt = new JWTToken(token); expiration = tokenStateService.renewToken(jwt, renewInterval.orElse(tokenStateService.getDefaultRenewInterval())); log.renewedToken(getTopologyName(), TokenUtils.getTokenDisplayText(token), TokenUtils.getTokenId(jwt)); } catch (ParseException e) { log.invalidToken(getTopologyName(), TokenUtils.getTokenDisplayText(token), e); <START> error = e.getMessage(); <END> } catch (Exception e) { error = e.getMessage(); } } else { errorStatus = Response.Status.FORBIDDEN; error = "Caller (" + renewer + ") not authorized to renew tokens."; } } if(error.isEmpty()) { resp = Response.status(Response.Status.OK) .entity("{\n \"renewed\": \"true\",\n \"expires\": \"" + expiration + "\"\n}\n") .build(); } else { log.badRenewalRequest(getTopologyName(), TokenUtils.getTokenDisplayText(token), error); resp = Response.status(errorStatus) .entity("{\n \"renewed\": \"false\",\n \"error\": \"" + error + "\"\n}\n") .build(); } return resp; }</code><technical_language>e.getMessage() throw NPE in case message is null</technical_language>

Target:
public Response renew(String token) { Response resp; long expiration = 0; String error = ""; Response.Status errorStatus = Response.Status.BAD_REQUEST; if (tokenStateService == null) { error = "Token renewal support is not configured"; } else { String renewer = SubjectUtils.getCurrentEffectivePrincipalName(); if (allowedRenewers.contains(renewer)) { try { JWTToken jwt = new JWTToken(token); expiration = tokenStateService.renewToken(jwt, renewInterval.orElse(tokenStateService.getDefaultRenewInterval())); log.renewedToken(getTopologyName(), TokenUtils.getTokenDisplayText(token), TokenUtils.getTokenId(jwt)); } catch (ParseException e) { log.invalidToken(getTopologyName(), TokenUtils.getTokenDisplayText(token), e); error = safeGetMessage(e); } catch (Exception e) { error = safeGetMessage(e); } } else { errorStatus = Response.Status.FORBIDDEN; error = "Caller (" + renewer + ") not authorized to renew tokens."; } } if(error.isEmpty()) { resp = Response.status(Response.Status.OK) .entity("{\n \"renewed\": \"true\",\n \"expires\": \"" + expiration + "\"\n}\n") .build(); } else { log.badRenewalRequest(getTopologyName(), TokenUtils.getTokenDisplayText(token), error); resp = Response.status(errorStatus) .entity("{\n \"renewed\": \"false\",\n \"error\": \"" + error + "\"\n}\n") .build(); } return resp; }