auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void testDoDoDelete() throws Exception{ FreeStyleProject project = j.createFreeStyleProject("project"); GlobalMatrixAuthorizationStrategy auth = new GlobalMatrixAuthorizationStrategy(); j.jenkins.setAuthorizationStrategy(auth); j.jenkins.setCrumbIssuer(null); HudsonPrivateSecurityRealm realm = new HudsonPrivateSecurityRealm(false); j.jenkins.setSecurityRealm(realm); User user = realm.createAccount("John Smith", "password"); try (ACLContext as = ACL.as(user)) { project.doDoDelete(null, null); fail("User should not have permission to build project"); } catch(Exception e){ if(!(e.getClass().isAssignableFrom(AccessDeniedException2.class))){ fail("AccessDeniedException should be thrown."); } } auth.add(Jenkins.READ, user.getId()); auth.add(Job.READ, user.getId()); auth.add(Job.DELETE, user.getId()); JenkinsRule.WebClient wc = j.createWebClient(); <START> wc.withBasicCredentials(user.getId(), "password"); <END> HtmlPage p = wc.goTo(project.getUrl() + "delete"); List<HtmlForm> forms = p.getForms(); for(HtmlForm form:forms){ if("doDelete".equals(form.getAttribute("action"))){ j.submit(form); } } assertNull("Project should be deleted form memory.", j.jenkins.getItem(project.getDisplayName())); assertFalse("Project should be deleted form disk.", project.getRootDir().exists()); }</code><technical_language>BTW usage of HudsonPrivateSecurityRealm is unnecessary; DummySecurityRealm simpler</technical_language>

Target:
public void testDoDoDelete() throws Exception{ FreeStyleProject project = j.createFreeStyleProject("project"); GlobalMatrixAuthorizationStrategy auth = new GlobalMatrixAuthorizationStrategy(); j.jenkins.setAuthorizationStrategy(auth); j.jenkins.setCrumbIssuer(null); j.jenkins.setSecurityRealm(j.createDummySecurityRealm()); User user = User.getById("john", true); try (ACLContext as = ACL.as(user)) { project.doDoDelete(null, null); fail("User should not have permission to build project"); } catch(Exception e){ if(!(e.getClass().isAssignableFrom(AccessDeniedException2.class))){ fail("AccessDeniedException should be thrown."); } } auth.add(Jenkins.READ, user.getId()); auth.add(Job.READ, user.getId()); auth.add(Job.DELETE, user.getId()); JenkinsRule.WebClient wc = j.createWebClient(); wc.withBasicCredentials(user.getId()); HtmlPage p = wc.goTo(project.getUrl() + "delete"); List<HtmlForm> forms = p.getForms(); for(HtmlForm form:forms){ if("doDelete".equals(form.getAttribute("action"))){ j.submit(form); } } assertNull("Project should be deleted form memory.", j.jenkins.getItem(project.getDisplayName())); assertFalse("Project should be deleted form disk.", project.getRootDir().exists()); }
Source:
<code>public void close() throws IOException, SQLException { if (!executorService.isShutdown()) { <START> executorService.shutdown(); <END> } s3.shutdown(); closeCurrentFile().delete(); if (connection != null) { connection.close(); connection = null; } }</code><technical_language>finish() exception executorService.awaitTermination, flow here. ExecutorService#shutdown() works. So, call #shutdownNow()</technical_language>

Target:
public void close() throws IOException, SQLException { executorService.shutdownNow(); try { executorService.awaitTermination(60, TimeUnit.SECONDS); } catch (InterruptedException e) s3.shutdown(); closeCurrentFile().delete(); if (connection != null) { connection.close(); connection = null; } }
Source:
<code>void trackExpiration(I id) { final ExpirationInfo expiration; synchronized (this) { if (trackedIds.containsKey(id)) { expiration = trackedIds.get(id); if (expiration.nextExpiration != null) { expiration.nextExpiration.previousExpiration = expiration.previousExpiration; } if (expiration.previousExpiration != null) { expiration.previousExpiration.nextExpiration = expiration.nextExpiration; } else if (firstExpiration == expiration && firstExpiration != lastExpiration) { firstExpiration = firstExpiration.nextExpiration; } <START> expiration.previousExpiration = null; <END> } else { expiration = new ExpirationInfo(id); trackedIds.put(id, expiration); } if (lastExpiration == null) { firstExpiration = lastExpiration = expiration; } else if (lastExpiration != expiration) { expiration.previousExpiration = lastExpiration; lastExpiration.nextExpiration = expiration; lastExpiration = expiration; } } synchronized(expiration) { expiration.expiration = System.currentTimeMillis() + timeout; } }</code><technical_language>nextExpriation cleared, endless loop result</technical_language>

Target:
void trackExpiration(I id) { final ExpirationInfo expiration; synchronized (this) { if (trackedIds.containsKey(id)) { expiration = trackedIds.get(id); if (expiration != lastExpiration) { if (expiration.nextExpiration != null) { expiration.nextExpiration.previousExpiration = expiration.previousExpiration; } if (expiration.previousExpiration != null) { expiration.previousExpiration.nextExpiration = expiration.nextExpiration; } else if (firstExpiration == expiration) { firstExpiration = firstExpiration.nextExpiration; } expiration.previousExpiration = null; expiration.nextExpiration = null; } } else { expiration = new ExpirationInfo(id); trackedIds.put(id, expiration); } if (lastExpiration == null) { firstExpiration = lastExpiration = expiration; } else if (lastExpiration != expiration) { expiration.previousExpiration = lastExpiration; lastExpiration.nextExpiration = expiration; lastExpiration = expiration; } } synchronized(expiration) { expiration.expiration = System.currentTimeMillis() + timeout; } }
Source:
<code>public void onBackPressed() { Drawable drawable = getDrawable(R.drawable.shape); GradientDrawable gradientDrawable = (GradientDrawable) drawable; gradientDrawable.setColor(getPrimaryColor()); checkForReveal = true; if ((editMode && all_photos) || (editMode && fav_photos)) clearSelectedPhotos(); getNavigationBar(); if (editMode) finishEditMode(); else { if (albumsMode) { if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) mDrawerLayout.closeDrawer(GravityCompat.START); else { if (doubleBackToExitPressedOnce && isTaskRoot()) finish(); else if (isTaskRoot()) { doubleBackToExitPressedOnce = true; final View layouttoast; LayoutInflater inflater = getLayoutInflater(); layouttoast = inflater.inflate(R.layout.toast_custom, (ViewGroup) findViewById(R.id.toastcustom)); <START> ((TextView) layouttoast.findViewById(R.id.texttoast)).setText("Press back again to exit"); <END> Toast mytoast = new Toast(getBaseContext()); mytoast.setView(layouttoast); mytoast.setDuration(Toast.LENGTH_SHORT); mytoast.show(); new Handler().postDelayed(new Runnable() { @Override public void run() { doubleBackToExitPressedOnce = false; } }, 2000); } else super.onBackPressed(); } } else { displayAlbums(); } } }</code><technical_language>Please string resource</technical_language>

Target:
public void onBackPressed() { Drawable drawable = getDrawable(R.drawable.shape); GradientDrawable gradientDrawable = (GradientDrawable) drawable; gradientDrawable.setColor(getPrimaryColor()); checkForReveal = true; if ((editMode && all_photos) || (editMode && fav_photos)) clearSelectedPhotos(); getNavigationBar(); if (editMode) finishEditMode(); else { if (albumsMode) { if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) mDrawerLayout.closeDrawer(GravityCompat.START); else { if (doubleBackToExitPressedOnce && isTaskRoot()) finish(); else if (isTaskRoot()) { doubleBackToExitPressedOnce = true; final View layouttoast; LayoutInflater inflater = getLayoutInflater(); layouttoast = inflater.inflate(R.layout.toast_custom, (ViewGroup) findViewById(R.id.toastcustom)); ((TextView) layouttoast.findViewById(R.id.texttoast)).setText(R.string.back_to_exit); Toast mytoast = new Toast(getBaseContext()); mytoast.setView(layouttoast); mytoast.setDuration(Toast.LENGTH_SHORT); mytoast.show(); new Handler().postDelayed(new Runnable() { @Override public void run() { doubleBackToExitPressedOnce = false; } }, 2000); } else super.onBackPressed(); } } else { displayAlbums(); } } }
Source:
<code>public boolean needsInput() <START> { <END> if (isSinglePartition() && maxRowsPerPartition.isPresent()) { return partitionRowCount.get(0) < maxRowsPerPartition.get() && !finishing && inputPage == null; } return !finishing && inputPage == null && unfinishedWork == null; }</code><technical_language>reason add unfinishedWork == null another condition isFinished()</technical_language>

Target:
public boolean needsInput() { if (isSinglePartition() && maxRowsPerPartition.isPresent()) { return partitionRowCount.get(0) < maxRowsPerPartition.get() && !finishing && !hasUnfinishedInput(); } return !finishing && !hasUnfinishedInput(); }
Source:
<code>public void getZeroScore() { BendableBigDecimalScore score = new BendableBigDecimalScoreDefinition(1, 2).getZeroScore(); <START> assertThat(score.toLevelNumbers()).containsOnly(BigDecimal.ZERO); <END> }</code><technical_language>I recommend avoid toLevelNumbers if possible. assert getZeroScore equals BendableScore.of(new int[]{0}, new int[]{0, 0})</technical_language>

Target:
public void getZeroScore() { BendableBigDecimalScore score = new BendableBigDecimalScoreDefinition(1, 2).getZeroScore(); assertThat(score).isEqualTo(BendableBigDecimalScore.zero(1, 2)); }
Source:
<code>protected void initializeWriteHandleState() { if (!getLedgerMetadata().isClosed() <START> && !(this instanceof ReadOnlyLedgerHandle) <END> && clientCtx.getConf().explicitLacInterval > 0) { explicitLacFlushPolicy = new ExplicitLacFlushPolicy.ExplicitLacFlushPolicyImpl( this, clientCtx); } else { explicitLacFlushPolicy = ExplicitLacFlushPolicy.VOID_EXPLICITLAC_FLUSH_POLICY; } if (clientCtx.getConf().addEntryQuorumTimeoutNanos > 0) { SafeRunnable monitor = new SafeRunnable() { @Override public void safeRun() { monitorPendingAddOps(); } }; this.timeoutFuture = clientCtx.getScheduler().scheduleAtFixedRate( monitor, clientCtx.getConf().timeoutMonitorIntervalSec, clientCtx.getConf().timeoutMonitorIntervalSec, TimeUnit.SECONDS); } }</code><technical_language>This is weird, avoid</technical_language>

Target:
protected void initializeWriteHandleState() { if (clientCtx.getConf().explicitLacInterval > 0) { explicitLacFlushPolicy = new ExplicitLacFlushPolicy.ExplicitLacFlushPolicyImpl( this, clientCtx); } else { explicitLacFlushPolicy = ExplicitLacFlushPolicy.VOID_EXPLICITLAC_FLUSH_POLICY; } if (clientCtx.getConf().addEntryQuorumTimeoutNanos > 0) { SafeRunnable monitor = new SafeRunnable() { @Override public void safeRun() { monitorPendingAddOps(); } }; this.timeoutFuture = clientCtx.getScheduler().scheduleAtFixedRate( monitor, clientCtx.getConf().timeoutMonitorIntervalSec, clientCtx.getConf().timeoutMonitorIntervalSec, TimeUnit.SECONDS); } }
Source:
<code>void withPrivateIoThreadPool() { <START> bindConfig(binder).annotatedWith(annotation).to(NettyAsyncHttpClientIoPoolProviderConfig.class); <END> binder.bind(NettyAsyncHttpClientIoPoolProvider.class).annotatedWith(annotation).toProvider(new NettyAsyncHttpClientIoPoolMetaProvider(name, annotation)).in(Scopes.SINGLETON); }</code><technical_language>I need a .prefixedWith(name)</technical_language>

Target:
void withPrivateIoThreadPool() { bindConfig(binder).annotatedWith(annotation).prefixedWith(name).to(NettyIoPoolConfig.class); binder.bind(NettyIoPool.class).annotatedWith(annotation).toProvider(new NettyIoPoolProvider(name, annotation)).in(Scopes.SINGLETON); }
Source:
<code>public int hashCode() { final int prime = 31; <START> int result = 1; <END> result = prime * result + ((resource == null) ? 0 : resource.hashCode()); return result; }</code><technical_language>I link change of hashCode equals, feature of this issue... remarks for items</technical_language>

Target:
public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((parent == null) ? 0 : parent.hashCode()); result = prime * result + ((resource == null) ? 0 : resource.hashCode()); return result; }
Source:
<code>protected Function<E, Object> customFieldExtractor(String field) { if (!field.startsWith(languagePrefix) || !languageParameter.isPresent()) { return null; } <START> String realField = field.replaceFirst(languagePrefix, ""); <END> if (CLE_VALUE.equals(realField) || CLE_ADDITIONAL_VALUE.equals(realField) || CLE_DESCRIPTION.equals(realField)) { return codeListEntry -> codeListEntry.getTranslations() .getText(Mapping.named(realField), languageParameter.get()) .orElse(null); } return null; }</code><technical_language>this belong in import handler</technical_language>

Target:
protected Function<E, Object> customFieldExtractor(String field) { if (!languageParameter.isPresent() || languagePrefix == null || !field.startsWith(languagePrefix)) { return null; } String realField = field.replaceFirst(languagePrefix, ""); if (CLE_VALUE.equals(realField) || CLE_ADDITIONAL_VALUE.equals(realField) || CLE_DESCRIPTION.equals(realField)) { return codeListEntry -> codeListEntry.getTranslations() .getText(Mapping.named(realField), languageParameter.get()) .orElse(null); } return null; }
Source:
<code>public void send(Mail mail) { final Map<String, Object> model = mail.getTemplateModel(); model.put("baseLinkURL", getApplicationUrl()); final String subject = getTranslation(mail.getSubjectMessageKey(), mail.getSubjectMessageArguments()); final String sender = mailProperties.getSender(); <START> if (mail.isSendToTechnicalMail()) { <END> final String body = mailBuilder.buildMailBody(mail.getTemplateName(), model, LOCALE); mailSenderService.sendEmail(sender, List.of(mailProperties.getAdministrator()), subject, body); } else { final List<Person> recipients = getRecipients(mail); if (mail.getMailAttachments().isEmpty()) { if (mail.isSendToEachIndividually()) { recipients.forEach(recipient -> { model.put("recipient", recipient); final String body = mailBuilder.buildMailBody(mail.getTemplateName(), model, LOCALE); mailSenderService.sendEmail(sender, List.of(recipient.getEmail()), subject, body); }); } else { final String body = mailBuilder.buildMailBody(mail.getTemplateName(), model, LOCALE); mailSenderService.sendEmail(sender, getMailAddresses(recipients), subject, body); } } else { if (mail.isSendToEachIndividually()) { recipients.forEach(recipient -> { model.put("recipient", recipient); final String body = mailBuilder.buildMailBody(mail.getTemplateName(), model, LOCALE); mailSenderService.sendEmail(sender, List.of(recipient.getEmail()), subject, body, mail.getMailAttachments()); }); } else { final String body = mailBuilder.buildMailBody(mail.getTemplateName(), model, LOCALE); mailSenderService.sendEmail(sender, getMailAddresses(recipients), subject, body, mail.getMailAttachments()); } } } }</code><technical_language>if/else ensure current builder pattern allows sendToTechnical **and** other recipients e.g. Mail.builder() .withRecipient(NOTIFICATION_OFFICE) .withRecipient(true) .withSubject(subjectMessageKey) .withTemplate(templateName, model) .build();</technical_language>

Target:
public void send(Mail mail) { final Map<String, Object> model = mail.getTemplateModel(); model.put("baseLinkURL", getApplicationUrl()); final String subject = getTranslation(mail.getSubjectMessageKey(), mail.getSubjectMessageArguments()); final String sender = mailProperties.getSender(); getRecipients(mail).forEach(recipient -> { model.put("recipient", recipient); final String body = mailContentBuilder.buildMailBody(mail.getTemplateName(), model, LOCALE); mail.getMailAttachments().ifPresentOrElse( mailAttachments -> mailSenderService.sendEmail(sender, List.of(recipient.getEmail()), subject, body, mailAttachments), () -> mailSenderService.sendEmail(sender, List.of(recipient.getEmail()), subject, body)); }); }
Source:
<code>public void enable(CommandSource src) { try { <START> final WorldArchetype archetype1 = Sponge.getRegistry().getType(WorldArchetype.class, "multi-world-test:overnether").orElseGet(() -> <END> WorldArchetype.builder(). from(WorldArchetypes.THE_NETHER) .serializationBehavior(SerializationBehaviors.NONE) .generator(GeneratorTypes.OVERWORLD) .build("multi-world-test:overnether", "Overnether") ); final WorldProperties world1 = Sponge.getServer().createWorldProperties("no-save", archetype1); Sponge.getServer().loadWorld(world1); final WorldArchetype archetype2 = Sponge.getRegistry().getType(WorldArchetype.class, "multi-world-test:overend").orElseGet(() -> WorldArchetype.builder(). from(WorldArchetypes.THE_END) .serializationBehavior(SerializationBehaviors.METADATA_ONLY) .generator(GeneratorTypes.OVERWORLD) .build("multi-world-test:overend", "Overend") ); final WorldProperties world2 = Sponge.getServer().createWorldProperties("metadata-only", archetype2); Sponge.getServer().loadWorld(world2); } catch (IOException e) { e.printStackTrace(); } }</code><technical_language>change</technical_language>

Target:
public void enable(CommandSource src) { try { final Server server = Sponge.getServer(); final WorldArchetype archetypeNoSave = Sponge.getRegistry().getType(WorldArchetype.class, "multi-world-test:overnether").orElseGet(() -> WorldArchetype.builder(). from(WorldArchetypes.THE_NETHER) .serializationBehavior(SerializationBehaviors.NONE) .generator(GeneratorTypes.OVERWORLD) .build("multi-world-test:overnether", "Overnether") ); final WorldProperties worldNoSave = server.createWorldProperties("no-save", archetypeNoSave); server.loadWorld(worldNoSave); final WorldArchetype archetypeMetadataOnly = Sponge.getRegistry().getType(WorldArchetype.class, "multi-world-test:overend").orElseGet(() -> WorldArchetype.builder(). from(WorldArchetypes.THE_END) .serializationBehavior(SerializationBehaviors.METADATA_ONLY) .generator(GeneratorTypes.OVERWORLD) .build("multi-world-test:overend", "Overend") ); final WorldProperties worldMetadataOnly = server.createWorldProperties("metadata-only", archetypeMetadataOnly); server.loadWorld(worldMetadataOnly); } catch (IOException e) { e.printStackTrace(); } }
Source:
<code>public void testUpdateFailureOnReadFromRouter() throws Exception { assumeTrue(!forBackfill); RouterStore store = new RouterStore(accountServiceMetrics, backup, helixStore, new AtomicReference<>(router), forBackfill, TOTAL_NUMBER_OF_VERSION_TO_KEEP); Map<Short, Account> idToRefAccountMap = new HashMap<>(); Map<Short, Map<Short, Container>> idtoRefContainerMap = new HashMap<>(); Set<Short> accountIDSet = new HashSet<>(); AccountTestUtils.generateRefAccounts(idToRefAccountMap, idtoRefContainerMap, accountIDSet, 1, 1); assertUpdateAndFetch(store, idToRefAccountMap, idToRefAccountMap, 1, 1); router.close(); Map<Short, Account> anotherIdToRefAccountMap = new HashMap<>(); AccountTestUtils.generateRefAccounts(anotherIdToRefAccountMap, idtoRefContainerMap, accountIDSet, 1, 1); for (Map.Entry<Short, Account> entry : anotherIdToRefAccountMap.entrySet()) { idToRefAccountMap.put(entry.getKey(), entry.getValue()); } <START> boolean succeeded = store.updateAccounts(anotherIdToRefAccountMap.values()); <END> assertFalse("Update account should fail on read error", succeeded); }</code><technical_language>need succeeded boolean variable here. Merge line164 165</technical_language>

Target:
public void testUpdateFailureOnReadFromRouter() throws Exception { assumeTrue(!forBackfill); RouterStore store = new RouterStore(accountServiceMetrics, backup, helixStore, new AtomicReference<>(router), forBackfill, TOTAL_NUMBER_OF_VERSION_TO_KEEP); Map<Short, Account> idToRefAccountMap = new HashMap<>(); Map<Short, Map<Short, Container>> idtoRefContainerMap = new HashMap<>(); Set<Short> accountIDSet = new HashSet<>(); AccountTestUtils.generateRefAccounts(idToRefAccountMap, idtoRefContainerMap, accountIDSet, 1, 1); assertUpdateAndFetch(store, idToRefAccountMap, idToRefAccountMap, 1, 1); router.clear(); Map<Short, Account> anotherIdToRefAccountMap = new HashMap<>(); AccountTestUtils.generateRefAccounts(anotherIdToRefAccountMap, idtoRefContainerMap, accountIDSet, 1, 1); for (Map.Entry<Short, Account> entry : anotherIdToRefAccountMap.entrySet()) { idToRefAccountMap.put(entry.getKey(), entry.getValue()); } assertFalse("Update account should fail on read error", store.updateAccounts(anotherIdToRefAccountMap.values())); }
Source:
<code>public void setCollection(Object[] items) { if (items == null) { setEntitySummaries(new EntitySummary[0]); } else { <START> EntitySummary[] summaries = new EntitySummary[items.length]; <END> for (int index = 0; index < items.length; index++) { summaries[index] = (EntitySummary)items[index]; } setEntitySummaries(summaries); } }</code><technical_language>Instead of iterating array casting element, do - EntitySummary[] summaries = Arrays.copyOf(items, items.length, EntitySummary[].class);</technical_language>

Target:
public void setCollection(Object[] items) { if (items == null) { setEntitySummaries(new EntitySummary[0]); } else { EntitySummary[] summaries = Arrays.copyOf(items, items.length, EntitySummary[].class); setEntitySummaries(summaries); } }
Source:
<code>public static void setUp() { <START> Assume.assumeTrue(SystemUtils.IS_OS_MAC); <END> final Path scriptFolder = Paths.get("src").resolve("test").resolve("resources"); commands = new ArrayList<>(); commands.add("bash"); commands.add("-c"); commands.add(scriptFolder.resolve("scriptMainProcess.sh").toAbsolutePath().toString() + " \"" + scriptFolder.toAbsolutePath() + "\""); }</code><technical_language>this test executed UNIX platforms exclude Windows</technical_language>

Target:
public static void setUp() { Assume.assumeFalse(SystemUtils.IS_OS_WINDOWS); final Path scriptFolder = Paths.get("src").resolve("test").resolve("resources"); commands = new ArrayList<>(); commands.add("bash"); commands.add("-c"); commands.add(scriptFolder.resolve("scriptMainProcess.sh").toAbsolutePath().toString() + " \"" + scriptFolder.toAbsolutePath() + "\""); }
Source:
<code>public int compareTo(FileAndName o) { int retVal = getFile().compareTo(o.getFile()); if (retVal == 0) { if (getTraceTypeId() != null) { <START> if (o.getTraceTypeId() != null) { <END> retVal = getTraceTypeId().compareTo(o.getTraceTypeId()); } } } return retVal; }</code><technical_language>While it, merge if's together: if (retVal == 0 && getTraceTypeId() != null && o.getTraceTypeId() != null) { retVal = .... } Technically, if getTraceTypeId() returns a mutable value, safer extract a local variable first, change if check in compareTo() is more condition in if. I trace type ID is supposed change fine</technical_language>

Target:
public int compareTo(FileAndName o) { int retVal = getFile().compareTo(o.getFile()); if (retVal == 0) { if (getTraceTypeId() != null && o.getTraceTypeId() != null) { retVal = getTraceTypeId().compareTo(o.getTraceTypeId()); } } return retVal; }
Source:
<code>private List<ScreenshotMetadata> getOrReadMetadata() throws IOException { if (mMetadata == null) { File metadataFile = getMetadataFile(); if (metadataFile.exists()) { Gson gson = new Gson(); JsonReader jsonReader = new JsonReader(new FileReader(getMetadataFile())); <START> mMetadata = gson.fromJson(jsonReader, new TypeToken<List<Map<String, Object>>>() { <END> }.getType()); if (mMetadata == null) { mMetadata = new ArrayList<>(); } } else { mMetadata = new ArrayList<>(); } } return mMetadata; }</code><technical_language>isnt this type token for type List<ScreenshotMetadata> matches type of mMetadata</technical_language>

Target:
private List<ScreenshotMetadata> getOrReadMetadata() throws IOException { if (mMetadata == null) { File metadataFile = getMetadataFile(); if (metadataFile.exists()) { Gson gson = new Gson(); JsonReader jsonReader = new JsonReader(new FileReader(getMetadataFile())); mMetadata = gson.fromJson(jsonReader, new TypeToken<List<ScreenshotMetadata>>() { }.getType()); if (mMetadata == null) { mMetadata = new ArrayList<>(); } } else { mMetadata = new ArrayList<>(); } } return mMetadata; }
Source:
<code>public Privilege[] getPrivileges() { <START> return privileges; <END> }</code><technical_language>This method exposes/leaks privileges array, allowing callers modify list. This method return a defensive copy. And, if this class a list, this method List.toArray(...)</technical_language>

Target:
public Privilege[] getPrivileges() { return privileges.toArray(new Privilege[privileges.size()]); }
Source:
<code>protected void positionToTimestamp(LogManager manager, String group, String name, long timestamp) { try (LogTailer<Record> tailer = manager.createTailer(group, name)) { int size = manager.getAppender(name).size(); IntStream.range(0, size).boxed().map(partition -> new LogPartition(name, partition)).forEach(lp -> { LogOffset logOffset = tailer.offsetForTimestamp(lp, timestamp); if (logOffset != null) { tailer.seek(logOffset); tailer.commit(); System.out.println( String.format("# Set log %s, group: %s, to offset %s", name, group, logOffset.offset())); } else { System.err.println( <START> String.format("# Could not find an offset for log %s, group: %s", name, group)); <END> } }); } }</code><technical_language>if command fails (timestamp is invalid) run method return false (which generate error exit code), assertion returned state in unit tests</technical_language>

Target:
protected boolean positionToTimestamp(LogManager manager, String group, String name, long timestamp) { try (LogTailer<Record> tailer = manager.createTailer(group, name)) { int size = manager.getAppender(name).size(); boolean movedOffset = false; for (int partition = 0; partition < size; partition++) { LogPartition logPartition = new LogPartition(name, partition); LogOffset logOffset = tailer.offsetForTimestamp(logPartition, timestamp); if (logOffset != null) { tailer.seek(logOffset); movedOffset = true; System.out.println( String.format("# Set log %s, group: %s, to offset %s", name, group, logOffset.offset())); } else { System.err.println( String.format("# Could not find an offset for group: %s, partition: %s", group, logPartition)); } } if (movedOffset) { tailer.commit(); return true; } } return false; }
Source:
<code>public T map(int index, ResultSet r, StatementContext ctx) throws SQLException { try { Constructor<T> constructor = c.getDeclaredConstructor(); constructor.setAccessible(true); T result = constructor.newInstance(); <START> if (columns.size() == 0) <END> mapColumns(r.getMetaData(), columns); for (Map.Entry<Integer, String> col : columns.entrySet()) { Integer columnIndex = col.getKey(); String matchCode = col.getValue(); Field field = fields.get(matchCode); if (field != null) field.set(result, r.getObject(columnIndex)); } return result; } catch (Exception e) { throw new IllegalArgumentException(e); } }</code><technical_language>This thread-safe. AtomicReference map</technical_language>

Target:
public T map(int index, ResultSet r, StatementContext ctx) throws SQLException { try { Constructor<T> constructor = c.getDeclaredConstructor(); constructor.setAccessible(true); T result = constructor.newInstance(); Map<Integer, String> columns = threadSafeGetColumns(r.getMetaData()); for (Map.Entry<Integer, String> col : columns.entrySet()) { Integer columnIndex = col.getKey(); String matchCode = col.getValue(); Field field = fields.get(matchCode); if (field != null) field.set(result, r.getObject(columnIndex)); } return result; } catch (Exception e) { throw new IllegalArgumentException(e); } }
Source:
<code>public <T> T transaction(TransactionAction<T, D> action) { Handle nested = currentTransaction.get(); if (nested != null) { return nested.inTransaction((h, status) -> action.call(h, h.attach(daoIface))); } else { try { return transactionRetryExecutor.runInterruptible(() -> { try (Handle handle = dbi.open()) { currentTransaction.set(handle); return handle.inTransaction((h, status) -> action.call(h, h.attach(daoIface))); } finally { currentTransaction.set(null); } }); } catch (RetryGiveupException ex) { Throwable innerException = ex.getCause(); throw Throwables.propagate(innerException); } catch (InterruptedException ex) { <START> throw Throwables.propagate(ex); <END> } } }</code><technical_language>If interrupted state restored this RuntimeException is caught, okay. If not, restoring state better</technical_language>

Target:
public <T> T transaction(TransactionAction<T, D> action) { Handle nested = currentTransaction.get(); if (nested != null) { return nested.inTransaction((h, status) -> action.call(h, h.attach(daoIface))); } else { try { return transactionRetryExecutor.runInterruptible(() -> { try (Handle handle = dbi.open()) { currentTransaction.set(handle); return handle.inTransaction((h, status) -> action.call(h, h.attach(daoIface))); } finally { currentTransaction.set(null); } }); } catch (RetryGiveupException ex) { Throwable innerException = ex.getCause(); throw Throwables.propagate(innerException); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); throw Throwables.propagate(ex); } } }
Source:
<code>public Response add(Driver entity) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); Context.getDriversManager().addItem(entity); <START> LinkedHashMap<String, Long> link = new LinkedHashMap<>(); <END> link.put("userId", getUserId()); link.put("driverId", entity.getId()); Context.getDataManager().linkObject(link, true); Context.getDriversManager().refreshUserItems(); return Response.ok(entity).build(); }</code><technical_language>Another thought I code. link un-link one-by-only, 4 parameters in linkObject method? shorter cleaner IMHO</technical_language>

Target:
public Response add(Driver entity) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); Context.getDriversManager().addItem(entity); Context.getDataManager().linkObject(User.class, getUserId(), entity.getClass(), entity.getId(), true); Context.getDriversManager().refreshUserItems(); return Response.ok(entity).build(); }
Source:
<code>public void setSubject(ISubject <START> priceSetter) { <END> this.subject = priceSetter; }</code><technical_language>check if priceSetter is null</technical_language>

Target:
public void setSubject(ISubject priceSetter) { if(priceSetter!=null){ this.isubject = priceSetter; } }
Source:
<code>protected void paintFigure(final Graphics g) { g.setBackgroundColor(getBackgroundColor()); g.setForegroundColor(getForegroundColor()); g.setLineWidth(getLineWidth()); <START> g.setLineStyle(getLineStyle()); <END> final PointList points = calculatePoints(new Rectangle(getBounds())); g.fillPolygon(points); g.drawPolygon(points); }</code><technical_language>Line dash / line attributes</technical_language>

Target:
protected void paintFigure(final Graphics g) { g.setBackgroundColor(getBackgroundColor()); g.setForegroundColor(getForegroundColor()); g.setLineWidth(getLineWidth()); final PointList points = calculatePoints(new Rectangle(getBounds())); g.fillPolygon(points); g.drawPolygon(points); }
Source:
<code>protected void initializeDataSource() { ITmfTrace trace = getTrace(); if (trace != null) { fModule = TmfTraceUtils.getAnalysisModuleOfClass(trace, TmfStateSystemAnalysisModule.class, KernelMemoryAnalysisModule.ID); if (fModule == null) { return; } fModule.schedule(); Chart chart = getSwtChart(); chart.getDisplay().asyncExec(new Runnable() { @Override public void run() { chart.getAxisSet().getYAxis(0).getTick().setFormat(new MemoryFormat()); } }); } fModule.waitForInitialization(); ITmfStateSystem ss = fModule.getStateSystem(); if (ss == null) { return; } ss.waitUntilBuilt(); lowestValueMap = new HashMap<>(); try { List<Integer> threadQuarkList = ss.getSubAttributes(-1, false); for (Integer threadQuark : threadQuarkList) { String tid = ss.getAttributeName(threadQuark); int lowestValueQuark = ss.getQuarkRelative(threadQuark, KernelMemoryAnalysisModule.THREAD_LOWEST_MEMORY_VALUE); long ts = ss.getCurrentEndTime(); ITmfStateInterval lowestValueState = ss.querySingleState(ts, lowestValueQuark); long lowestValue = lowestValueState.getStateValue().unboxLong(); lowestValueMap.put(tid, (double) lowestValue); } double totalIncrementation = lowestValueMap.values().stream().mapToDouble(Double::doubleValue).sum(); lowestValueMap.put(TOTAL, totalIncrementation); <START> } catch (AttributeNotFoundException e) { <END> Activator.getDefault().logError(e.getMessage(), e); } catch (StateSystemDisposedException e2) { Activator.getDefault().logError(e2.getMessage(), e2); } }</code><technical_language>multicatch</technical_language>

Target:
protected void initializeDataSource() { ITmfTrace trace = getTrace(); if (trace != null) { fModule = TmfTraceUtils.getAnalysisModuleOfClass(trace, TmfStateSystemAnalysisModule.class, KernelMemoryAnalysisModule.ID); if (fModule == null) { return; } fModule.schedule(); } }
Source:
<code>public String update(Artifact artifact) throws CarbonDeploymentException { logger.info("Updating : " + artifact.getName()); <START> if (artifact.getName().contains("sample1.txt")) { <END> sample1Updated = true; } else if (artifact.getName().contains("sample2.txt")) { sample2Updated = true; } return artifact.getName(); }</code><technical_language>NPE calling contains artifact.getName() ? checking for nullity calling .contains</technical_language>

Target:
public String update(Artifact artifact) throws CarbonDeploymentException { logger.info("Updating : " + artifact.getName()); if (artifact.getName() != null && artifact.getName().contains("sample1.txt")) { sample1Updated = true; } else if (artifact.getName() != null && artifact.getName().contains("sample2.txt")) { sample2Updated = true; } return artifact.getName(); }
Source:
<code>private void loadOptionalParameters(Properties properties) { if (log.isDebugEnabled()) { log.debug("Starting to load the salesforce credentials"); } if (properties.getProperty(SalesforceConstant.CONNECTION_TIMEOUT) == null) { connectionTimeout = SalesforceConstant.CONNECTION_TIMEOUT_DEFAULT; } else { <START> connectionTimeout = Integer.parseInt(properties.getProperty(SalesforceConstant.CONNECTION_TIMEOUT)); <END> } if (properties.getProperty(SalesforceConstant.READ_TIMEOUT) == null) { readTimeout = SalesforceConstant.READ_TIMEOUT_DEFAULT; } else { readTimeout = Integer.parseInt(properties.getProperty(SalesforceConstant.READ_TIMEOUT)); } if (properties.getProperty(SalesforceConstant.WAIT_TIME) == null) { connectionTimeout = SalesforceConstant.WAIT_TIME_DEFAULT; } else { waitTime = Integer.parseInt(properties.getProperty(SalesforceConstant.WAIT_TIME)); } }</code><technical_language>catch NumberFormateException</technical_language>

Target:
private void loadOptionalParameters(Properties properties) { if (log.isDebugEnabled()) { log.debug("Starting to load the salesforce credentials"); } if (properties.getProperty(SalesforceConstant.CONNECTION_TIMEOUT) == null) { connectionTimeout = SalesforceConstant.CONNECTION_TIMEOUT_DEFAULT; } else { try { connectionTimeout = Integer.parseInt(properties.getProperty(SalesforceConstant.CONNECTION_TIMEOUT)); } catch (NumberFormatException e) { log.error("The Value should be in Number", e); } } if (properties.getProperty(SalesforceConstant.READ_TIMEOUT) == null) { readTimeout = SalesforceConstant.READ_TIMEOUT_DEFAULT; } else { try { readTimeout = Integer.parseInt(properties.getProperty(SalesforceConstant.READ_TIMEOUT)); } catch (NumberFormatException e) { log.error("The Value should be in Number", e); } } if (properties.getProperty(SalesforceConstant.WAIT_TIME) == null) { connectionTimeout = SalesforceConstant.WAIT_TIME_DEFAULT; } else { try { waitTime = Integer.parseInt(properties.getProperty(SalesforceConstant.WAIT_TIME)); } catch (NumberFormatException e) { log.error("The Value should be in Number", e); } } }
Source:
<code>public Supplier<Boolean> getTask(@NotNull Context context) { DaggerUtils.getComponent(context).inject(this); return () -> { try { List<ServerFormDetails> serverForms = serverFormsDetailsFetcher.fetchFormDetails(); List<ServerFormDetails> updatedForms = serverForms.stream().filter(ServerFormDetails::isUpdated).collect(Collectors.toList()); if (!updatedForms.isEmpty()) { if (preferencesProvider.getGeneralSharedPreferences().getBoolean(KEY_AUTOMATIC_UPDATE, false)) { changeLock.withLock(acquiredLock -> { if (acquiredLock) { HashMap<ServerFormDetails, String> results = new HashMap<>(); for (ServerFormDetails serverFormDetails : updatedForms) { try { formDownloader.downloadForm(serverFormDetails, null, null); results.put(serverFormDetails, Collect.getInstance().getString(R.string.success)); } catch (FormDownloadException e) { results.put(serverFormDetails, e.getMessage()); } catch (InterruptedException e) { <START> return null; <END> } } notifier.onUpdatesDownloaded(results); } return null; }); } else { notifier.onUpdatesAvailable(updatedForms); } } return true; } catch (FormApiException e) { return true; } }; }</code><technical_language>This is UI, is it? If is, status for forms download updated</technical_language>

Target:
public Supplier<Boolean> getTask(@NotNull Context context) { DaggerUtils.getComponent(context).inject(this); return () -> { try { List<ServerFormDetails> serverForms = serverFormsDetailsFetcher.fetchFormDetails(); List<ServerFormDetails> updatedForms = serverForms.stream().filter(ServerFormDetails::isUpdated).collect(Collectors.toList()); if (!updatedForms.isEmpty()) { if (preferencesProvider.getGeneralSharedPreferences().getBoolean(KEY_AUTOMATIC_UPDATE, false)) { changeLock.withLock(acquiredLock -> { if (acquiredLock) { HashMap<ServerFormDetails, String> results = new HashMap<>(); for (ServerFormDetails serverFormDetails : updatedForms) { try { formDownloader.downloadForm(serverFormDetails, null, null); results.put(serverFormDetails, TranslationHandler.getString(context, R.string.success)); } catch (FormDownloadException e) { results.put(serverFormDetails, TranslationHandler.getString(context, R.string.failure)); } catch (InterruptedException e) { break; } } notifier.onUpdatesDownloaded(results); } return null; }); } else { notifier.onUpdatesAvailable(updatedForms); } } return true; } catch (FormSourceException e) { return true; } }; }
Source:
<code>public void doSaveAs() { new WorkspaceJob("Do save as") { @Override public IStatus runInWorkspace(IProgressMonitor monitor) throws CoreException { Shell shell = getSite().getShell(); if (shell != null && !shell.isDisposed()) { shell.getDisplay().syncExec(new Runnable() { @Override public void run() { SwaggerEditor.super.doSaveAs(); } }); } return Status.OK_STATUS; } }.schedule(); <START> validate(); <END> }</code><technical_language>@tfesenko for this validate call workspace job</technical_language>

Target:
public void doSaveAs() { new WorkspaceJob("Do save as") { @Override public IStatus runInWorkspace(IProgressMonitor monitor) throws CoreException { Shell shell = getSite().getShell(); if (shell != null && !shell.isDisposed()) { shell.getDisplay().syncExec(new Runnable() { @Override public void run() { SwaggerEditor.super.doSaveAs(); } }); } validate(); return Status.OK_STATUS; } }.schedule(); }
Source:
<code>public void returnResult(Intent data) { <START> boolean isInternal = getIntent().getBooleanExtra(EXTRA_IS_INTERNAL, false); <END> if (isInternal) { setResult(RESULT_OK, data); finish(); } else { OperationResult result = data.getParcelableExtra(OperationResult.EXTRA_RESULT); String str = getString(result.getLog().getLast().mType.getMsgId()); Toast.makeText(this, str, Toast.LENGTH_LONG).show(); finish(); } }</code><technical_language>I this replaced a check if activity started ACTION_SCAN_WITH_RESULT ACTION_SCAN_IMPORT, ACTION_QR_CODE_API is outside</technical_language>

Target:
public void returnResult(Intent data) { String action = getIntent().getAction(); if (ACTION_QR_CODE_API.equals(action)) { OperationResult result = data.getParcelableExtra(OperationResult.EXTRA_RESULT); String str = getString(result.getLog().getLast().mType.getMsgId()); Toast.makeText(this, str, Toast.LENGTH_LONG).show(); finish(); } else { setResult(RESULT_OK, data); finish(); } }
Source:
<code>public final void publish(P payload) { if (payload instanceof Message) { this.publishMessage((Message<?>) payload); <START> return; <END> } Message<P> message = MessageBuilder.withPayload(payload).build(); this.listenerEventsChannel.send(message); }</code><technical_language>standard, else a return in a void method (yes this is picking)</technical_language>

Target:
public final void publish(P payload) { if (payload instanceof Message) { this.publishMessage((Message<?>) payload); } else { Message<P> message = MessageBuilder.withPayload(payload).build(); this.listenerEventsChannel.send(message); } }
Source:
<code>public static Client init(Context androidContext) { client = new Client(androidContext); <START> configureClientObservers(); <END> return client; }</code><technical_language>(should?) this moved constructor for Client object itself? I remember, a supported of Bugsnag Android is instantiating a Client object Bugsnag static class</technical_language>

Target:
public static Client init(Context androidContext) { client = new Client(androidContext); NativeInterface.configureClientObservers(client); return client; }
Source:
<code>public PoolDTO setProvidedProducts(Set<ProvidedProductDTO> providedProducts) { if (providedProducts != null) { if (this.providedProducts == null) { this.providedProducts = new HashSet<ProvidedProductDTO>(); } else { this.providedProducts.clear(); } for (ProvidedProductDTO dto : providedProducts) { if (isNullOrIncomplete(dto)) { <START> throw new IllegalArgumentException("collection contains null " + <END> "or incomplete provided products"); } } this.providedProducts.addAll(providedProducts); } else { this.providedProducts = null; } return this; }</code><technical_language>wrapping</technical_language>

Target:
public PoolDTO setProvidedProducts(Set<ProvidedProductDTO> providedProducts) { if (providedProducts != null) { if (this.providedProducts == null) { this.providedProducts = new HashSet<ProvidedProductDTO>(); } else { this.providedProducts.clear(); } for (ProvidedProductDTO dto : providedProducts) { if (isNullOrIncomplete(dto)) { throw new IllegalArgumentException( "collection contains null or incomplete provided products"); } } this.providedProducts.addAll(providedProducts); } else { this.providedProducts = null; } return this; }
Source:
<code><START> public void updateStatisticsData(VdsStatistics statisticsData) { <END> DbFacade.getInstance().getVdsStatisticsDao().update(statisticsData); }</code><technical_language>statistics? in some cases this is called right updateDynamic, for example setting status</technical_language>

Target:
public void updateStatisticsData(VdsStatistics statisticsData) { DbFacade.getInstance().getVdsStatisticsDao().update(statisticsData); cachedVds.setStatisticsData(statisticsData); }
Source:
<code>private synchronized void setupCacheDir(String id) { String cacheDirName = fileCacheDir + "/file-cache-" + id; cacheDir = new File(cacheDirName); if (!cacheDir.mkdirs()) { throw new IllegalStateException("Failed to create cache dir: " + cacheDirName); } shutdownHook = new Thread(() -> { CountDownLatch latch = new CountDownLatch(1); new Thread(() -> { try { deleteCacheDir(); } catch (IOException ignore) { } latch.countDown(); }).start(); try { <START> latch.await(10, TimeUnit.SECONDS); <END> } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }); Runtime.getRuntime().addShutdownHook(shutdownHook); }</code><technical_language>instead of a Latch thread.join thread started</technical_language>

Target:
private synchronized void setupCacheDir(String id) { String cacheDirName = fileCacheDir + "/file-cache-" + id; cacheDir = new File(cacheDirName); if (!cacheDir.mkdirs()) { throw new IllegalStateException("Failed to create cache dir: " + cacheDirName); } shutdownHook = new Thread(() -> { final Thread deleteCacheDirThread = new Thread(() -> { try { deleteCacheDir(); } catch (IOException ignore) { } }); deleteCacheDirThread.start(); try { deleteCacheDirThread.join(10 * 1000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }); Runtime.getRuntime().addShutdownHook(shutdownHook); }
Source:
<code>public void testHsqlDb() { Jdbi jdbi = Jdbi.create("jdbc:hsqldb:mem:" + UUID.randomUUID()); init(jdbi); try (Handle handle = jdbi.open()) { handle.execute("create table player_stats (" + "name varchar(64) primary key, " + "seasons varchar(36) array, " + "points int array)"); handle.createUpdate("insert into player_stats (name,seasons,points) values (?,?,?)") .bind(0, "Jack Johnson") .bind(1, new String[]{"2013-2014", "2014-2015", "2015-2016"}) .bind(2, new Integer[]{42, 51, 50}) .execute(); String[] seasons = handle.createQuery("select seasons from player_stats") <START> .bind("name", "Jack Johnson") <END> .mapTo(String[].class) .findOnly(); assertThat(seasons).containsExactly("2013-2014", "2014-2015", "2015-2016"); } }</code><technical_language>Unused bind</technical_language>

Target:
public void testHsqlDb() { Jdbi jdbi = Jdbi.create("jdbc:hsqldb:mem:" + UUID.randomUUID()); init(jdbi); try (Handle handle = jdbi.open()) { handle.execute("create table player_stats (" + "name varchar(64) primary key, " + "seasons varchar(36) array, " + "points int array)"); handle.createUpdate("insert into player_stats (name,seasons,points) values (?,?,?)") .bind(0, "Jack Johnson") .bind(1, new String[]{"2013-2014", "2014-2015", "2015-2016"}) .bind(2, new Integer[]{42, 51, 50}) .execute(); String[] seasons = handle.createQuery("select seasons from player_stats where name=:name") .bind("name", "Jack Johnson") .mapTo(String[].class) .findOnly(); assertThat(seasons).containsExactly("2013-2014", "2014-2015", "2015-2016"); } }
Source:
<code>private static Map<String, Integer> getCommands() { Map<String, Integer> commands = new HashMap<>(); commands.put("--help", 0); commands.put("--checkstyle", 2); commands.put("--scanexercise", 2); commands.put("--runtests", 2); commands.put("--preparestub", 1); <START> commands.put("--preparesolution", 1); <END> return commands; }</code><technical_language>I programs argument a command typically command double dash in front of it. Some examples: git, svn, VirtualBox, virsh. (i.e. git clone, git --clone) In addition command, support -h --help position</technical_language>

Target:
private static Map<String, Integer> getCommands() { Map<String, Integer> commands = new HashMap<>(); commands.put("help", 0); commands.put("checkstyle", 2); commands.put("scan-exercise", 2); commands.put("run-tests", 2); commands.put("prepare-stub", 1); commands.put("prepare-solution", 1); return commands; }