auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private boolean setCurrentFile(TrackedFile file, boolean resetParsing) { try { Preconditions.checkArgument(file == null || file.isOpen()); if (resetParsing || file == null) stopParsing("Parsing is reset by caller."); if (file != null) { long newOffset = file.getChannel().position(); if (currentFile == null || resetParsing) { logger.info("{}: Opening for parsing.", name, file.getPath()); currentBufferFileEnded = true; } else { currentBufferFileEnded = currentBufferFileEnded || (currentFileChannelOffset != newOffset); if (!sameAsCurrentFile(file)) { logger.info("{}: Continuing to parse {}.", name, file.getPath()); } logger.debug("{}: Old offset: {}, new offset: {}", name, currentFileChannelOffset, newOffset); } currentFile = file; currentFileChannel = currentFile.getChannel(); currentFileChannelOffset = currentFileChannel.position(); headerLinesToSkip = currentFileChannelOffset == 0 ? flow.getSkipHeaderLines() : 0; <START> fileFooterPattern = flow.getFleFooterPattern(); <END> return true; } else { return false; } } catch(IOException e) { logger.error("{}: Failed when setting current file to (reset={}).", name, file, resetParsing, e); stopParsing("Unhandled error."); totalUndhandledErrors.incrementAndGet(); return false; } }</code><technical_language>typo here, getFileFooterPattern(). I guess failing</technical_language>

Target:
private boolean setCurrentFile(TrackedFile file, boolean resetParsing) { try { Preconditions.checkArgument(file == null || file.isOpen()); if (resetParsing || file == null) stopParsing("Parsing is reset by caller."); if (file != null) { long newOffset = file.getChannel().position(); if (currentFile == null || resetParsing) { logger.info("{}: Opening for parsing.", name, file.getPath()); currentBufferFileEnded = true; } else { currentBufferFileEnded = currentBufferFileEnded || (currentFileChannelOffset != newOffset); if (!sameAsCurrentFile(file)) { logger.info("{}: Continuing to parse {}.", name, file.getPath()); } logger.debug("{}: Old offset: {}, new offset: {}", name, currentFileChannelOffset, newOffset); } currentFile = file; currentFileChannel = currentFile.getChannel(); currentFileChannelOffset = currentFileChannel.position(); headerLinesToSkip = currentFileChannelOffset == 0 ? flow.getSkipHeaderLines() : 0; fileFooterPattern = flow.getFileFooterPattern(); return true; } else { return false; } } catch(IOException e) { logger.error("{}: Failed when setting current file to (reset={}).", name, file, resetParsing, e); stopParsing("Unhandled error."); totalUndhandledErrors.incrementAndGet(); return false; } }
Source:
<code>TaskData getTaskData(AbstractRepositoryConnector connector, IProgressMonitor monitor) throws CoreException { if (taskId != null && taskKey != null && connector.supportsSearchByTaskKey(repository)) { try { <START> return getTaskDataWithKey(connector, monitor); <END> } catch (CoreException | RuntimeException e) { return connector.getTaskData(repository, taskId, monitor); } } else if (taskId != null) { return connector.getTaskData(repository, taskId, monitor); } else if (taskKey != null && connector.supportsSearchByTaskKey(repository)) { return getTaskDataWithKey(connector, monitor); } return null; }</code><technical_language>this return null, in case perform a lookup ID</technical_language>

Target:
TaskData getTaskData(AbstractRepositoryConnector connector, IProgressMonitor monitor) throws CoreException { if (taskId != null && taskKey != null && connector.supportsSearchByTaskKey(repository)) { try { TaskData data = getTaskDataWithKey(connector, monitor); if (data != null) { return data; } return connector.getTaskData(repository, taskId, monitor); } catch (CoreException | RuntimeException e) { return connector.getTaskData(repository, taskId, monitor); } } else if (taskId != null) { return connector.getTaskData(repository, taskId, monitor); } else if (taskKey != null && connector.supportsSearchByTaskKey(repository)) { return getTaskDataWithKey(connector, monitor); } return null; }
Source:
<code>void updatePartitionCountMetric() { try { Map<SystemStream, SystemStreamMetadata> currentMetadata = getMetadata(streamsToMonitor, metadataCache); Set<SystemStream> streamsChanged = new HashSet<>(); for (Map.Entry<SystemStream, SystemStreamMetadata> metadataEntry : initialMetadata.entrySet()) { try { SystemStream systemStream = metadataEntry.getKey(); SystemStreamMetadata metadata = metadataEntry.getValue(); int currentPartitionCount = currentMetadata.get(systemStream).getSystemStreamPartitionMetadata().keySet().size(); int prevPartitionCount = metadata.getSystemStreamPartitionMetadata().keySet().size(); Gauge gauge = gauges.get(systemStream); gauge.set(currentPartitionCount - prevPartitionCount); if (currentPartitionCount != prevPartitionCount) { <START> log.info(String.format("Change of partition count detected in stream %s. old partition count: %d, current partition count: %d", <END> systemStream.toString(), prevPartitionCount, currentPartitionCount)); streamsChanged.add(systemStream); } } catch (Exception e) { log.error(String.format("Error comparing partition count differences for stream: %s", metadataEntry.getKey().toString())); } } if (!streamsChanged.isEmpty() && this.callbackMethod != null) { this.callbackMethod.onSystemStreamPartitionChange(streamsChanged); } } catch (Exception e) { log.error("Exception while updating partition count metric.", e); } }</code><technical_language>this level of warn instead</technical_language>

Target:
public void updatePartitionCountMetric() { try { Map<SystemStream, SystemStreamMetadata> currentMetadata = getMetadata(streamsToMonitor, metadataCache); Set<SystemStream> streamsChanged = new HashSet<>(); for (Map.Entry<SystemStream, SystemStreamMetadata> metadataEntry : initialMetadata.entrySet()) { try { SystemStream systemStream = metadataEntry.getKey(); SystemStreamMetadata metadata = metadataEntry.getValue(); int currentPartitionCount = currentMetadata.get(systemStream).getSystemStreamPartitionMetadata().size(); int prevPartitionCount = metadata.getSystemStreamPartitionMetadata().size(); Gauge gauge = gauges.get(systemStream); gauge.set(currentPartitionCount - prevPartitionCount); if (currentPartitionCount != prevPartitionCount) { log.warn(String.format("Change of partition count detected in stream %s. old partition count: %d, current partition count: %d", systemStream.toString(), prevPartitionCount, currentPartitionCount)); streamsChanged.add(systemStream); } } catch (Exception e) { log.error(String.format("Error comparing partition count differences for stream: %s", metadataEntry.getKey().toString())); } } if (!streamsChanged.isEmpty() && this.callbackMethod != null) { this.callbackMethod.onSystemStreamPartitionChange(streamsChanged); } } catch (Exception e) { log.error("Exception while updating partition count metric.", e); } }
Source:
<code>public void canUpdateBusinessService() throws Exception { BusinessService service = new BusinessService(); service.setName("Dummy Service"); service.addReductionKey("key1"); service.addReductionKey("key2-deleteMe"); final Long serviceId = m_businessServiceDao.save(service); m_businessServiceDao.flush(); final String businessServiceDtoXml = "<business-service>" + " <id>" + serviceId + "</id>" + " <name>Dummy Service Updated</name>" + " <reductionKeys>" + " <reductionKey>key1updated</reductionKey>" + " </reductionKeys>" + "</business-service>"; sendData(PUT, MediaType.APPLICATION_XML, "/business-services/" + serviceId, businessServiceDtoXml, 204); assertEquals(1, m_businessServiceDao.findAll().size()); <START> assertEquals("Dummy Service Updated", m_businessServiceDao.findAll().get(0).getName()); <END> assertEquals(1, m_businessServiceDao.findAll().get(0).getReductionKeys().size()); assertTrue(m_businessServiceDao.findAll().get(0).getReductionKeys().contains("key1updated")); }</code><technical_language>above: Please a meaningful description instead of a single name</technical_language>

Target:
public void canUpdateBusinessService() throws Exception { BusinessService service = new BusinessService(); service.setName("Dummy Service"); service.addReductionKey("key1"); service.addReductionKey("key2-deleteMe"); final Long serviceId = m_businessServiceDao.save(service); m_businessServiceDao.flush(); final String businessServiceDtoXml = "<business-service>" + " <id>" + serviceId + "</id>" + " <name>Dummy Service Updated</name>" + " <reductionKeys>" + " <reductionKey>key1updated</reductionKey>" + " </reductionKeys>" + "</business-service>"; sendData(PUT, MediaType.APPLICATION_XML, "/business-services/" + serviceId, businessServiceDtoXml, 204); assertEquals(1, m_businessServiceDao.findAll().size()); assertEquals("Expected that the update BusinessService name is present.", "Dummy Service Updated", m_businessServiceDao.findAll().get(0).getName()); assertEquals("Expected that there is exactly one reductionkey on the BusinessService.", 1, m_businessServiceDao.findAll().get(0).getReductionKeys().size()); assertTrue("Expected that the update reductionkey is present.", m_businessServiceDao.findAll().get(0).getReductionKeys().contains("key1updated")); }
Source:
<code>public void unbindOutputs(BindingService bindingService) { if (log.isDebugEnabled()) { log.debug(String.format("Unbinding outputs for %s:%s", this.channelNamespace, this.type)); } <START> for (Map.Entry<String, BoundElementHolder> channelHolderEntry : this.outputHolders.entrySet()) { <END> if (channelHolderEntry.getValue().isBindable()) { if (log.isDebugEnabled()) { log.debug(String.format("Binding %s:%s:%s", this.channelNamespace, this.type, channelHolderEntry.getKey())); } bindingService.unbindProducers(channelHolderEntry.getKey()); } } }</code><technical_language>thing... I tracking I encountered, necessary address of changes scope of this PR if easier submit a subsequent PR addresses naming changes... I review it! ;)</technical_language>

Target:
public void unbindOutputs(BindingService bindingService) { if (log.isDebugEnabled()) { log.debug(String.format("Unbinding outputs for %s:%s", this.channelNamespace, this.type)); } for (Map.Entry<String, BoundTargetHolder> channelHolderEntry : this.outputHolders.entrySet()) { if (channelHolderEntry.getValue().isBindable()) { if (log.isDebugEnabled()) { log.debug(String.format("Binding %s:%s:%s", this.channelNamespace, this.type, channelHolderEntry.getKey())); } bindingService.unbindProducers(channelHolderEntry.getKey()); } } }
Source:
<code>private ElasticsearchAnalysisDefinitionRegistry createDefaultDefinitionRegistry() { ElasticsearchAnalysisDefinitionRegistryBuilderImpl builder = new ElasticsearchAnalysisDefinitionRegistryBuilderImpl(); String providerClassName = cfg.getProperty( ElasticsearchEnvironment.ANALYZER_DEFINITION_PROVIDER ); if ( providerClassName != null ) { ElasticsearchAnalysisDefinitionProvider provider; try { <START> Class<?> providerClazz = ClassLoaderHelper.classForName( providerClassName, serviceManager ); <END> provider = (ElasticsearchAnalysisDefinitionProvider) ReflectionHelper.createInstance( providerClazz, true ); } catch (RuntimeException e) { throw LOG.invalidElasticsearchAnalyzerDefinitionProvider( providerClassName, e ); } try { provider.register( builder ); } catch (SearchException e) { throw e; } catch (RuntimeException e) { throw LOG.invalidLuceneAnalyzerDefinitionProvider( providerClassName, e ); } } return builder.build(); }</code><technical_language>ClassLoaderHelper.instanceFromName instead ? provide more sanity checks errors consistent other services</technical_language>

Target:
private SimpleElasticsearchAnalysisDefinitionRegistry createDefaultDefinitionRegistry() { ElasticsearchAnalysisDefinitionRegistryBuilderImpl builder = new ElasticsearchAnalysisDefinitionRegistryBuilderImpl(); String providerClassName = cfg.getProperty( ElasticsearchEnvironment.ANALYZER_DEFINITION_PROVIDER ); if ( providerClassName != null ) { ElasticsearchAnalysisDefinitionProvider provider; try { Class<?> providerClazz = ClassLoaderHelper.classForName( providerClassName, serviceManager ); provider = (ElasticsearchAnalysisDefinitionProvider) ReflectionHelper.createInstance( providerClazz, true ); } catch (RuntimeException e) { throw LOG.invalidElasticsearchAnalyzerDefinitionProvider( providerClassName, e ); } try { provider.register( builder ); } catch (SearchException e) { throw e; } catch (RuntimeException e) { throw LOG.invalidLuceneAnalyzerDefinitionProvider( providerClassName, e ); } } return builder.build(); }
Source:
<code>public Obs getObs(Obs obs, String view) { File file = getComplexDataFile(obs); log.debug("value complex: " + obs.getValueComplex()); log.debug("file path: " + file.getAbsolutePath()); ComplexData complexData = null; if (ComplexObsHandler.RAW_VIEW.equals(view)) { String[] names = obs.getValueComplex().split("\\|"); <START> if (names != null) { <END> String originalFilename = names[0]; originalFilename = originalFilename.replaceAll(",", "").replaceAll(" ", "").replaceAll("file$", ""); try { complexData = new ComplexData(originalFilename, OpenmrsUtil.getFileAsBytes(file)); } catch (IOException e) { log.error("Trying to read file: " + file.getAbsolutePath(), e); } } } else { return null; } Assert.notNull(complexData, "Complex data must not be null"); String mimeType = OpenmrsUtil.getFileMimeType(file); complexData.setMimeType(mimeType); obs.setComplexData(complexData); return obs; }</code><technical_language>added this, intention of this loop @HerbertYiga</technical_language>

Target:
public Obs getObs(Obs obs, String view) { File file = getComplexDataFile(obs); log.debug("value complex: " + obs.getValueComplex()); log.debug("file path: " + file.getAbsolutePath()); ComplexData complexData = null; if (ComplexObsHandler.RAW_VIEW.equals(view)) { if(obs.getValueComplex()!=null && !obs.getValueComplex().isEmpty()) { String[] names = obs.getValueComplex().split("\\|"); String originalFilename = names[0]; originalFilename = originalFilename.replaceAll(",", "").replaceAll(" ", "").replaceAll("file$", ""); try { complexData = new ComplexData(originalFilename, OpenmrsUtil.getFileAsBytes(file)); } catch (IOException e) { log.error("Trying to read file: " + file.getAbsolutePath(), e); } } else { log.error("The file must exist!!"); } } else { return null; } Assert.notNull(complexData, "Complex data must not be null"); String mimeType = OpenmrsUtil.getFileMimeType(file); complexData.setMimeType(mimeType); obs.setComplexData(complexData); return obs; }
Source:
<code>public ActionBinding generate() throws UnableToCompleteException { String implName = getSuperTypeName() + SUFFIX; PrintWriter printWriter = getGeneratorUtil().tryCreatePrintWriter(getPackage(), implName); if (printWriter != null) { try { doGenerate(implName, printWriter); registerMetadata(); } finally { printWriter.close(); <START> } <END> } else { getLogger().debug("Action already generated. Returning."); } return createActionBinding(implName); }</code><technical_language>save a lot of duplication if move this try finally mergeTemplate. printwriter is called anyways</technical_language>

Target:
public ActionBinding generate() throws UnableToCompleteException { String implName = getSuperTypeName() + SUFFIX; if (doGenerate(implName)) { registerMetadata(); } return createActionBinding(implName); }
Source:
<code>public static Archive<?> createTestArchive() { WebArchive war = TestUtil.prepareArchive(JaxbMarshallingSoakTest.class.getSimpleName()); war.addClasses(JaxbMarshallingSoakItem.class, TestUtil.class, PortProviderUtil.class, TimeoutUtil.class); Map<String, String> contextParam = new HashMap<>(); contextParam.put("resteasy.async.job.service.enabled", "true"); war.addAsManifestResource(PermissionUtil.createPermissionsXmlAsset( new RuntimePermission("modifyThread"), <START> new ReflectPermission("suppressAccessChecks"), <END> new LoggingPermission("control", ""), new PropertyPermission("arquillian.*", "read"), new PropertyPermission("ipv6", "read"), new PropertyPermission("node", "read"), new PropertyPermission("org.jboss.resteasy.port", "read"), new PropertyPermission("ts.timeout.factor", "read"), new RuntimePermission("accessDeclaredMembers"), new RuntimePermission("getClassLoader"), new RuntimePermission("getenv.RESTEASY_PORT"), new SocketPermission(PortProviderUtil.getHost(), "connect,resolve") ), "permissions.xml"); return TestUtil.finishContainerPrepare(war, contextParam, JaxbMarshallingSoakAsyncService.class); }</code><technical_language>Out of curiosity, is jboss-modules needing this permission</technical_language>

Target:
public static Archive<?> createTestArchive() { WebArchive war = TestUtil.prepareArchive(JaxbMarshallingSoakTest.class.getSimpleName()); war.addClasses(JaxbMarshallingSoakItem.class, TestUtil.class, PortProviderUtil.class, TimeoutUtil.class); Map<String, String> contextParam = new HashMap<>(); contextParam.put("resteasy.async.job.service.enabled", "true"); war.addAsManifestResource(PermissionUtil.createPermissionsXmlAsset( new RuntimePermission("getClassLoader"), new RuntimePermission("modifyThread"), new ReflectPermission("suppressAccessChecks"), new LoggingPermission("control", ""), new PropertyPermission("arquillian.*", "read"), new PropertyPermission("ipv6", "read"), new PropertyPermission("node", "read"), new PropertyPermission("org.jboss.resteasy.port", "read"), new PropertyPermission("ts.timeout.factor", "read"), new RuntimePermission("accessDeclaredMembers"), new RuntimePermission("getenv.RESTEASY_PORT"), new SocketPermission(PortProviderUtil.getHost(), "connect,resolve") ), "permissions.xml"); return TestUtil.finishContainerPrepare(war, contextParam, JaxbMarshallingSoakAsyncService.class); }
Source:
<code>protected File determineActualFile(final HttpServletRequest request, Locale locale) { File file = ServletUtils.makeFileFromSanePath(request.getPathInfo(), base); <START> if (null != file && !ServletUtils.canReadFile(file)) { <END> file = ServletUtils.makeFileFromSanePath(replaceLocaleWithUSLocale(request.getPathInfo(), locale), base); } return file; }</code><technical_language>Please "something <operator> null" convention</technical_language>

Target:
protected File determineActualFile(final HttpServletRequest request, Locale locale) { File file = ServletUtils.makeFileFromSanePath(request.getPathInfo(), base); if (file != null && !ServletUtils.canReadFile(file)) { file = ServletUtils.makeFileFromSanePath(replaceLocaleWithUSLocale(request.getPathInfo(), locale), base); } return file; }
Source:
<code>private static void assertValidDeviceData(PostPutUserDto postPutUser) { if (postPutUser.deviceName == null) { String hint = "If the device name is not provided, the other properties should not be provided either"; Require.isNull(postPutUser.deviceOperatingSystemStr, () -> InvalidDataException.extraProperty("deviceOperatingSystem", hint)); Require.isNull(postPutUser.deviceAppVersion, () -> InvalidDataException.extraProperty("deviceAppVersion", hint)); Require.isNull(postPutUser.deviceAppVersionCode, () -> InvalidDataException.extraProperty("deviceAppVersionCode", hint)); } else { String hint = "If the device name is provided, the other properties must be present too"; Require.isNonNull(postPutUser.deviceOperatingSystemStr, <START> () -> InvalidDataException.extraProperty("deviceOperatingSystem", hint)); <END> Require.isNonNull(postPutUser.deviceAppVersion, () -> InvalidDataException.extraProperty("deviceAppVersion", hint)); Require.isNonNull(postPutUser.deviceAppVersionCode, () -> InvalidDataException.extraProperty("deviceAppVersionCode", hint)); } }</code><technical_language>this missingProperty instead of extraProperty</technical_language>

Target:
private static void assertValidDeviceData(PostPutUserDto postPutUser) { if (postPutUser.deviceName == null) { String hint = "If the device name is not provided, the other properties should not be provided either"; Require.isNull(postPutUser.deviceOperatingSystemStr, () -> InvalidDataException.extraProperty("deviceOperatingSystem", hint)); Require.isNull(postPutUser.deviceAppVersion, () -> InvalidDataException.extraProperty("deviceAppVersion", hint)); Require.isNull(postPutUser.deviceAppVersionCode, () -> InvalidDataException.extraProperty("deviceAppVersionCode", hint)); } else { String hint = "If the device name is provided, the other properties must be present too"; Require.isNonNull(postPutUser.deviceOperatingSystemStr, () -> InvalidDataException.missingProperty("deviceOperatingSystem", hint)); Require.isNonNull(postPutUser.deviceAppVersion, () -> InvalidDataException.missingProperty("deviceAppVersion", hint)); Require.isNonNull(postPutUser.deviceAppVersionCode, () -> InvalidDataException.missingProperty("deviceAppVersionCode", hint)); } }
Source:
<code>public Bucket getOrCreateBucket(String bucketName) { try { Bucket bucket = storage.get(bucketName); if (bucket == null) { log.debug(String.format("Creating a new bucket %s", bucketName)); return storage.create(BucketInfo.of(bucketName)); } return bucket; } catch (StorageException e) { <START> throw new NuxeoException(e); <END> } }</code><technical_language>StorageException is a runtime exception, need catch rethrow (several occurrences)</technical_language>

Target:
public Bucket getOrCreateBucket(String bucketName) { Bucket bucket = storage.get(bucketName); if (bucket == null) { log.debug(String.format("Creating a new bucket %s", bucketName)); return storage.create(BucketInfo.of(bucketName)); } return bucket; }
Source:
<code>private static Instance buildOafEntityResultInstance(Patent patent, String patentEpoUrlRoot) { Instance instance = new Instance(); instance.setInstancetype(buildOafEntityResultInstanceInstancetype()); instance.setHostedby(buildOafEntityPatentKeyValue()); instance.setCollectedfrom(buildOafEntityPatentKeyValue()); <START> instance.setUrl(Arrays.asList(buildOafEntityResultInstanceUrl(patent, patentEpoUrlRoot))); <END> return instance; }</code><technical_language>IDE Collections.singletonList</technical_language>

Target:
private static Instance buildOafEntityResultInstance(Patent patent, String patentEpoUrlRoot) { Instance instance = new Instance(); instance.setInstancetype(buildOafEntityResultInstanceInstancetype()); instance.setHostedby(buildOafEntityPatentKeyValue()); instance.setCollectedfrom(buildOafEntityPatentKeyValue()); instance.setUrl(Collections.singletonList(buildOafEntityResultInstanceUrl(patent, patentEpoUrlRoot))); return instance; }
Source:
<code>public void setMetaData(int x, int z, int y, int metaData) { if (metaData < 0 || metaData >= 16) throw new IllegalArgumentException("Metadata out of range: " + metaData); ChunkSection section = getSection(y); if (section == null) return; int index = section.index(x, y, z); if ((section.types[index] << 4) == 0) return; <START> section.types[index] |= metaData; <END> }</code><technical_language>If metadata 0, bits cleared. metaData range checked (or & 0xF'd)</technical_language>

Target:
public void setMetaData(int x, int z, int y, int metaData) { if (metaData < 0 || metaData >= 16) throw new IllegalArgumentException("Metadata out of range: " + metaData); ChunkSection section = getSection(y); if (section == null) return; int index = section.index(x, y, z); if (section.types[index] == 0) return; section.types[index] &= 0xfff0; section.types[index] |= metaData; }
Source:
<code>protected boolean checkStorageDomainStatusNotEqual(StorageDomainStatus status) { <START> if (getStorageDomainStatus() != null && getStorageDomainStatus() != status) { <END> addStorageDomainStatusIllegalMessage(); return true; } return false; }</code><technical_language>null check removed.</technical_language>

Target:
protected boolean checkStorageDomainStatusNotEqual(StorageDomainStatus status) { boolean returnValue = false; if (getStorageDomainStatus() != null && getStorageDomainStatus() != null) { returnValue = (getStorageDomainStatus() != status); if (!returnValue) { addStorageDomainStatusIllegalMessage(); } } return returnValue; }
Source:
<code>public void run(StreamApplication app) { try { ProcessorGraph processorGraph = getExecutionPlan(app); List<StreamSpec> streams = processorGraph.getIntermediateStreams().stream() .map(streamEdge -> streamEdge.getStreamSpec()) .collect(Collectors.toList()); <START> StreamManager streamManager = new StreamManager(new JavaSystemConfig(config).getSystemAdmins()); <END> streamManager.createStreams(streams); processorGraph.getProcessorNodes().forEach(processor -> { Config processorConfig = processor.generateConfig(); log.info("Starting processor with config {}", processor.getId(), processorConfig); JobRunner runner = new JobRunner(processorConfig); runner.run(true); }); } catch (Throwable t) { throw new SamzaException("Failed to run application", t); } }</code><technical_language>create StreamManager in beginning of run() pass planner system admins created twice</technical_language>

Target:
public void run(StreamApplication app) { try { ProcessorGraph processorGraph = getExecutionPlan(app); List<StreamSpec> streams = processorGraph.getIntermediateStreams().stream() .map(streamEdge -> streamEdge.getStreamSpec()) .collect(Collectors.toList()); streamManager.createStreams(streams); processorGraph.getProcessorNodes().forEach(processor -> { Config processorConfig = processor.generateConfig(); log.info("Starting processor with config {}", processor.getId(), processorConfig); JobRunner runner = new JobRunner(processorConfig); runner.run(true); }); } catch (Throwable t) { throw new SamzaException("Failed to run application", t); } }
Source:
<code>public String humanReadablePath() { String path = super.humanReadablePath(); <START> if(order == null <END> || type == Type.SAVED || type == Type.UPVOTED || type == Type.DOWNVOTED || type == Type.HIDDEN) { return path; } switch(order) { case TOP_HOUR: case TOP_DAY: case TOP_WEEK: case TOP_MONTH: case TOP_YEAR: case TOP_ALL: return path + "?t=" + General.asciiLowercase(order.name().split("_")[1]); default: return path + "?sort=" + General.asciiLowercase(order.name()); } }</code><technical_language>if(order == null || type != SUBMITTED)</technical_language>

Target:
public String humanReadablePath() { String path = super.humanReadablePath(); if(order == null || type != Type.SUBMITTED) { return path; } switch(order) { case TOP_HOUR: case TOP_DAY: case TOP_WEEK: case TOP_MONTH: case TOP_YEAR: case TOP_ALL: return path + "?t=" + General.asciiLowercase(order.name().split("_")[1]); default: return path + "?sort=" + General.asciiLowercase(order.name()); } }
Source:
<code>public void stop() throws Exception { applicationContext.close(); super.stop(); Thread stopThread = new Thread(() -> { try { <START> Thread.sleep(Duration.ofSeconds(20).toMillis()); <END> } catch (InterruptedException e) { } Thread.getAllStackTraces() .entrySet() .stream() .filter(e -> !e.getKey().isDaemon()) .forEach(e -> { log.info("Non daemon Thread \"{}\" (id: {}) still active in state: {}", e.getKey().getName(), e.getKey().getId(), e.getKey().getState()); log.info("Stacktrace of thread {}:\n{}", e.getKey().getName(), Arrays.stream(e.getValue()).map(Object::toString).collect(Collectors.joining("\n"))); }); try { Thread.sleep(Duration.ofSeconds(1).toMillis()); } catch (InterruptedException e) { } System.exit(-1); }); stopThread.setDaemon(true); stopThread.start(); }</code><technical_language>30 seconds</technical_language>

Target:
public void stop() throws Exception { applicationContext.close(); super.stop(); Thread timeoutThread = new Thread(() -> { try { Thread.sleep(Duration.ofSeconds(30).toMillis()); } catch (InterruptedException e) { } Set<Entry<Thread, StackTraceElement[]>> threads = Thread.getAllStackTraces().entrySet(); if (threads.stream().allMatch(t -> t.getKey().isDaemon())) { return; } threads.stream() .filter(e -> !e.getKey().isDaemon()) .forEach(e -> { log.error("Non daemon Thread \"{}\" (id: {}) still active in state: {}", e.getKey().getName(), e.getKey().getId(), e.getKey().getState()); log.error("Stacktrace of thread {}:\n{}", e.getKey().getName(), Arrays.stream(e.getValue()).map(Object::toString).collect(Collectors.joining("\n"))); }); try { Thread.sleep(Duration.ofSeconds(1).toMillis()); } catch (InterruptedException e) { } System.exit(-1); }); timeoutThread.setDaemon(true); timeoutThread.start(); }
Source:
<code>public static String getNestedHtml(String raw_html){ <START> String html = raw_html.replace("\\",""); <END> Document doc = Jsoup.parse(html); Elements scripts = doc.getElementsByTag("script"); Pattern pttrn = Pattern.compile("\"html\":\""); String nested_html = ""; for (Element script:scripts){ Matcher m = pttrn.matcher(html = script.html()); if(m.find()){ nested_html += html.substring(m.end(), html.length() -3); } } return nested_html; }</code><technical_language>pass URL getNestedHtml , call buildRequest get html ? i getNestedHtml method directly. folder structure do suggest? create a weibo folder add request files it</technical_language>

Target:
private static String getNestedHtml(String raw_html){ String html = raw_html.replace("\\",""); Document doc = Jsoup.parse(html); Elements scripts = doc.getElementsByTag("script"); Pattern pttrn = Pattern.compile("\"html\":\""); String nested_html = ""; for (Element script:scripts){ Matcher m = pttrn.matcher(html = script.html()); if(m.find()){ nested_html += html.substring(m.end(), html.length() -3); } } return nested_html; }
Source:
<code>public Boolean getNoZooKeeperRegistration() { <START> return fromNullable(options.getBoolean(noZooKeeperRegistrationArg.getDest())).or(true); <END> }</code><technical_language>I this is tests failing. true master registers default? Part of master registration is creating root nodes in ZooKeeper. creating nodes explain SoloIT fails</technical_language>

Target:
public Boolean getNoZooKeeperRegistration() { return fromNullable(options.getBoolean(noZooKeeperRegistrationArg.getDest())).or(false); }
Source:
<code>public CertificateClientBuilder addPolicy(HttpPipelinePolicy policy) { <START> Objects.requireNonNull(policy, "Http pipeline policy cannot be null."); <END> policies.add(policy); return this; }</code><technical_language>suggestion Objects.requireNonNull(policy, "'policy' null.");</technical_language>

Target:
public CertificateClientBuilder addPolicy(HttpPipelinePolicy policy) { Objects.requireNonNull(policy, "'policy' cannot be null."); policies.add(policy); return this; }
Source:
<code>protected void configureWebResources(GenericWebApplicationContext context, WebMergedContextConfiguration webMergedConfig) { ApplicationContext parent = context.getParent(); <START> if ((!(parent instanceof WebApplicationContext))) { <END> String resourceBasePath = webMergedConfig.getResourceBasePath(); ResourceLoader resourceLoader = (resourceBasePath.startsWith(ResourceLoader.CLASSPATH_URL_PREFIX) ? new DefaultResourceLoader() : new FileSystemResourceLoader()); ServletContext servletContext = new MockServletContext(resourceBasePath, resourceLoader); servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, context); context.setServletContext(servletContext); } else { ServletContext servletContext = null; while (parent != null) { if (parent instanceof WebApplicationContext && !(parent.getParent() instanceof WebApplicationContext)) { servletContext = ((WebApplicationContext) parent).getServletContext(); break; } parent = parent.getParent(); } Assert.state(servletContext != null, "Failed to find root WebApplicationContext in the context hierarchy"); context.setServletContext(servletContext); } }</code><technical_language>suggestion if (!(parent instanceof WebApplicationContext)) {</technical_language>

Target:
protected void configureWebResources(GenericWebApplicationContext context, WebMergedContextConfiguration webMergedConfig) { ApplicationContext parent = context.getParent(); if (!(parent instanceof WebApplicationContext)) { String resourceBasePath = webMergedConfig.getResourceBasePath(); ResourceLoader resourceLoader = (resourceBasePath.startsWith(ResourceLoader.CLASSPATH_URL_PREFIX) ? new DefaultResourceLoader() : new FileSystemResourceLoader()); ServletContext servletContext = new MockServletContext(resourceBasePath, resourceLoader); servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, context); context.setServletContext(servletContext); } else { ServletContext servletContext = null; while (parent != null) { if (parent instanceof WebApplicationContext && !(parent.getParent() instanceof WebApplicationContext)) { servletContext = ((WebApplicationContext) parent).getServletContext(); break; } parent = parent.getParent(); } Assert.state(servletContext != null, "Failed to find root WebApplicationContext in the context hierarchy"); context.setServletContext(servletContext); } }
Source:
<code>private void setDefaultDateFormatterBuilder() { if (dateFormatterBuilder == null) { String tzStr = config.getString("gitiles", null, "fixedTimeZone"); Optional<TimeZone> tz; if (tzStr == null) { tz = Optional.absent(); <START> } else if (tzStr.equalsIgnoreCase("default")) { tz = Optional.of(SystemReader.getInstance().getTimeZone()); <END> } else { tz = Optional.of(TimeZone.getTimeZone(tzStr)); } dateFormatterBuilder = new DateFormatterBuilder(tz); } }</code><technical_language>For sake of load balanced multihomed setups enlightened enough PST prefer support this case if needs it</technical_language>

Target:
private void setDefaultDateFormatterBuilder() { if (dateFormatterBuilder == null) { String tzStr = config.getString("gitiles", null, "fixedTimeZone"); Optional<TimeZone> tz; if (tzStr == null) { tz = Optional.absent(); } else { tz = Optional.of(TimeZone.getTimeZone(tzStr)); } dateFormatterBuilder = new DateFormatterBuilder(tz); } }
Source:
<code>public void processVirtualAttributeChanged(String msg, MessageBeans beans) { <START> if (beans.getUser() == null || beans.getAttribute() == null || beans.getResource() == null) { <END> return; } try { log.debug("Getting resources assigned to facility {}", beans.getFacility().getId()); List<Resource> resources = ldapcManager.getPerunBl().getFacilitiesManager().getAssignedResources(ldapcManager.getPerunSession(), beans.getFacility()); Attribute virtAttr = ((PerunBl) ldapcManager.getPerunBl()).getAttributesManagerBl(). getAttribute(ldapcManager.getPerunSession(), beans.getUser(), beans.getAttribute().getName()); for (Resource resource : resources) { log.debug("Changing virtual attribute for resource {}", beans.getAttribute(), resource); perunResource.modifyEntry(resource, virtAttr); } } catch (InternalErrorException | AttributeNotExistsException | WrongAttributeAssignmentException | FacilityNotExistsException | PrivilegeException | NamingException e) { log.error("Error changing virtual attribute:", e); } }</code><technical_language>it. beans checked ? If this is a change virtual facility attribute, check presence of Attribute Facility beans read message</technical_language>

Target:
public void processVirtualAttributeChanged(String msg, MessageBeans beans) { PerunBl perun = (PerunBl) ldapcManager.getPerunBl(); if (beans.getAttribute() == null || beans.getFacility() == null) { return; } try { log.debug("Getting resources assigned to facility {}", beans.getFacility().getId()); List<Resource> resources = perun.getFacilitiesManagerBl().getAssignedResources(ldapcManager.getPerunSession(), beans.getFacility()); Attribute virtAttr = perun.getAttributesManagerBl(). getAttribute(ldapcManager.getPerunSession(), beans.getFacility(), beans.getAttribute().getName()); log.debug("Changing virtual attribute for facility {}", virtAttr, beans.getFacility()); perunFacility.modifyEntry(beans.getFacility(), virtAttr); for (Resource resource : resources) { log.debug("Changing virtual attribute for resource {}", virtAttr, resource); perunResource.modifyEntry(resource, virtAttr); } } catch (InternalErrorException | AttributeNotExistsException | WrongAttributeAssignmentException | NamingException e) { log.error("Error changing virtual attribute:", e); } }
Source:
<code>public boolean remove(Connection connection) { boolean removed = connectionPool.remove(connection); if (getHttpExchanges().isEmpty()) { tryRemoveIdleDestination(); } else { if (removed) <START> process(true); <END> } return connectionPool.remove(connection); }</code><technical_language>this check queue is 0? acquire a connection if waiting exchanges</technical_language>

Target:
public boolean remove(Connection connection) { boolean removed = connectionPool.remove(connection); if (getHttpExchanges().isEmpty()) { tryRemoveIdleDestination(); } else if (removed) { process(true); } return removed; }
Source:
<code>public void cancelInput() { if (aliquotHandlingSteps.stream().anyMatch(this::hasInput)) { <START> getLastCompletedAliquotHandlingStep().cancelInput(); <END> } else if (hasInput(boxStep)) { boxStep.cancelInput(); } else if (hasInput(aliquotStep)) { aliquotStep.cancelInput(); } else if (hasInput(qcStep)) { qcStep.cancelInput(); } else if (hasInput(sampleStep)) { sampleStep.cancelInput(); } }</code><technical_language>![MAJOR](<LINK_0> 'Severity: MAJOR') A "NullPointerException" thrown; "getLastCompletedAliquotHandlingStep()" return null. [![rule](<LINK_1>](<LINK_2></technical_language>

Target:
public void cancelInput() { if (aliquotHandlingSteps.stream().anyMatch(this::hasInput)) { getLastCompletedAliquotHandlingStep().cancelInput(); } else if (hasInput(aliquotBoxStep)) { aliquotBoxStep.cancelInput(); } else if (hasInput(aliquotStep)) { aliquotStep.cancelInput(); } else if (hasInput(stockBoxPositionStep)) { stockBoxPositionStep.cancelInput(); } else if (hasInput(stockBoxStep)) { stockBoxStep.cancelInput(); } else if (hasInput(qcStep)) { qcStep.cancelInput(); } else if (hasInput(stockStep)) { stockStep.cancelInput(); } }
Source:
<code>public Uri insertTestRaw() { <START> ContentValues values = new ContentValues(); values.put("address", "+19998880002"); values.put("display_originating_addr", "+1234567890"); values.put("count", 1); values.put("message_body", TEST_RAW_MESSAGE_BODY); <END> return mContentResolver.insert(RAW_URI, values); }</code><technical_language>constants for column names</technical_language>

Target:
public Uri insertTestRaw() { ContentValues values = new ContentValues(); values.put(Telephony.Raw.ADDRESS, "1234567890"); values.put(Telephony.Raw.DISPLAY_ORIGINATING_ADDRESS, "+1234567890"); values.put(Telephony.Raw.COUNT, 1); values.put(Telephony.Raw.MESSAGE_BODY, TEST_RAW_MESSAGE_BODY); return mContentResolver.insert(RAW_URI, values); }
Source:
<code>public Relationship getByTypeUuidAndPersonUuid(String configName, String typeUuid, String personUuid) { Config config = configService.getConfigByName(configName); RelationshipListResult result = relationshipResource.getByPersonUuid(config, personUuid); List<Relationship> relationships = new ArrayList<>(Collections2.filter(result.getResults(), new Predicate<Relationship>() { @Override public boolean apply(Relationship relationship) { String personBUuid = null; String relationshipTypeUuid = null; if (relationship.getPersonB() != null) { personBUuid = relationship.getPersonB().getUuid(); } if (relationship.getRelationshipType() != null) { relationshipTypeUuid = relationship.getRelationshipType().getUuid(); } <START> return StringUtils.equals(personBUuid, personUuid) <END> && StringUtils.equals(relationshipTypeUuid, typeUuid); } })); if (relationships.size() > 1) { LOGGER.warn(String.format("Multiple relationships found for the type with the \"%s\" UUID and the person" + "with the \"%s\" UUID. The first relationship in the list will be returned", typeUuid, personUuid)); } return relationships.isEmpty() ? null : relationships.get(0); }</code><technical_language>checking person uuid here? fetch handle that, pass uuid aparameter</technical_language>

Target:
public List<Relationship> getByTypeUuidAndPersonUuid(String configName, String typeUuid, String personUuid) { Config config = configService.getConfigByName(configName); RelationshipListResult result = relationshipResource.getByPersonUuid(config, personUuid); return new ArrayList<>(Collections2.filter(result.getResults(), new Predicate<Relationship>() { @Override public boolean apply(Relationship relationship) { String personBUuid = null; String relationshipTypeUuid = null; if (relationship.getPersonB() != null) { personBUuid = relationship.getPersonB().getUuid(); } if (relationship.getRelationshipType() != null) { relationshipTypeUuid = relationship.getRelationshipType().getUuid(); } return StringUtils.equals(personBUuid, personUuid) && StringUtils.equals(relationshipTypeUuid, typeUuid); } })); }
Source:
<code>protected IScalarEvaluator createEvaluator(IHyracksTaskContext ctx, IScalarEvaluator[] args) throws AlgebricksException { final ArrayBackedValueStorage abvs = new ArrayBackedValueStorage(); final UTF8StringPointable stringp = (UTF8StringPointable) UTF8StringPointable.FACTORY.createPointable(); final TaggedValuePointable nodep = (TaggedValuePointable) TaggedValuePointable.FACTORY.createPointable(); final ByteBufferInputStream bbis = new ByteBufferInputStream(); final DataInputStream di = new DataInputStream(bbis); final SequenceBuilder sb = new SequenceBuilder(); final ArrayBackedValueStorage abvsFileNode = new ArrayBackedValueStorage(); final int partition = ctx.getTaskAttemptId().getTaskId().getPartition(); final String nodeId = ctx.getJobletContext().getApplicationContext().getNodeId(); final ITreeNodeIdProvider nodeIdProvider = new TreeNodeIdProvider((short) partition); return new AbstractTaggedValueArgumentScalarEvaluator(args) { @Override protected void evaluate(TaggedValuePointable[] args, IPointable result) throws SystemException { IndexUpdater updater = new IndexUpdater(args, result, stringp, bbis, di, sb, abvs, nodeIdProvider, abvsFileNode, nodep, nodeId); try { updater.setup(); updater.deleteAllIndexes(); } catch (IOException | NoSuchAlgorithmException e) { <START> e.printStackTrace(); <END> } } }; }</code><technical_language>Throw exception</technical_language>

Target:
protected IScalarEvaluator createEvaluator(IHyracksTaskContext ctx, IScalarEvaluator[] args) throws AlgebricksException { final ArrayBackedValueStorage abvs = new ArrayBackedValueStorage(); final UTF8StringPointable stringp = (UTF8StringPointable) UTF8StringPointable.FACTORY.createPointable(); final TaggedValuePointable nodep = (TaggedValuePointable) TaggedValuePointable.FACTORY.createPointable(); final ByteBufferInputStream bbis = new ByteBufferInputStream(); final DataInputStream di = new DataInputStream(bbis); final SequenceBuilder sb = new SequenceBuilder(); final ArrayBackedValueStorage abvsFileNode = new ArrayBackedValueStorage(); final int partition = ctx.getTaskAttemptId().getTaskId().getPartition(); final String nodeId = ctx.getJobletContext().getApplicationContext().getNodeId(); final ITreeNodeIdProvider nodeIdProvider = new TreeNodeIdProvider((short) partition); return new AbstractTaggedValueArgumentScalarEvaluator(args) { @Override protected void evaluate(TaggedValuePointable[] args, IPointable result) throws SystemException { IndexUpdater updater = new IndexUpdater(args, result, stringp, bbis, di, sb, abvs, nodeIdProvider, abvsFileNode, nodep, nodeId); try { updater.setup(); updater.deleteAllIndexes(); } catch (IOException | NoSuchAlgorithmException | JAXBException e) { throw new SystemException(ErrorCode.SYSE0001, e); } } }; }
Source:
<code>protected Object readInternal(Class<? extends Object> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException { Object result = null; InputStream inputStream = inputMessage.getBody(); try { result = convertStreamToConsoleConnectionDetails(inputStream); } finally { <START> if (inputStream != null) { <END> try { inputStream.close(); } catch (IOException e) { Log.e(TAG, "failed to close input stream"); } } } return result; }</code><technical_language>inputStream null? If yes, happen convertStreamToConsoleConnectionDetails if pass null</technical_language>

Target:
protected Object readInternal(Class<? extends Object> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException { Object result = null; InputStream inputStream = inputMessage.getBody(); try { result = convertStreamToConsoleConnectionDetails(inputStream); } catch (Exception x) { throw new IllegalStateException("Couldn't parse .vv file response", x); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { Log.e(TAG, "failed to close input stream"); } } } return result; }
Source:
<code>public void delay(Guid vdsId) { log.debug("try to wait for te engine update the host memory and cpu stats"); try { long t = Math.max( ResourceManager.getInstance().GetVdsManager(vdsId).getLastUpdateElapsed(), TimeUnit.SECONDS.toMillis(Config.<Integer> getValue(VdsRefreshRate))); t = Math.max(Config.<Integer> getValue(ConfigValues.ThrottlerMaxWaitForVdsUpdateInMillis), t); <START> VmHandler.getBlockingQueue(vdsId).poll(t, TimeUnit.MILLISECONDS); <END> } catch (InterruptedException e) { } }</code><technical_language>need extract getBlockingQueue, is needed stop command</technical_language>

Target:
public void delay(Guid vdsId) { log.debug("try to wait for te engine update the host memory and cpu stats"); try { long t = Math.max( ResourceManager.getInstance().GetVdsManager(vdsId).getLastUpdateElapsed(), TimeUnit.SECONDS.toMillis(Config.<Integer> getValue(VdsRefreshRate))); t = Math.max(Config.<Integer> getValue(ConfigValues.ThrottlerMaxWaitForVdsUpdateInMillis), t); getBlockingQueue(vdsId).poll(t, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { } }
Source:
<code>public GithubProfileScraper() { super(); this.baseUrl = "<LINK_0>"; <START> String scraperName = "Github"; <END> }</code><technical_language>this a local varaible. This a class property right</technical_language>

Target:
public GithubProfileScraper() { super(); this.baseUrl = "<LINK_0>"; this.scraperName = "Github"; }
Source:
<code>public void testCleanResource() throws Exception { String[] cmdArrayToRecreateDB; if (CarbonCommandToolsUtil.isCurrentOSWindows()) { cmdArrayToRecreateDB = new String[]{"-Dsetup"}; process = CarbonCommandToolsUtil. startServerUsingCarbonHome(carbonHome, 1, context, cmdArrayToRecreateDB); } else { cmdArrayToRecreateDB = new String[]{"-Dsetup"}; process = CarbonCommandToolsUtil. startServerUsingCarbonHome(carbonHome, 1, context, cmdArrayToRecreateDB); } boolean startupStatus = CarbonCommandToolsUtil.isServerStartedUp(context, portOffset); log.info("Server startup status : " + startupStatus); boolean fileCreated = CarbonCommandToolsUtil. waitForFileCreation(carbonHome + File.separator + "repository" + File.separator + "database" + File.separator + "DsetupCommandTEST_DB.h2.db"); <START> Assert.assertTrue(fileCreated, "Java file not created successfully"); <END> String loginStatusString = authenticatorClient.login(); assertTrue(loginStatusString.contains("JSESSIONID"), "Unsuccessful login"); }</code><technical_language>static testng assert imports</technical_language>

Target:
public void testCleanResource() throws Exception { String[] cmdArrayToRecreateDB; if ((CarbonCommandToolsUtil.getCurrentOperatingSystem(). contains(OperatingSystems.WINDOWS.name().toLowerCase()))) { cmdArrayToRecreateDB = new String[]{"-Dsetup"}; process = CarbonCommandToolsUtil. startServerUsingCarbonHome(carbonHome, 1, context, cmdArrayToRecreateDB); } else { cmdArrayToRecreateDB = new String[]{"-Dsetup"}; process = CarbonCommandToolsUtil. startServerUsingCarbonHome(carbonHome, 1, context, cmdArrayToRecreateDB); } boolean startupStatus = CarbonCommandToolsUtil.isServerStartedUp(context, portOffset); log.info("Server startup status : " + startupStatus); boolean fileCreated = CarbonCommandToolsUtil. waitForFileCreation(carbonHome + File.separator + "repository" + File.separator + "database" + File.separator + "DsetupCommandTEST_DB.h2.db"); Assert.assertTrue(fileCreated, "Java file not created successfully"); String loginStatusString = authenticatorClient.login(); assertTrue(loginStatusString.contains("JSESSIONID"), "Unsuccessful login"); }
Source:
<code>public Object deserialize(byte[] data) { try { ByteArrayInputStream buffer = new ByteArrayInputStream(data); FSTObjectInput in = fastSerialConfig.getObjectInput(buffer); Object result = in.readObject(); buffer.close(); return result; } catch (IOException e) { <START> throw new Fast2WicketSerialException("deserialize", e); <END> } catch (ClassNotFoundException e) { throw new Fast2WicketSerialException("deserialize", e); } }</code><technical_language>if provide "serialize" message please improve this too</technical_language>

Target:
public Object deserialize(byte[] data) { try { return fastSerializationConfig.getObjectInput(data).readObject(); } catch (Exception e) { throw new Fast2WicketSerialException("Unable to deserialize the data", e); } }