auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void adjustKVMDataForBlockSD() { if (getVm().getOrigin() == OriginType.KVM && getActionState() == CommandActionState.EXECUTE && getStorageDomain() != null && getStorageDomain().getStorageType().isBlockDomain()) { getVm().getImages().forEach(image -> { image.setActualSizeInBytes(image.getSize()); image.setVolumeType(VolumeType.Preallocated); }); <START> log.info("Block <END> Storage Domains do not support Sparseness. The Import is defaulting to Preallocated."); } }</code><technical_language>please add name of VM message, message more informative..</technical_language>

Target:
private void adjustKVMDataForBlockSD() { if (getVm().getOrigin() == OriginType.KVM && getActionState() == CommandActionState.EXECUTE && getStorageDomain() != null && getStorageDomain().getStorageType().isBlockDomain()) { getVm().getImages().forEach(image -> { image.setActualSizeInBytes(image.getSize()); image.setVolumeType(VolumeType.Preallocated); }); log.info("Block Storage Domains do not support Sparseness. The Importing of VM '{}' is defaulting to Preallocated.", getVm().getId()); } }
Source:
<code>public void covers() { Map<String, TrackingToken> newTokens = new HashMap<>(); newTokens.put("token1", new GlobalSequenceTrackingToken(0)); newTokens.put("token2", new GlobalSequenceTrackingToken(0)); assertTrue(testSubject.covers(new MultiSourceTrackingToken(newTokens))); <START> newTokens.put("token2", null); <END> MultiSourceTrackingToken tokenWithNullConstituent = new MultiSourceTrackingToken(newTokens); assertTrue(testSubject.covers(tokenWithNullConstituent)); assertTrue(tokenWithNullConstituent.covers(tokenWithNullConstituent)); }</code><technical_language>honest, prefer a separate named test class for this null case uncovered @sgrimm-sg. mind moving asserts in covers doesNotCover a method</technical_language>

Target:
public void covers() { Map<String, TrackingToken> newTokens = new HashMap<>(); newTokens.put("token1", new GlobalSequenceTrackingToken(0)); newTokens.put("token2", new GlobalSequenceTrackingToken(0)); assertTrue(testSubject.covers(new MultiSourceTrackingToken(newTokens))); }
Source:
<code>public Permissionable getParentPermissionable() { try{ if (FolderAPI.SYSTEM_FOLDER.equals(this.folder())) { PermissionableProxy host = new PermissionableProxy(); host.setIdentifier(this.host()); host.setInode(this.host()); return host; } else { Folder folder = new Folder(); <START> DotConnect dc = new DotConnect(); <END> dc.setSQL("select identifier from folder where inode = ?"); dc.addParam(this.folder()); folder.setIdentifier(dc.loadObjectResults().get(0).get("identifier").toString()); folder.setInode(this.folder()); return folder; } }catch (Exception e) { throw new DotRuntimeException(e.getMessage(), e); } }</code><technical_language>if dotConnect here, mark method CloseDbIfOpened annotation</technical_language>

Target:
public Permissionable getParentPermissionable() { try{ if (FolderAPI.SYSTEM_FOLDER.equals(this.folder())) { PermissionableProxy host = new PermissionableProxy(); host.setIdentifier(this.host()); host.setInode(this.host()); return host; } else { return APILocator.getFolderAPI().find(this.folder(), APILocator.systemUser(), false); } }catch (Exception e) { throw new DotRuntimeException(e.getMessage(), e); } }
Source:
<code>public PoolDefinition(long size, MemoryUnit unit) { if (unit == null) { throw new NullPointerException("Unit cannot be null"); } <START> this.size = size; <END> this.unit = unit; this.serverResource = null; }</code><technical_language>size > 0 enforced</technical_language>

Target:
public PoolDefinition(long size, MemoryUnit unit) { if (unit == null) { throw new NullPointerException("Unit cannot be null"); } if (size <= 0) { throw new IllegalArgumentException("Pool must have a positive size"); } this.size = size; this.unit = unit; this.serverResource = null; }
Source:
<code><START> public DataSourceArray<BlockHeader> headerSource() { <END> DbSource<byte[]> dataSource = keyValueDataSource("headers"); BatchSourceWriter<byte[], byte[]> batchSourceWriter = new BatchSourceWriter<>(dataSource); WriteCache.BytesKey<byte[]> writeCache = new WriteCache.BytesKey<>(batchSourceWriter, WriteCache.CacheType.SIMPLE); writeCache.withSizeEstimators(MemSizeEstimator.ByteArrayEstimator, MemSizeEstimator.ByteArrayEstimator); writeCache.setFlushSource(true); ObjectDataSource<BlockHeader> objectDataSource = new ObjectDataSource<>(dataSource, Serializers.BlockHeaderSerializer, 0); DataSourceArray<BlockHeader> dataSourceArray = new DataSourceArray<>(objectDataSource); return dataSourceArray; }</code><technical_language>get rid of this. created manually run a migration</technical_language>

Target:
public DbSource<byte[]> headerSource() { return keyValueDataSource("headers"); }
Source:
<code>public boolean feasible(Optimizable innerTable, OptimizablePredicateList predList, Optimizer optimizer, CostEstimate outerCost, boolean wasHinted, boolean skipKeyCheck) throws StandardException { if(outerCost.isUninitialized() ||(outerCost.localCost()==0d)) { return false; } if (JoinStrategyUtil.isNonCoveringIndex(innerTable)) return false; AccessPath currentAccessPath = innerTable.getCurrentAccessPath(); boolean isSpark = false; boolean isForcedControl = false; boolean isOneRow = false; boolean isHinted = currentAccessPath.isHintedJoinStrategy(); if (innerTable instanceof FromBaseTable) { DataSetProcessorType dspt = ((FromBaseTable) innerTable).getDataSetProcessorTypeForAccessPath(currentAccessPath); <START> dspt.combine(((FromBaseTable) innerTable).getCompilerContext().getDataSetProcessorType()); <END> isSpark = dspt.isSpark(); isForcedControl = (dspt.isHinted() || dspt.isForced()) && !dspt.isSpark(); isOneRow = ((FromBaseTable) innerTable).isOneRowResultSet(); } return !outerCost.isOuterJoin() && (isSpark || (isForcedControl && isHinted)) && !isOneRow; }</code><technical_language>I need read dataSetProcessorType FromBaseTable, instead, ((FromBaseTable) innerTable).getCompilerContext().getDataSetProcessorType(), Spark is pre-set now</technical_language>

Target:
public boolean feasible(Optimizable innerTable, OptimizablePredicateList predList, Optimizer optimizer, CostEstimate outerCost, boolean wasHinted, boolean skipKeyCheck) throws StandardException { if(outerCost.isUninitialized() ||(outerCost.localCost()==0d)) { return false; } if (JoinStrategyUtil.isNonCoveringIndex(innerTable)) return false; AccessPath currentAccessPath = innerTable.getCurrentAccessPath(); boolean isSpark = false; boolean isForcedControl = false; boolean isOneRow = false; boolean isHinted = currentAccessPath.isHintedJoinStrategy(); if (innerTable instanceof FromBaseTable) { DataSetProcessorType dspt = (((FromBaseTable) innerTable).getCompilerContext().getDataSetProcessorType()); isSpark = optimizer.isForSpark(); isForcedControl = (dspt.isHinted() || dspt.isForced()) && !optimizer.isForSpark(); isOneRow = ((FromBaseTable) innerTable).isOneRowResultSet(); } return !outerCost.isOuterJoin() && (isSpark || (isForcedControl && isHinted)) && !isOneRow; }
Source:
<code>public int compareTo(PersonAttribute other) { int retValue; if ((retValue = OpenmrsUtil.compareWithNullAsGreatest(getAttributeType(), other.getAttributeType())) != 0) { return retValue; } <START> if ((retValue = isVoided().compareTo(other.isVoided())) != 0) { <END> return retValue; } if ((retValue = OpenmrsUtil.compareWithNullAsLatest(getDateCreated(), other.getDateCreated())) != 0) { return retValue; } if ((retValue = OpenmrsUtil.compareWithNullAsGreatest(getValue(), other.getValue())) != 0) { return retValue; } return OpenmrsUtil.compareWithNullAsGreatest(getPersonAttributeId(), other.getPersonAttributeId()); }</code><technical_language>supposed remove deprecated annotation change method code? delegating DefaultComparator anyways, i this deprecation invalid</technical_language>

Target:
public int compareTo(PersonAttribute other) { DefaultComparator paDComparator = new DefaultComparator(); return paDComparator.compare(this, other); }
Source:
<code>public void record(PlanOptimizer optimizer, long nanos) { requireNonNull(optimizer, "optimizer is null"); <START> stats.get(optimizer.getClass()).record(nanos); <END> }</code><technical_language>add check? requireNonNull(stats.get(...), "optimizer X registered")</technical_language>

Target:
public void record(PlanOptimizer optimizer, long nanos) { requireNonNull(optimizer, "optimizer is null"); OptimizerStats optimizerStats = requireNonNull(stats.get(optimizer.getClass()), "optimizer is not registered"); optimizerStats.record(nanos); }
Source:
<code>public void testRunStarted(String runName, int testCount) { if (mExpectedTestCount == 0) { mExpectedTestCount = testCount; <START> } <END> mTestRunName = runName; mIsRunComplete = false; }</code><technical_language>add else a log</technical_language>

Target:
public void testRunStarted(String runName, int testCount) { if (mExpectedTestCount == 0) { mExpectedTestCount = testCount; } else { CLog.w("%s calls testRunStarted more than once", runName); } mTestRunName = runName; mIsRunComplete = false; }
Source:
<code>public void pullFromProjectRepo() throws Exception { SWTBotTree repositoriesTree = <START> repoView.bot().tree(); <END> repositoriesTree.select(0); repositoriesTree.contextMenu("Pull...").click(); bot.shell("Pull").setFocus(); assertTrue("Remote combo misses items", bot.comboBox().items().length > 1); bot.button(IDialogConstants.FINISH_LABEL).click(); ShellWithTextPrefixMatcher shellWithTextPrefixMatcher = new ShellWithTextPrefixMatcher( "Pull Result"); bot.waitUntil(waitForShell(shellWithTextPrefixMatcher)); shellWithTextPrefixMatcher.getFoundShell().setFocus(); bot.button(IDialogConstants.OK_LABEL).click(); }</code><technical_language>getOrOpenView() here</technical_language>

Target:
public void pullFromProjectRepo() throws Exception { SWTBotTree repositoriesTree = getOrOpenView().bot().tree(); repositoriesTree.select(0); repositoriesTree.contextMenu("Pull...").click(); bot.shell("Pull").setFocus(); assertTrue("Remote combo misses items", bot.comboBox().items().length > 1); bot.button(IDialogConstants.FINISH_LABEL).click(); ShellWithTextPrefixMatcher shellWithTextPrefixMatcher = new ShellWithTextPrefixMatcher( "Pull Result"); bot.waitUntil(waitForShell(shellWithTextPrefixMatcher)); shellWithTextPrefixMatcher.getFoundShell().setFocus(); bot.button(IDialogConstants.OK_LABEL).click(); }
Source:
<code><START> private Group setUpGroup(User u0, User u1) throws PrivilegeException, InternalErrorException, UserNotExistsException, VoExistsException, GroupExistsException, VoNotExistsException, GroupNotExistsException, AlreadyMemberException, MemberNotExistsException, WrongReferenceAttributeValueException, WrongAttributeValueException, ExtendMembershipException, WrongAttributeAssignmentException, AttributeNotExistsException, ExternallyManagedException, PolicyNotExistsException { <END> Vo vo = new Vo(); vo.setShortName("testVo"); vo.setName("Test VO"); perun.getVosManager().createVo(sess, vo); Group authGroup = new Group(); authGroup.setShortName("testGroup"); authGroup.setName("Test Group"); Member m0 = perun.getMembersManager().createMember(sess, vo, u0); Member m1 = perun.getMembersManager().createMember(sess, vo, u1); perun.getGroupsManager().createGroup(sess, vo, authGroup); perun.getGroupsManager().addMember(sess, authGroup, m0); perun.getGroupsManager().addMember(sess, authGroup, m1); return authGroup; }</code><technical_language>Please, remove this useless throw declaration. Otherwise, is working, better</technical_language>

Target:
private Group setUpGroup(User u0, User u1) throws PrivilegeException, InternalErrorException, UserNotExistsException, VoExistsException, GroupExistsException, VoNotExistsException, GroupNotExistsException, AlreadyMemberException, MemberNotExistsException, WrongReferenceAttributeValueException, WrongAttributeValueException, ExtendMembershipException, WrongAttributeAssignmentException, AttributeNotExistsException, ExternallyManagedException { Vo vo = new Vo(); vo.setShortName("testVo"); vo.setName("Test VO"); perun.getVosManager().createVo(sess, vo); Group authGroup = new Group(); authGroup.setShortName("testGroup"); authGroup.setName("Test Group"); Member m0 = perun.getMembersManager().createMember(sess, vo, u0); Member m1 = perun.getMembersManager().createMember(sess, vo, u1); perun.getGroupsManager().createGroup(sess, vo, authGroup); perun.getGroupsManager().addMember(sess, authGroup, m0); perun.getGroupsManager().addMember(sess, authGroup, m1); return authGroup; }
Source:
<code>protected void createCacheManagers() throws Throwable { ConfigurationBuilder builder = getDefaultClusteredCacheConfig(getCacheMode(), true); <START> builder.clustering().stateTransfer().chunkSize(128); <END> createClusteredCaches(4, cacheName(), builder); }</code><technical_language>I originally set this 2 intermediate values split test. happen 128</technical_language>

Target:
protected void createCacheManagers() throws Throwable { ConfigurationBuilder builder = getDefaultClusteredCacheConfig(getCacheMode(), true); builder.clustering().stateTransfer().chunkSize(2); createClusteredCaches(4, cacheName(), builder); }
Source:
<code>public boolean include(TreeWalk tw) throws MissingObjectException, IncorrectObjectTypeException, IOException { final int wm = tw.getRawMode(workingTree); if (wm == 0) return true; final int cnt = tw.getTreeCount(); final int dm = tw.getRawMode(dirCache); WorkingTreeIterator workingTreeIterator = workingTree(tw); if (dm == 0) { if (honorIgnores && workingTreeIterator.isEntryIgnored()) { <START> ignoredPaths.add(workingTreeIterator.getEntryPathString()); <END> int i = 0; for (; i < cnt; i++) { if (i == dirCache || i == workingTree) continue; if (tw.getRawMode(i) != 0) break; } return i == cnt ? false : true; } else { return true; } } if (tw.isSubtree()) return true; for (int i = 0; i < cnt; i++) { if (i == dirCache || i == workingTree) continue; if (tw.getRawMode(i) != dm || !tw.idEqual(i, dirCache)) return true; } WorkingTreeIterator wi = workingTreeIterator; DirCacheIterator di = tw.getTree(dirCache, DirCacheIterator.class); return wi.isModified(di.getDirCacheEntry(), true); }</code><technical_language>place add stuff 'ignoredPaths' is a block enter if find entry in index. is files listed in .gitignore added index before? git init echo a > a git add a git commit -m initial echo b > b git add b echo b > .gitignore processing b dm 0 b is ignored, or</technical_language>

Target:
public boolean include(TreeWalk tw) throws MissingObjectException, IncorrectObjectTypeException, IOException { final int wm = tw.getRawMode(workingTree); if (wm == 0) return true; final int cnt = tw.getTreeCount(); final int dm = tw.getRawMode(dirCache); WorkingTreeIterator wi = workingTree(tw); if (dm == 0) { if (honorIgnores && wi.isEntryIgnored()) { ignoredPaths.add(wi.getEntryPathString()); int i = 0; for (; i < cnt; i++) { if (i == dirCache || i == workingTree) continue; if (tw.getRawMode(i) != 0) break; } return i == cnt ? false : true; } else { return true; } } if (tw.isSubtree()) return true; for (int i = 0; i < cnt; i++) { if (i == dirCache || i == workingTree) continue; if (tw.getRawMode(i) != dm || !tw.idEqual(i, dirCache)) return true; } DirCacheIterator di = tw.getTree(dirCache, DirCacheIterator.class); return wi.isModified(di.getDirCacheEntry(), true); }
Source:
<code>public void startOfExecution(Scope functionScope) { operandsWithIssues.clear(); <START> super.startOfExecution(functionScope); <END> }</code><technical_language>@ivandalbosco remove call super,</technical_language>

Target:
public void startOfExecution(Scope functionScope) { operandsWithIssues.clear(); }
Source:
<code>private void restoreStudentFeedbackResponseToDatastore(FeedbackResponseAttributes response) throws InvalidParametersException, EntityDoesNotExistException { <START> frLogic.createFeedbackResponses(Arrays.asList(response)); <END> fsLogic.addStudentRespondent(response.giver, response.feedbackSessionName, response.courseId); }</code><technical_language>Hmm. method is restoring feedback response (i.e. update/create values). However, frLogic.createFeedbackResponses update existing one</technical_language>

Target:
private void restoreStudentFeedbackResponseToDatastore(FeedbackResponseAttributes response) throws InvalidParametersException, EntityDoesNotExistException, EntityAlreadyExistsException { restoreFeedbackResponse(response); fsLogic.addStudentRespondent(response.giver, response.feedbackSessionName, response.courseId); }
Source:
<code>public RqWithBody(final Request req, final CharSequence bdy) { super( <START> new RqOf( <END> req::head, () -> new ByteArrayInputStream( new Utf8String(bdy.toString()).asBytes() ) ) ); }</code><technical_language>@fanifieiev above</technical_language>

Target:
public RqWithBody(final Request req, final CharSequence bdy) { super( new RequestOf( req::head, () -> new ByteArrayInputStream( new Utf8String(bdy.toString()).asBytes() ) ) ); }
Source:
<code>public void visit(DataChartStringDescriptor<?> desc) { <START> setType(EnumSet.of(DescriptorType.STRING)); <END> }</code><technical_language>replace fType.add(DescriptorType.STRING); idea EnumSet is values add() set, care for current contents. reading check contains(), utility methods isNumer() proposed above</technical_language>

Target:
public void visit(DataChartStringDescriptor<?> desc) { fType.add(DescriptorType.STRING); }
Source:
<code>public String getOption() { final Function<Path, FileTime> createTimeComp = path -> { try { return Files.readAttributes(path, BasicFileAttributes.class).creationTime(); } catch (IOException e) { throw new RuntimeException(UNABLE_TO_DETERMINE_EXAM_DIR_ERROR, e); } }; System.err.println("HomeAwareVmOption"); System.err.println(UNPACK_DIRECTORY.toString()); System.err.println(super.getOption()); System.err.println("------------------------------------*************---------------------"); File f = new File("target/"); System.err.println(f.getAbsolutePath()); try (final Stream<Path> dirContents = Files.list(UNPACK_DIRECTORY.toPath())) { return dirContents .max(Comparator.comparing(createTimeComp)) .map(Path::toAbsolutePath) <START> .map(Path::toString) <END> .map( s -> { System.err.println(s); return s; }) .map(s -> StringUtils.replace(super.getOption(), KARAF_HOME, s)) .map(s -> s.replace('\\', '/')) .map(s -> s.replace("/bin/..", "/")) .orElseGet(super::getOption); } catch (IOException e) { throw new RuntimeException(UNABLE_TO_DETERMINE_EXAM_DIR_ERROR, e); } }</code><technical_language>This is Optional a stream is peek operation</technical_language>

Target:
public String getOption() { final Function<Path, FileTime> createTimeComp = path -> { try { return Files.readAttributes(path, BasicFileAttributes.class).creationTime(); } catch (IOException e) { throw new RuntimeException(UNABLE_TO_DETERMINE_EXAM_DIR_ERROR, e); } }; try (final Stream<Path> dirContents = Files.list(UNPACK_DIRECTORY.toPath())) { return dirContents .max(Comparator.comparing(createTimeComp)) .map(Path::toAbsolutePath) .map(Path::toString) .map( s -> { LOGGER.error(s); return s; }) .map(s -> StringUtils.replace(super.getOption(), KARAF_HOME, s)) .map(s -> s.replace('\\', '/')) .map(s -> s.replace("/bin/..", "/")) .orElseGet(super::getOption); } catch (IOException e) { throw new RuntimeException(UNABLE_TO_DETERMINE_EXAM_DIR_ERROR, e); } }
Source:
<code>public APIResult submit( @PathParam("extension-name") String extensionName, @Context HttpServletRequest request, @DefaultValue("") @QueryParam("doAs") String doAsUser, @QueryParam("jobName") String jobName, @FormDataParam("processes") List<FormDataBodyPart> processForms, @FormDataParam("feeds") List<FormDataBodyPart> feedForms, @FormDataParam("config") InputStream config) { checkIfExtensionServiceIsEnabled(); Map<EntityType, List<Entity>> entityMap; try { entityMap = getEntityList(extensionName, jobName, feedForms, processForms, config); <START> submitEntities(extensionName, jobName, entityMap, config, request); <END> } catch (FalconException | IOException | JAXBException e) { LOG.error("Error while submitting extension job: ", e); throw FalconWebException.newAPIException(e, Response.Status.INTERNAL_SERVER_ERROR); } return new APIResult(APIResult.Status.SUCCEEDED, "Extension job submitted successfully:" + jobName); }</code><technical_language>doAsUser knocked off? I now. But, is a plan enable later, removing it</technical_language>

Target:
public APIResult submit( @PathParam("extension-name") String extensionName, @Context HttpServletRequest request, @DefaultValue("") @QueryParam("doAs") String doAsUser, @QueryParam("jobName") String jobName, @FormDataParam("processes") List<FormDataBodyPart> processForms, @FormDataParam("feeds") List<FormDataBodyPart> feedForms, @FormDataParam("config") InputStream config) { checkIfExtensionServiceIsEnabled(); SortedMap<EntityType, List<Entity>> entityMap; try { entityMap = getEntityList(extensionName, jobName, feedForms, processForms, config); submitEntities(extensionName, jobName, entityMap, config, request); } catch (FalconException | IOException | JAXBException e) { LOG.error("Error while submitting extension job: ", e); throw FalconWebException.newAPIException(e, Response.Status.INTERNAL_SERVER_ERROR); } return new APIResult(APIResult.Status.SUCCEEDED, "Extension job submitted successfully:" + jobName); }
Source:
<code>synchronized void register(File watchFile, Store keyStore) throws IOException { File canonical = watchFile.getCanonicalFile(); File parentDir = canonical.getParentFile(); String fileName = canonical.getName(); Path dirPath = parentDir.toPath(); boolean watchRequired = false; Map<String, List<Store>> pathRegistration = watchedPaths.get(dirPath); List<Store> pathStores = null; if (pathRegistration == null) { watchRequired = true; pathRegistration = new HashMap<String, List<Store>>(); <START> pathStores = new LinkedList<Store>(); <END> } else { pathRegistration = new HashMap<String, List<Store>>(pathRegistration); List<Store> tmpStore = pathRegistration.get(fileName); if (tmpStore != null) { pathStores = new LinkedList<Store>(tmpStore); } else { pathStores = new LinkedList<Store>(); } } pathStores.add(keyStore); pathRegistration.put(fileName, pathStores); Map<Path, Map<String, List<Store>>> newWatchedPaths = new HashMap<Path, Map<String, List<Store>>>(watchedPaths); newWatchedPaths.put(dirPath, pathRegistration); watchedPaths = newWatchedPaths; if (watchRequired) { if (watchService == null) { watchService = fileSystem.newWatchService(); executor.execute(new EventTaker()); } WatchKey key = dirPath.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY); registrations.put(dirPath, key); } }</code><technical_language>LinkedList is worst list, if do lots of removes middle (unless tens of thousands of elements more). ArrayList ArrayDeque instead</technical_language>

Target:
synchronized void register(File watchFile, Store keyStore) throws IOException { File canonical = watchFile.getCanonicalFile(); File parentDir = canonical.getParentFile(); String fileName = canonical.getName(); Path dirPath = parentDir.toPath(); boolean watchRequired = false; Map<String, List<Store>> pathRegistration = watchedPaths.get(dirPath); List<Store> pathStores = null; if (pathRegistration == null) { watchRequired = true; pathRegistration = new HashMap<String, List<Store>>(); pathStores = new ArrayList<Store>(); } else { pathRegistration = new HashMap<String, List<Store>>(pathRegistration); List<Store> tmpStore = pathRegistration.get(fileName); if (tmpStore != null) { pathStores = new ArrayList<Store>(tmpStore); } else { pathStores = new ArrayList<Store>(); } } pathStores.add(keyStore); pathRegistration.put(fileName, pathStores); Map<Path, Map<String, List<Store>>> newWatchedPaths = new HashMap<Path, Map<String, List<Store>>>(watchedPaths); newWatchedPaths.put(dirPath, pathRegistration); watchedPaths = newWatchedPaths; if (watchRequired) { if (watchService == null) { watchService = fileSystem.newWatchService(); Thread pollThread = new Thread(new EventTaker(), "KeyStoreWatcher Daemon"); pollThread.setDaemon(true); pollThread.start(); } WatchKey key = dirPath.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY); registrations.put(dirPath, key); } }
Source:
<code>public String toString(JCCompilationUnit compilationUnit) { StringBuilder result = new StringBuilder("replace "); for (Replacement replacement : getReplacements(compilationUnit.endPositions)) { result <START> .append("position ") <END> .append(replacement.startPosition()) .append(":") .append(replacement.endPosition()) .append(" with \"") .append(replacement.replaceWith()) .append("\" "); } return result.toString(); }</code><technical_language>String.format? easier read. java result.append(String.format("position %d:%d \"%s\"", replacement.startPosition(), replacement.endPosition(), replacement.replaceWith())</technical_language>

Target:
public String toString(JCCompilationUnit compilationUnit) { StringBuilder result = new StringBuilder("replace "); for (Replacement replacement : getReplacements(compilationUnit.endPositions)) { result.append( String.format( "position %d:%d with \"%s\" ", replacement.startPosition(), replacement.endPosition(), replacement.replaceWith())); } return result.toString(); }
Source:
<code>public Page getOutput() { if (unfinishedWork != null) { boolean finished = unfinishedWork.process(); updateMemoryReservation(); <START> if (finished) { <END> unfinishedWork = null; } else { return null; } } if (!finishing) { return null; } if (outputIterator == null) { outputIterator = groupedTopNBuilder.buildResult(); } Page output = null; if (outputIterator.hasNext()) { Page page = outputIterator.next(); Block[] blocks = new Block[page.getChannelCount()]; for (int i = 0; i < outputChannels.size(); i++) { blocks[i] = page.getBlock(outputChannels.get(i)); } output = new Page(blocks); } updateMemoryReservation(); return output; }</code><technical_language>I easier read this inverted (and else omitted)</technical_language>

Target:
public Page getOutput() { if (unfinishedWork != null) { boolean finished = unfinishedWork.process(); updateMemoryReservation(); if (!finished) { return null; } unfinishedWork = null; } if (!finishing) { return null; } if (outputIterator == null) { outputIterator = groupedTopNBuilder.buildResult(); } Page output = null; if (outputIterator.hasNext()) { Page page = outputIterator.next(); Block[] blocks = new Block[page.getChannelCount()]; for (int i = 0; i < outputChannels.size(); i++) { blocks[i] = page.getBlock(outputChannels.get(i)); } output = new Page(blocks); } updateMemoryReservation(); return output; }
Source:
<code>public void getAssignedGroupsResourceMember() throws Exception { System.out.println(CLASS_NAME + "getAssignedGroupsResourceMember"); vo = setUpVo(); member = setUpMember(vo); group = setUpGroup(vo, member); facility = setUpFacility(); resource = setUpResource(); resourcesManager.assignGroupToResource(sess, group, resource); List<Group> groups = resourcesManager.getAssignedGroups(sess, resource, member); <START> groups.forEach(System.out::println); <END> assertTrue("only one group should be assigned",groups.size() == 1); assertTrue("our group should be assigned",groups.contains(group)); }</code><technical_language>do print objects in tests, for debug writing code. Test output name in case of fail, reason for it</technical_language>

Target:
public void getAssignedGroupsResourceMember() throws Exception { System.out.println(CLASS_NAME + "getAssignedGroupsResourceMember"); vo = setUpVo(); member = setUpMember(vo); group = setUpGroup(vo, member); facility = setUpFacility(); resource = setUpResource(); resourcesManager.assignGroupToResource(sess, group, resource); List<Group> groups = resourcesManager.getAssignedGroups(sess, resource, member); assertTrue("only one group should be assigned",groups.size() == 1); assertTrue("our group should be assigned",groups.contains(group)); }
Source:
<code>@Override public <K, V> ModelsComposition fit(DatasetBuilder<K, V> datasetBuilder, IgniteBiFunction<K, V, Vector> featureExtractor, IgniteBiFunction<K, V, Double> lbExtractor) { MLLogger log = environment.logger(getClass()); log.log(MLLogger.VerboseLevel.MIN, "Start learning"); Long startTs = System.currentTimeMillis(); List<Promise<ModelOnFeaturesSubspace>> learnedModelsF = new ArrayList<>(); for (int i = 0; i < ensembleSize; i++) { <START> learnedModelsF.add(environment.parallelismStrategy().submit(() -> <END> learnModel(datasetBuilder, featureExtractor, lbExtractor) )); } List<Model<Vector, Double>> models = learnedModelsF.stream() .map(Promise::unsafeGet) .peek(model -> log.log(MLLogger.VerboseLevel.MAX, model)) .collect(Collectors.toList()); double learningTime = (double)(System.currentTimeMillis() - startTs) / 1000.0; log.log(MLLogger.VerboseLevel.MID, "The training time was %.2fs", learningTime); log.log(MLLogger.VerboseLevel.MIN, "Learning finished"); return new ModelsComposition(models, predictionsAggregator); }</code><technical_language>Strange part of code, need a time understand happened</technical_language>

Target:
@Override public <K, V> ModelsComposition fit(DatasetBuilder<K, V> datasetBuilder, IgniteBiFunction<K, V, Vector> featureExtractor, IgniteBiFunction<K, V, Double> lbExtractor) { MLLogger log = environment.logger(getClass()); log.log(MLLogger.VerboseLevel.LOW, "Start learning"); Long startTs = System.currentTimeMillis(); List<IgniteSupplier<ModelOnFeaturesSubspace>> tasks = new ArrayList<>(); for(int i = 0; i < ensembleSize; i++) tasks.add(() -> learnModel(datasetBuilder, featureExtractor, lbExtractor)); List<Model<Vector, Double>> models = environment.parallelismStrategy().submit(tasks) .stream().map(Promise::unsafeGet) .collect(Collectors.toList()); double learningTime = (double)(System.currentTimeMillis() - startTs) / 1000.0; log.log(MLLogger.VerboseLevel.LOW, "The training time was %.2fs", learningTime); log.log(MLLogger.VerboseLevel.LOW, "Learning finished"); return new ModelsComposition(models, predictionsAggregator); }
Source:
<code>private static ProxyOptions attemptToLoadJavaProxy(Configuration configuration, String type) { if (!Boolean.parseBoolean(configuration.get(JAVA_PROXY_PREREQUISITE))) { return null; } String host = configuration.get(type + "." + JAVA_PROXY_HOST); if (CoreUtils.isNullOrEmpty(host)) { return null; } int port; try { port = Integer.parseInt(configuration.get(type + "." + JAVA_PROXY_PORT)); } catch (NumberFormatException ex) { <START> port = HTTPS.equals(type) ? 443 : 80; <END> } ProxyOptions proxyOptions = new ProxyOptions(Type.HTTP, new InetSocketAddress(host, port)) .setNonProxyHosts(configuration.get(JAVA_NON_PROXY_HOSTS)); String username = configuration.get(type + "." + JAVA_PROXY_USER); String password = configuration.get(type + "." + JAVA_PROXY_PASSWORD); if (username != null && password != null) { proxyOptions.setCredentials(username, password); } return proxyOptions; }</code><technical_language>Consider making named constants DEFAULT_HTTPS_PORT DEFAULT_HTTP_PORT</technical_language>

Target:
private static ProxyOptions attemptToLoadJavaProxy(Configuration configuration, String type) { if (!Boolean.parseBoolean(configuration.get(JAVA_PROXY_PREREQUISITE))) { return null; } String host = configuration.get(type + "." + JAVA_PROXY_HOST); if (CoreUtils.isNullOrEmpty(host)) { return null; } int port; try { port = Integer.parseInt(configuration.get(type + "." + JAVA_PROXY_PORT)); } catch (NumberFormatException ex) { port = HTTPS.equals(type) ? DEFAULT_HTTPS_PORT : DEFAULT_HTTP_PORT; } ProxyOptions proxyOptions = new ProxyOptions(Type.HTTP, new InetSocketAddress(host, port)) .setNonProxyHosts(configuration.get(JAVA_NON_PROXY_HOSTS)); String username = configuration.get(type + "." + JAVA_PROXY_USER); String password = configuration.get(type + "." + JAVA_PROXY_PASSWORD); if (username != null && password != null) { proxyOptions.setCredentials(username, password); } return proxyOptions; }
Source:
<code>public static byte[] concat(Bytes... listOfBytes) { int offset = 0; int counter = 0; for (Bytes b : listOfBytes) { <START> counter += b.length() + 1; <END> } byte[] data = new byte[counter]; for (Bytes b : listOfBytes) { writeVint(data, offset, b.length()); offset++; b.copyTo(0, b.length(), data, offset); offset += b.length(); } return data; }</code><technical_language>variable lenght int more byte, add 1. I another method calculates expected length of vint called here. This method a simpler form of writeVint basically returns number of times writeVint increment offset in implementation</technical_language>

Target:
public static byte[] concat(Bytes... listOfBytes) { int offset = 0; int size = 0; for (Bytes b : listOfBytes) { size += b.length() + checkVlen(b.length()); } byte[] data = new byte[size]; for (Bytes b : listOfBytes) { offset = writeVint(data, offset, b.length()); b.copyTo(0, b.length(), data, offset); offset += b.length(); } return data; }
Source:
<code>public String getLoginFromSessionId(String sessionId) { try { return sessionStore.get(sessionId).getUserName(); } catch (Exception e) { return ""; <START> } <END> }</code><technical_language>log it</technical_language>

Target:
public String getLoginFromSessionId(String sessionId) { try { return sessionStore.get(sessionId).getUserName(); } catch (Exception e) { LOGGER.debug("Invalid session : " + sessionId); return ""; } }
Source:
<code>public String posts(Model model, @PathVariable String slug, @RequestParam(required = false, defaultValue = "1") int page, @RequestParam(required = false) String query, @RequestParam(required = false) String category, @RequestParam(required = false, defaultValue = "false") boolean showAll, @RequestParam(required = false, defaultValue = "false") boolean archived) { Site site = Site.fromSlug(slug); <START> ensureCanDoThis(site,Permission.SEE_POSTS); <END> Collection<Post> posts = (archived) ? site.getArchivedPostsSet() : site.getPostSet(); if (!Strings.isNullOrEmpty(category)) { Category cat = site.categoryForSlug(category); posts = cat.getPostsSet().stream() .filter(p -> (archived) ? p.getArchivedSite() != null : p.getSite() != null) .collect(Collectors.toSet()); model.addAttribute("category", cat); } if(!showAll) { posts = posts.stream().filter(post -> !post.isStaticPost()).collect(Collectors.toList()); } if (!Strings.isNullOrEmpty(query)) { posts = searchPosts(posts, query); } SearchUtils.Partition<Post> partition = new SearchUtils.Partition<>(posts, Post.CREATION_DATE_COMPARATOR, PER_PAGE, page); model.addAttribute("site", site); model.addAttribute("query", query); model.addAttribute("partition", partition); model.addAttribute("posts", partition.getItems()); return (archived) ? "fenixedu-cms/archivedPosts" : "fenixedu-cms/posts"; }</code><technical_language>SEE_POSTS permission</technical_language>

Target:
public String posts(Model model, @PathVariable String slug, @RequestParam(required = false, defaultValue = "1") int page, @RequestParam(required = false) String query, @RequestParam(required = false) String category, @RequestParam(required = false, defaultValue = "false") boolean showAll, @RequestParam(required = false, defaultValue = "false") boolean archived) { Site site = Site.fromSlug(slug); ensureCanDoThis(site,Permission.SEE_POSTS); if (archived) { ensureCanDoThis(site, Permission.DELETE_POSTS); } Collection<Post> posts = (archived) ? site.getArchivedPostsSet() : site.getPostSet(); if (!Strings.isNullOrEmpty(category)) { Category cat = site.categoryForSlug(category); posts = cat.getPostsSet().stream() .filter(p -> (archived) ? p.getArchivedSite() != null : p.getSite() != null) .collect(Collectors.toSet()); model.addAttribute("category", cat); } if(!showAll) { posts = posts.stream().filter(post -> !post.isStaticPost()).collect(Collectors.toList()); } if (!Strings.isNullOrEmpty(query)) { posts = searchPosts(posts, query); } SearchUtils.Partition<Post> partition = new SearchUtils.Partition<>(posts, Post.CREATION_DATE_COMPARATOR, PER_PAGE, page); model.addAttribute("site", site); model.addAttribute("query", query); model.addAttribute("partition", partition); model.addAttribute("posts", partition.getItems()); return (archived) ? "fenixedu-cms/archivedPosts" : "fenixedu-cms/posts"; }
Source:
<code>public OperatingSystem getImage(final String id) { return find(listImages(), new Predicate<OperatingSystem>() { @Override public boolean apply(OperatingSystem input) { <START> return input.equals(id); <END> } }, null); }</code><technical_language>OperatingSystem.equals(String)</technical_language>

Target:
public OperatingSystem getImage(final String id) { return find(listImages(), new Predicate<OperatingSystem>() { @Override public boolean apply(OperatingSystem input) { return input.getId().equals(id); } }, null); }
Source:
<code>private RecognizeOptions getRecognizeOptionsProperties(RecognizeOptions userProvidedOptions) { if (userProvidedOptions != null) { <START> return new RecognizeOptions() .setPollInterval(userProvidedOptions.getPollInterval()) .setFormContentType(userProvidedOptions.getFormContentType()) .setIncludeTextContent(userProvidedOptions.isIncludeTextContent()); <END> } else { return new RecognizeOptions(); } }</code><technical_language>do a copy of user-provided options here</technical_language>

Target:
private RecognizeOptions getRecognizeOptionsProperties(RecognizeOptions userProvidedOptions) { if (userProvidedOptions != null) { return userProvidedOptions; } else { return new RecognizeOptions(); } }
Source:
<code>private List<Integer> createProxyPorts(int portCount) { PortChooser portChooser = new PortChooser(); int firstProxyPort = portChooser.chooseRandomPorts(portCount); List<Integer> proxyPorts = new ArrayList<>(portCount); <START> for (int i = 0; i < portCount; i++) { <END> proxyPorts.add(firstProxyPort + i); } return proxyPorts; }</code><technical_language>IntStream.range(portCount).map(i -> firstProxyPort + i).collector(Collectors::toList())</technical_language>

Target:
private List<Integer> createProxyPorts(int portCount) { PortChooser portChooser = new PortChooser(); int firstProxyPort = portChooser.chooseRandomPorts(portCount); return IntStream .range(0, portCount) .map(i -> firstProxyPort + i) .boxed() .collect(Collectors.toList()); }
Source:
<code><START> private BigDecimal getBigDecimalLowerBoundFromFloatString(String floatStr) <END> { BigDecimal convertedBD; try { convertedBD = new BigDecimal(floatStr); } catch (NumberFormatException nfe) { return null; } if (lowerStrict) { convertedBD = convertedBD.setScale(0, RoundingMode.FLOOR); } else { convertedBD = convertedBD.setScale(0, RoundingMode.CEILING); } return convertedBD; }</code><technical_language>@Nullable</technical_language>

Target:
private BigDecimal getBigDecimalLowerBoundFromFloatString(String floatStr) { BigDecimal convertedBD; try { convertedBD = new BigDecimal(floatStr); } catch (NumberFormatException nfe) { return null; } if (lowerStrict) { return convertedBD.setScale(0, RoundingMode.FLOOR); } else { return convertedBD.setScale(0, RoundingMode.CEILING); } }
Source:
<code>public synchronized void addBinding(final Binding binding) throws Exception { <START> server.callBrokerPlugins(server.hasBrokerPlugins() ? plugin -> plugin.beforeAddBinding(binding) : null); <END> addressManager.addBinding(binding); TypedProperties props = new TypedProperties(); props.putIntProperty(ManagementHelper.HDR_BINDING_TYPE, binding.getType().toInt()); props.putSimpleStringProperty(ManagementHelper.HDR_ADDRESS, binding.getAddress()); props.putSimpleStringProperty(ManagementHelper.HDR_CLUSTER_NAME, binding.getClusterName()); props.putSimpleStringProperty(ManagementHelper.HDR_ROUTING_NAME, binding.getRoutingName()); props.putLongProperty(ManagementHelper.HDR_BINDING_ID, binding.getID()); props.putIntProperty(ManagementHelper.HDR_DISTANCE, binding.getDistance()); Filter filter = binding.getFilter(); if (filter != null) { props.putSimpleStringProperty(ManagementHelper.HDR_FILTERSTRING, filter.getFilterString()); } String uid = UUIDGenerator.getInstance().generateStringUUID(); if (logger.isDebugEnabled()) { logger.debug("ClusterCommunication::Sending notification for addBinding " + binding + " from server " + server); } managementService.sendNotification(new Notification(uid, CoreNotificationType.BINDING_ADDED, props)); server.callBrokerPlugins(server.hasBrokerPlugins() ? plugin -> plugin.afterAddBinding(binding) : null); }</code><technical_language>Due default callBrokerPlugins other wierd reasons dependent JIT works compilations/inlining/interface optimization turn into: if(server.hasBrokerPlugins()){ .... } noticed is "cold path" of broker is fine left is in this place too: a hot path. suggestion is for wider puporses :+1:</technical_language>

Target:
public synchronized void addBinding(final Binding binding) throws Exception { if (server.hasBrokerPlugins()) { server.callBrokerPlugins(plugin -> plugin.beforeAddBinding(binding)); } addressManager.addBinding(binding); TypedProperties props = new TypedProperties(); props.putIntProperty(ManagementHelper.HDR_BINDING_TYPE, binding.getType().toInt()); props.putSimpleStringProperty(ManagementHelper.HDR_ADDRESS, binding.getAddress()); props.putSimpleStringProperty(ManagementHelper.HDR_CLUSTER_NAME, binding.getClusterName()); props.putSimpleStringProperty(ManagementHelper.HDR_ROUTING_NAME, binding.getRoutingName()); props.putLongProperty(ManagementHelper.HDR_BINDING_ID, binding.getID()); props.putIntProperty(ManagementHelper.HDR_DISTANCE, binding.getDistance()); Filter filter = binding.getFilter(); if (filter != null) { props.putSimpleStringProperty(ManagementHelper.HDR_FILTERSTRING, filter.getFilterString()); } String uid = UUIDGenerator.getInstance().generateStringUUID(); if (logger.isDebugEnabled()) { logger.debug("ClusterCommunication::Sending notification for addBinding " + binding + " from server " + server); } managementService.sendNotification(new Notification(uid, CoreNotificationType.BINDING_ADDED, props)); if (server.hasBrokerPlugins()) { server.callBrokerPlugins(plugin -> plugin.afterAddBinding(binding)); } }
Source:
<code>protected BackendQuotaLimitsResource(Guid quotaId, Class<N> baseResourcesClass) { <START> super(baseResourcesClass, Quota.class, SUB_COLLECTIONS); <END> this.quotaId = quotaId; }</code><technical_language>constructor work SUB_COLLECTIONS</technical_language>

Target:
protected BackendQuotaLimitsResource(Guid quotaId, Class<N> baseResourcesClass) { super(baseResourcesClass, Quota.class); this.quotaId = quotaId; }
Source:
<code>public Optional<JobExecution.Success<Report.Result>> getLastSuccess(final UUID jobId, final Organization organization) throws NoSuchElementException { assertIsOpen(); final Optional<ReportExecution> row = _ebeanServer.find(ReportExecution.class) .orderBy() .desc("completed_at") .where() .eq("report.uuid", jobId) .eq("report.organization.uuid", organization.getId()) .eq("state", ReportExecution.State.SUCCESS) <START> .setMaxRows(1) <END> .findOneOrEmpty(); if (row.isPresent()) { final JobExecution<Report.Result> execution = toInternalModel(row.get()); if (execution instanceof JobExecution.Success) { return Optional.of((JobExecution.Success<Report.Result>) execution); } throw new IllegalStateException("execution returned was not a success"); } return Optional.empty(); }</code><technical_language>question above</technical_language>

Target:
public Optional<JobExecution.Success<Report.Result>> getLastSuccess(final UUID jobId, final Organization organization) throws NoSuchElementException { assertIsOpen(); final Optional<ReportExecution> row = _ebeanServer.find(ReportExecution.class) .orderBy() .desc("completed_at") .where() .eq("report.uuid", jobId) .eq("report.organization.uuid", organization.getId()) .eq("state", ReportExecution.State.SUCCESS) .setMaxRows(1) .findOneOrEmpty(); if (row.isPresent()) { final JobExecution<Report.Result> execution = toInternalModel(row.get()); if (execution instanceof JobExecution.Success) { return Optional.of((JobExecution.Success<Report.Result>) execution); } throw new IllegalStateException( String.format("execution returned was not a success when specified by the query: %s", row.get()) ); } return Optional.empty(); }
Source:
<code>public String enqueueSetSpecialDaysRequest(@Identification final String organisationIdentification, @Identification final String deviceIdentification, final SpecialDaysRequest requestData) throws FunctionalException { <START> LOGGER.debug("enqueueSpecialDaysRequest called with organisation and device {}", organisationIdentification, <END> deviceIdentification); final String correlationUid = this.correlationIdProviderService.getCorrelationId(organisationIdentification, deviceIdentification); final SmartMeteringRequestMessage message = new SmartMeteringRequestMessage( SmartMeteringRequestMessageType.REQUEST_SPECIAL_DAYS, correlationUid, organisationIdentification, deviceIdentification, requestData); this.smartMeteringRequestMessageSender.send(message); return correlationUid; }</code><technical_language>method name refactored, log statement name</technical_language>

Target:
public String enqueueSetSpecialDaysRequest(@Identification final String organisationIdentification, @Identification final String deviceIdentification, final SpecialDaysRequest requestData) throws FunctionalException { LOGGER.debug("enqueueSetSpecialDaysRequest called with organisation and device {}", organisationIdentification, deviceIdentification); final String correlationUid = this.correlationIdProviderService.getCorrelationId(organisationIdentification, deviceIdentification); final SmartMeteringRequestMessage message = new SmartMeteringRequestMessage( SmartMeteringRequestMessageType.REQUEST_SPECIAL_DAYS, correlationUid, organisationIdentification, deviceIdentification, requestData); this.smartMeteringRequestMessageSender.send(message); return correlationUid; }
Source:
<code>public List<? extends CatalogItem<?,?>> addItems(String yaml, boolean forceUpdate) { log.debug("Adding manual catalog item to "+mgmt+": "+yaml); checkNotNull(yaml, "yaml"); List<CatalogItemDtoAbstract<?, ?>> result = collectCatalogItems(yaml); for (final CatalogItemDtoAbstract<?, ?> item : result) { if (item.getCatalogItemType().equals(CatalogItemType.ENTITY) || item.getCatalogItemType().equals(CatalogItemType.TEMPLATE)) { <START> Class<?> type = CatalogUtils.newClassLoadingContext(mgmt, item).tryLoadClass(item.getReferenceType()).orNull(); <END> while (type == null) { CatalogItem refCatalogItem = getCatalogItem(item.getReferenceType(), item.getVersion()); if (refCatalogItem == null) { refCatalogItem = Iterables.tryFind(result, new Predicate<CatalogItemDtoAbstract<?, ?>>() { @Override public boolean apply(@Nullable CatalogItemDtoAbstract<?, ?> catalogItemDtoAbstract) { return catalogItemDtoAbstract != null && StringUtils.equals(catalogItemDtoAbstract.getSymbolicName(), item.getReferenceType()); } }).orNull(); } if (refCatalogItem == null) { break; } type = CatalogUtils.newClassLoadingContext(mgmt, refCatalogItem).tryLoadClass(refCatalogItem.getReferenceType()).orNull(); } if (type != null) { item.tags().addTag(BrooklynTags.newInterfacesTag(ClassUtils.getAllInterfaces(type))); } } } for (CatalogItemDtoAbstract<?, ?> item: result) { addItemDto(item, forceUpdate); } return result; }</code><technical_language>I easier create a spec out of catalog item get type there. if referenceType is another catalog item</technical_language>

Target:
public List<? extends CatalogItem<?,?>> addItems(String yaml, boolean forceUpdate) { log.debug("Adding manual catalog item to "+mgmt+": "+yaml); checkNotNull(yaml, "yaml"); List<CatalogItemDtoAbstract<?, ?>> result = collectCatalogItems(yaml); for (CatalogItemDtoAbstract<?, ?> item: result) { addItemDto(item, forceUpdate); } return result; }