auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private Set<SerialPortInfo> getSerialPortInfos() throws IOException { <START> Set<SerialPortInfo> result = Sets.newHashSet(); <END> try (DirectoryStream<Path> sysfsTtyPaths = newDirectoryStream(Paths.get(sysfsTtyDevicesDirectory))) { for (Path sysfsTtyPath : sysfsTtyPaths) { String serialPortName = sysfsTtyPath.getFileName().toString(); Path devicePath = Paths.get(devDirectory).resolve(serialPortName); Path sysfsDevicePath = getSysfsDevicePath(sysfsTtyPath); if (sysfsDevicePath != null && isAccessible(devicePath)) { result.add(new SerialPortInfo(devicePath, sysfsDevicePath)); } } } return result; }</code><technical_language>new HashSet<>();</technical_language>

Target:
private Set<SerialPortInfo> getSerialPortInfos() throws IOException { Set<SerialPortInfo> result = new HashSet<>(); try (DirectoryStream<Path> sysfsTtyPaths = newDirectoryStream(Paths.get(sysfsTtyDevicesDirectory))) { for (Path sysfsTtyPath : sysfsTtyPaths) { String serialPortName = sysfsTtyPath.getFileName().toString(); Path devicePath = Paths.get(devDirectory).resolve(serialPortName); Path sysfsDevicePath = getSysfsDevicePath(sysfsTtyPath); if (sysfsDevicePath != null && isAccessible(devicePath)) { result.add(new SerialPortInfo(devicePath, sysfsDevicePath)); } } } return result; }
Source:
<code>int getPatchSetNumber(TaskRepository repository, String url, String taskId) { <START> String taskUrl = TasksUi.getRepositoryConnector(GerritConnector.CONNECTOR_KIND).getTaskUrl(repository.getUrl(), <END> taskId); String urlQualifiers = StringUtils.remove(url, taskUrl); String[] fragments = StringUtils.split(urlQualifiers, "/"); if (fragments.length > 0) { String patchSetFragment = fragments[0]; try { return Integer.valueOf(patchSetFragment); } catch (NumberFormatException e) { } } return -1; }</code><technical_language>Extract a method returns fragments, call in getFilePath</technical_language>

Target:
int getPatchSetNumber(TaskRepository repository, String url, String taskId) { String[] fragments = extractUrlFragments(repository, url, taskId); if (fragments.length > 0) { String patchSetFragment = fragments[0]; try { return Integer.valueOf(patchSetFragment); } catch (NumberFormatException e) { } } return -1; }
Source:
<code>private TextKafkaStreamGenerator(@Parameter (ZkSourceAddress.class) final String zkAddress, @Parameter (ZkSourcePort.class)final int zkPort, @Parameter (KafkaTopicName.class)final String topic, @Parameter (DataFetchSleepTime.class)final long sleepTime, @Parameter (SourceId.class)final String sourceId, @Parameter (QueryId.class)final String queryId, final StringIdentifierFactory identifierFactory) { this.executorService = Executors.newSingleThreadExecutor(); this.closed = new AtomicBoolean(false); this.started = new AtomicBoolean(false); this.sleepTime = sleepTime; this.queryId = identifierFactory.getNewInstance(queryId); this.identifier = identifierFactory.getNewInstance(sourceId); final Properties props = new Properties(); props.put("group.id", "group1"); props.put("zookeeper.connect", zkAddress+":"+zkPort); final ConsumerConfig consumerConfig = new ConsumerConfig(props); <START> consumer = Consumer.createJavaConsumerConnector(consumerConfig); <END> final Map<String, Integer> topicCountMap = new HashMap<>(); topicCountMap.put(topic, numThreads); final Map<String, List<KafkaStream<byte[], byte[]>>> consumerMap = consumer.createMessageStreams(topicCountMap); streams = consumerMap.get(topic); }</code><technical_language>If create connect a consumer kafka source of queries, is benefit of Kafka instead of Socket</technical_language>

Target:
private TextKafkaStreamGenerator(@Parameter (ZkSourceAddress.class) final String zkAddress, @Parameter (ZkSourcePort.class)final int zkPort, @Parameter (KafkaTopicName.class)final String topic, @Parameter (DataFetchSleepTime.class)final long sleepTime, @Parameter (SourceId.class)final String sourceId, @Parameter (QueryId.class)final String queryId, final StringIdentifierFactory identifierFactory) { this.executorService = Executors.newSingleThreadExecutor(); this.closed = new AtomicBoolean(false); this.started = new AtomicBoolean(false); this.sleepTime = sleepTime; this.queryId = identifierFactory.getNewInstance(queryId); this.identifier = identifierFactory.getNewInstance(sourceId); final Properties props = new Properties(); props.put("group.id", "group1"); props.put("zookeeper.connect", String.format("%s:%s", zkAddress, zkPort)); final ConsumerConfig consumerConfig = new ConsumerConfig(props); consumer = Consumer.createJavaConsumerConnector(consumerConfig); final Map<String, Integer> topicCountMap = new HashMap<>(); topicCountMap.put(topic, numThreads); final Map<String, List<KafkaStream<byte[], byte[]>>> consumerMap = consumer.createMessageStreams(topicCountMap); streams = consumerMap.get(topic); }
Source:
<code>public void createPartControl(Composite parent) { final SashForm sash = new SashForm(parent, SWT.NONE); fTreeViewer = new CpuUsageComposite(sash); fXYViewer = new CpuUsageXYViewer(sash); fTreeViewer.addSelectionChangeListener(new ISelectionChangedListener() { @Override public void selectionChanged(SelectionChangedEvent event) { if (event.getSelection() instanceof IStructuredSelection) { <START> Object selection = ((IStructuredSelection) event.getSelection()).getFirstElement(); <END> if (selection instanceof CpuUsageEntry) { CpuUsageEntry entry = (CpuUsageEntry) selection; fTreeViewer.setSelectedThread(entry.getTid()); fXYViewer.setSelectedThread(Long.valueOf(entry.getTid())); } } } }); sash.setLayout(new FillLayout()); ITmfTrace trace = getActiveTrace(); if (trace != null) { TmfTraceSelectedSignal signal = new TmfTraceSelectedSignal(this, trace); fTreeViewer.traceSelected(signal); fXYViewer.traceSelected(signal); } }</code><technical_language>assuming "event.getSelection()" change calls... unlucky, happen! extracted a local variable instanceof check</technical_language>

Target:
public void createPartControl(Composite parent) { final SashForm sash = new SashForm(parent, SWT.NONE); fTreeViewer = new CpuUsageComposite(sash); fXYViewer = new CpuUsageXYViewer(sash); fTreeViewer.addSelectionChangeListener(new ISelectionChangedListener() { @Override public void selectionChanged(SelectionChangedEvent event) { ISelection selection = event.getSelection(); if (selection instanceof IStructuredSelection) { Object structSelection = ((IStructuredSelection) selection).getFirstElement(); if (structSelection instanceof CpuUsageEntry) { CpuUsageEntry entry = (CpuUsageEntry) structSelection; fTreeViewer.setSelectedThread(entry.getTid()); fXYViewer.setSelectedThread(Long.valueOf(entry.getTid())); } } } }); sash.setLayout(new FillLayout()); ITmfTrace trace = getActiveTrace(); if (trace != null) { TmfTraceSelectedSignal signal = new TmfTraceSelectedSignal(this, trace); fTreeViewer.traceSelected(signal); fXYViewer.traceSelected(signal); } }
Source:
<code>private boolean shouldFragment(FrameType frameType, int readableBytes) { <START> if (frameType.isFragmentable()) { <END> return readableBytes > mtu; } else { return false; } }</code><technical_language>tioli: more readable a liner return frameType.isFragmentable() && readableBytes > mtu</technical_language>

Target:
private boolean shouldFragment(FrameType frameType, int readableBytes) { return frameType.isFragmentable() && readableBytes > mtu; }
Source:
<code>public Result visit(Join e) { final Result leftResult = visitChild(0, e.getLeft()).resetAlias(); final Result rightResult = visitChild(1, e.getRight()).resetAlias(); final Context leftContext = leftResult.qualifiedContext(); final Context rightContext = rightResult.qualifiedContext(); SqlNode sqlCondition = null; SqlLiteral condType = JoinConditionType.ON.symbol(POS); JoinType joinType = joinType(e.getJoinType()); <START> if ((e.getJoinType() == JoinRelType.INNER || e.getJoinType() == JoinRelType.FULL) <END> && e.getCondition().isAlwaysTrue()) { sqlCondition = SqlLiteral.createBoolean(true, POS); } else { sqlCondition = convertConditionToSqlNode(e.getCondition(), leftContext, rightContext, e.getLeft().getRowType().getFieldCount()); } SqlNode join = new SqlJoin(POS, leftResult.asFrom(), SqlLiteral.createBoolean(false, POS), joinType.symbol(POS), rightResult.asFrom(), condType, sqlCondition); return result(join, leftResult, rightResult); }</code><technical_language>remove of leave isAlwaysTrue()</technical_language>

Target:
public Result visit(Join e) { final Result leftResult = visitChild(0, e.getLeft()).resetAlias(); final Result rightResult = visitChild(1, e.getRight()).resetAlias(); final Context leftContext = leftResult.qualifiedContext(); final Context rightContext = rightResult.qualifiedContext(); SqlNode sqlCondition = null; SqlLiteral condType = JoinConditionType.ON.symbol(POS); JoinType joinType = joinType(e.getJoinType()); if (e.getCondition().isAlwaysTrue()) { sqlCondition = SqlLiteral.createBoolean(true, POS); } else { sqlCondition = convertConditionToSqlNode(e.getCondition(), leftContext, rightContext, e.getLeft().getRowType().getFieldCount()); } SqlNode join = new SqlJoin(POS, leftResult.asFrom(), SqlLiteral.createBoolean(false, POS), joinType.symbol(POS), rightResult.asFrom(), condType, sqlCondition); return result(join, leftResult, rightResult); }
Source:
<code>public long saveProjectOverview(ProjectOverview overview) throws IOException { <START> if (overview.getId() != ProjectOverview.UNSAVED_ID) { <END> ProjectOverview original = projectStore.getProjectOverviewById(overview.getId()); original.setAllLibrariesQcPassed(overview.getAllLibrariesQcPassed()); original.setAllPoolsConstructed(overview.getAllPoolsConstructed()); original.setAllRunsCompleted(overview.getAllRunsCompleted()); original.setLocked(overview.getLocked()); original.setPrimaryAnalysisCompleted(overview.getPrimaryAnalysisCompleted()); original.setPrincipalInvestigator(overview.getPrincipalInvestigator()); original.setStartDate(overview.getStartDate()); original.setEndDate(overview.getEndDate()); original.setNumProposedSamples(overview.getNumProposedSamples()); original.setAllSampleQcPassed(overview.getAllSampleQcPassed()); overview = original; } overview.setLastUpdated(new Date()); return projectStore.saveOverview(overview); }</code><technical_language>![MINOR](<LINK_1> 'Severity: MINOR') Immediately return this expression instead of assigning temporary variable "id". [![rule](<LINK_0>](<LINK_2></technical_language>

Target:
public long saveProjectOverview(ProjectOverview overview) throws IOException { if (overview.getId() != ProjectOverview.UNSAVED_ID) { ProjectOverview original = projectStore.getProjectOverviewById(overview.getId()); authorizationManager.throwIfNotWritable(original.getProject()); original.setAllLibrariesQcPassed(overview.getAllLibrariesQcPassed()); original.setAllPoolsConstructed(overview.getAllPoolsConstructed()); original.setAllRunsCompleted(overview.getAllRunsCompleted()); original.setLocked(overview.getLocked()); original.setPrimaryAnalysisCompleted(overview.getPrimaryAnalysisCompleted()); original.setPrincipalInvestigator(overview.getPrincipalInvestigator()); original.setStartDate(overview.getStartDate()); original.setEndDate(overview.getEndDate()); original.setNumProposedSamples(overview.getNumProposedSamples()); original.setAllSampleQcPassed(overview.getAllSampleQcPassed()); overview = original; } else { authorizationManager.throwIfNotWritable(overview.getProject()); } overview.setLastUpdated(new Date()); return projectStore.saveOverview(overview); }
Source:
<code>void closeSockSync() { try { long startTime = Time.currentElapsedTime(); <START> sock.close(); <END> ServerMetrics.getMetrics().SOCKET_CLOSING_TIME.add(Time.currentElapsedTime() - startTime); } catch (IOException e) { LOG.warn("Ignoring error closing connection to leader", e); } }</code><technical_language>want add 2 more here: - double check if sock is null - sock = null close prevent usage of object GC collect</technical_language>

Target:
void closeSockSync() { try { long startTime = Time.currentElapsedTime(); if (sock != null) { sock.close(); sock = null; } ServerMetrics.getMetrics().SOCKET_CLOSING_TIME.add(Time.currentElapsedTime() - startTime); } catch (IOException e) { LOG.warn("Ignoring error closing connection to leader", e); } }
Source:
<code><START> synchronized void bumpIdempotentProducerEpoch() { <END> if (isTransactional()) { log.debug("Skipping epoch bump for transactional producer. The epoch will be bumped after the ongoing " + "transaction is aborted"); } else { if (this.producerIdAndEpoch.epoch == Short.MAX_VALUE) { resetIdempotentProducerId(); } else { setProducerIdAndEpoch(new ProducerIdAndEpoch(this.producerIdAndEpoch.producerId, (short) (this.producerIdAndEpoch.epoch + 1))); } for (TopicPartition topicPartition : this.partitionsToRewriteSequences) { this.topicPartitionBookkeeper.startSequencesAtBeginning(topicPartition, this.producerIdAndEpoch); this.partitionsWithUnresolvedSequences.remove(topicPartition); } this.partitionsToRewriteSequences.clear(); epochBumpRequired = false; } }</code><technical_language>This private? drop synchronization</technical_language>

Target:
private void bumpIdempotentProducerEpoch() { if (this.producerIdAndEpoch.epoch == Short.MAX_VALUE) { resetIdempotentProducerId(); } else { setProducerIdAndEpoch(new ProducerIdAndEpoch(this.producerIdAndEpoch.producerId, (short) (this.producerIdAndEpoch.epoch + 1))); log.debug("Incremented producer epoch, current producer ID and epoch are now {}", this.producerIdAndEpoch); } for (TopicPartition topicPartition : this.partitionsToRewriteSequences) { this.topicPartitionBookkeeper.startSequencesAtBeginning(topicPartition, this.producerIdAndEpoch); this.partitionsWithUnresolvedSequences.remove(topicPartition); } this.partitionsToRewriteSequences.clear(); epochBumpRequired = false; }
Source:
<code>protected void runInternal() { if (dataRecords == null) { for (int i = 0; i < recordAndDataValuePairs.size(); i += 2) { <START> Object obj = recordAndDataValuePairs.get(i); <END> if (obj != null) { putBackup((Record) obj); } } } else { for (Record<Data> record : dataRecords) { putBackup(record); } } }</code><technical_language>record null explicitly check for null adding in PutAllOperation#toBackupListByRemovingEvictedRecords MergeOperation#toBackupListByRemovingEvictedRecords</technical_language>

Target:
protected void runInternal() { if (dataRecords != null) { for (Record<Data> record : dataRecords) { putBackup(record); } } else { for (int i = 0; i < recordAndDataValuePairs.size(); i += 2) { putBackup((Record) recordAndDataValuePairs.get(i)); } } }
Source:
<code>public void remove(final Task task) { giant.lock(); try { log.info("Removing task[%s] from activeTasks", task.getId()); for (final TaskLockPosse taskLockPosse : findLockPossesForTask(task)) { unlock(task, taskLockPosse.getTaskLock().getInterval()); } } finally { <START> activeTasks.remove(task.getId()); <END> giant.unlock(); } }</code><technical_language>unlock a finally block of own, if this remove is in try{}finally{} block</technical_language>

Target:
public void remove(final Task task) { giant.lock(); try { try { log.info("Removing task[%s] from activeTasks", task.getId()); for (final TaskLockPosse taskLockPosse : findLockPossesForTask(task)) { unlock(task, taskLockPosse.getTaskLock().getInterval()); } } finally { activeTasks.remove(task.getId()); } } finally { giant.unlock(); } }
Source:
<code>public String connectToMongo( @CliOption(key = {"username"}, mandatory = false, help = "The username that will be used to connect to MongoDB when performing administrative tasks.") final String username, @CliOption(key= {"hostname"}, mandatory = true, help = "The hostname of the MongoDB that will be connected to.") final String hostname, @CliOption(key= {"port"}, mandatory = true, help = "The port of the MongoDB that will be connected to.") final String port) { try { char[] password = null; if(username != null) { password = passwordPrompt.getPassword(); } final MongoConnectionDetails connectionDetails = new MongoConnectionDetails( hostname, Integer.parseInt(port), Optional.ofNullable(username), Optional.ofNullable(password)); final MongoClient adminClient = new MongoClient(hostname, Integer.parseInt(port)); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { adminClient.close(); } }); try { adminClient.getConnectPoint(); } catch (MongoException e) { <START> throw new IOException(e); <END> } final RyaClient ryaClient = MongoRyaClientFactory.build(connectionDetails, adminClient); sharedState.connectedToMongo(connectionDetails, ryaClient); } catch (final IOException e) { throw new RuntimeException("Could not connection to MongoDB. Reason: " + e.getMessage(), e); } return "Connected. You must select a Rya instance to interact with next."; }</code><technical_language>Instead of rethrowing exception, return a message explaining wrong? connecting a Mongo DB exceptional state in shell. returning early, connection commands presented user. message like, "Could connect Mongo DB." need close adminClient returning</technical_language>

Target:
public String connectToMongo( @CliOption(key = {"username"}, mandatory = false, help = "The username that will be used to connect to MongoDB when performing administrative tasks.") final String username, @CliOption(key= {"hostname"}, mandatory = true, help = "The hostname of the MongoDB that will be connected to.") final String hostname, @CliOption(key= {"port"}, mandatory = true, help = "The port of the MongoDB that will be connected to.") final String port) { try { char[] password = null; if(username != null) { password = passwordPrompt.getPassword(); } final MongoConnectionDetails connectionDetails = new MongoConnectionDetails( hostname, Integer.parseInt(port), Optional.ofNullable(username), Optional.ofNullable(password)); final MongoClient adminClient = new MongoClient(hostname, Integer.parseInt(port)); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { adminClient.close(); } }); try { adminClient.getConnectPoint(); } catch(final MongoException e) { adminClient.close(); throw e; } final RyaClient ryaClient = MongoRyaClientFactory.build(connectionDetails, adminClient); sharedState.connectedToMongo(connectionDetails, ryaClient); } catch (final IOException | MongoException e) { throw new RuntimeException("Could not connection to MongoDB. Reason: " + e.getMessage(), e); } return "Connected. You must select a Rya instance to interact with next."; }
Source:
<code>public void testBasicResolving() throws Exception { Resolver resolver = cn.getResolver(); <START> List<Endpoint> endpoints = resolver.resolve("foo.01.service.user.cell"); <END> assertEquals(1, endpoints.size()); assertEquals("foo", endpoints.get(0).getName()); assertEquals("localhost", endpoints.get(0).getHost()); assertEquals("1.service.user.cell", endpoints.get(0).getCoordinate().toString()); assertEquals("data", endpoints.get(0).getEndpointData()); assertEquals("http", endpoints.get(0).getProtocol()); }</code><technical_language>beware prefixing integers 0 means number is base 8 -- octal</technical_language>

Target:
public void testBasicResolving() throws Exception { Resolver resolver = cn.getResolver(); List<Endpoint> endpoints = resolver.resolve("foo.1.service.user.cell"); assertEquals(1, endpoints.size()); assertEquals("foo", endpoints.get(0).getName()); assertEquals("localhost", endpoints.get(0).getHost()); assertEquals("1.service.user.cell", endpoints.get(0).getCoordinate().toString()); assertEquals("data", endpoints.get(0).getEndpointData()); assertEquals("http", endpoints.get(0).getProtocol()); }
Source:
<code>private static void setSinkForSource(UserDataSource source, HttpMessage sinkMsg) { if (log.isDebugEnabled()) { log.debug( "setSinkForSource src=" + source.getUri() + " param=" + source.getParam() + " sink=" + sinkMsg.getRequestHeader().getURI()); } HashSet<Integer> sinks = sourceToSinks.get(source.toString()); if (sinks == null) { sinks = new HashSet<>(); } int id = messagesStorage.storeMessage(sinkMsg); sinks.add(id); <START> sourceToSinks.put(source.toString(), sinks); <END> }</code><technical_language>This class static maps, this class invoked serially</technical_language>

Target:
private static void setSinkForSource(UserDataSource source, HttpMessage sinkMsg) { if (log.isDebugEnabled()) { log.debug( "setSinkForSource src=" + source.getUri() + " param=" + source.getParam() + " sink=" + sinkMsg.getRequestHeader().getURI()); } synchronized (sourceToSinks) { Set<Integer> sinks = sourceToSinks.get(source.toString()); Set<Integer> sinksHashCodes = sourceToSinksHashCodes.get(source.toString()); if (sinks == null) { sinks = Collections.synchronizedSet(new HashSet<>()); sinksHashCodes = Collections.synchronizedSet(new HashSet<>()); } int msgHashCode = sinkMsg.hashCode(); if (!sinksHashCodes.contains(msgHashCode)) { int id = messagesStorage.storeMessage(sinkMsg); sinks.add(id); sourceToSinks.put(source.toString(), sinks); sinksHashCodes.add(msgHashCode); sourceToSinksHashCodes.put(source.toString(), sinksHashCodes); } } }
Source:
<code>public Optional<Timeout> getTimeout() { final Optional<Long> active = getInt64(this.document, "flowActiveTimeout").map(t -> t * 1000L); <START> final Optional<Long> inactive = getInt64(this.document, "flowActiveTimeout").map(t -> t * 1000L); <END> if (active.isPresent() && inactive.isPresent()) { return Optional.of(new Timeout(active.get(), inactive.get())); } else { return Optional.empty(); } }</code><technical_language>this "flowInactiveTimeout"</technical_language>

Target:
public Optional<Timeout> getTimeout() { final Optional<Long> active = getInt64(this.document, "flowActiveTimeout").map(t -> t * 1000L); final Optional<Long> inactive = getInt64(this.document, "flowInactiveTimeout").map(t -> t * 1000L); if (active.isPresent() && inactive.isPresent()) { return Optional.of(new Timeout(active.get(), inactive.get())); } else { return Optional.empty(); } }
Source:
<code>protected void ExecuteVmCommand() { VmStatic oldVmStatic = getVm().getStaticData(); <START> VmStatic newVmStatic = getParameters().getVmStaticData(); <END> newVmStatic.setcreation_date(oldVmStatic.getcreation_date()); if (newVmStatic.getcreation_date().equals(DateTime.getMinValue()) || newVmStatic.getcreation_date().equals(DateTime.getMinValue())) { newVmStatic.setcreation_date(new Date()); } UpdateVmNetworks(); DbFacade.getInstance().getVmStaticDAO().update(getParameters().getVmStaticData()); updateVmPayload(); VmDeviceUtils.updateVmDevices(getParameters(), oldVmStatic); if (((Boolean) runVdsCommand(VDSCommandType.IsValid, new IrsBaseVDSCommandParameters(getVm().getstorage_pool_id())).getReturnValue()) .booleanValue()) { setVm(null); UpdateVmInSpm(getVm().getstorage_pool_id(), new ArrayList<VM>(Arrays.asList(new VM[] { getVm() }))); } setSucceeded(true); }</code><technical_language>dropped null check for newVMData oldVmData potantialy hava NPE checking this in another place I it? (canDoAction?) BTW put @NotNull paramter class avoid null check if want</technical_language>

Target:
protected void ExecuteVmCommand() { VmStatic oldVmStatic = getVm().getStaticData(); VmStatic newVmStatic = getParameters().getVmStaticData(); newVmStatic.setcreation_date(oldVmStatic.getcreation_date()); if (newVmStatic.getcreation_date().equals(DateTime.getMinValue()) || newVmStatic.getcreation_date().equals(DateTime.getMinValue())) { newVmStatic.setcreation_date(new Date()); } UpdateVmNetworks(); getVmStaticDAO().update(newVmStatic); updateVmPayload(); VmDeviceUtils.updateVmDevices(getParameters(), oldVmStatic); if (((Boolean) runVdsCommand(VDSCommandType.IsValid, new IrsBaseVDSCommandParameters(getVm().getstorage_pool_id())).getReturnValue())) { setVm(null); UpdateVmInSpm(getVm().getstorage_pool_id(), new ArrayList<VM>(Arrays.asList(new VM[] { getVm() }))); } setSucceeded(true); }
Source:
<code>private String listDir(File dir) { File[] files = repo.listFiles(); <START> StringBuilder fileList = new StringBuilder(); <END> for (File file : files) { fileList.append(file.getName()); fileList.append(','); } fileList.deleteCharAt(fileList.length() - 1); return fileList.toString(); }</code><technical_language>simpler [StringJoiner](<LINK_0></technical_language>

Target:
private String listDir(File dir) { File[] files = repo.listFiles(); StringJoiner joiner = new StringJoiner(","); for (File file : files) { joiner.add(file.getName()); } return joiner.toString(); }
Source:
<code>public void testItTimesOutProperly() throws Exception { String validationQuery = "select 1"; DBI dbi = mock(DBI.class); Handle handle = mock(Handle.class); when(dbi.open()).thenReturn(handle); Mockito.doAnswer(new Answer() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { try { TimeUnit.SECONDS.sleep(10); } catch (Exception ignored) return null; } }).when(handle).execute(validationQuery); <START> DBIHealthCheck dbiHealthCheck = new DBIHealthCheck(Executors.newSingleThreadExecutor(), <END> Duration.milliseconds(5), dbi, validationQuery); HealthCheck.Result result = dbiHealthCheck.check(); assertThat("is unhealthy", false, is(result.isHealthy())); }</code><technical_language>created this executor manually close test</technical_language>

Target:
public void testItTimesOutProperly() throws Exception { String validationQuery = "select 1"; DBI dbi = mock(DBI.class); Handle handle = mock(Handle.class); when(dbi.open()).thenReturn(handle); Mockito.doAnswer(new Answer() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { try { TimeUnit.SECONDS.sleep(10); } catch (Exception ignored) { } return null; } }).when(handle).execute(validationQuery); ExecutorService executorService = Executors.newSingleThreadExecutor(); DBIHealthCheck dbiHealthCheck = new DBIHealthCheck(executorService, Duration.milliseconds(5), dbi, validationQuery); HealthCheck.Result result = dbiHealthCheck.check(); executorService.shutdown(); assertThat("is unhealthy", false, is(result.isHealthy())); }
Source:
<code>public List<Object> load(List<EntityInfo> entityInfos) { int entitiesSize = entityInfos.size(); Set<Object> keys = new LinkedHashSet<>(entitiesSize); for (EntityInfo e : entityInfos) { keys.add(decodeKey(e)); } Map<?, ?> entries = cache.getAll(keys); List<Object> results = new LinkedList<>(); <START> for (Object key : keys) { <END> Object value = entries.get(key); if (value != null) { results.add(value); } } return results; }</code><technical_language>iterate entries.values() instead</technical_language>

Target:
public List<Object> load(List<EntityInfo> entityInfos) { int entitiesSize = entityInfos.size(); Set<Object> keys = new LinkedHashSet<>(entitiesSize); for (EntityInfo e : entityInfos) { keys.add(decodeKey(e)); } Map<?, ?> entries = cache.getAll(keys); List<Object> results = new ArrayList<>(entitiesSize); for (Object key : keys) { Object value = entries.get(key); if (value != null) { results.add(value); } } return results; }
Source:
<code>public ITypedElement getRight() { <START> return getFileRevisionTypedElement(gitPath, baseCommit, repo); <END> }</code><technical_language>This returns parent of HEAD commit HEAD commit</technical_language>

Target:
public ITypedElement getRight() { return getFileRevisionTypedElement(gitPath, remoteCommit, repo); }
Source:
<code>private Object createComplexRecord(int index) { GenericRecord record = new GenericData.Record(ComplexRecord.SCHEMA$); record.put("id", index); record.put("string_value", "Name" + index); <START> record.put("bytes_value", java.nio.ByteBuffer.wrap(("sample bytes").getBytes())); <END> GenericData.Array<String> arrayValues = new GenericData.Array<>(index, ComplexRecord.SCHEMA$.getField("array_values").schema().getTypes().get(1)); arrayValues.addAll(IntStream.range(0, index).mapToObj(String::valueOf).collect(Collectors.toList())); record.put("array_values", arrayValues); return record; }</code><technical_language>s/java.nio.ByteBuffer.wrap/ByteBuffer.wrap Or, naming conflicts ByteBuffer class require fully namespace it</technical_language>

Target:
private Object createComplexRecord(int index) { GenericRecord record = new GenericData.Record(ComplexRecord.SCHEMA$); record.put("id", index); record.put("string_value", "Name" + index); record.put("bytes_value", ByteBuffer.wrap(("sample bytes").getBytes())); GenericData.Array<String> arrayValues = new GenericData.Array<>(index, ComplexRecord.SCHEMA$.getField("array_values").schema().getTypes().get(1)); arrayValues.addAll(IntStream.range(0, index).mapToObj(String::valueOf).collect(Collectors.toList())); record.put("array_values", arrayValues); return record; }
Source:
<code>public void write(byte[] data, final int offset, final int length) { currentBlock = getOrCreateCurrentBlock(); try { currentBlock.write(data, offset, length); } catch (FixedBlock.OutOfBlockBufferMemoryException e) { FixedBlock previousBlock = null; previousBlock = moveToNextBlock(); if(!currentBlock.isFresh()) { <START> throw new RuntimeException("New block is not flash."); <END> } if(!previousBlock.isClear()) { previousBlock.moveLastObjectDataTo(currentBlock); } currentBlock.write(data, offset, length); } size += length; }</code><technical_language>this IllegalStateException? Please correct message</technical_language>

Target:
public void write(byte[] data, final int offset, final int length) { currentBlock = getOrCreateCurrentBlock(); try { currentBlock.write(data, offset, length); } catch (FixedBlock.OutOfBlockBufferMemoryException e) { FixedBlock previousBlock = null; previousBlock = moveToNextBlock(); if(!currentBlock.isFresh()) { throw new RuntimeException("New block is not fresh."); } if(!previousBlock.isClear()) { previousBlock.moveLastObjectDataTo(currentBlock); } currentBlock.write(data, offset, length); } size += length; }
Source:
<code>private static List<TestPropertySourceAttributes> resolveTestPropertySourceAttributes(Class<?> testClass) { <START> Assert.notNull(testClass, "Class must not be null"); <END> return MergedAnnotations .from(testClass, MergedAnnotations.SearchStrategy.EXHAUSTIVE) .stream(TestPropertySource.class) .map(a -> new TestPropertySourceAttributes((Class<?>) a.getSource(), a.synthesize())) .collect(Collectors.toList()); }</code><technical_language>Please reintroduce trace logging</technical_language>

Target:
private static List<TestPropertySourceAttributes> resolveTestPropertySourceAttributes(Class<?> testClass) { Assert.notNull(testClass, "Class must not be null"); return MergedAnnotations .from(testClass, MergedAnnotations.SearchStrategy.EXHAUSTIVE) .stream(TestPropertySource.class) .map(TestPropertySourceUtils::makeTestPropertySourceAttribute) .collect(Collectors.toList()); }
Source:
<code>public static void migrateOsgiLaunchConfiguration(ILaunchConfigurationWorkingCopy configuration) throws CoreException { <START> ILaunchConfigurationWorkingCopy wc = getWorkingCopy(configuration); <END> convertToSet(wc, IPDELauncherConstants.WORKSPACE_BUNDLES, IPDELauncherConstants.SELECTED_WORKSPACE_BUNDLES); convertToSet(wc, IPDELauncherConstants.TARGET_BUNDLES, IPDELauncherConstants.SELECTED_TARGET_BUNDLES); convertToSet(wc, IPDELauncherConstants.DESELECTED_WORKSPACE_PLUGINS, IPDELauncherConstants.DESELECTED_WORKSPACE_BUNDLES); }</code><technical_language>unnecessary</technical_language>

Target:
public static void migrateOsgiLaunchConfiguration(ILaunchConfigurationWorkingCopy configuration) throws CoreException { convertToSet(configuration, IPDELauncherConstants.WORKSPACE_BUNDLES, IPDELauncherConstants.SELECTED_WORKSPACE_BUNDLES); convertToSet(configuration, IPDELauncherConstants.TARGET_BUNDLES, IPDELauncherConstants.SELECTED_TARGET_BUNDLES); convertToSet(configuration, IPDELauncherConstants.DESELECTED_WORKSPACE_PLUGINS, IPDELauncherConstants.DESELECTED_WORKSPACE_BUNDLES); }
Source:
<code>public Object apply(ReviewerResource rsrc) throws OrmException, <START> NoSuchChangeException { <END> return json.format(rsrc); }</code><technical_language>Unnecessary delta</technical_language>

Target:
public Object apply(ReviewerResource rsrc) throws OrmException { return json.format(rsrc); }
Source:
<code>private OrcRecordReader createRecordReader() throws IOException { OrcDataSource dataSource = new FileOrcDataSource(booleanNoNullFile, new DataSize(1, MEGABYTE), new DataSize(1, MEGABYTE), new DataSize(1, MEGABYTE), true); OrcReader orcReader = new OrcReader(dataSource, ORC, new DataSize(1, MEGABYTE), new DataSize(1, MEGABYTE), new DataSize(1, MEGABYTE), new DataSize(1, MEGABYTE)); return orcReader.createRecordReader( ImmutableMap.of(0, BOOLEAN), OrcPredicate.TRUE, <START> DateTimeZone.UTC, END> newSimpleAggregatedMemoryContext(), INITIAL_BATCH_SIZE); }</code><technical_language>static import UTC</technical_language>

Target:
private OrcRecordReader createRecordReader() throws IOException { OrcDataSource dataSource = new FileOrcDataSource(booleanNoNullFile, new DataSize(1, MEGABYTE), new DataSize(1, MEGABYTE), new DataSize(1, MEGABYTE), true); OrcReader orcReader = new OrcReader(dataSource, ORC, new DataSize(1, MEGABYTE), new DataSize(1, MEGABYTE), new DataSize(1, MEGABYTE), new DataSize(1, MEGABYTE)); return orcReader.createRecordReader( ImmutableMap.of(0, BOOLEAN), OrcPredicate.TRUE, UTC, newSimpleAggregatedMemoryContext(), INITIAL_BATCH_SIZE); }
Source:
<code>public static String[] getCompletionResults(String match) { ArrayList<String> data = new ArrayList<String>(); if (barLookups) return new String[] {"No completion data found."}; boolean tapsetAndProbeIncluded = isTapsetAndProbe(match); if (tapsetAndProbeIncluded) { ArrayList<String> temp = builtMetadata.get(getTapset(match)); String probe = getTapsetProbe(match); <START> for (int i=0; i<temp.size(); i++) { <END> if (temp.get(i).startsWith(probe)) { data.add(temp.get(i)); } } } else{ Set<String> tapset = builtMetadata.keySet(); for (String probePoint : tapset) { if (probePoint.startsWith(match)){ data.add(probePoint); } } } if (data == null) return new String[] {}; else return data.toArray(new String[0]); }</code><technical_language>Npe thrown in this line completion hint is of form "<invalid tapset><period>". A null check is a quick fix for this minor issue</technical_language>

Target:
public static String[] getCompletionResults(String match) { ArrayList<String> data = new ArrayList<String>(); if (barLookups) return new String[] {"No completion data found."}; boolean tapsetAndProbeIncluded = isTapsetAndProbe(match); if (tapsetAndProbeIncluded) { ArrayList<String> temp = builtMetadata.get(getTapset(match)); if (temp == null) return new String[] {"No completion data found."}; String probe = getTapsetProbe(match); for (int i=0; i<temp.size(); i++) { if (temp.get(i).startsWith(probe)) { data.add(temp.get(i)); } } } else{ Set<String> tapset = builtMetadata.keySet(); for (String probePoint : tapset) { if (probePoint.startsWith(match)){ data.add(probePoint); } } } if (data == null) return new String[] {}; else return data.toArray(new String[0]); }
Source:
<code>private static Either<byte[]> runCompilerFile( final Context context, final File compiler, final List<String> arguments) throws ExitException { Either<Utils.CommandResult> result; if (Utils.isWindows()) { result = Utils.runCommand(context, compiler.getAbsolutePath(), compiler.getParentFile(), arguments); } else { final Either<String> mono = Mono.findMono(context); if (mono.isSuccess()) { arguments.add(0, compiler.getAbsolutePath()); <START> int retryCount = 0; <END> result = Utils.runCommand(context, mono.get(), compiler.getParentFile(), arguments); while(monoNativeFailure(result) && retryCount < 4) { retryCount++; if(retryCount > 0) { context.warning("Running Mono failed. Mono is buggy, so retry("+retryCount+") is in order... in 1 second"); context.error(result.explainError()); Utils.sleep(1000); } result = Utils.runCommand(context, mono.get(), compiler.getParentFile(), arguments); } } else { context.error("Mono is required to run DSL compiler. Mono not detected or specified."); throw new ExitException(); } } if (!result.isSuccess()) { return Either.fail(result.whyNot()); } if (result.get().exitCode != 0) { return Either.fail(result.get().output + result.get().error); } return Either.success(result.get().output.getBytes(UTF_8)); }</code><technical_language>I need try 4 times. retry sounds good enough, prompt user if prompt context is</technical_language>

Target:
private static Either<byte[]> runCompilerFile( final Context context, final File compiler, final List<String> arguments) throws ExitException { Either<Utils.CommandResult> result; if (Utils.isWindows()) { result = Utils.runCommand(context, compiler.getAbsolutePath(), compiler.getParentFile(), arguments); } else { final Either<String> mono = Mono.findMono(context); if (mono.isSuccess()) { arguments.add(0, compiler.getAbsolutePath()); result = Utils.runCommand(context, mono.get(), compiler.getParentFile(), arguments); if(monoNativeFailure(result) && promptUserMonoRetry(context)) { context.warning("Retrying in 1 second ..."); context.error(result.explainError()); sleep(1000); result = Utils.runCommand(context, mono.get(), compiler.getParentFile(), arguments); } } else { context.error("Mono is required to run DSL compiler. Mono not detected or specified."); throw new ExitException(); } } if (!result.isSuccess()) { return Either.fail(result.whyNot()); } if (result.get().exitCode != 0) { return Either.fail(result.get().output + result.get().error); } return Either.success(result.get().output.getBytes(UTF_8)); }
Source:
<code>public void marshal( DatabaseName databaseName, WritableChannel channel ) throws IOException { if ( databaseName == null ) { channel.put( (byte) 0 ); } <START> else if ( databaseName.name().length() > 127 ) <END> { throw new IOException( "The database name is too large to be stored. It must be fewer than 128 UTF-8 characters." ); } else { channel.put( (byte) 1 ); channel.put( (byte) databaseName.name().length() ); channel.put( UTF8.encode( databaseName.name() ), databaseName.name().length() ); } }</code><technical_language>a maximum length? necessarily it, wondering. If choose a maximum length a bit longer (e.g. for bother anyone, 2048?) extract a constant field. logic in Marshal wrong place though. validated reading setting. is some helper classes aid this in configuration-framework. validate in CausalClusterConfigurationValidator. I totally fine skipping a check altogether</technical_language>

Target:
public void marshal( DatabaseName databaseName, WritableChannel channel ) throws IOException { StringMarshal.marshal( channel, databaseName.name() ); }
Source:
<code>public ConnectHostToStoragePoolServerCommandBase() { <START> super(); <END> }</code><technical_language>super() spared here</technical_language>

Target:
public ConnectHostToStoragePoolServerCommandBase() { }
Source:
<code>public List<INetwork> getApprovedNetworkList() throws QuadrigaStorageException { List<INetwork> networkList = new ArrayList<INetwork>(); try { networkList = networkmapper.getListOfApprovedNetworks(); } catch (QuadrigaStorageException e) { <START> logger.error("Something went wrong in DB", e); <END> } return networkList; }</code><technical_language>method signature throws exception log throw anything</technical_language>

Target:
public List<INetwork> getApprovedNetworkList() throws QuadrigaStorageException { List<INetwork> networkList = new ArrayList<INetwork>(); try { networkList = networkmapper.getListOfApprovedNetworks(); } catch (QuadrigaStorageException e) { logger.error("Something went wrong in DB", e); throw e; } return networkList; }
Source:
<code>private boolean isJava8() { String version = System.getProperty("java.version"); int pos = version.indexOf('.'); pos = version.indexOf('.', pos+1); <START> return Double.valueOf(version.substring (0, pos)).compareTo(Double.valueOf(1.8)) >= 0; <END> }</code><technical_language>I do string comparison. right happen: return System.getProperty("java.version").compareTo("1.8") >= 0;</technical_language>

Target:
private boolean isJava8() { return Util.DEFAULT != null; }
Source:
<code><START> public void removeValue() { <END> thrown.expect(UnsupportedOperationException.class); VerboseIterable<String> verboseIterable = new VerboseIterable<String>( VALID_LIST, NO_NEXT_VALUE_ERROR); verboseIterable.iterator().remove(); MatcherAssert.assertThat(verboseIterable, IsIterableWithSize .<String> iterableWithSize(VALID_LIST.size() - 1)); }</code><technical_language>@m4solutions is idea for this test</technical_language>

Target:
public final void removeValue() { new VerboseIterable<String>( Arrays.asList( "If-None-Match: \"737060cd8c284d8af7ad3082f209582d\"", "If-Range: \"737060cd8c284d8af7ad3082f209582d\"", "Max-Forwards: 10", "Origin: <LINK_0>", "User-Agent: Mozilla/5.0 (X11; Linux x86_64) Gecko/2010010" ), "Thrown Error Message" ).iterator().remove(); }
Source:
<code>private Repository openRepository() { try { return args.server.openRepository(change.getProject()); } catch (RepositoryNotFoundException e) { <START> return null; <END> } }</code><technical_language>This is unexpected. log exception server log admin troubleshoot a problem</technical_language>

Target:
private Repository openRepository() { try { return args.server.openRepository(change.getProject()); } catch (RepositoryNotFoundException e) { log.error("Cannot open repository", e); return null; } }
Source:
<code>public void registerImport(DetailAST imp) { final FullIdent ident = FullIdent.createFullIdent( imp.getLastChild().getPreviousSibling()); final String fullName = ident.getText(); if (fullName.charAt(fullName.length() - 1) != '*') { <START> final int lastDot = fullName.lastIndexOf('.'); <END> importedClassPackage.put(fullName.substring(lastDot + 1), fullName); } }</code><technical_language>DOT variable instead of constant</technical_language>

Target:
public void registerImport(DetailAST imp) { final FullIdent ident = FullIdent.createFullIdent( imp.getLastChild().getPreviousSibling()); final String fullName = ident.getText(); if (fullName.charAt(fullName.length() - 1) != '*') { final int lastDot = fullName.lastIndexOf(DOT); importedClassPackage.put(fullName.substring(lastDot + 1), fullName); } }
Source:
<code>public final synchronized void addFunctions(String catalog, List<? extends SqlFunction> functions) { <START> if (functionNamespaces.get(catalog) == null) { <END> FunctionNamespace namespace = new StaticFunctionNamespace(typeManager, blockEncodingSerde, featuresConfig); namespace.addFunctions(functions); ImmutableMap.Builder<String, FunctionNamespace> builder = ImmutableMap.<String, FunctionNamespace>builder() .putAll(functionNamespaces) .put(catalog, namespace); functionNamespaces = builder.build(); } else { functionNamespaces.get(catalog).addFunctions(functions); } }</code><technical_language>!functionNamespaces.containsKey(catalog)</technical_language>

Target:
public synchronized void addFunctions(String catalog, List<? extends SqlFunction> functions) { Map<Boolean, List<SqlFunction>> operatorAndFunctionMap = functions.stream() .collect(Collectors.partitioningBy(function -> isOperator(function.getSignature()))); operatorNamespace.addFunctions(operatorAndFunctionMap.get(true)); if (!functionNamespaces.containsKey(catalog)) { FunctionNamespace namespace = new StaticFunctionNamespace(typeManager, blockEncodingSerde, featuresConfig); namespace.addFunctions(operatorAndFunctionMap.get(false)); functionNamespaces = ImmutableMap.<String, FunctionNamespace>builder() .putAll(functionNamespaces) .put(catalog, namespace) .build(); } else { functionNamespaces.get(catalog).addFunctions(operatorAndFunctionMap.get(false)); } }
Source:
<code>public Priority getPriority(DBObject dbObject) { Double score = null; List<String> positiveScoreReasons = Lists.newArrayList(); List<String> negativeScoreReasons = Lists.newArrayList(); try { score = TranslatorUtils.toDouble(dbObject, ITEM_PRIORITY_KEY); } catch (ClassCastException e) { DBObject priority = TranslatorUtils.toDBObject(dbObject, ITEM_PRIORITY_KEY); score = TranslatorUtils.toDouble(priority, SCORE_KEY); DBObject priorityReasons = TranslatorUtils.toDBObject(priority, REASONS_KEY); List<DBObject> positiveReasons = TranslatorUtils.toDBObjectList(priorityReasons, POSITIVE_REASONS_KEY); <START> for (Object reason : positiveReasons) { <END> if (reason != null && reason instanceof String) { String string = (String) reason; positiveScoreReasons.add(string); } } List<DBObject> negativeReasons = TranslatorUtils.toDBObjectList(priorityReasons, NEGATIVE_REASONS_KEY); for (Object reason : positiveReasons) { if (reason != null && reason instanceof String) { String string = (String) reason; negativeScoreReasons.add(string); } } } PriorityScoreReasons priorityScoreReasons = new PriorityScoreReasons(positiveScoreReasons, negativeScoreReasons); return new Priority(score, priorityScoreReasons); }</code><technical_language>TranslatorUtils.toIterable fromIterable</technical_language>

Target:
public Priority getPriority(DBObject dbObject) { Double score = null; List<String> positiveScoreReasons = Lists.newArrayList(); List<String> negativeScoreReasons = Lists.newArrayList(); try { score = TranslatorUtils.toDouble(dbObject, ITEM_PRIORITY_KEY); } catch (ClassCastException e) { DBObject priority = TranslatorUtils.toDBObject(dbObject, ITEM_PRIORITY_KEY); score = TranslatorUtils.toDouble(priority, SCORE_KEY); DBObject priorityReasons = TranslatorUtils.toDBObject(priority, REASONS_KEY); List<DBObject> positiveReasons = TranslatorUtils.toDBObjectList(priorityReasons, POSITIVE_REASONS_KEY); for (Object reason : positiveReasons) { if (reason != null && reason instanceof String) { String string = (String) reason; positiveScoreReasons.add(string); } } List<DBObject> negativeReasons = TranslatorUtils.toDBObjectList(priorityReasons, NEGATIVE_REASONS_KEY); for (Object reason : negativeReasons) { if (reason != null && reason instanceof String) { String string = (String) reason; negativeScoreReasons.add(string); } } } PriorityScoreReasons priorityScoreReasons = new PriorityScoreReasons(positiveScoreReasons, negativeScoreReasons); return new Priority(score, priorityScoreReasons); }
Source:
<code><START> public synchronized void remove(Object key) { <END> tMultiTheadLockMap.remove(key); }</code><technical_language>methods need synchronized more due ConcurrentHashMap of atomic operations</technical_language>

Target:
public void remove(Object key) { tMultiTheadLockMap.remove(key); }
Source:
<code>private PagedResources.PageMetadata buildPageMetadata(Integer pageSize, Integer pageNumber, Integer totalNumberOfResults) throws IllegalArgumentException { Long totalPages = pageSize == 0L ? 0L : (long) Math.ceil((double) totalNumberOfResults / (double) pageSize); if (pageNumber < 0 || pageNumber >= totalPages) { throw new IllegalArgumentException("For the given page size, there are " + totalPages + " page(s), so " + <START> "the correct page range is from 0 to " + String.valueOf(totalPages - 1) + " (both included)."); <END> } return new PagedResources.PageMetadata(pageSize, pageNumber, totalNumberOfResults, totalPages); }</code><technical_language>suggestion "the correct page range is 0 " + (totalPages - 1) + " (both included).");</technical_language>

Target:
private PagedResources.PageMetadata buildPageMetadata(Integer pageSize, Integer pageNumber, Integer totalNumberOfResults) throws IllegalArgumentException { Long totalPages = pageSize == 0L ? 0L : (long) Math.ceil((double) totalNumberOfResults / (double) pageSize); if (pageNumber < 0 || pageNumber >= totalPages) { throw new IllegalArgumentException("For the given page size, there are " + totalPages + " page(s), so " + "the correct page range is from 0 to " + (totalPages - 1) + " (both included)."); } return new PagedResources.PageMetadata(pageSize, pageNumber, totalNumberOfResults, totalPages); }