auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void revisionActionsTwoChangeChangesInTopic() throws Exception { String changeId = createChangeWithTopic("foo2").getChangeId(); approve(changeId); createChangeWithTopic("foo2").getChangeId(); Map<String, ActionInfo> actions = getActions(changeId); assertThat(actions).containsKey("cherrypick"); assertThat(actions).containsKey("submit"); assertThat(actions).hasSize(2); if (isSubmitWholeTopicEnabled()) { ActionInfo info = actions.get("submit"); <START> assertThat(info.enabled).isEqualTo(null); <END> assertThat(info.label).isEqualTo("Submit whole topic"); assertThat(info.method).isEqualTo("POST"); assertThat(info.title).isEqualTo("Other changes in this topic are not ready"); } else { noSubmitWholeTopicAssertions(actions); } }</code><technical_language>isNull()</technical_language>

Target:
public void revisionActionsTwoChangeChangesInTopic() throws Exception { String changeId = createChangeWithTopic("foo2").getChangeId(); approve(changeId); createChangeWithTopic("foo2").getChangeId(); Map<String, ActionInfo> actions = getActions(changeId); assertThat(actions).containsKey("cherrypick"); assertThat(actions).containsKey("submit"); assertThat(actions).hasSize(2); if (isSubmitWholeTopicEnabled()) { ActionInfo info = actions.get("submit"); assertThat(info.enabled).isNull(); assertThat(info.label).isEqualTo("Submit whole topic"); assertThat(info.method).isEqualTo("POST"); assertThat(info.title).isEqualTo("Other changes in this topic are not ready"); } else { noSubmitWholeTopicAssertions(actions); } }
Source:
<code>public void setup() throws Exception { contexts.startRequestScope(); contexts.startSessionScope(); <START> contexts.startApplicationScope(); <END> initEvent.fire(new VRaptorInitialized(null)); super.setup(); }</code><technical_language>started largest scope smallest</technical_language>

Target:
public void setup() throws Exception { contexts.startApplicationScope(); contexts.startSessionScope(); initEvent.fire(new VRaptorInitialized(null)); super.setup(); }
Source:
<code>private RebaseResult abort() throws IOException { try { String commitId = readFile(repo.getDirectory(), "ORIG_HEAD"); monitor.beginTask("Aborting rebase: resetting to " + commitId, ProgressMonitor.UNKNOWN); RevCommit commit = walk.parseCommit(repo.resolve(commitId)); DirCacheCheckout dco = new DirCacheCheckout(repo, repo .lockDirCache(), commit.getTree()); dco.setFailOnConflict(false); dco.checkout(); walk.release(); } finally { monitor.endTask(); } try { String headName = readFile(rebaseDir, "head-name"); if (headName.startsWith(Constants.R_REFS)) { monitor.beginTask("Resetting head to " + headName, ProgressMonitor.UNKNOWN); RefUpdate refUpdate = repo.updateRef(Constants.HEAD, false); Result res = refUpdate.link(headName); switch (res) { case FAST_FORWARD: case FORCED: case NO_CHANGE: break; default: <START> throw new IOException("Could not abort rebase"); <END> } } deleteRecursive(rebaseDir); return new RebaseResult(Status.ABORTED); } finally { monitor.endTask(); } }</code><technical_language>This a JGitInternalException do IO</technical_language>

Target:
private RebaseResult abort() throws IOException { try { String commitId = readFile(repo.getDirectory(), "ORIG_HEAD"); monitor.beginTask(MessageFormat.format( JGitText.get().abortingRebase, commitId), ProgressMonitor.UNKNOWN); RevCommit commit = walk.parseCommit(repo.resolve(commitId)); DirCacheCheckout dco = new DirCacheCheckout(repo, repo .lockDirCache(), commit.getTree()); dco.setFailOnConflict(false); dco.checkout(); walk.release(); } finally { monitor.endTask(); } try { String headName = readFile(rebaseDir, "head-name"); if (headName.startsWith(Constants.R_REFS)) { monitor.beginTask(MessageFormat.format( JGitText.get().resettingHead, headName), ProgressMonitor.UNKNOWN); RefUpdate refUpdate = repo.updateRef(Constants.HEAD, false); Result res = refUpdate.link(headName); switch (res) { case FAST_FORWARD: case FORCED: case NO_CHANGE: break; default: throw new IOException("Could not abort rebase"); } } deleteRecursive(rebaseDir); return new RebaseResult(Status.ABORTED); } finally { monitor.endTask(); } }
Source:
<code>private void loadSchema(final String schemaFile) throws IOException { final XmlSchemaCollection schemaCollection = new XmlSchemaCollection(); <START> try (final InputStream schemaStream = new FileInputStream("src/test/resources/" + schemaFile)) { <END> schema = schemaCollection.read(new StreamSource(schemaStream)); } }</code><technical_language>Alternatively load file stream classloader try (final InputStream schemaStream = getClass().getClassLoader().getResourceAsStream(schemaFile)) {</technical_language>

Target:
private void loadSchema(final String schemaFile) throws IOException { final XmlSchemaCollection schemaCollection = new XmlSchemaCollection(); try (final InputStream schemaStream = getClass().getClassLoader().getResourceAsStream(schemaFile)) { schema = schemaCollection.read(new StreamSource(schemaStream)); } }
Source:
<code>NettyServerCnxnFactory() { x509Util = new ClientX509Util(); EventLoopGroup bossGroup = new NioEventLoopGroup(0, Executors.newCachedThreadPool()); EventLoopGroup workerGroup = new NioEventLoopGroup(0, Executors.newCachedThreadPool()); bootstrap = new ServerBootstrap(); bootstrap.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .option(ChannelOption.SO_REUSEADDR, true) <START> .childOption(ChannelOption.TCP_NODELAY, true) <END> .childOption(ChannelOption.SO_LINGER, -1) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); if (secure) { initSSL(pipeline); } pipeline.addLast("servercnxnfactory", channelHandler); } }); ByteBufAllocator testAllocator = TEST_ALLOCATOR.get(); if (testAllocator != null) { bootstrap.option(ChannelOption.ALLOCATOR, testAllocator) .childOption(ChannelOption.ALLOCATOR, testAllocator); } bootstrap.validate(); }</code><technical_language>Consider EPoll</technical_language>

Target:
NettyServerCnxnFactory() { x509Util = new ClientX509Util(); EventLoopGroup bossGroup = NettyUtils.newNioOrEpollEventLoopGroup(); EventLoopGroup workerGroup = NettyUtils.newNioOrEpollEventLoopGroup(); ServerBootstrap bootstrap = new ServerBootstrap() .group(bossGroup, workerGroup) .channel(NettyUtils.nioOrEpollServerSocketChannel()) .option(ChannelOption.SO_REUSEADDR, true) .childOption(ChannelOption.TCP_NODELAY, true) .childOption(ChannelOption.SO_LINGER, -1) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); if (secure) { initSSL(pipeline); } pipeline.addLast("servercnxnfactory", channelHandler); } }); this.bootstrap = configureBootstrapAllocator(bootstrap); this.bootstrap.validate(); }
Source:
<code>private void readHeaders() throws IOException { <START> String line; <END> while ((line = in.readString()) != PacketLineIn.END) { if (line.startsWith("restart ")) restartToken = line.substring("restart ".length()); else if (line.startsWith("last-pack-number ")) lastPackId = line.substring("last-pack-number ".length()); } }</code><technical_language>clear out restartToken lastPackId start? class variables is error prone. remembered sessions stored in Session, pass information arguments. This require create some helper types hold data e.g. a Header class fields, restartToken lastPackId. This apply in out, everywhere</technical_language>

Target:
private Header readHeaders() throws IOException { Header h = new Header(); String line; while ((line = in.readString()) != PacketLineIn.END) { if (line.startsWith("restart ")) h.restartToken = line.substring("restart ".length()); else if (line.startsWith("last-pack-number ")) h.lastPackId = line.substring("last-pack-number ".length()); } return h; }
Source:
<code>public void testRibbonLoadBalancingHttpClient() { RibbonCommandContext context = new RibbonCommandContext("foo"," GET", "http://localhost", false, new LinkedMultiValueMap<String, String>(), new LinkedMultiValueMap<String, String>(), <START> null, new ArrayList<RibbonRequestCustomizer>(), 0l, null); <END> HttpClientRibbonCommand command = httpClientRibbonCommandFactory.create(context); RibbonLoadBalancingHttpClient ribbonClient = command.getClient(); CloseableHttpClient httpClient = getField(ribbonClient, "delegate"); MockingDetails httpClientDetails = mockingDetails(httpClient); assertTrue(httpClientDetails.isMock()); }</code><technical_language>change tests constructor</technical_language>

Target:
public void testRibbonLoadBalancingHttpClient() { RibbonCommandContext context = new RibbonCommandContext("foo"," GET", "http://localhost", false, new LinkedMultiValueMap<String, String>(), new LinkedMultiValueMap<String, String>(), null, new ArrayList<RibbonRequestCustomizer>(), 0l); HttpClientRibbonCommand command = httpClientRibbonCommandFactory.create(context); RibbonLoadBalancingHttpClient ribbonClient = command.getClient(); CloseableHttpClient httpClient = getField(ribbonClient, "delegate"); MockingDetails httpClientDetails = mockingDetails(httpClient); assertTrue(httpClientDetails.isMock()); }
Source:
<code>public void fetchRegions () { LOGGER.info("Fetching ANSS Authoritative Regions from Geoserve"); File regionsJson = new File(REGIONS_JSON); try { JsonObject json = this.geoserveLayersService.getLayer("anss"); this.regions = new RegionsJSON().parseRegions(json); LOGGER.info("Loaded ANSS Authoritative Regions from Geoserve"); FileUtils.writeFileThenMove( new File(REGIONS_JSON + ".temp"), regionsJson, json.toString().getBytes()); LOGGER.finer("Storing ANSS Authoritative Regions to " + REGIONS_JSON); <START> return; <END> } catch (Exception e) { LOGGER.log(Level.WARNING, "Error updating ANSS Authoritative Regions", e); } if (regionsJson.exists()) { LOGGER.finer("Loading ANSS Authoritative Regions from " + REGIONS_JSON); try (InputStream in = StreamUtils.getInputStream(regionsJson)) { JsonObject json = Json.createReader(in).readObject(); this.regions = new RegionsJSON().parseRegions(json); LOGGER.fine("Loaded ANSS Authoritative Regions from " + REGIONS_JSON + ", last modified=" + XmlUtils.formatDate( new Date(regionsJson.lastModified()))); return; } catch (Exception e) { LOGGER.log(Level.WARNING, "Error loading ANSS Authoritative Regions from " + REGIONS_JSON, e); } } LOGGER.warning("Unable to load ANSS Authoritative Regions"); }</code><technical_language>a huge fan of short-circuit returns. code harder read/understand. functions loadFromGeoserve loadFromFile. parent function calls needed</technical_language>

Target:
public void fetchRegions () { try { this.regions = loadFromGeoserve(); } catch (Exception e) { LOGGER.log(Level.WARNING, "Error fetching ANSS Regions from geoserve", e); try { if (this.regions == null) { this.regions = loadFromFile(); } } catch (Exception e2) { LOGGER.log(Level.WARNING, "Error fetching ANSS Regions from local file", e); } } }
Source:
<code>public byte[] readRound(long seq) throws IOException { lock.readLock().lock(); try { byte[] result = currentLog.readRound(seq); byte[] experimentalResult = experimentalLog.readRound(seq); if (!Arrays.equals(result, experimentalResult)) { log.error("Mismatch in reading round for sequence number between legacy and current " + "implementations. Legacy result {}, current result {}.", SafeArg.of("sequence", seq), UnsafeArg.of("legacy", hydrator.hydrateFromBytes(result)), <START> UnsafeArg.of("current", hydrator.hydrateFromBytes(experimentalResult))); <END> } return result; } finally { lock.readLock().unlock(); } }</code><technical_language>discussed: This needs resilient null results</technical_language>

Target:
public byte[] readRound(long seq) throws IOException { lock.readLock().lock(); try { byte[] result = currentLog.readRound(seq); byte[] experimentalResult = safeReadFromExperimental(psl -> psl.readRound(seq)); if (!Arrays.equals(result, experimentalResult)) { log.error("Mismatch in reading round for sequence number between legacy and current " + "implementations. Legacy result {}, current result {}.", SafeArg.of("sequence", seq), UnsafeArg.of("legacy", hydrateIfNotNull(result)), UnsafeArg.of("current", hydrateIfNotNull(experimentalResult))); } return result; } finally { lock.readLock().unlock(); } }
Source:
<code>public synchronized void shutdown() { <START> shutdown.set(true); <END> for (ManagedConnectionPool mcp : pools.values()) mcp.shutdown(); pools.clear(); }</code><technical_language>Remove</technical_language>

Target:
public synchronized void shutdown() { for (ManagedConnectionPool mcp : pools.values()) mcp.shutdown(); pools.clear(); }
Source:
<code>public void testSensitivity(final double expected, final File metricsFile, final double alleleFraction, final int sampleSize) throws Exception { final double tolerance = 0.02; final MetricsFile Metrics = new MetricsFile(); <START> Metrics.read(new FileReader(metricsFile)); <END> final List<Histogram<Integer>> histograms = Metrics.getAllHistograms(); final Histogram<Integer> depthHistogram = histograms.get(0); final Histogram<Integer> qualityHistogram = histograms.get(1); final double result = TheoreticalSensitivity.theoreticalSensitivity(depthHistogram, qualityHistogram, sampleSize, 3, alleleFraction); Assert.assertEquals(result, expected, tolerance); }</code><technical_language>try-with-resources for FileReader</technical_language>

Target:
public void testSensitivity(final double expected, final File metricsFile, final double alleleFraction, final int sampleSize) throws Exception { final double tolerance = 0.02; final MetricsFile metrics = new MetricsFile(); try (final FileReader metricsFileReader = new FileReader(metricsFile)) { metrics.read(metricsFileReader); } final List<Histogram<Integer>> histograms = metrics.getAllHistograms(); final Histogram<Integer> depthHistogram = histograms.get(0); final Histogram<Integer> qualityHistogram = histograms.get(1); final double result = TheoreticalSensitivity.theoreticalSensitivity(depthHistogram, qualityHistogram, sampleSize, 3, alleleFraction); Assert.assertEquals(result, expected, tolerance); }
Source:
<code>public static int randomInt(int max) { <START> return SolRandom.randomInt(0f, max); <END> }</code><technical_language>Replace 0f 0 please</technical_language>

Target:
public static int randomInt(int max) { return SolRandom.randomInt(0, max); }
Source:
<code>private boolean shouldEnablePlatformSpecificConfig( OptionValueDescription enablePlatformSpecificConfigDescription, ListMultimap<String, RcChunkOfArgs> commandToRcArgs) { if (enablePlatformSpecificConfigDescription == null || <START> !(boolean) enablePlatformSpecificConfigDescription.getValue()) { <END> return false; } Multiset<String> keys = commandToRcArgs.keys(); for (String commandName : getCommandNamesToParse(commandAnnotation)) { String defaultConfigDef = commandName + ":" + OS.getCurrent().getCanonicalName(); if (keys.contains(defaultConfigDef)) { return true; } } return false; }</code><technical_language>Is this cast safe? (Boolean) check for null</technical_language>

Target:
private boolean shouldEnablePlatformSpecificConfig( OptionValueDescription enablePlatformSpecificConfigDescription, ListMultimap<String, RcChunkOfArgs> commandToRcArgs) { if (enablePlatformSpecificConfigDescription == null || !(boolean) enablePlatformSpecificConfigDescription.getValue()) { return false; } for (String commandName : getCommandNamesToParse(commandAnnotation)) { String defaultConfigDef = commandName + ":" + OS.getCurrent().getCanonicalName(); if (commandToRcArgs.containsKey(defaultConfigDef)) { return true; } } return false; }
Source:
<code>public UserResetTokenDTO create(String resetToken, Long userId) { UserResetTokenEntity entity = new UserResetTokenEntity(); entity.setUserResetToken(resetToken); entity.setUserId(userId); entity.setCreationDate(new Date()); <START> entity.setLastModifiedDate(new Date()); <END> if(Util.getCurrentUser() != null) { entity.setLastModifiedUser(Util.getCurrentUser().getId()); } else { entity.setLastModifiedUser(userId); } entity.setDeleted(false); create(entity); return new UserResetTokenDTO(entity); }</code><technical_language>Creation date modified date need set database sets them. need mark insertable = false, updatable = false in entity</technical_language>

Target:
public UserResetTokenDTO create(String resetToken, Long userId) { UserResetTokenEntity entity = new UserResetTokenEntity(); entity.setUserResetToken(resetToken); entity.setUserId(userId); if (Util.getCurrentUser() != null) { entity.setLastModifiedUser(Util.getCurrentUser().getId()); } else { entity.setLastModifiedUser(userId); } entity.setDeleted(false); create(entity); return new UserResetTokenDTO(entity); }
Source:
<code>public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int i) { SimpleDateFormat sdf = new SimpleDateFormat("MMM d"); switch (viewHolder.getItemViewType()) { case 0: News news = this.dataset; NewsViewHolder newsViewHolder = (NewsViewHolder) viewHolder; newsViewHolder.getTitle().setText(news.getTitle()); newsViewHolder.getSubmitter().setText(news.getSubmitter()); newsViewHolder.getUrl().setText(news.getUrl()); newsViewHolder.getDate().setText(sdf.format(news.getDate())); newsViewHolder.getScore().setText(Integer.toString(news.getScore())); newsViewHolder.getCommentCount().setText(Integer.toString(news.getComments().size()) + " comments"); if (news.getBody() != null && !news.getBody().isEmpty()) { newsViewHolder.getBody().setText(news.getBody()); } else { newsViewHolder.getBody().setVisibility(View.GONE); } break; case 1: <START> Comment comment = this.dataset.getComments().get(i - 1); <END> CommentViewHolder commentViewHolder = (CommentViewHolder) viewHolder; commentViewHolder.getSubmitter().setText(comment.getSubmitter()); commentViewHolder.getDate().setText(sdf.format(comment.getDate())); commentViewHolder.getBody().setText(comment.getBody()); break; } }</code><technical_language>ok, noted</technical_language>

Target:
public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int i) { switch (viewHolder.getItemViewType()) { case 0: News news = this.dataset; NewsViewHolder newsViewHolder = (NewsViewHolder) viewHolder; newsViewHolder.getTitle().setText(news.getTitle()); newsViewHolder.getSubmitter().setText(news.getSubmitter()); newsViewHolder.getUrl().setText(Util.getDomainName(news.getUrl())); newsViewHolder.getDate().setText(this.dateFormatter.timeAgo(news.getDate())); newsViewHolder.getScore().setText(Integer.toString(news.getScore())); Resources r = this.fragment.getActivity().getResources(); int nComment = news.getComments().size(); String commentCountFormat = r.getQuantityString(R.plurals.comments, nComment, nComment); newsViewHolder.getCommentCount().setText(commentCountFormat); if (news.getBody() != null && !news.getBody().isEmpty()) { newsViewHolder.getBody().setText(news.getBody()); } else { newsViewHolder.getBody().setVisibility(View.GONE); } break; case 1: Comment comment = this.dataset.getComments().get(i - 1); CommentViewHolder commentViewHolder = (CommentViewHolder) viewHolder; commentViewHolder.getSubmitter().setText(comment.getSubmitter()); commentViewHolder.getDate().setText(this.dateFormatter.timeAgo(comment.getDate())); commentViewHolder.getBody().setText(comment.getBody()); break; } }
Source:
<code>private static void addStates(final State current, final String value, final int i, final List<State> allStates) { if (i == value.length()) { return; } <START> byte[] bytes = value.getBytes(Charset.forName("UTF-8")); <END> final byte currentByte = bytes[i]; State newState = current.next.get(currentByte); if (newState == null) { current.next.put(currentByte, newState = new State(currentByte, value.substring(0, i + 1))); allStates.add(newState); } addStates(newState, value, i + 1, allStates); }</code><technical_language>StandardCharsets</technical_language>

Target:
private static void addStates(final State current, final String value, final int i, final List<State> allStates) { if (i == value.length()) { return; } byte[] bytes = value.getBytes(StandardCharsets.UTF_8); final byte currentByte = bytes[i]; State newState = current.next.get(currentByte); if (newState == null) { current.next.put(currentByte, newState = new State(currentByte, value.substring(0, i + 1))); allStates.add(newState); } addStates(newState, value, i + 1, allStates); }
Source:
<code>public String createAccount(Study study, Account account) { String userId = BridgeUtils.generateGuid(); account.setId(userId); account.setStudyId(study.getIdentifier()); DateTime timestamp = DateUtils.getCurrentDateTime(); account.setCreatedOn(timestamp); account.setModifiedOn(timestamp); <START> account.setPasswordModifiedOn(DateUtils.getCurrentDateTime()); <END> account.setMigrationVersion(AccountDao.MIGRATION_VERSION); hibernateHelper.create(account); return userId; }</code><technical_language>Minor: reason timestamp variable for of setters, call DateUtils.getCurrentDateTime() for third</technical_language>

Target:
public String createAccount(Study study, Account account) { String userId = BridgeUtils.generateGuid(); account.setId(userId); account.setStudyId(study.getIdentifier()); DateTime timestamp = DateUtils.getCurrentDateTime(); account.setCreatedOn(timestamp); account.setModifiedOn(timestamp); account.setPasswordModifiedOn(timestamp); account.setMigrationVersion(AccountDao.MIGRATION_VERSION); hibernateHelper.create(account); return userId; }
Source:
<code>protected void initUniqueTag(String uniqueTag, Object ...valsForDefault) { if (Strings.isNonBlank(uniqueTag)) this.uniqueTag = uniqueTag; <START> else if (Strings.isBlank(this.uniqueTag)) this.uniqueTag = getDefaultUniqueTag(valsForDefault); <END> }</code><technical_language>need for if isBlank</technical_language>

Target:
protected void initUniqueTag(String uniqueTag, Object ...valsForDefault) { if (Strings.isNonBlank(uniqueTag)) this.uniqueTag = uniqueTag; else this.uniqueTag = getDefaultUniqueTag(valsForDefault); }
Source:
<code>protected boolean defaultAccountIndicatorIsActive(String rowIndicatorValue) { <START> return StringUtils.equals(rowIndicatorValue, KFSConstants.ACTIVE_INDICATOR) ? true : false; <END> }</code><technical_language>return StringUtils.equals() result directly; making a ternary of "? true : false" is redundant</technical_language>

Target:
protected boolean defaultAccountIndicatorIsActive(String rowIndicatorValue) { return StringUtils.equals(rowIndicatorValue, KFSConstants.ACTIVE_INDICATOR); }
Source:
<code>private static Set<String> asSet(String... x) { HashSet<String> set=new HashSet<>(); for(String a:x) <START> set.add(a); <END> return set; }</code><technical_language>personal preference is brackets for line loops condition. a blocker merging</technical_language>

Target:
private static Set<String> asSet(String... x) { return new HashSet<String>(Arrays.asList(x)); }
Source:
<code>private Set<TypeElement> gather(Set<? extends TypeElement> annotations, RoundEnvironment roundEnvironment, Class<? extends Annotation> annotation, Set<TypeElement> sink) { if (annotations.stream() .map(TypeElement::getQualifiedName) .noneMatch(name -> name.contentEquals(annotation.getName()))) { return ImmutableSet.of(); } return roundEnvironment.getElementsAnnotatedWith(annotation).stream() .filter(element -> TypeElement.class.isAssignableFrom(element.getClass())) <START> .map(element -> (TypeElement) element) <END> .filter(element -> !sink.contains(element)) .collect(toImmutableSet()); }</code><technical_language>TypeElement.class::cast</technical_language>

Target:
private Set<TypeElement> gather(Set<? extends TypeElement> annotations, RoundEnvironment roundEnvironment, Class<? extends Annotation> annotation, Set<TypeElement> sink) { if (annotations.stream() .map(TypeElement::getQualifiedName) .noneMatch(name -> name.contentEquals(annotation.getName()))) { return ImmutableSet.of(); } return roundEnvironment.getElementsAnnotatedWith(annotation).stream() .filter(element -> TypeElement.class.isAssignableFrom(element.getClass())) .map(TypeElement.class::cast) .filter(element -> !sink.contains(element)) .collect(toImmutableSet()); }
Source:
<code>private QueryRequest createQueryRequest(Filter filter) { QueryImpl query = new QueryImpl(filter); <START> query.setPageSize(maxSubscriptions.get()); <END> return new QueryRequestImpl(query, createProperties()); }</code><technical_language>If this page size is greater internal framework limit means subscription size greater that. want ResultIterator here</technical_language>

Target:
private QueryRequest createQueryRequest(Filter filter) { QueryImpl query = new QueryImpl(filter); query.setPageSize(maxSubscriptions); query.setSortBy(new SortByImpl(Core.MODIFIED, SortOrder.DESCENDING)); return new QueryRequestImpl(query, createProperties()); }
Source:
<code>public Object setup(Map context, Object target, Member member, String propertyName) { Object result = null; if (isAccessible(context, target, member, propertyName)) { AccessibleObject accessible = (AccessibleObject) member; if (!accessible.isAccessible()) { <START> result = Boolean.TRUE; <END> accessible.setAccessible(true); } } return result; }</code><technical_language>result in restore method state parameter? if I Boolean.FALSE</technical_language>

Target:
public Object setup(Map context, Object target, Member member, String propertyName) { Object result = null; if (isAccessible(context, target, member, propertyName)) { AccessibleObject accessible = (AccessibleObject) member; if (!accessible.isAccessible()) { result = Boolean.FALSE; accessible.setAccessible(true); } } return result; }
Source:
<code>private void setSearchQuery(@Nullable String query) { if (readingList == null) { return; } currentSearchQuery = query; if (TextUtils.isEmpty(query)) { readingListPairs.clear(); for (ReadingListPage page : readingList.pages()) { readingListPairs.add(new Pair<>(readingList, page)); } adapter.notifyDataSetChanged(); updateEmptyState(query); } else { <START> ReadingListSearchUtil.INSTANCE.searchListsAndPages(query, <END> pairs -> { readingListPairs = pairs; adapter.notifyDataSetChanged(); updateEmptyState(query); }); } touchCallback.setSwipeableEnabled(TextUtils.isEmpty(query)); }</code><technical_language>Wait, do want search lists+pages a *single* list? Is part of design expectations</technical_language>

Target:
private void setSearchQuery(@Nullable String query) { if (readingList == null) { return; } currentSearchQuery = query; if (TextUtils.isEmpty(query)) { displayedLists.clear(); displayedLists.addAll(readingList.pages()); adapter.notifyDataSetChanged(); updateEmptyState(query); } else { ReadingListSearchUtil.INSTANCE.searchListsAndPages(query, lists -> { displayedLists = lists; adapter.notifyDataSetChanged(); updateEmptyState(query); }); } touchCallback.setSwipeableEnabled(TextUtils.isEmpty(query)); }
Source:
<code>private void displayTournamentItem(TournamentBean tournamentBean) { String startingDate = i18n.get("tournament.noStartingDate"); if (tournamentBean.getStartingAt() != null) { <START> startingDate = MessageFormat.format("{0} {1}", timeService.asDate(tournamentBean.getStartingAt()), timeService.asShortTime(tournamentBean.getStartingAt())); <END> } String completedDate = i18n.get("tournament.noCompletionDate"); if (tournamentBean.getCompletedAt() != null) { completedDate = MessageFormat.format("{0} {1}", timeService.asDate(tournamentBean.getCompletedAt()), timeService.asShortTime(tournamentBean.getCompletedAt())); } try (Reader reader = new InputStreamReader(TOURNAMENT_DETAIL_HTML_RESOURCE.getInputStream())) { String html = CharStreams.toString(reader).replace("{name}", tournamentBean.getName()) .replace("{challonge-url}", tournamentBean.getChallongeUrl()) .replace("{tournament-type}", tournamentBean.getTournamentType()) .replace("{starting-date}", startingDate) .replace("{completed-date}", completedDate) .replace("{description}", tournamentBean.getDescription()) .replace("{tournament-image}", tournamentBean.getLiveImageUrl()); tournamentDetailWebView.getEngine().loadContent(html); } catch (IOException e) { throw new RuntimeException(e); } }</code><technical_language>this (and below) internationalized string. {0} {1} {0} um {1} etc</technical_language>

Target:
private void displayTournamentItem(TournamentBean tournamentBean) { String startingDate = i18n.get("tournament.noStartingDate"); if (tournamentBean.getStartingAt() != null) { startingDate = MessageFormat.format(i18n.get("dateWithTime"), timeService.asDate(tournamentBean.getStartingAt()), timeService.asShortTime(tournamentBean.getStartingAt())); } String completedDate = i18n.get("tournament.noCompletionDate"); if (tournamentBean.getCompletedAt() != null) { completedDate = MessageFormat.format(i18n.get("dateWithTime"), timeService.asDate(tournamentBean.getCompletedAt()), timeService.asShortTime(tournamentBean.getCompletedAt())); } Reader reader = new InputStreamReader(TOURNAMENT_DETAIL_HTML_RESOURCE.getInputStream()); String html = CharStreams.toString(reader).replace("{name}", tournamentBean.getName()) .replace("{challonge-url}", tournamentBean.getChallongeUrl()) .replace("{tournament-type}", tournamentBean.getTournamentType()) .replace("{starting-date}", startingDate) .replace("{completed-date}", completedDate) .replace("{description}", tournamentBean.getDescription()) .replace("{tournament-image}", tournamentBean.getLiveImageUrl()); tournamentDetailWebView.getEngine().loadContent(html); }
Source:
<code>public void doOnTerminateErrorCrash() { Maybe.error(new TestException()) .doOnTerminate(new Action() { @Override public void run() { throw new TestException(); } }) .test() .assertFailure(CompositeException.class); <START> } <END></code><technical_language>Please verify correct exceptions received. Example: <LINK_0></technical_language>

Target:
public void doOnTerminateErrorCrash() { TestObserver<Object> to = Maybe.error(new TestException("Outer")) .doOnTerminate(new Action() { @Override public void run() { throw new TestException("Inner"); } }) .test() .assertFailure(CompositeException.class); List<Throwable> errors = TestHelper.compositeList(to.errors().get(0)); TestHelper.assertError(errors, 0, TestException.class, "Outer"); TestHelper.assertError(errors, 1, TestException.class, "Inner"); }
Source:
<code>private void canTerminate(IProcessDMContext[] procDmcs, DataRequestMonitor<Boolean> rm) { if (procDmcs.length == 0) { rm.setData(false); rm.done(); return; } IMultiTerminate multiTerminate = fTracker.getService(IMultiTerminate.class); if (multiTerminate != null) { multiTerminate.canTerminateSome(procDmcs, rm); } else { IProcesses procService = fTracker.getService(IProcesses.class); <START> if (procService != null && procDmcs.length == 1) { <END> procService.canTerminate(procDmcs[0], rm); } else { rm.setData(false);; rm.done(); } } }</code><technical_language>suggestion allow terminate for a single selection is MultiTerminate service a problem multi-process. In case, selecting launch, code converts multiple processes allow terminate launch selected multiple selections. This is a pretty rare bug: 1- replacing IMultiTerminate service support multi-terminate (maybe want support it) 2- running multi-process I wanted know, I ok leaving this in. If wants replace service, replace this class well</technical_language>

Target:
private void canTerminate(IProcessDMContext[] procDmcs, DataRequestMonitor<Boolean> rm) { if (procDmcs.length == 0) { IGDBControl gdbControl = fTracker.getService(IGDBControl.class); if (gdbControl != null) { rm.setData(true); } else { rm.setStatus(new Status(IStatus.ERROR, GdbUIPlugin.PLUGIN_ID, "Service is not available.")); } rm.done(); return; } IMultiTerminate multiTerminate = fTracker.getService(IMultiTerminate.class); if (multiTerminate != null) { multiTerminate.canTerminateSome(procDmcs, rm); } else { IProcesses procService = fTracker.getService(IProcesses.class); if (procService != null && procDmcs.length == 1) { procService.canTerminate(procDmcs[0], rm); } else { rm.setData(false);; rm.done(); } } }
Source:
<code>public ILifecycle getLifecycle() { <START> ModelNode lifecycle = get(node, propertyKeys, LIFECYCLE); <END> if (lifecycle.isDefined()) { return Lifecycle.fromJson(lifecycle); } else { return null; } }</code><technical_language>I this pattern, introduced 'has' for checking if there, is use. benefit is wont add node underlying json if 'not defined'</technical_language>

Target:
public ILifecycle getLifecycle() { if (node.has(LIFECYCLE)) { return Lifecycle.fromJson(get(node, propertyKeys, LIFECYCLE)); } else { return new Lifecycle.Builder().build(); } }
Source:
<code>public ValueMatcher makeMatcher(ColumnSelectorFactory factory) { return Filters.makeValueMatcher( factory, dimension, new DruidPredicateFactory() { @Override public Predicate<String> makeStringPredicate() { return new Predicate<String>() { @Override public boolean apply(String input) { if (input == null) { return false; } final float[] coordinate = SpatialDimensionRowTransformer.decode(input); return bound.contains(coordinate); } }; } @Override public DruidLongPredicate makeLongPredicate() { return new DruidLongPredicate() { @Override public boolean applyLong(long input) { return false; } }; } @Override public DruidFloatPredicate makeFloatPredicate() { <START> return new DruidFloatPredicate() <END> { @Override public boolean applyFloat(float input) { return false; } }; } } ); }</code><technical_language>Please replace a singleton</technical_language>

Target:
public ValueMatcher makeMatcher(ColumnSelectorFactory factory) { return Filters.makeValueMatcher( factory, dimension, new DruidPredicateFactory() { @Override public Predicate<String> makeStringPredicate() { return new Predicate<String>() { @Override public boolean apply(String input) { if (input == null) { return false; } final float[] coordinate = SpatialDimensionRowTransformer.decode(input); return bound.contains(coordinate); } }; } @Override public DruidLongPredicate makeLongPredicate() { return DruidLongPredicate.ALWAYS_FALSE; } @Override public DruidFloatPredicate makeFloatPredicate() { return DruidFloatPredicate.ALWAYS_FALSE; } } ); }
Source:
<code>public final void execute(BlockingRunnable runnable) { if (shutdown) { throw new RejectedExecutionException("Executor Service is already shutdown"); } if (runnable.isReady()) { doExecute(runnable); } else { if (!blockedTasks.offer(runnable)) { <START> throw new RejectedExecutionException("Queue is full"); <END> } } checkForUnblockTasks(); if (log.isTraceEnabled()) { log.tracef("Added a new task: %s task(s) are waiting", blockedTasks.size()); } }</code><technical_language>AFAICT queue is unlimited, need throw a RejectedExecutionException</technical_language>

Target:
public final void execute(BlockingRunnable runnable) { if (shutdown) { throw new RejectedExecutionException("Executor Service is already shutdown"); } if (runnable.isReady()) { doExecute(runnable); } else { blockedTasks.offer(runnable); } if (log.isTraceEnabled()) { log.tracef("Added a new task: %s task(s) are waiting", blockedTasks.size()); } }
Source:
<code>public Map<Tree, SymbolicBooleanConstraint> evaluateMethod(JavaFileScannerContext context, ExecutionState state, MethodTree tree) { result.clear(); if (tree.block() != null) { try { evaluateStatement(ImmutableList.of(state), tree.block()); } catch (SymbolicExecutionException e) { JavaTree javaTree = (JavaTree) tree; <START> LOGGER.debug("in " + context.getFile() + ": analysis of " + tree.simpleName().name() + " at line " + javaTree.getLine() + " failed: " + e.getMessage(), e); <END> result.clear(); } } return result; }</code><technical_language>I separate message logged info exception logged debug want pollute log a stacktrace times</technical_language>

Target:
public Map<Tree, SymbolicBooleanConstraint> evaluateMethod(JavaFileScannerContext context, ExecutionState state, MethodTree tree) { result.clear(); if (tree.block() != null) { try { evaluateStatement(ImmutableList.of(state), tree.block()); } catch (SymbolicExecutionException e) { JavaTree javaTree = (JavaTree) tree; LOGGER.info("in " + context.getFile() + ": analysis of " + tree.simpleName().name() + " at line " + javaTree.getLine() + " failed: " + e.getMessage()); LOGGER.debug(e); result.clear(); } } return result; }
Source:
<code>public void addItem(int category, Key<Technology> technology, UserProfileItem profileItem) { <START> if (category == POSITIVE_RECOMMENDATION) { <END> negativeRecItems.remove(technology.getString()); otherItems.remove(technology.getString()); positiveRecItems.put(technology.getString(), profileItem); } else if (category == NEGATIVE_RECOMMENDATION) { otherItems.remove(technology.getString()); positiveRecItems.remove(technology.getString()); negativeRecItems.put(technology.getString(), profileItem); } else if (category == OTHER) { positiveRecItems.remove(technology.getString()); negativeRecItems.remove(technology.getString()); otherItems.put(technology.getString(), profileItem); } }</code><technical_language>@edugfilho changing elseif switch? :-)</technical_language>

Target:
public void addItem(int category, Key<Technology> technology, UserProfileItem profileItem) { switch (category) { case POSITIVE_RECOMMENDATION: negativeRecItems.remove(technology.getString()); otherItems.remove(technology.getString()); positiveRecItems.put(technology.getString(), profileItem); break; case NEGATIVE_RECOMMENDATION: otherItems.remove(technology.getString()); positiveRecItems.remove(technology.getString()); negativeRecItems.put(technology.getString(), profileItem); break; case OTHER: positiveRecItems.remove(technology.getString()); negativeRecItems.remove(technology.getString()); otherItems.put(technology.getString(), profileItem); break; default: break; } }
Source:
<code>public void disablePlugins(Set<String> names) { synchronized (this) { for (String name : names) { Plugin active = running.get(name); if (active == null) { continue; } log.info(String.format("Disabling plugin %s", active.getName())); <START> File off = new File(pluginsDir, active.getSrcFile() + ".disabled"); <END> active.getSrcFile().renameTo(off); unloadPlugin(active); try { FileSnapshot snapshot = FileSnapshot.save(off); Plugin offPlugin = loadPlugin(name, off, snapshot); disabled.put(name, offPlugin); } catch (Throwable e) { log.warn(String.format( "Cannot load disabled plugin %s", active.getName()), e.getCause()); } } cleanInBackground(); } }</code><technical_language>wrong. path is included now. want is: File = new File(active.getSrcFile() + ".disabled"); File = new File(pluginsDir, active.getSrcFile().getName() + ".disabled");</technical_language>

Target:
public void disablePlugins(Set<String> names) { synchronized (this) { for (String name : names) { Plugin active = running.get(name); if (active == null) { continue; } log.info(String.format("Disabling plugin %s", active.getName())); File off = new File(active.getSrcFile() + ".disabled"); active.getSrcFile().renameTo(off); unloadPlugin(active); try { FileSnapshot snapshot = FileSnapshot.save(off); Plugin offPlugin = loadPlugin(name, off, snapshot); disabled.put(name, offPlugin); } catch (Throwable e) { log.warn(String.format( "Cannot load disabled plugin %s", active.getName()), e.getCause()); } } cleanInBackground(); } }
Source:
<code>protected DocumentModel getTokenDoc(NuxeoOAuth2ServiceProvider provider, String nxuser) throws RestOperationException { Map<String, Serializable> filter = new HashMap<>(); filter.put("serviceName", provider.getServiceName()); filter.put(NuxeoOAuth2Token.KEY_NUXEO_LOGIN, nxuser); List<DocumentModel> tokens = Framework.doPrivileged(() -> { List<DocumentModel> entries = provider.getCredentialDataStore().query(filter); <START> return entries.stream().filter(doc -> doc != null).collect(Collectors.toList()); <END> }); if (tokens.size() > 1) { throw new NuxeoException("Found multiple " + provider.getId() + " accounts for " + nxuser); } else if (tokens.size() == 0) { throw new RestOperationException("No token found for provider: " + provider.getId(), HttpServletResponse.SC_NOT_FOUND); } else { return tokens.get(0); } }</code><technical_language>filter(Objects::nonNull)</technical_language>

Target:
protected DocumentModel getTokenDoc(NuxeoOAuth2ServiceProvider provider, String nxuser) throws RestOperationException { Map<String, Serializable> filter = new HashMap<>(); filter.put("serviceName", provider.getServiceName()); filter.put(NuxeoOAuth2Token.KEY_NUXEO_LOGIN, nxuser); List<DocumentModel> tokens = Framework.doPrivileged(() -> { List<DocumentModel> entries = provider.getCredentialDataStore().query(filter); return entries.stream().filter(Objects::nonNull).collect(Collectors.toList()); }); if (tokens.size() > 1) { throw new NuxeoException("Found multiple " + provider.getId() + " accounts for " + nxuser); } else if (tokens.size() == 0) { throw new RestOperationException("No token found for provider: " + provider.getId(), HttpServletResponse.SC_NOT_FOUND); } else { return tokens.get(0); } }
Source:
<code>public TimeGraphControl(Composite parent, TimeGraphColorScheme colors) { super(parent, colors, SWT.NO_BACKGROUND | SWT.DOUBLE_BUFFERED); fItemData = new ItemData(); addFocusListener(this); addMouseListener(this); addMouseMoveListener(this); addMouseTrackListener(this); addMouseWheelListener(this); addTraverseListener(this); addKeyListener(this); addMenuDetectListener(this); addListener(SWT.MouseWheel, this); <START> addDisposeListener(new DisposeListener() { <END> @Override public void widgetDisposed(DisposeEvent e) { fResourceManager.dispose(); for (Font font : fFonts.values()) { font.dispose(); } } }); }</code><technical_language>lambda</technical_language>

Target:
public TimeGraphControl(Composite parent, TimeGraphColorScheme colors) { super(parent, colors, SWT.NO_BACKGROUND | SWT.DOUBLE_BUFFERED); fItemData = new ItemData(); addFocusListener(this); addMouseListener(this); addMouseMoveListener(this); addMouseTrackListener(this); addMouseWheelListener(this); addTraverseListener(this); addKeyListener(this); addMenuDetectListener(this); addListener(SWT.MouseWheel, this); addDisposeListener((e) -> { fResourceManager.dispose(); for (Font font : fFonts.values()) { font.dispose(); } }); }
Source:
<code>private int writeDebugInfo(final OutputStream os) throws IOException { int byteCount = 0; os.write(B_DEBUG_BEGIN); byteCount += B_DEBUG_BEGIN.length; final DateTime now = new DateTime(DateTimeZone.UTC); final InetAddress ip; try { <START> ip = InetAddress.getLocalHost(); <END> } catch (final UnknownHostException e) { throw new MyNakadiRuntimeException1("problem getting servers ip", e); } final String debugString = "Batch written at " + now.toString() + " from server " + ip.getHostAddress(); final byte[] debug = debugString.getBytes(UTF_8); os.write(debug); byteCount += debug.length; os.write(B_DEBUG_END); byteCount += B_DEBUG_END.length; return byteCount; }</code><technical_language>show real IP, some docker-local IP</technical_language>

Target:
private int writeDebugInfo(final OutputStream os) throws IOException { int byteCount = 0; os.write(B_DEBUG_BEGIN); byteCount += B_DEBUG_BEGIN.length; final DateTime now = new DateTime(DateTimeZone.UTC); final String stackVersion = System.getenv("STACK_VERSION"); final String debugString = "Batch written at " + now.toString() + " from server " + stackVersion; final byte[] debug = debugString.getBytes(UTF_8); os.write(debug); byteCount += debug.length; os.write(B_DEBUG_END); byteCount += B_DEBUG_END.length; return byteCount; }
Source:
<code>public void testFullTokenIdentifierRoundTrip() throws Throwable { Text renewer = new Text("renewerName"); FullCredentialsTokenIdentifier id = new FullCredentialsTokenIdentifier( landsatUri, new Text(), renewer, new MarshalledCredentials("a", "b", ""), new EncryptionSecrets(), ""); FullCredentialsTokenIdentifier result = S3ATestUtils.roundTrip(id, null); String ids = id.toString(); assertEquals("URI in " + ids, id.getUri(), result.getUri()); assertEquals("credentials in " + ids, id.getMarshalledCredentials(), result.getMarshalledCredentials()); <START> assertEquals(renewer, result.getRenewer()); <END> }</code><technical_language>message "renewer in " + ids</technical_language>

Target:
public void testFullTokenIdentifierRoundTrip() throws Throwable { Text renewer = new Text("renewerName"); FullCredentialsTokenIdentifier id = new FullCredentialsTokenIdentifier( landsatUri, new Text(), renewer, new MarshalledCredentials("a", "b", ""), new EncryptionSecrets(), ""); FullCredentialsTokenIdentifier result = S3ATestUtils.roundTrip(id, null); String ids = id.toString(); assertEquals("URI in " + ids, id.getUri(), result.getUri()); assertEquals("credentials in " + ids, id.getMarshalledCredentials(), result.getMarshalledCredentials()); assertEquals("renewer in " + ids, renewer, result.getRenewer()); }
Source:
<code>private void processStopFileRequest(Intent intent) { OCFile file = intent.getExtras().getParcelable(EXTRA_FILE); try { if(file.equals(mFile)) { processStopRequest(true); } } catch (NullPointerException e) { <START> e.printStackTrace(); <END> } }</code><technical_language>I instead of printing stack write log @davivel @tobiasKaminsky thoughts</technical_language>

Target:
private void processStopFileRequest(Intent intent) { OCFile file = intent.getExtras().getParcelable(EXTRA_FILE); try { if(file.equals(mFile)) { processStopRequest(true); } } catch (NullPointerException e) { Log_OC.e(TAG, "NullPointerException while stopping on OCFile ", e); } }
Source:
<code>public void shouldCreateRabbitMQContainerWithExchange() throws IOException, InterruptedException { try (RabbitMQContainer container = new RabbitMQContainer()) { container.withExchange("test-exchange", "direct"); container.start(); <START> container.waitUntilContainerStarted(); <END> assertThat(container.execInContainer("rabbitmqctl", "list_exchanges").getStdout()) .containsPattern("test-exchange\\s+direct"); } }</code><technical_language>waitUntilContainerStarted is executed .start(), need do</technical_language>

Target:
public void shouldCreateRabbitMQContainerWithExchange() throws IOException, InterruptedException { try (RabbitMQContainer container = new RabbitMQContainer()) { container.withExchange("test-exchange", "direct"); container.start(); assertThat(container.execInContainer("rabbitmqctl", "list_exchanges").getStdout()) .containsPattern("test-exchange\\s+direct"); } }
Source:
<code>public void testPurgeDocumentById() throws CouchbaseLiteException { String docID = "doc1"; MutableDocument doc = createMutableDocument(docID); doc.setValue("type", "profile"); doc.setValue("name", "Scott"); try { db.purge(docID); fail(); } catch (CouchbaseLiteException e) { if (e.getCode() == CBLError.Code.CBLErrorNotFound) ; else <START> fail(); <END> } assertEquals("profile", doc.getValue("type")); assertEquals("Scott", doc.getValue("name")); Document savedDoc = save(doc); db.purge(docID); assertNull(db.getDocument(docID)); }</code><technical_language>add Assert instead of if/else here</technical_language>

Target:
public void testPurgeDocumentById() throws CouchbaseLiteException { String docID = "doc1"; MutableDocument doc = createMutableDocument(docID); doc.setValue("type", "profile"); doc.setValue("name", "Scott"); try { db.purge(docID); fail(); } catch (CouchbaseLiteException e) { assertEquals(e.getCode(), CBLError.Code.CBLErrorNotFound); } assertEquals("profile", doc.getValue("type")); assertEquals("Scott", doc.getValue("name")); Document savedDoc = save(doc); db.purge(docID); assertNull(db.getDocument(docID)); }