auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>protected String decryptedFilePath(SecretEngine secretEngine, EncryptedSecret encryptedSecret) { String plainText = secretEngine.decrypt(encryptedSecret); try { File tempFile = File.createTempFile(secretEngine.identifier() + '-', ".secret"); try (FileWriter fileWriter = new FileWriter(tempFile)) { fileWriter.write(plainText); } tempFile.deleteOnExit(); return tempFile.getAbsolutePath(); } catch (IOException e) { <START> throw new SecretDecryptionException(); <END> } }</code><technical_language>This a reference e</technical_language>

Target:
protected Path decryptedFilePath(SecretEngine secretEngine, EncryptedSecret encryptedSecret) { String plainText = secretEngine.decrypt(encryptedSecret); try { File tempFile = File.createTempFile(secretEngine.identifier() + '-', ".secret"); try (FileWriter fileWriter = new FileWriter(tempFile)) { fileWriter.write(plainText); } tempFile.deleteOnExit(); return tempFile.toPath(); } catch (IOException e) { throw new SecretDecryptionException(e.getMessage()); } }
Source:
<code>public void jpegRESTim2txtTest() throws Exception { <START> String[] expectedObjects = {"baseball", "bat", "field"}; <END> doRecognize(CONFIG_REST_FILE_IM2TXT, BASEBALL_IMAGE_JPEG, ObjectRecognitionParser.MD_KEY_IMG_CAP, expectedObjects); }</code><technical_language>This is a weak assertion. this is a caption, considering adding phrases baseball player holding bat instead of object names</technical_language>

Target:
public void jpegRESTim2txtTest() throws Exception { String[] expectedCaption = {"a baseball player holding a bat on a field"}; doRecognize(CONFIG_REST_FILE_IM2TXT, BASEBALL_IMAGE_JPEG, ObjectRecognitionParser.MD_KEY_IMG_CAP, expectedCaption); }
Source:
<code>protected void executeCommand() { if (getDiskImages().isEmpty()) { setSucceeded(true); return; } <START> auditLogDirector.log(this, AuditLogType.USER_SYSPREP_VM_TEMPLATE_START); <END> SysprepVDSCommandParameters parameters = new SysprepVDSCommandParameters(); getDiskImages().forEach(diskImage -> parameters.addVolume( diskImage.getStorageIds().get(0), diskImage.getId(), diskImage.getImageId())); lockTemplateInDb(); VDSReturnValue vdsReturnValue = VdsCommandsHelper.runVdsCommandWithFailover( VDSCommandType.Sysprep, parameters, getDiskImages().get(0).getStoragePoolId(), this); if (!vdsReturnValue.getSucceeded()) { setCommandStatus(CommandStatus.FAILED); jobFailed(); } setSucceeded(vdsReturnValue.getSucceeded()); }</code><technical_language>do need call explicitly getAuditLogTypeValue</technical_language>

Target:
protected void executeCommand() { if (getDiskImages().isEmpty()) { setSucceeded(true); return; } SysprepVDSCommandParameters parameters = new SysprepVDSCommandParameters(getParameters().getStorageJobId()); getDiskImages().forEach(diskImage -> parameters.addVolume( diskImage.getStorageIds().get(0), diskImage.getId(), diskImage.getImageId())); VmTemplateHandler.lockVmTemplateInTransaction(getVmTemplateId(), getCompensationContext()); lockTemplateInDb(); lockDiskImagesInDb(); VDSReturnValue vdsReturnValue = VdsCommandsHelper.runVdsCommandWithFailover( VDSCommandType.Sysprep, parameters, getDiskImages().get(0).getStoragePoolId(), this); if (!vdsReturnValue.getSucceeded()) { setCommandStatus(CommandStatus.FAILED); unlockDiskImagesInDb(); unlockTemplateInDb(); } setSucceeded(vdsReturnValue.getSucceeded()); }
Source:
<code>private void checkThresholdMonitors(T obj) throws RuntimeException { for (ThresholdMonitor<T> m: monitors) { if (dataSizeB > m.thresholdB && !m.fired) { m.fired = true; <START> m.event.fire(dataSizeB, m.thresholdB, obj); <END> } } }</code><technical_language>worth capturing a TODO monitor throw exception stop other callbacks firing. a general purpose class, this is surprising, current usages problematic. So, I suggest a TODO and/or open issue remind this catch thrown exceptions aggregate them</technical_language>

Target:
private void checkThresholdMonitors(T obj) throws RuntimeException { for (ThresholdMonitor<T> m: monitors) { if (dataSizeB > m.thresholdB && !m.fired) { m.fired = true; m.callback.fire(dataSizeB, m.thresholdB, obj); } } }
Source:
<code>public static URL getAccumuloPropsLocation() { URL siteUrl = SiteConfiguration.class.getClassLoader().getResource("accumulo-site.xml"); if (siteUrl != null) { throw new IllegalArgumentException("Found deprecated config file 'accumulo-site.xml' on " + "classpath. Since 2.0.0, this file was replaced by 'accumulo.properties'."); } <START> String configFile = System.getProperty("accumulo.configuration", "accumulo.properties"); <END> if (configFile.startsWith("file://")) { try { File f = new File(new URI(configFile)); if (f.exists() && !f.isDirectory()) { log.info("Found Accumulo configuration at {}", configFile); return f.toURI().toURL(); } else { throw new IllegalArgumentException( "Failed to load Accumulo configuration at " + configFile); } } catch (MalformedURLException | URISyntaxException e) { throw new IllegalArgumentException( "Failed to load Accumulo configuration from " + configFile, e); } } else { URL accumuloConfigUrl = SiteConfiguration.class.getClassLoader().getResource(configFile); if (accumuloConfigUrl == null) { throw new IllegalArgumentException( "Failed to load Accumulo configuration '" + configFile + "' from classpath"); } else { log.info("Found Accumulo configuration on classpath at {}", accumuloConfigUrl.getFile()); return accumuloConfigUrl; } } }</code><technical_language>This imply --props argument is redundant. confusing if ways do this. Personally, I prefer -Daccumulo.configuration=... method, called -Daccumulo.properties=... instead for naming consistency clarity</technical_language>

Target:
public static URL getAccumuloPropsLocation() { URL siteUrl = SiteConfiguration.class.getClassLoader().getResource("accumulo-site.xml"); if (siteUrl != null) { throw new IllegalArgumentException("Found deprecated config file 'accumulo-site.xml' on " + "classpath. Since 2.0.0, this file was replaced by 'accumulo.properties'."); } String configFile = System.getProperty("accumulo.properties", "accumulo.properties"); if (configFile.startsWith("file://")) { try { File f = new File(new URI(configFile)); if (f.exists() && !f.isDirectory()) { log.info("Found Accumulo configuration at {}", configFile); return f.toURI().toURL(); } else { throw new IllegalArgumentException( "Failed to load Accumulo configuration at " + configFile); } } catch (MalformedURLException | URISyntaxException e) { throw new IllegalArgumentException( "Failed to load Accumulo configuration from " + configFile, e); } } else { URL accumuloConfigUrl = SiteConfiguration.class.getClassLoader().getResource(configFile); if (accumuloConfigUrl == null) { throw new IllegalArgumentException( "Failed to load Accumulo configuration '" + configFile + "' from classpath"); } else { log.info("Found Accumulo configuration on classpath at {}", accumuloConfigUrl.getFile()); return accumuloConfigUrl; } } }
Source:
<code>public void deployWithExtensions() throws IOException { String name = "my.comp4"; StreamRef compRef = new URLStreamRef(getResource("MyComp4.xml")); assertNotComponentDeployed(name); TargetExtensions te = new TargetExtensions() { @Override protected void initialize() { addTargetExtension("my.comp3.alias2", "xp"); } }; <START> deployPartialComponent(getContext(), Sets.newHashSet(te), compRef); <END> assertComponentDeployed(name); assertComponentDeployed(name.concat("-partial")); assertExtensionsEquals(1, name); }</code><technical_language>Collections.singleton(te) work here</technical_language>

Target:
public void deployWithExtensions() throws IOException { String name = "my.comp4"; String partial = name + "-partial"; StreamRef compRef = new URLStreamRef(getResource("MyComp4.xml")); assertNull(getComponent(name)); assertNull(getComponent(partial)); TargetExtensions te = new TargetExtensions() { @Override protected void initialize() { addTargetExtension("my.comp3.alias2", "xp"); } }; deployPartialComponent(getContext(), Collections.singleton(te), compRef); assertNull(getComponent(name)); assertNotNull(getComponent(partial)); assertNumberOfExtensionsEquals(1, partial); }
Source:
<code>public Folder findFolderByPath(String path, String hostid, User user, boolean respectFrontEndPermissions) throws DotStateException, DotDataException, DotSecurityException { <START> if(user==null) user = APILocator.getUserAPI().getSystemUser(); <END> Host host = APILocator.getHostAPI().find(hostid, user, false); return findFolderByPath(path,host,user, respectFrontEndPermissions); }</code><technical_language>lines do this, if(user==null) { user = APILocator.getUserAPI().getSystemUser(); } Eventually introduce error current code</technical_language>

Target:
public Folder findFolderByPath(String path, String hostid, User user, boolean respectFrontEndPermissions) throws DotStateException, DotDataException, DotSecurityException { if(user==null){ user = APILocator.systemUser(); } Host host = APILocator.getHostAPI().find(hostid, user, false); return findFolderByPath(path,host,user, respectFrontEndPermissions); }
Source:
<code>public void run(final SpringConfiguration configuration, final Environment environment) throws Exception { <START> log.info("_____spring scanning________*******************"); <END> initializeSpring(configuration, environment); addResources(environment); addHealthChecks(environment); addTasks(environment); addManaged(environment); }</code><technical_language>clean message</technical_language>

Target:
public void run(final SpringConfiguration configuration, final Environment environment) throws Exception { initializeSpring(configuration, environment); addResources(environment); addHealthChecks(environment); addTasks(environment); addManaged(environment); }
Source:
<code>private OAuthToken getToken(final String userId) throws IOException, InvalidKeySpecException, NoSuchAlgorithmException { OAuthCredentialsResponse credentials; credentialsStoreLock.lock(); try { credentials = credentialsStore.get(userId); } finally { credentialsStoreLock.unlock(); } <START> return newDto(OAuthToken.class).withToken(credentials.token).withScope(credentials.tokenSecret); <END> }</code><technical_language>credentials null here</technical_language>

Target:
private OAuthToken getToken(final String userId) { OAuthCredentialsResponse credentials; credentialsStoreLock.lock(); try { credentials = credentialsStore.get(userId); } finally { credentialsStoreLock.unlock(); } if (credentials != null) { return newDto(OAuthToken.class).withToken(credentials.token).withScope(credentials.tokenSecret); } return null; }
Source:
<code>private List<URL> getList() { List<URL> list = new ArrayList<>(); <START> URL url_1 = new URL("dubbo", "127.0.0.0", 1000); <END> URL url_2 = new URL("dubbo", "127.0.0.1", 1001); URL url_3 = new URL("dubbo", "127.0.0.2", 1002); list.add(url_1); list.add(url_2); list.add(url_3); return list; }</code><technical_language>underscore _, instead, fine name url1, url2, etc</technical_language>

Target:
private List<URL> getList() { List<URL> list = new ArrayList<>(); URL url1 = new URL("dubbo", "127.0.0.0", 1000); URL url2 = new URL("dubbo", "127.0.0.1", 1001); URL url3 = new URL("dubbo", "127.0.0.2", 1002); list.add(url1); list.add(url2); list.add(url3); return list; }
Source:
<code>public int unlinkCallback(String path) { try { return unlink(path); } catch (Exception e) { <START> e.printStackTrace(); <END> return -ErrorCodes.EIO(); } }</code><technical_language>LOG.error("Failed unlink {}: ", path, e)</technical_language>

Target:
public int unlinkCallback(String path) { try { return unlink(path); } catch (Exception e) { LOG.error("Failed to unlink {}: ", path, e); return -ErrorCodes.EIO(); } }
Source:
<code>public void testReindexingSingleStringHashIdentityValueIsDeleted() { Patient p = new Patient(); p.addName().setFamily("family1"); final IIdType id = myPatientDao.create(p, mySrd).getId().toUnqualifiedVersionless(); SearchParameterMap searchParamMap = new SearchParameterMap(); searchParamMap.setLoadSynchronous(true); searchParamMap.add(Patient.SP_FAMILY, new StringParam("family1")); assertEquals(1, myPatientDao.search(searchParamMap).size().intValue()); runInTransaction(()->{ Long i = myEntityManager .createQuery("SELECT count(s) FROM ResourceIndexedSearchParamString s WHERE s.myHashIdentity IS null", Long.class) .getSingleResult(); assertEquals(0L, i.longValue()); myEntityManager .createQuery("UPDATE ResourceIndexedSearchParamString s SET s.myHashIdentity = null") .executeUpdate(); i = myEntityManager .createQuery("SELECT count(s) FROM ResourceIndexedSearchParamString s WHERE s.myHashIdentity IS null", Long.class) .getSingleResult(); assertThat(i, greaterThan(1L)); }); myResourceReindexingSvc.markAllResourcesForReindexing(); myResourceReindexingSvc.forceReindexingPass(); runInTransaction(()->{ Long i = myEntityManager <START> .createQuery("SELECT count(s) FROM ResourceIndexedSearchParamString s WHERE s.myHashIdentity IS nullhir", Long.class) <END> .getSingleResult(); assertEquals(0L, i.longValue()); }); }</code><technical_language>I imagine this is a typo</technical_language>

Target:
public void testReindexingSingleStringHashIdentityValueIsDeleted() { Patient p = new Patient(); p.addName().setFamily("family1"); final IIdType id = myPatientDao.create(p, mySrd).getId().toUnqualifiedVersionless(); SearchParameterMap searchParamMap = new SearchParameterMap(); searchParamMap.setLoadSynchronous(true); searchParamMap.add(Patient.SP_FAMILY, new StringParam("family1")); assertEquals(1, myPatientDao.search(searchParamMap).size().intValue()); runInTransaction(()->{ Long i = myEntityManager .createQuery("SELECT count(s) FROM ResourceIndexedSearchParamString s WHERE s.myHashIdentity IS null", Long.class) .getSingleResult(); assertEquals(0L, i.longValue()); myEntityManager .createQuery("UPDATE ResourceIndexedSearchParamString s SET s.myHashIdentity = null") .executeUpdate(); i = myEntityManager .createQuery("SELECT count(s) FROM ResourceIndexedSearchParamString s WHERE s.myHashIdentity IS null", Long.class) .getSingleResult(); assertThat(i, greaterThan(1L)); }); myResourceReindexingSvc.markAllResourcesForReindexing(); myResourceReindexingSvc.forceReindexingPass(); runInTransaction(()->{ Long i = myEntityManager .createQuery("SELECT count(s) FROM ResourceIndexedSearchParamString s WHERE s.myHashIdentity IS null", Long.class) .getSingleResult(); assertEquals(0L, i.longValue()); }); }
Source:
<code>public WorkspaceMetacardImpl() { super(TYPE); Set<String> setOfTags = new HashSet<String>(); setOfTags.add(WorkspaceAttributes.WORKSPACE_TAG); <START> setOfTags.add(ShareableMetacardAttributes.NAME); <END> setTags(setOfTags); }</code><technical_language>Is a tag necessary is presence of SecurityAttributes enough</technical_language>

Target:
public WorkspaceMetacardImpl() { super(TYPE); setTags(Collections.singleton(WorkspaceAttributes.WORKSPACE_TAG)); }
Source:
<code>public void update() { <START> FBO ssaoFbo = displayResolutionDependentFBOs.get(SSAO_FBO); <END> outputFboWidth = ssaoFbo.width(); outputFboHeight = ssaoFbo.height(); }</code><technical_language>discussed this already, please remind me: update() is executed, for example, user resize window. avoid form of memory allocation in circumstances, if admittedly small in this case</technical_language>

Target:
public void update() { ssaoFbo = displayResolutionDependentFBOs.get(SSAO_FBO); outputFboWidth = ssaoFbo.width(); outputFboHeight = ssaoFbo.height(); }
Source:
<code>public void run() { SourceDataLine line; AudioFormat audioFormat = convertAudioFormat(this.audioStream.getFormat()); if (audioFormat == null) { logger.warn("Audio format is unsupported or does not have enough details in order to be played"); return; } DataLine.Info info = new DataLine.Info(SourceDataLine.class, audioFormat); try { line = (SourceDataLine) AudioSystem.getLine(info); line.open(audioFormat); } catch (Exception e) { logger.warn("No line found: {}", e.getMessage()); logger.info("Available lines are:"); Mixer.Info[] mixerInfo = AudioSystem.getMixerInfo(); Mixer mixer = null; for (int cnt = 0; cnt < mixerInfo.length; cnt++) { mixer = AudioSystem.getMixer(mixerInfo[cnt]); Line.Info[] lineInfos = mixer.getSourceLineInfo(); for (Info lineInfo : lineInfos) { <START> logger.info("{}", lineInfo.toString()); <END> } } return; } line.start(); int nRead = 0; byte[] abData = new byte[65532]; try { while (-1 != nRead) { nRead = audioStream.read(abData, 0, abData.length); if (nRead >= 0) { line.write(abData, 0, nRead); } } } catch (IOException e) { logger.error("Error while playing audio: {}", e.getMessage()); return; } finally { line.drain(); line.close(); try { audioStream.close(); } catch (IOException e) { } } }</code><technical_language>remove toString()</technical_language>

Target:
public void run() { SourceDataLine line; AudioFormat audioFormat = convertAudioFormat(this.audioStream.getFormat()); if (audioFormat == null) { logger.warn("Audio format is unsupported or does not have enough details in order to be played"); return; } DataLine.Info info = new DataLine.Info(SourceDataLine.class, audioFormat); try { line = (SourceDataLine) AudioSystem.getLine(info); line.open(audioFormat); } catch (Exception e) { logger.warn("No line found: {}", e.getMessage()); logger.info("Available lines are:"); Mixer.Info[] mixerInfo = AudioSystem.getMixerInfo(); Mixer mixer = null; for (int cnt = 0; cnt < mixerInfo.length; cnt++) { mixer = AudioSystem.getMixer(mixerInfo[cnt]); Line.Info[] lineInfos = mixer.getSourceLineInfo(); for (Info lineInfo : lineInfos) { logger.info("{}", lineInfo); } } return; } line.start(); int nRead = 0; byte[] abData = new byte[65532]; try { while (-1 != nRead) { nRead = audioStream.read(abData, 0, abData.length); if (nRead >= 0) { line.write(abData, 0, nRead); } } } catch (IOException e) { logger.error("Error while playing audio: {}", e.getMessage()); return; } finally { line.drain(); line.close(); try { audioStream.close(); } catch (IOException e) { } } }
Source:
<code>private void addImportToSourcePackageTypes(ICompilationUnit movedUnit, IProgressMonitor pm) throws CoreException{ List<ICompilationUnit> cuList= Arrays.asList(fCus); IType[] allCuTypes= movedUnit.getAllTypes(); ImportRewrite importEdit= getImportRewrite(movedUnit); importEdit.setFilterImplicitImports(false); IPackageFragment srcPack= (IPackageFragment)movedUnit.getParent(); for (IType <START> iType : <END> ReferenceFinderUtil.getTypesReferencedIn(allCuTypes, pm)) { if (! iType.exists()) continue; if (!JavaModelUtil.isSamePackage(iType.getPackageFragment(), srcPack)) continue; if (cuList.contains(iType.getCompilationUnit())) continue; importEdit.addImport(iType.getFullyQualifiedName('.')); } }</code><technical_language>rename type</technical_language>

Target:
private void addImportToSourcePackageTypes(ICompilationUnit movedUnit, IProgressMonitor pm) throws CoreException{ List<ICompilationUnit> cuList= Arrays.asList(fCus); IType[] allCuTypes= movedUnit.getAllTypes(); ImportRewrite importEdit= getImportRewrite(movedUnit); importEdit.setFilterImplicitImports(false); IPackageFragment srcPack= (IPackageFragment)movedUnit.getParent(); for (IType type : ReferenceFinderUtil.getTypesReferencedIn(allCuTypes, pm)) { if (! type.exists()) continue; if (!JavaModelUtil.isSamePackage(type.getPackageFragment(), srcPack)) continue; if (cuList.contains(type.getCompilationUnit())) continue; importEdit.addImport(type.getFullyQualifiedName('.')); } }
Source:
<code>public void finished(Request request) { RenderTimeStatistics statistics = (RenderTimeStatistics) request.getHttpRequest().getAttribute(RenderTimeStatistics.ID); RequestData data = monitor.current(); if (data == null) { return; } if (request.getError() != null) { data.setStatus(Status.FAILED); data.setErrorMessage(request.getError().getLocalizedMessage()); data.setError(request.getError()); monitor.update(); } if (statistics != null) { List<Long> renderingTimeLayers = new ArrayList<>(statistics.getRenderingLayersIdxs().size()); data.setLabellingProcessingTime(statistics.getLabellingTime()); <START> data.setResources(statistics.getLayerNames()); <END> for (Integer idx: statistics.getRenderingLayersIdxs()){ renderingTimeLayers.add(statistics.getRenderingTime(idx)); } data.setResourcesProcessingTime(renderingTimeLayers); if (data.getEndTime()==null) data.setEndTime(new Date()); monitor.complete(); monitor.postProcessed(data); } }</code><technical_language>update? Is a risk of resource list collected matching list in stats? is worrysome</technical_language>

Target:
public void finished(Request request) { if (request.getError() != null) { RequestData data = monitor.current(); if (data == null) { return; } data.setStatus(Status.FAILED); data.setErrorMessage(request.getError().getLocalizedMessage()); data.setError(request.getError()); monitor.update(); } }
Source:
<code>public boolean visit(ConstructorInvocation constructorInvocation) { List<?> arguments= constructorInvocation.arguments(); if (!arguments.isEmpty()) { IMethodBinding constructorBinding= <START> constructorInvocation.resolveConstructorBinding(); <END> IMethod method = resolveMethodBinding(constructorBinding); collectParameterNamesCodeMinings(method, arguments, constructorBinding.isVarargs()); } return super.visit(constructorInvocation); }</code><technical_language>mentioned happen here</technical_language>

Target:
public boolean visit(ConstructorInvocation constructorInvocation) { List<?> arguments= constructorInvocation.arguments(); if (!arguments.isEmpty()) { IMethodBinding constructorBinding= constructorInvocation.resolveConstructorBinding(); if (constructorBinding != null) { IMethod method = resolveMethodBinding(constructorBinding); collectParameterNamesCodeMinings(method, arguments, constructorBinding.isVarargs()); } } return super.visit(constructorInvocation); }
Source:
<code>private void writeMessageToDisk(EDUCore request) { PutMessageRequestType putMessage = EDUCoreFactory.createPutMessageFromCore(request); try { Marshaller marshaller = jaxbContextdomain.createMarshaller(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); <START> marshaller.marshal(new JAXBElement<>(new QName("uri", "local"), PutMessageRequestType.class, putMessage), bos); <END> try { FileOutputStream fos = new FileOutputStream(new File("failed_messages/" + request.getId() + "_failed.xml")); bos.writeTo(fos); } catch (IOException e) { logger.error("Error writing failed message to disk", e); } } catch (JAXBException e) { logger.error("Failed marshalling message", e); } }</code><technical_language>![MINOR](<LINK_2> 'Severity: MINOR') Define a constant instead of duplicating this literal "local" 3 times. [![rule](<LINK_1>](<LINK_0></technical_language>

Target:
private void writeMessageToDisk(EDUCore request) { PutMessageRequestType putMessage = EDUCoreFactory.createPutMessageFromCore(request); try { Marshaller marshaller = jaxbContextdomain.createMarshaller(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); marshaller.marshal(new JAXBElement<>(new QName("uri", "local"), PutMessageRequestType.class, putMessage), bos); FileOutputStream fos = new FileOutputStream(new File("failed_messages/" + request.getId() + "_failed.xml")); bos.writeTo(fos); } catch (JAXBException | IOException e) { logger.error("Failed writing message to disk", e); } }
Source:
<code>public void createWithCorrectEvents() throws Exception { final Iterable<String> events = Arrays.asList("event1", "event2"); final int number = 123; final Coordinates coords = new Coordinates.Simple("user/repo"); final Directives xml = this.hookDirs(number, coords).add("events"); events.forEach(e -> xml.add("event").set(e).up()); final MkStorage storage = new MkStorage.InFile(); storage.apply(xml); MatcherAssert.assertThat( "", new MkHook( storage, "", coords, number ).json().getJsonArray("events") .stream() .map(JsonValue::toString) .map(event -> event.replace("\"", "")) .collect(Collectors.toList()), <START> Matchers.containsInAnyOrder("event1", "event2") <END> ); }</code><technical_language>@llorllale above, IsIterableContainingInAnyOrder</technical_language>

Target:
public void createWithCorrectEvents() throws Exception { final Iterable<String> events = Arrays.asList("event1", "event2"); final int number = 123; final Coordinates coords = new Coordinates.Simple("user/repo"); final Directives xml = this.hookDirs(number, coords).add("events"); events.forEach(e -> xml.add("event").set(e).up()); final MkStorage storage = new MkStorage.InFile(); storage.apply(xml); MatcherAssert.assertThat( "", new MkHook( storage, "", coords, number ).json().getJsonArray("events") .stream() .map(JsonValue::toString) .map(event -> event.replace("\"", "")) .collect(Collectors.toList()), new IsIterableContainingInAnyOrder<>( Arrays.asList( new IsEqual<>("event1"), new IsEqual<>("event2") ) ) ); }
Source:
<code>protected void executeQueryCommand() { <START> ArrayList<storage_domains> result = new ArrayList<storage_domains>(); <END> VmTemplate vmTemplate = DbFacade.getInstance().getVmTemplateDAO() .get(getParameters().getId()); if (vmTemplate != null && vmTemplate.getstorage_pool_id() != null) { List<DiskImage> templateDisks = getTemplateDisks(); if (templateDisks.size() > 0) { Set<Guid> domains = new HashSet<Guid>(); for (DiskImage templateDisk : templateDisks) { domains.addAll(templateDisk.getstorage_ids()); } for (Guid domainId : domains) { storage_domains domain = DbFacade.getInstance().getStorageDomainDAO().getForStoragePool(domainId, vmTemplate.getstorage_pool_id().getValue(), getUserID(), getParameters().isFiltered()); if (domain != null) { result.add(domain); } } } } getQueryReturnValue().setReturnValue(result); }</code><technical_language>This call filtered for permissions</technical_language>

Target:
protected void executeQueryCommand() { ArrayList<storage_domains> result = new ArrayList<storage_domains>(); VmTemplate vmTemplate = DbFacade.getInstance().getVmTemplateDAO() .get(getParameters().getId(), getUserID(), getParameters().isFiltered()); if (vmTemplate != null && vmTemplate.getstorage_pool_id() != null) { List<DiskImage> templateDisks = getTemplateDisks(); if (templateDisks.size() > 0) { Set<Guid> domains = new HashSet<Guid>(); for (DiskImage templateDisk : templateDisks) { domains.addAll(templateDisk.getstorage_ids()); } for (Guid domainId : domains) { storage_domains domain = DbFacade.getInstance().getStorageDomainDAO().getForStoragePool(domainId, vmTemplate.getstorage_pool_id().getValue()); if (domain != null) { result.add(domain); } } } } getQueryReturnValue().setReturnValue(result); }
Source:
<code>public OmemoBundleElement_VAxolotl parse(XmlPullParser parser, int initialDepth) throws Exception { boolean stop = false; boolean inPreKeys = false; int signedPreKeyId = -1; String signedPreKey = null; String signedPreKeySignature = null; String identityKey = null; HashMap<Integer, String> preKeys = new HashMap<>(); while (!stop) { int tag = parser.next(); String name = parser.getName(); switch (tag) { case START_TAG: if (name.equals(SIGNED_PRE_KEY_PUB)) { for (int i = 0; i < parser.getAttributeCount(); i++) { if (parser.getAttributeName(i).equals(SIGNED_PRE_KEY_ID)) { int id = Integer.parseInt(parser.getAttributeValue(i)); signedPreKey = parser.nextText(); signedPreKeyId = id; } } } else if (name.equals(SIGNED_PRE_KEY_SIG)) { signedPreKeySignature = parser.nextText(); } else if (name.equals(IDENTITY_KEY)) { identityKey = parser.nextText(); } else if (name.equals(PRE_KEYS)) { inPreKeys = true; } else if (inPreKeys && name.equals(PRE_KEY_PUB)) { for (int i = 0; i < parser.getAttributeCount(); i++) { if (parser.getAttributeName(i).equals(PRE_KEY_ID)) { preKeys.put(Integer.parseInt(parser.getAttributeValue(i)), parser.nextText()); } } } break; case END_TAG: if (name.equals(BUNDLE)) { stop = true; } break; } } if (preKeys.isEmpty()) { <START> throw new XmlPullParserException("OMEMO Bundle MUST contain at least one prekey."); <END> } return new OmemoBundleElement_VAxolotl(signedPreKeyId, signedPreKey, signedPreKeySignature, identityKey, preKeys); }</code><technical_language>This a SmackException is thrown XML pull parser</technical_language>

Target:
public OmemoBundleElement_VAxolotl parse(XmlPullParser parser, int initialDepth) throws Exception { boolean stop = false; boolean inPreKeys = false; int signedPreKeyId = -1; String signedPreKey = null; String signedPreKeySignature = null; String identityKey = null; HashMap<Integer, String> preKeys = new HashMap<>(); while (!stop) { int tag = parser.next(); String name = parser.getName(); switch (tag) { case START_TAG: if (name.equals(SIGNED_PRE_KEY_PUB)) { for (int i = 0; i < parser.getAttributeCount(); i++) { if (parser.getAttributeName(i).equals(SIGNED_PRE_KEY_ID)) { int id = Integer.parseInt(parser.getAttributeValue(i)); signedPreKey = parser.nextText(); signedPreKeyId = id; } } } else if (name.equals(SIGNED_PRE_KEY_SIG)) { signedPreKeySignature = parser.nextText(); } else if (name.equals(IDENTITY_KEY)) { identityKey = parser.nextText(); } else if (name.equals(PRE_KEYS)) { inPreKeys = true; } else if (inPreKeys && name.equals(PRE_KEY_PUB)) { for (int i = 0; i < parser.getAttributeCount(); i++) { if (parser.getAttributeName(i).equals(PRE_KEY_ID)) { preKeys.put(Integer.parseInt(parser.getAttributeValue(i)), parser.nextText()); } } } break; case END_TAG: if (name.equals(BUNDLE)) { stop = true; } break; } } return new OmemoBundleElement_VAxolotl(signedPreKeyId, signedPreKey, signedPreKeySignature, identityKey, preKeys); }
Source:
<code>public List<Timeline> getTimelines( @Scope(OAuthScope.SLEEP_TIMELINE)final AccessToken accessToken, @PathParam("date") String date) { boolean forceUpdate = false; if (this.hasHmmEnabled(accessToken.accountId)) { <START> forceUpdate = true; <END> } return getTimelinesFromCacheOrReprocess(accessToken.accountId, date,forceUpdate); }</code><technical_language>rewrite this in a single immutable statement? final boolean forceUpdate = this.hasHmmEnabled(accessToken.accountId);</technical_language>

Target:
public List<Timeline> getTimelines( @Scope(OAuthScope.SLEEP_TIMELINE)final AccessToken accessToken, @PathParam("date") String date) { return getTimelinesFromCacheOrReprocess(accessToken.accountId, date); }
Source:
<code>private synchronized StreamObserver<CommandProviderOutbound> getSubscriberObserver() { if (subscriberStreamObserver == null) { logger.info("Create new subscriber"); StreamObserver<CommandProviderInbound> commandsFromRoutingServer = new StreamObserver<CommandProviderInbound>() { @Override public void onNext(CommandProviderInbound commandToSubscriber) { logger.debug("Received from server: {}", commandToSubscriber); switch (commandToSubscriber.getRequestCase()) { case COMMAND: commandQueue.add(commandToSubscriber.getCommand()); break; } } @Override public void onError(Throwable throwable) { logger.warn("Received error from server: {}", throwable.getMessage()); subscriberStreamObserver = null; <START> resubscribe(); <END> } @Override public void onCompleted() { logger.debug("Received completed from server"); subscriberStreamObserver = null; } }; StreamObserver<CommandProviderOutbound> stream = platformConnectionManager.getCommandStream(commandsFromRoutingServer, interceptors); subscriberStreamObserver = new FlowControllingStreamObserver<>(stream, configuration, flowControl -> CommandProviderOutbound.newBuilder().setFlowControl(flowControl).build(), t -> t.getRequestCase().equals(CommandProviderOutbound.RequestCase.COMMANDRESPONSE)).sendInitialPermits(); } return subscriberStreamObserver; }</code><technical_language>Do resubscribe error is StatusRuntimeException Error code UNAVAILABLE. In this case AxonServer is gone, is handled PlatformConnectionManager</technical_language>

Target:
private synchronized StreamObserver<CommandProviderOutbound> getSubscriberObserver() { if (subscriberStreamObserver == null) { logger.info("Create new subscriber"); StreamObserver<CommandProviderInbound> commandsFromRoutingServer = new StreamObserver<CommandProviderInbound>() { @Override public void onNext(CommandProviderInbound commandToSubscriber) { logger.debug("Received from server: {}", commandToSubscriber); switch (commandToSubscriber.getRequestCase()) { case COMMAND: commandQueue.add(commandToSubscriber.getCommand()); break; } } @Override public void onError(Throwable ex) { logger.warn("Received error from server: {}", ex.getMessage()); subscriberStreamObserver = null; if (ex instanceof StatusRuntimeException && ((StatusRuntimeException) ex).getStatus().getCode().equals( Status.UNAVAILABLE.getCode())) { return; } resubscribe(); } @Override public void onCompleted() { logger.debug("Received completed from server"); subscriberStreamObserver = null; } }; StreamObserver<CommandProviderOutbound> stream = platformConnectionManager.getCommandStream(commandsFromRoutingServer, interceptors); subscriberStreamObserver = new FlowControllingStreamObserver<>(stream, configuration, flowControl -> CommandProviderOutbound.newBuilder().setFlowControl(flowControl).build(), t -> t.getRequestCase().equals(CommandProviderOutbound.RequestCase.COMMANDRESPONSE)).sendInitialPermits(); } return subscriberStreamObserver; }
Source:
<code>public void testDateFormatTransform() throws Exception { <START> SimpleFeature f = transform(new DateFormatTransform("date", null, null, null), <END> "date", String.class, "1980-09-10" ); GregorianCalendar cal = new GregorianCalendar(TimeZone.getTimeZone("UTC")); cal.setTime((Date) f.getAttribute("date")); assertEquals(1980, cal.get(GregorianCalendar.YEAR)); assertEquals(9, cal.get(GregorianCalendar.MONTH) + 1); assertEquals(10, cal.get(GregorianCalendar.DAY_OF_MONTH)); }</code><technical_language>overloaded constructor, this change is longer necessary</technical_language>

Target:
public void testDateFormatTransform() throws Exception { SimpleFeature f = transform(new DateFormatTransform("date", null), "date", String.class, "1980-09-10" ); GregorianCalendar cal = new GregorianCalendar(TimeZone.getTimeZone("UTC")); cal.setTime((Date) f.getAttribute("date")); assertEquals(1980, cal.get(GregorianCalendar.YEAR)); assertEquals(9, cal.get(GregorianCalendar.MONTH) + 1); assertEquals(10, cal.get(GregorianCalendar.DAY_OF_MONTH)); }
Source:
<code>public void openFolderOnGitHubTest() { projectExplorer.waitAndSelectItem(PROJECT_NAME + PATH_TO_EXPAND); projectExplorer.openContextMenuByPathSelectedItem(PROJECT_NAME + PATH_TO_EXPAND); projectExplorer.waitContextMenu(); projectExplorer.clickOnItemInContextMenu( TestProjectExplorerContextMenuConstants.ContextMenuFirstLevelItems.OPEN_ON_GITHUB); seleniumWebDriverHelper.switchToNextWindow(seleniumWebDriver.getWindowHandle()); <START> Assert.assertEquals( <END> seleniumWebDriver.getCurrentUrl(), testRepo.getHtmlUrl() + "/tree/master" + PATH_TO_EXPAND); }</code><technical_language><LINK_0></technical_language>

Target:
public void openFolderOnGitHubTest() { projectExplorer.waitAndSelectItem(PROJECT_NAME + "/" + PATH_TO_EXPAND, 5); projectExplorer.waitAndSelectItem(PROJECT_NAME + "/" + PATH_TO_EXPAND, 5); projectExplorer.openContextMenuByPathSelectedItem(PROJECT_NAME + "/" + PATH_TO_EXPAND); projectExplorer.waitContextMenu(); projectExplorer.clickOnItemInContextMenu( TestProjectExplorerContextMenuConstants.ContextMenuFirstLevelItems.OPEN_ON_GITHUB); seleniumWebDriverHelper.switchToNextWindow(seleniumWebDriver.getWindowHandle()); seleniumWebDriverHelper.waitSuccessCondition( urlToBe(testRepo.getHtmlUrl() + "/tree/master/" + PATH_TO_EXPAND)); }
Source:
<code><START> public boolean equals(Object aThat){ <END> if(this == aThat) return true; if(!(aThat instanceof NamespaceIdentifier)) return false; NamespaceIdentifier that = (NamespaceIdentifier)aThat; List<String> thisName = this.getName(); List<String> thatName = that.getName(); if(thisName.size() != thatName.size()) return false; for(int i = 0; i < thisName.size(); ++i){ String nThis = thisName.get(i); String nThat = thatName.get(i); if(!nThis.equals(nThat)) return false; } return true; }</code><technical_language>aThat that? curious</technical_language>

Target:
public boolean equals(Object aThat){ if(this == aThat) return true; if(!(aThat instanceof NamespaceIdentifier)) return false; NamespaceIdentifier that = (NamespaceIdentifier)aThat; return this.getName().equals(that.getName()); }
Source:
<code>public StreamsAddressRequest(Byte reqType) { this.reqType = reqType; <START> this.streamsRanges = Collections.EMPTY_LIST; <END> this.beforeCompactionMark = false; }</code><technical_language>Collections.emptyList() prevent generating warnings</technical_language>

Target:
public StreamsAddressRequest(Byte reqType) { this.reqType = reqType; this.streamsRanges = Collections.emptyList(); this.forSequencerTrim = false; }
Source:
<code>public ResourceTraversal[] getTraversals(ResourceMapping[] mappings, ResourceMappingContext context, IProgressMonitor monitor) throws CoreException { try { SubMonitor subMonitor = SubMonitor.convert(monitor, mappings.length); List<ResourceTraversal> traversals = new ArrayList<>(); for (int i = 0; i < mappings.length; i++) { ResourceMapping mapping = mappings[i]; Collections.addAll(traversals, mapping.getTraversals(context, subMonitor.newChild(1))); } return traversals.toArray(new ResourceTraversal[traversals.size()]); } finally { <START> monitor.done(); <END> } }</code><technical_language>Suggest removing call monitor.done() try/finally block</technical_language>

Target:
public ResourceTraversal[] getTraversals(ResourceMapping[] mappings, ResourceMappingContext context, IProgressMonitor monitor) throws CoreException { SubMonitor subMonitor = SubMonitor.convert(monitor, mappings.length); List<ResourceTraversal> traversals = new ArrayList<>(); for (int i = 0; i < mappings.length; i++) { ResourceMapping mapping = mappings[i]; Collections.addAll(traversals, mapping.getTraversals(context, subMonitor.newChild(1))); } return traversals.toArray(new ResourceTraversal[traversals.size()]); }
Source:
<code>private SelectionAdapter onFileSystemBrowseClicked() { return new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { FileDialog dialog = createFileDialog(model.getSource()); String file = dialog.open(); setLocalSourceFileName(file); } <START> private FileDialog createFileDialog(String selectedFile) { <END> FileDialog dialog = new FileDialog(getShell(), SWT.OPEN); dialog.setText("Select an OpenShift resource"); if(isFile(selectedFile)) { File file = new File(selectedFile); dialog.setFilterPath(file.getParentFile().getAbsolutePath()); } return dialog; } }; }</code><technical_language>this dialog limit resources *.json other browses workspace</technical_language>

Target:
private SelectionAdapter onFileSystemBrowseClicked() { return new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { FileDialog dialog = createFileDialog(model.getSource()); String file = dialog.open(); setLocalSourceFileName(file); } private FileDialog createFileDialog(String selectedFile) { FileDialog dialog = new FileDialog(getShell(), SWT.OPEN); dialog.setText("Select an OpenShift resource"); dialog.setFilterExtensions(new String[] {"*.json"}); if(exists(selectedFile)) { File file = new File(selectedFile); if (file.isFile()) { file = file.getParentFile(); } dialog.setFilterPath(file.getAbsolutePath()); } return dialog; } }; }
Source:
<code>public OrderedPartitionableRecord<Integer, Long> poll(long timeout) { ConsumerRecords<byte[], byte[]> polledRecords = consumer.poll(timeout); if (!polledRecords.isEmpty()) { <START> ConsumerRecord<byte[], byte[]> record = polledRecords.iterator().next(); <END> return new OrderedPartitionableRecord<>( record.topic(), record.partition(), record.offset(), record.value() == null ? null : ImmutableList.of(record.value()) ); } return null; }</code><technical_language>I realize this in code yet, this correct thing, is grabbing record is returned consumer.poll() in fact multiple records. I noticed BlockingQueue records this is why. RecordSupplier.poll() returns a single item, rest of results consumer.poll() need stored in a bounded queue somewhere, call consumer.poll() if queue is empty (or if consumer.poll() call is slow, want consider feeder threads similar Kinesis implementation). Alternately, another approach change RecordSupplier.poll() return a list simplify logic in this class</technical_language>

Target:
public List<OrderedPartitionableRecord<Integer, Long>> poll(long timeout) { List<OrderedPartitionableRecord<Integer, Long>> polledRecords = new ArrayList<>(); for (ConsumerRecord<byte[], byte[]> record : consumer.poll(timeout)) { polledRecords.add(new OrderedPartitionableRecord<>( record.topic(), record.partition(), record.offset(), record.value() == null ? null : ImmutableList.of(record.value()) )); } return polledRecords; }
Source:
<code>public void parseParallelPipelineOutput() throws IOException { Collection<FileAnnotation> warnings = parse("javac-parallel-pipeline.txt"); assertEquals(WRONG_NUMBER_OF_WARNINGS_DETECTED, 2, warnings.size()); <START> } <END></code><technical_language>Add checks for warnings properties: checkWarning(...) sure, regexp works correctly</technical_language>

Target:
public void parseParallelPipelineOutput() throws IOException { Collection<FileAnnotation> warnings = parse("javac-parallel-pipeline.txt"); assertEquals(WRONG_NUMBER_OF_WARNINGS_DETECTED, 2, warnings.size()); String fileName = "C:/Build/Results/jobs/ADT-Base/workspace/com.avaloq.adt.ui/src/main/java/com/avaloq/adt/ui/elements/AvaloqDialog.java"; Iterator<Warning> expectedWarnings = Arrays.asList( new Warning(fileName, 12, WARNING_TYPE, "Deprecation", "org.eclipse.jface.contentassist.SubjectControlContentAssistant in org.eclipse.jface.contentassist has been deprecated"), new Warning(fileName, 40, WARNING_TYPE, "Deprecation", "org.eclipse.ui.contentassist.ContentAssistHandler in org.eclipse.ui.contentassist has been deprecated") ).iterator(); Iterator<FileAnnotation> iterator = warnings.iterator(); while (iterator.hasNext()) { assertTrue(WRONG_NUMBER_OF_WARNINGS_DETECTED, expectedWarnings.hasNext()); Warning expectedWarning = expectedWarnings.next(); checkWarning(iterator.next(), expectedWarning.getPrimaryLineNumber(), expectedWarning.getMessage(), expectedWarning.getFileName(), expectedWarning.getType(), expectedWarning.getCategory(), expectedWarning.getPriority()); } }
Source:
<code>public Map<StreamId, OrcInputStream> readDiskRanges(StripeId stripeId, Map<StreamId, DiskRange> diskRanges, AggregatedMemoryContext systemMemoryUsage) throws IOException { ImmutableMap.Builder<StreamId, DiskRange> diskRangesBuilder = ImmutableMap.builder(); for (Entry<StreamId, DiskRange> entry : diskRanges.entrySet()) { DiskRange diskRange = entry.getValue(); diskRangesBuilder.put(entry.getKey(), new DiskRange(stripeId.getOffset() + diskRange.getOffset(), diskRange.getLength())); } diskRanges = diskRangesBuilder.build(); Map<StreamId, OrcDataSourceInput> streamsData = orcDataSource.readFully(diskRanges); ImmutableMap.Builder<StreamId, OrcInputStream> streamsBuilder = ImmutableMap.builder(); for (Entry<StreamId, OrcDataSourceInput> entry : streamsData.entrySet()) { FixedLengthSliceInput input; <START> if (entry.getKey().getStreamKind() == BLOOM_FILTER || entry.getKey().getStreamKind() == ROW_INDEX) { <END> input = new BasicSliceInput(stripeMetadataSource.getStreamSlice(new StripeStreamId(stripeId, entry.getKey()), entry.getValue())); } else { input = entry.getValue().getInput(); } streamsBuilder.put(entry.getKey(), new OrcInputStream(orcDataSource.getId(), input, decompressor, systemMemoryUsage, input.getRetainedSize())); } return streamsBuilder.build(); }</code><technical_language>Is this necessary? BTW, this is isIndexStream()</technical_language>

Target:
private Map<StreamId, OrcInputStream> readDiskRanges(StripeId stripeId, Map<StreamId, DiskRange> diskRanges, AggregatedMemoryContext systemMemoryUsage) throws IOException { Map<StreamId, OrcDataSourceInput> streamsData = stripeMetadataSource.getInputs(orcDataSource, stripeId, diskRanges); ImmutableMap.Builder<StreamId, OrcInputStream> streamsBuilder = ImmutableMap.builder(); for (Entry<StreamId, OrcDataSourceInput> entry : streamsData.entrySet()) { OrcDataSourceInput sourceInput = entry.getValue(); streamsBuilder.put(entry.getKey(), new OrcInputStream(orcDataSource.getId(), sourceInput.getInput(), decompressor, systemMemoryUsage, sourceInput.getRetainedSizeInBytes())); } return streamsBuilder.build(); }
Source:
<code>public void canReadNextIfNotProgressedBeyondForThorough() { progress.updateLastSweptTimestamp(thorough(shardCons), TS2); progress.updateLastSweptTimestamp(conservative(shardThor), TS2); <START> progress.updateLastSweptTimestamp(thorough(shardThor), TS2 - 1); <END> progress.updateLastSweptTimestamp(conservative(shardCons), TS2); assertThat(readThorough(shardThor)).contains(TS2_FINE_PARTITION); }</code><technical_language>mixtures of conservative confusing - I step is supposed do</technical_language>

Target:
public void canReadNextIfNotProgressedBeyondForThorough() { progress.updateLastSweptTimestamp(thorough(shardThor), TS2 - 1); assertThat(readThorough(shardThor)).contains(TS2_FINE_PARTITION); }
Source:
<code>private List<String> getOutputFolder() throws ValueStorageException { String outputDir; try { <START> outputDir = extensionService.getOutputDir(prefixURI(wsPath)); <END> } catch (Exception e) { throw new ValueStorageException( format("Failed to get '%s'. ", OUTPUT_FOLDER), e.getCause()); } String fsPath = transformer.transform(wsPath).toString(); return outputDir.startsWith(fsPath) ? singletonList(outputDir.substring(fsPath.length() + 1)) : singletonList(outputDir); }</code><technical_language>Dont add prefix for wsPath. added getOutDir method</technical_language>

Target:
private List<String> getOutputFolder() throws ValueStorageException { String outputDir; try { outputDir = extensionService.getOutputDir(wsPath); } catch (Exception e) { throw new ValueStorageException( format("Failed to get '%s'. ", OUTPUT_FOLDER), e.getCause()); } String fsPath = transformer.transform(wsPath).toString(); return outputDir.startsWith(fsPath) ? singletonList(outputDir.substring(fsPath.length() + 1)) : singletonList(outputDir); }
Source:
<code>public boolean verifyEvidence(Evidence evidence) throws RealmUnavailableException { if (!isBearerTokenEvidence(evidence.getClass())) { return false; } BearerTokenEvidence tokenEvidence = BearerTokenEvidence.class.cast(evidence); try { return strategy.validate(tokenEvidence) != null; } catch (RealmUnavailableException rue) { throw rue; <START> } catch (Exception unknown) { <END> ElytronMessages.log.debugf(unknown, "Failed to verify token evidence [%s]", tokenEvidence.getToken()); } return false; }</code><technical_language>catch expected exception type I think. Or, move exception catching logic strategy.validate() this code simple</technical_language>

Target:
public boolean verifyEvidence(Evidence evidence) throws RealmUnavailableException { return validateToken(evidence) != null; }