auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public IntegrationFlow serverOut(AbstractServerConnectionFactory server) { return IntegrationFlows.from(() -> "seed", e -> e.poller(Pollers.fixedDelay(5000))) <START> .split(new AbstractMessageSplitter() { <END> @Override protected Object splitMessage(Message<?> message) { return ServerPeer.this.clients.iterator(); } }) .enrichHeaders(h -> h.headerExpression(IpHeaders.CONNECTION_ID, "payload")) .transform(p -> "Hello from server") .handle(Tcp.outboundAdapter(server)) .get(); }</code><technical_language>this instead: .split(this.clients, "iterator")</technical_language>

Target:
public IntegrationFlow serverOut(AbstractServerConnectionFactory server) { return IntegrationFlows.from(() -> "seed", e -> e.poller(Pollers.fixedDelay(5000))) .split(this.clients, "iterator") .enrichHeaders(h -> h.headerExpression(IpHeaders.CONNECTION_ID, "payload")) .transform(p -> "Hello from server") .handle(Tcp.outboundAdapter(server)) .get(); }
Source:
<code>List<Long> evaluate(long dataSourceId) throws ExportRulesException { try { SleuthkitCase db = Case.getCurrentCaseThrows().getSleuthkitCase(); ResultSet resultSet = null; try (SleuthkitCase.CaseDbQuery queryResult = db.executeQuery(getQuery(dataSourceId))) { <START> resultSet = queryResult.getResultSet(); <END> List<Long> fileIds = new ArrayList<>(); while (resultSet.next()) { fileIds.add(resultSet.getLong("obj_id")); } return fileIds; } finally { if (resultSet != null) { resultSet.close(); } } } catch (NoCurrentCaseException ex) { throw new ExportRulesException("No current case", ex); } catch (TskCoreException ex) { throw new ExportRulesException("Error querying case database", ex); } catch (SQLException ex) { throw new ExportRulesException("Error processing result set", ex); } }</code><technical_language>Is feasible include ResultSet in try is closed AutoCloseable</technical_language>

Target:
List<Long> evaluate(long dataSourceId) throws ExportRulesException { try { SleuthkitCase db = Case.getCurrentCaseThrows().getSleuthkitCase(); try (SleuthkitCase.CaseDbQuery queryResult = db.executeQuery(getQuery(dataSourceId)); ResultSet resultSet = queryResult.getResultSet();) { List<Long> fileIds = new ArrayList<>(); while (resultSet.next()) { fileIds.add(resultSet.getLong("obj_id")); } return fileIds; } } catch (NoCurrentCaseException ex) { throw new ExportRulesException("No current case", ex); } catch (TskCoreException ex) { throw new ExportRulesException("Error querying case database", ex); } catch (SQLException ex) { throw new ExportRulesException("Error processing result set", ex); } }
Source:
<code>public Object execute(final ExecutionEvent event) { final ImageBuild wizard = new ImageBuild(); final WizardDialog wizardDialog = new NonModalWizardDialog(HandlerUtil.getActiveShell(event), wizard); wizardDialog.create(); IWorkbenchWindow window = PlatformUI.getWorkbench() .getActiveWorkbenchWindow(); IWorkbenchPage activePage = null; IWorkbenchPart activePart = null; if (window != null) activePage = window.getActivePage(); if (activePage != null) activePart = activePage.getActivePart(); connection = CommandUtils.getCurrentConnection(activePart); if (connection == null) { IDockerConnection[] connections = DockerConnectionManager .getInstance().getConnections(); if (connections.length > 0) connection = connections[0]; } if (connection == null || <START> connection.getState() != EnumDockerConnectionState.ESTABLISHED) { <END> Display.getDefault().syncExec(() -> MessageDialog.openError( PlatformUI.getWorkbench().getActiveWorkbenchWindow() .getShell(), WizardMessages.getString("ErrorNoActiveConnection.msg"), WizardMessages.getString("ErrorNoActiveConnection.desc"))); return null; } final boolean buildImage = wizardDialog.open() == Window.OK; if (buildImage) { performBuildImage(wizard); } return null; }</code><technical_language>risk in !connection.isOpen()</technical_language>

Target:
public Object execute(final ExecutionEvent event) { final ImageBuild wizard = new ImageBuild(); final WizardDialog wizardDialog = new NonModalWizardDialog(HandlerUtil.getActiveShell(event), wizard); wizardDialog.create(); IWorkbenchWindow window = PlatformUI.getWorkbench() .getActiveWorkbenchWindow(); IWorkbenchPage activePage = null; IWorkbenchPart activePart = null; if (window != null) activePage = window.getActivePage(); if (activePage != null) activePart = activePage.getActivePart(); connection = CommandUtils.getCurrentConnection(activePart); if (connection == null) { IDockerConnection[] connections = DockerConnectionManager .getInstance().getConnections(); if (connections.length > 0) connection = connections[0]; } if (connection == null || connection.isOpen()) { Display.getDefault().syncExec(() -> MessageDialog.openError( PlatformUI.getWorkbench().getActiveWorkbenchWindow() .getShell(), WizardMessages.getString("ErrorNoActiveConnection.msg"), WizardMessages.getString("ErrorNoActiveConnection.desc"))); return null; } final boolean buildImage = wizardDialog.open() == Window.OK; if (buildImage) { performBuildImage(wizard); } return null; }
Source:
<code>byte[] getCachedBytes(RevObject obj, ObjectLoader ldr) throws LargeObjectException, MissingObjectException, IOException { try { <START> return ldr.getCachedBytes(streamFileThreshold); <END> } catch (LargeObjectException tooBig) { tooBig.setObjectId(obj); throw tooBig; } }</code><technical_language>I drop this parameter, MiB constant is entire commit</technical_language>

Target:
byte[] getCachedBytes(RevObject obj, ObjectLoader ldr) throws LargeObjectException, MissingObjectException, IOException { try { return ldr.getCachedBytes(); } catch (LargeObjectException tooBig) { tooBig.setObjectId(obj); throw tooBig; } }
Source:
<code>protected Session doCreateSession( SessionContext context ) { Session session; if( WebUtils.isHttp( context ) ) { session = newSessionInstance( context ); if ( log.isTraceEnabled() ) { log.trace( "Creating session for host {}", session.getHost() ); } HttpServletRequest request = WebUtils.getHttpRequest( context ); if ( isStatelessClient( request ) ) { ( (SimpleSession) session ).setId( fakeSessionIdGenerator.generateId( session ) ); log.debug( "Stateless client session is not persisted.", session.getId() ); session.setAttribute( DO_NOT_STORE_SESSION_KEY, Boolean.TRUE ); } else { create( session ); } if ( log.isTraceEnabled() ) { log.trace( "Session was created for User-Agent {}", session.getId(), getUserAgent( request ) ); } } else { <START> log.trace( "Non http request, falling back to default implemenation." ); <END> session = super.doCreateSession( context ); } return session; }</code><technical_language>typo</technical_language>

Target:
protected Session doCreateSession( SessionContext context ) { Session session; if( WebUtils.isHttp( context ) ) { session = newSessionInstance( context ); if ( log.isTraceEnabled() ) { log.trace( "Creating session for host {}", session.getHost() ); } HttpServletRequest request = WebUtils.getHttpRequest( context ); if ( isStatelessClient( request ) ) { ( (SimpleSession) session ).setId( fakeSessionIdGenerator.generateId( session ) ); log.debug( "Stateless client session is not persisted.", session.getId() ); session.setAttribute( DO_NOT_STORE_SESSION_KEY, Boolean.TRUE ); } else { create( session ); } if ( log.isTraceEnabled() ) { log.trace( "Session was created for User-Agent {}", session.getId(), getUserAgent( request ) ); } } else { log.trace( "Non http request, falling back to default implementation." ); session = super.doCreateSession( context ); } return session; }
Source:
<code>public TableMetadata withDataColumns(List<Column> dataColumns) { return new TableMetadata( owner, tableType, dataColumns, partitionColumns, parameters, storageFormat, bucketProperty, <START> Optional.of(preferredOrderingColumns), <END> serdeParameters, externalLocation, viewOriginalText, viewExpandedText, columnStatistics); }</code><technical_language>pass preferredOrderingColumns consistent</technical_language>

Target:
public TableMetadata withDataColumns(List<Column> dataColumns) { return new TableMetadata( owner, tableType, dataColumns, partitionColumns, parameters, storageFormat, bucketProperty, storageParameters, serdeParameters, externalLocation, viewOriginalText, viewExpandedText, columnStatistics); }
Source:
<code>SshLog(final Provider<SshSession> session, final Provider<Context> context, final SitePaths site, @GerritServerConfig Config config, AuditService auditService) { this.session = session; this.context = context; this.auditService = auditService; <START> if (config.getBoolean("sshd", "requestlog", true)) { <END> final DailyRollingFileAppender dst = new DailyRollingFileAppender(); dst.setName(LOG_NAME); dst.setLayout(new MyLayout()); dst.setEncoding("UTF-8"); dst.setFile(new File(resolve(site.logs_dir), LOG_NAME).getPath()); dst.setImmediateFlush(true); dst.setAppend(true); dst.setThreshold(Level.INFO); dst.setErrorHandler(new DieErrorHandler()); dst.activateOptions(); dst.setErrorHandler(new LogLogHandler()); async = new AsyncAppender(); async.setBlocking(true); async.setBufferSize(config.getInt("core", "asyncLoggingBufferSize", 64)); async.setLocationInfo(false); async.addAppender(dst); async.activateOptions(); } else { async = null; } }</code><technical_language>Also, new setting mentioned in commit message</technical_language>

Target:
SshLog(final Provider<SshSession> session, final Provider<Context> context, final SitePaths site, @GerritServerConfig Config config, AuditService auditService) { this.session = session; this.context = context; this.auditService = auditService; if (config.getBoolean("sshd", "requestLog", true)) { final DailyRollingFileAppender dst = new DailyRollingFileAppender(); dst.setName(LOG_NAME); dst.setLayout(new MyLayout()); dst.setEncoding("UTF-8"); dst.setFile(new File(resolve(site.logs_dir), LOG_NAME).getPath()); dst.setImmediateFlush(true); dst.setAppend(true); dst.setThreshold(Level.INFO); dst.setErrorHandler(new DieErrorHandler()); dst.activateOptions(); dst.setErrorHandler(new LogLogHandler()); async = new AsyncAppender(); async.setBlocking(true); async.setBufferSize(config.getInt("core", "asyncLoggingBufferSize", 64)); async.setLocationInfo(false); async.addAppender(dst); async.activateOptions(); } else { async = null; } }
Source:
<code>public MagicCommandFunctionality addImport() { return (code, command, message, executionCount) -> { String[] parts = command.split(" "); if (parts.length != 2) { return sendErrorMessage(message, "Wrong import format.", executionCount); } if (isValidImport(parts[1], executionCount)) { this.kernel.addImport(new ImportPath(parts[1])); return getMagicCommandItem(code, message, executionCount); } return sendErrorMessage(message, "Provided import doesn't exists. \n" <START> + "Try firstly add jar which contains class to classpath.", executionCount); <END> }; }</code><technical_language>Error message read: import "$class", class found</technical_language>

Target:
public MagicCommandFunctionality addImport() { return (code, command, message, executionCount) -> { String[] parts = command.split(" "); if (parts.length != 2) { return createResultWithCustomMessage(kernel.getImports().toString(), message, executionCount); } this.kernel.addImport(new ImportPath(parts[1])); if (isValidImport(parts[1], executionCount)) { return getMagicCommandItem(code, message, executionCount); } this.kernel.removeImport(new ImportPath(parts[1])); return sendErrorMessage(message, "Could not import " + parts[1] + ", class not found.", executionCount); }; }
Source:
<code>void updateVolumeHostInfo(AllocationAttempt attempt, AllocationCandidate candidate, Long newHost) { List<Object> storageDriverIds = new ArrayList<>(); for (Volume v : attempt.getVolumes()) { if (v.getStorageDriverId() != null) { storageDriverIds.add(v.getStorageDriverId()); } } Map<Object, Object> criteria = new HashMap<Object, Object>(); criteria.put(STORAGE_DRIVER.REMOVED, new io.github.ibuildthecloud.gdapi.condition.Condition(ConditionType.NULL)); criteria.put(STORAGE_DRIVER.ID, new io.github.ibuildthecloud.gdapi.condition.Condition(ConditionType.IN, storageDriverIds)); List<StorageDriver> drivers = objectManager.find(StorageDriver.class, criteria); Map<Long, StorageDriver> storageDrivers = new HashMap<>(); for (StorageDriver d : drivers) { storageDrivers.put(d.getId(), d); } for (Volume v : attempt.getVolumes()) { boolean persist = false; StorageDriver d = v.getStorageDriverId() != null ? storageDrivers.get(v.getStorageDriverId()) : null; if (d != null && StorageDriverConstants.SCOPE_LOCAL.equals(DataAccessor.fieldString(d, StorageDriverConstants.FIELD_SCOPE))) { persist = true; getAllocatedHostUuidProp(v).set(candidate.getHostUuid()); } if (VolumeConstants.ACCESS_MODE_SINGLE_HOST_RW.equals(v.getAccessMode())) { persist = true; <START> DataAccessor.setField(v, VolumeConstants.FIELD_LAST_ALLOCATED_HOST_ID, newHost); <END> } if (persist) { objectManager.persist(v); } } }</code><technical_language>setField is meant for api fields. want this api field, want a internal flag. Instead DataAccessor.fromDataFieldOf(v).withKey(VolumeConstants.FIELD_LAST_ALLOCATED_HOST_ID).set(newHost)</technical_language>

Target:
void updateVolumeHostInfo(AllocationAttempt attempt, AllocationCandidate candidate, Long newHost) { List<Object> storageDriverIds = new ArrayList<>(); for (Volume v : attempt.getVolumes()) { if (v.getStorageDriverId() != null) { storageDriverIds.add(v.getStorageDriverId()); } } Map<Object, Object> criteria = new HashMap<Object, Object>(); criteria.put(STORAGE_DRIVER.REMOVED, new io.github.ibuildthecloud.gdapi.condition.Condition(ConditionType.NULL)); criteria.put(STORAGE_DRIVER.ID, new io.github.ibuildthecloud.gdapi.condition.Condition(ConditionType.IN, storageDriverIds)); List<StorageDriver> drivers = objectManager.find(StorageDriver.class, criteria); Map<Long, StorageDriver> storageDrivers = new HashMap<>(); for (StorageDriver d : drivers) { storageDrivers.put(d.getId(), d); } for (Volume v : attempt.getVolumes()) { boolean persist = false; StorageDriver d = v.getStorageDriverId() != null ? storageDrivers.get(v.getStorageDriverId()) : null; if (d != null && StorageDriverConstants.SCOPE_LOCAL.equals(DataAccessor.fieldString(d, StorageDriverConstants.FIELD_SCOPE))) { persist = true; getAllocatedHostUuidProp(v).set(candidate.getHostUuid()); } if (VolumeConstants.ACCESS_MODE_SINGLE_HOST_RW.equals(v.getAccessMode())) { persist = true; DataAccessor.fromDataFieldOf(v).withKey(VolumeConstants.FIELD_LAST_ALLOCATED_HOST_ID).set(newHost); } if (persist) { objectManager.persist(v); } } }
Source:
<code>private KieServerInstanceAccount getAccount(String id) { Map<String, KieServerInstanceAccount> users = new HashMap<>(); Properties file = loadKieServerInstanceData(); <START> file.stringPropertyNames().forEach(name -> users.put(name, new KieServerInstanceAccount(name, file.getProperty(name)))); <END> return users.get(id); }</code><technical_language>String pwd = file.getProperty(id) create instance of KieServerInstanceAccount return new KieServerInstanceAccount(id, pwd)? need iterate file time, do we</technical_language>

Target:
private KieServerInstanceAccount getAccount(String id) { Properties file = loadKieServerInstanceData(); if (!file.containsKey(id)) { return null; } return new KieServerInstanceAccount(id, file.getProperty(id)); }
Source:
<code>public void doRunWithObjectSafepoints(final ActorProcessingThread t) { WebDebugger dbg = null; if (VmSettings.TRUFFLE_DEBUGGER_ENABLED) { dbg = vm.getWebDebugger(); assert dbg != null; } t.currentlyExecutingActor = actor; if (VmSettings.UNIFORM_TRACING) { UniformExecutionTrace.recordActivityContext(actor, tracer); } else if (VmSettings.KOMPOS_TRACING) { KomposTrace.currentActivity(actor); } while (getCurrentMessagesOrCompleteExecution()) { processCurrentMessages(t, dbg); } <START> if (VmSettings.UNIFORM_TRACING || VmSettings.KOMPOS_TRACING) { t.swapTracingBufferIfRequestedUnsync(); } t.currentlyExecutingActor = null; <END> }</code><technical_language>suggestion I doRunWithObjectSafepoints private finally clause of doRun this. do think</technical_language>

Target:
private void doRunWithObjectSafepoints(final ActorProcessingThread t) { WebDebugger dbg = null; if (VmSettings.TRUFFLE_DEBUGGER_ENABLED) { dbg = vm.getWebDebugger(); assert dbg != null; } t.currentlyExecutingActor = actor; if (VmSettings.UNIFORM_TRACING) { UniformExecutionTrace.recordActivityContext(actor, tracer); } else if (VmSettings.KOMPOS_TRACING) { KomposTrace.currentActivity(actor); } while (getCurrentMessagesOrCompleteExecution()) { processCurrentMessages(t, dbg); } }
Source:
<code>public void purgeOrderType_shouldPurgeOrderTypeIfNotUse() { OrderService orderService = Context.getOrderService(); <START> orderService.purgeOrderType(orderService.getOrderType(13)); <END> assertNull(orderService.getOrderType(13)); }</code><technical_language>need assertion order type exists purging invalid if matched id 3</technical_language>

Target:
public void purgeOrderType_shouldPurgeOrderTypeIfNotUse() { OrderService orderService = Context.getOrderService(); OrderType orderType = orderService.getOrderType(13); assertNotNull(orderType); orderService.purgeOrderType(orderType); assertNull(orderService.getOrderType(13)); }
Source:
<code>protected FakeApplication provideFakeApplication() { <START> final int port = BASE_PORT + RANDOM.nextInt(1000); <END> final String jdbcUrl = "jdbc:h2:./target/h2/metrics" + RANDOM.nextInt(1000) + ":portal;AUTO_SERVER=TRUE;AUTO_SERVER_PORT=" + port + ";MODE=PostgreSQL;INIT=create schema if not exists portal;DB_CLOSE_DELAY=-1"; return new FakeApplication( new java.io.File("."), Helpers.class.getClassLoader(), ImmutableMap.of("db.metrics_portal_ddl.url", jdbcUrl, "db.default.url", jdbcUrl), new ArrayList<String>(), null); }</code><technical_language>No. Random ports a disaster. eventually collide people rerun. recommendation, in PCE, global increasing port numbers. I recommend a test helper class maintained this state generated JDBC urls (for example)</technical_language>

Target:
protected FakeApplication provideFakeApplication() { final String jdbcUrl = H2ConnectionStringFactory.generateJdbcUrl(); return new FakeApplication( new java.io.File("."), Helpers.class.getClassLoader(), ImmutableMap.of("db.metrics_portal_ddl.url", jdbcUrl, "db.default.url", jdbcUrl), new ArrayList<String>(), null); }
Source:
<code>public String getName() { <START> return SanitizationHelper.sanitizeForHtml(name); <END> }</code><technical_language>I sanitize this class. This unexpected twist for other callers of this class JSP</technical_language>

Target:
public String getName() { return name; }
Source:
<code>public boolean canRun(@NotNull String executorId, @NotNull RunProfile profile) { <START> if(DefaultDebugExecutor.EXECUTOR_ID.equals(executorId)) { <END> return false; } return DefaultRunExecutor.EXECUTOR_ID.equals(executorId) && profile instanceof GoRunConfigurationBase; }</code><technical_language>point? method is false for DefaultDebugExecutor.EXECUTOR_ID changes</technical_language>

Target:
public boolean canRun(@NotNull String executorId, @NotNull RunProfile profile) { return DefaultRunExecutor.EXECUTOR_ID.equals(executorId) && profile instanceof GoRunConfigurationBase; }
Source:
<code>public int openCallback(String path, ByteBuffer buf) { try { return open(path, FuseFileInfo.wrap(buf)); } catch (Exception e) { <START> e.printStackTrace(); <END> return -ErrorCodes.EIO(); } }</code><technical_language>e.printStackTrace(); prints stdout, for production code. LOG.error("Failed open {}: ", path, e) stack trace printed. claiming private static final Logger LOG = LoggerFactory.getLogger(AbstractFuseFileSystem.class); in beginning</technical_language>

Target:
public int openCallback(String path, ByteBuffer buf) { try { return open(path, FuseFileInfo.wrap(buf)); } catch (Exception e) { LOG.error("Failed to open {}: ", path, e); return -ErrorCodes.EIO(); } }
Source:
<code>public boolean add(Entity entity){ if (entity == null){ throw new IllegalArgumentException("Cannot add null entity"); } if (!isPassable() && !entity.isHideable()){ <START> throw new RuntimeException( <END> "Cannot place nonHidable object on impassable Square" ); } if (!entity.isPassable()){ if (!isPassable()){ throw new RuntimeException("Tried to add second impassable entity"); } impassableEntity = entity; return true; } return passableEntities.add(entity); }</code><technical_language>a more descriptive Exception IllegalArgumentException UnsupportedOperationException</technical_language>

Target:
public boolean add(Entity entity){ if (entity == null){ throw new IllegalArgumentException("Cannot add null entity"); } if (!isPassable() && !entity.isHideable()){ throw new IllegalArgumentException( "Cannot place nonHidable object on impassable Square" ); } if (!entity.isPassable()){ if (!isPassable()){ throw new IllegalArgumentException("Tried to add second impassable entity"); } impassableEntity = entity; return true; } return passableEntities.add(entity); }
Source:
<code>protected String imageIdForZone(String zoneId) { ImageApi imageApi = api.getImageApiForZone(zoneId); <START> return Iterables.getFirst(imageApi.list().concat(), null).getId(); <END> }</code><technical_language>Intended change in functionality here? default null passed immediately NPE</technical_language>

Target:
protected String imageIdForZone(String zoneId) { ImageApi imageApi = api.getImageApiForZone(zoneId); return Iterables.get(imageApi.list().concat(), 0).getId(); }
Source:
<code><START> private void updateDiskVmSnapshotId() { <END> if (disk.getDiskStorageType() == DiskStorageType.IMAGE) { Guid snapshotId = getSnapshotDao().getId(getVmId(), SnapshotType.ACTIVE); getImageDao().updateImageVmSnapshotId(disk.getId(), snapshotId); ((DiskImage) disk).setvm_snapshot_id(snapshotId); } }</code><technical_language>need check, snapshot relevant for image disks</technical_language>

Target:
private void updateDiskVmSnapshotId() { if (disk.getDiskStorageType() == DiskStorageType.IMAGE) { Guid snapshotId = getSnapshotDao().getId(getVmId(), SnapshotType.ACTIVE); DiskImage diskImage = ((DiskImage) disk); getImageDao().updateImageVmSnapshotId(diskImage.getImageId(), snapshotId); diskImage.setvm_snapshot_id(snapshotId); } }
Source:
<code><START> public boolean hasNext() { <END> if (this.count < this.values.count()) { return true; } return false; }</code><technical_language>return this.count < this.values.count();</technical_language>

Target:
public boolean hasNext() { return this.count < this.values.count(); }
Source:
<code>ImplementationInvocationMetadata(Method declaredMethod, Method baseClassMethod) { if (!KotlinDetector.isKotlinReflectPresent()) { suspendedDeclaredMethod = false; suspendedBaseClassMethod = false; reactiveBaseClassMethod = false; return; } <START> KFunction<?> declaredFunction = ReflectionUtils.isKotlinClass(declaredMethod.getDeclaringClass()) <END> ? KotlinReflectionUtils.findKotlinFunction(declaredMethod) : null; KFunction<?> baseClassFunction = ReflectionUtils.isKotlinClass(baseClassMethod.getDeclaringClass()) ? KotlinReflectionUtils.findKotlinFunction(baseClassMethod) : null; suspendedDeclaredMethod = declaredFunction != null && declaredFunction.isSuspend(); suspendedBaseClassMethod = baseClassFunction != null && baseClassFunction.isSuspend(); this.reactiveBaseClassMethod = !suspendedBaseClassMethod && ReactiveWrapperConverters.supports(baseClassMethod.getReturnType()); }</code><technical_language>work Kotlin classpath? is class then? able loaded, it</technical_language>

Target:
ImplementationInvocationMetadata(Method declaredMethod, Method baseClassMethod) { if (!KotlinDetector.isKotlinReflectPresent()) { suspendedDeclaredMethod = false; suspendedBaseClassMethod = false; reactiveBaseClassMethod = false; return; } KFunction<?> declaredFunction = KotlinDetector.isKotlinType(declaredMethod.getDeclaringClass()) ? KotlinReflectionUtils.findKotlinFunction(declaredMethod) : null; KFunction<?> baseClassFunction = KotlinDetector.isKotlinType(baseClassMethod.getDeclaringClass()) ? KotlinReflectionUtils.findKotlinFunction(baseClassMethod) : null; suspendedDeclaredMethod = declaredFunction != null && declaredFunction.isSuspend(); suspendedBaseClassMethod = baseClassFunction != null && baseClassFunction.isSuspend(); this.reactiveBaseClassMethod = !suspendedBaseClassMethod && ReactiveWrapperConverters.supports(baseClassMethod.getReturnType()); }
Source:
<code>private void verifyReplicationProceeded() throws Exception { try (Table table = utility1.getConnection().getTable(TABLE)) { Put put = new Put(ROW); put.addColumn(NORMAL_CF, QUALIFIER, VALUE); table.put(put); } <START> try (Table peerTable = utility2.getConnection().getTable(TABLE)) { for (int i = 0; i < NB_RETRIES; i++) { if (i == NB_RETRIES - 1) { fail("Waited too much time for put replication"); } Result result = peerTable.get(new Get(ROW).addColumn(NORMAL_CF, QUALIFIER)); if (result == null || result.isEmpty()) { LOG.info("Row not available in peer cluster"); Thread.sleep(SLEEP_TIME); } else { assertArrayEquals(VALUE, result.getValue(NORMAL_CF, QUALIFIER)); break; } } } <END> }</code><technical_language>HBaseTestingUtility some nice waitFor() methods simplify this kind of logic</technical_language>

Target:
private void verifyReplicationProceeded() throws Exception { try (Table table = utility1.getConnection().getTable(TABLE)) { Put put = new Put(ROW); put.addColumn(NORMAL_CF, QUALIFIER, VALUE); table.put(put); } utility2.waitFor(NB_RETRIES * SLEEP_TIME, (Predicate<Exception>) () -> { try (Table peerTable = utility2.getConnection().getTable(TABLE)) { Result result = peerTable.get(new Get(ROW).addColumn(NORMAL_CF, QUALIFIER)); return result != null && !result.isEmpty() && Bytes.equals(VALUE, result.getValue(NORMAL_CF, QUALIFIER)); } }); }
Source:
<code>private void setupLanguagePreference(final ListPreference languagePref) { Locale[] locales = getLocales(BuildConfig.SUPPORTED_LOCALES); <START> <END> Arrays.sort(locales, new Comparator<Locale>() { @Override public int compare(Locale o1, Locale o2) { return o1.getDisplayName().compareToIgnoreCase(o2.getDisplayName()); } }); String[] displayNames = new String[locales.length]; String[] entryValues = new String[locales.length]; for(int index = 0; index < locales.length; index++) { Locale locale = locales[index]; displayNames[index] = locale.getDisplayName(locale); entryValues[index] = getLanguageCountryCode(locale); } languagePref.setValue(getLanguageCountryCode(getCurrentLocale())); languagePref.setEntries(displayNames); languagePref.setEntryValues(entryValues); languagePref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object o) { languagePref.setValue(o.toString()); updatePreferredLanguage(o.toString()); return true; } }); }</code><technical_language>Locale currentLocale = getCurrentLocale();</technical_language>

Target:
private void setupLanguagePreference(final ListPreference languagePref) { Locale[] locales = getLocales(); final Locale currentLocale = getCurrentLocale(); Arrays.sort(locales, new Comparator<Locale>() { @Override public int compare(Locale o1, Locale o2) { return o1.getDisplayName().compareToIgnoreCase(o2.getDisplayName()); } }); String[] displayNames = new String[locales.length]; String[] entryValues = new String[locales.length]; for(int index = 0; index < locales.length; index++) { Locale locale = locales[index]; displayNames[index] = locale.getDisplayName(locale); entryValues[index] = getLanguageCountryCode(locale); } languagePref.setValue(getLanguageCountryCode(currentLocale)); languagePref.setEntries(displayNames); languagePref.setEntryValues(entryValues); languagePref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object o) { languagePref.setValue(o.toString()); updatePreferredLanguage(o.toString()); return true; } }); }
Source:
<code>public void testDetached() { final CountDownLatch stopped = new CountDownLatch(1); ZThread.start((args) -> { <START> ZContext ctx = new ZContext(); <END> Socket push = ctx.createSocket(SocketType.PUSH); assertThat(push, notNullValue()); ctx.close(); stopped.countDown(); }); try { stopped.await(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); e.printStackTrace(); } }</code><technical_language>This a good place a try-with-resources block: java try (ZContext ctx = new ZContext()) { Socket push = ctx.createSocket(SocketType.PUSH); assertThat(push, notNullValue()); }</technical_language>

Target:
public void testDetached() { final CountDownLatch stopped = new CountDownLatch(1); ZThread.start((args) -> { try (ZContext ctx = new ZContext()) { Socket push = ctx.createSocket(SocketType.PUSH); assertThat(push, notNullValue()); } stopped.countDown(); }); try { stopped.await(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); e.printStackTrace(); } }
Source:
<code>public void run(IProgressMonitor monitor) throws CoreException { if (!repository.getRepositoryState().canCheckout()) { MessageDialog.openError(getShell(), UIText.BranchAction_cannotCheckout, NLS.bind( UIText.BranchAction_repositoryState, repository .getRepositoryState().getDescription())); return; } if (refName == null) { BranchSelectionDialog dialog = new BranchSelectionDialog( getShell(), repository); if (dialog.open() != Window.OK) { return; } refName = dialog.getRefName(); } bop = new BranchOperation(repository, refName); <START> bop.execute(monitor); <END> BranchResultDialog.show(bop.getResult(), repository, refName); }</code><technical_language>BranchOperation locks resources execute in UI thread</technical_language>

Target:
public void run(IProgressMonitor monitor) throws CoreException { if (!repository.getRepositoryState().canCheckout()) { PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() { public void run() { MessageDialog.openError(getShell(), UIText.BranchAction_cannotCheckout, NLS.bind( UIText.BranchAction_repositoryState, repository.getRepositoryState() .getDescription())); } }); return; } if (refName == null) { BranchSelectionDialog dialog = new BranchSelectionDialog( getShell(), repository); if (dialog.open() != Window.OK) { return; } refName = dialog.getRefName(); } bop = new BranchOperation(repository, refName); bop.execute(monitor); BranchResultDialog.show(bop.getResult(), repository, refName); }
Source:
<code>public long writeTo(WritableByteChannel channel) throws IOException { <START> long written = 0; <END> if (!isSendComplete()) { written = channel.write(buffer); } return written; }</code><technical_language>java return isSendComplete() ? 0 : channel.write(buffer); if want more elegant</technical_language>

Target:
public long writeTo(WritableByteChannel channel) throws IOException { return isSendComplete() ? 0 : channel.write(buffer); }
Source:
<code>public IBinding getBinding() { <START> if (fBinding == null && fParameterOwner != null) { <END> ICPPParameter[] parameters = fParameterOwner.getParameters(); fBinding = parameters[fParameterPosition]; } return fBinding; }</code><technical_language>Returning null this method is call NPE in caller code</technical_language>

Target:
public IBinding getBinding() { if (fBinding == null) { ICPPParameter[] parameters = fParameterOwner.getParameters(); fBinding = parameters[fParameterPosition]; } return fBinding; }
Source:
<code>public String toString() { <START> return "MistWatermarkEvent with timestamp: " + timestamp; <END> }</code><technical_language>Please StringBuilder</technical_language>

Target:
public String toString() { return new StringBuilder("MistWatermarkEvent with timestamp: ") .append(timestamp) .toString(); }
Source:
<code>private void logUnhandledException(Throwable ex) { String errMessage = String.format("Got exception: [%s] / message [%s]", ex.getClass().getSimpleName(), ex.getMessage()); StackTraceElement elem = findFirstResourceCallFromCallStack(ex.getStackTrace()); String resourceClassName = null; if (elem != null) { errMessage += String.format(" / related resource location: [%s.%s](%s:%d)", elem.getClassName(), elem.getMethodName(), elem.getFileName(), elem.getLineNumber()); resourceClassName = elem.getClassName(); } Logger log = getEffectiveLogger(resourceClassName); <START> recordExceptionLog(log, errMessage, ex); <END> }</code><technical_language>nit: want inline this method is logging log.error(errMessage, ex)</technical_language>

Target:
private void logUnhandledException(Throwable ex) { String errMessage = String.format("Got exception: [%s] / message [%s]", ex.getClass().getSimpleName(), ex.getMessage()); StackTraceElement elem = findFirstResourceCallFromCallStack(ex.getStackTrace()); String resourceClassName = null; if (elem != null) { errMessage += String.format(" / related resource location: [%s.%s](%s:%d)", elem.getClassName(), elem.getMethodName(), elem.getFileName(), elem.getLineNumber()); resourceClassName = elem.getClassName(); } Logger log = getEffectiveLogger(resourceClassName); log.error(errMessage, ex); }
Source:
<code>public void setUp() { MockitoAnnotations.initMocks(this); rdfSourceOperationFactory = new RdfSourceOperationFactoryImpl(); setField(createResourceService, "rdfSourceOperationFactory", rdfSourceOperationFactory); nonRdfSourceOperationFactory = new NonRdfSourceOperationFactoryImpl(); setField(createResourceService, "nonRdfSourceOperationFactory", nonRdfSourceOperationFactory); setField(createResourceService, "containmentIndex", containmentIndex); <START> createResourceService.eventAccumulator = eventAccumulator; <END> when(psManager.getSession(ArgumentMatchers.any())).thenReturn(psSession); when(extContent.getURL()).thenReturn(EXTERNAL_URL); when(extContent.getHandling()).thenReturn(ExternalContent.PROXY); when(extContent.getContentType()).thenReturn(EXTERNAL_CONTENT_TYPE); when(transaction.getId()).thenReturn(TX_ID); cleanupList.add(FedoraId.getRepositoryRootId()); }</code><technical_language>curious departed setField(...</technical_language>

Target:
public void setUp() { MockitoAnnotations.initMocks(this); rdfSourceOperationFactory = new RdfSourceOperationFactoryImpl(); setField(createResourceService, "rdfSourceOperationFactory", rdfSourceOperationFactory); nonRdfSourceOperationFactory = new NonRdfSourceOperationFactoryImpl(); setField(createResourceService, "nonRdfSourceOperationFactory", nonRdfSourceOperationFactory); setField(createResourceService, "containmentIndex", containmentIndex); setField(createResourceService, "eventAccumulator", eventAccumulator); when(psManager.getSession(ArgumentMatchers.any())).thenReturn(psSession); when(extContent.getURL()).thenReturn(EXTERNAL_URL); when(extContent.getHandling()).thenReturn(ExternalContent.PROXY); when(extContent.getContentType()).thenReturn(EXTERNAL_CONTENT_TYPE); when(transaction.getId()).thenReturn(TX_ID); cleanupList.add(FedoraId.getRepositoryRootId()); }
Source:
<code>protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); synchronized (mutex) { <START> outState.putBoolean("_isCurrentUser", isCurrentUser); <END> } }</code><technical_language>here, a constant</technical_language>

Target:
protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); synchronized (mutex) { outState.putBoolean(PARCEL_KEY_IS_CURRENT_USER, isCurrentUser); } }
Source:
<code>public String stringify() { return StringUtils.format( "%s(%s)", name, <START> Joiner.on(", ").join(args.stream().map(Expr::stringify).iterator()) <END> ); }</code><technical_language>nit: Expr.ARG_JOINER</technical_language>

Target:
public String stringify() { return StringUtils.format( "%s(%s)", name, Expr.ARG_JOINER.join(args.stream().map(Expr::stringify).iterator()) ); }
Source:
<code>private void updateProjecterState(String deviceId) { long age = System.currentTimeMillis() - lastProjectorStateUpdateTime; boolean needsUpdate = age >= projectorStateUpdateInterval; if (needsUpdate) { <START> logger.debug("Quering projector '{}' state", deviceId); <END> OnOffType newState = (OnOffType) queryDataFromDevice(deviceId, EpsonProjectorCommandType.POWER, SwitchItem.class); updateProjecterStateVariable(newState); } }</code><technical_language>"Querying"</technical_language>

Target:
private void updateProjecterState(String deviceId) { long age = System.currentTimeMillis() - lastProjectorStateUpdateTime; boolean needsUpdate = age >= projectorStateUpdateInterval; if (needsUpdate) { logger.debug("Querying projector '{}' state", deviceId); OnOffType newState = (OnOffType) queryDataFromDevice(deviceId, EpsonProjectorCommandType.POWER, SwitchItem.class); updateProjecterStateVariable(newState); } }
Source:
<code>private void mergeLocalToBuilder() { if (id != null) { builder.setId(this.id.getProto()); } if (fragments != null) { for (FragmentProto fragment : fragments) { <START> builder.addFragments(fragment); <END> } } if (this.outputTable != null) { builder.setOutputTable(this.outputTable); } if (this.isUpdated) { builder.setClusteredOutput(this.clusteredOutput); } if (this.plan != null) { builder.setPlan(this.plan); } if (this.interQuery != null) { builder.setInterQuery(this.interQuery); } if (this.fetches != null) { for (FetchImpl fetche : fetches) { builder.addFetches(fetche.getProto()); } } if (this.queryMasterHostAndPort != null) { builder.setQueryMasterHostAndPort(this.queryMasterHostAndPort); } if (this.queryContext != null) { builder.setQueryContext(queryContext.getProto()); } if (this.dataChannel != null) { builder.setDataChannel(dataChannel.getProto()); } if (this.enforcer != null) { builder.setEnforcer(enforcer.getProto()); } }</code><technical_language>2 spaces instead of a tab character</technical_language>

Target:
private void mergeLocalToBuilder() { if (id != null) { builder.setId(this.id.getProto()); } if (fragments != null) { for (FragmentProto fragment : fragments) { builder.addFragments(fragment); } } if (this.outputTable != null) { builder.setOutputTable(this.outputTable); } if (this.isUpdated) { builder.setClusteredOutput(this.clusteredOutput); } if (this.plan != null) { builder.setPlan(this.plan); } if (this.interQuery != null) { builder.setInterQuery(this.interQuery); } if (this.fetches != null) { for (FetchProto fetch : fetches) { builder.addFetches(fetch); } } if (this.queryMasterHostAndPort != null) { builder.setQueryMasterHostAndPort(this.queryMasterHostAndPort); } if (this.queryContext != null) { builder.setQueryContext(queryContext.getProto()); } if (this.dataChannel != null) { builder.setDataChannel(dataChannel.getProto()); } if (this.enforcer != null) { builder.setEnforcer(enforcer.getProto()); } }
Source:
<code>public Operation operationDispatched(Request request, Operation operation) { <START> boolean isJsonLd = <END> request.getKvp().get("f") != null && request.getKvp().get("f").equals(JSONLDGetFeatureResponse.MIME) ? true : false; if (request.getHttpRequest().getServletPath().equals("/ogc") && isJsonLd) { try { String strFilter = (String) request.getKvp().get("FILTER"); if (strFilter != null && strFilter.indexOf(".") != -1) { FeatureTypeInfo typeInfo = getFeatureType((String) operation.getParameters()[0]); RootBuilder root = configuration.getTemplate(typeInfo); if (root != null) { JsonLdPathVisitor visitor = new JsonLdPathVisitor(typeInfo.getFeatureType()); Filter f = (Filter) XCQL.toFilter(strFilter).accept(visitor, root); String newFilter = ECQL.toCQL(f).replaceAll("\"", "").replaceAll("/", "."); newFilter = ExpressionsUtils.workXpathAttributeSyntax(newFilter); for (int i = 0; i < operation.getParameters().length; i++) { Object p = operation.getParameters()[i]; if (p != null && ((String.valueOf(p)).trim().equals(strFilter.trim()))) { operation.getParameters()[i] = newFilter; break; } } } } } catch (Exception e) { throw new RuntimeException(e); } } return super.operationDispatched(request, operation); }</code><technical_language>Weak test, content negotiation in OGC API services done "accept" headers</technical_language>

Target:
public Operation operationDispatched(Request request, Operation operation) { if ("FEATURES".equalsIgnoreCase(request.getService()) && isJsonLdMIME(request)) { try { String filterLang = (String) request.getKvp().get("FILTER-LANG"); if (filterLang != null && filterLang.equalsIgnoreCase("CQL-TEXT")) { String filter = (String) request.getKvp().get("FILTER"); replaceJsonLdPathWithFilter(filter, operation); } } catch (Exception e) { throw new RuntimeException(e); } } return super.operationDispatched(request, operation); }
Source:
<code>public static String getAppVersion() { <START> URL url = ApplicationUtils.class.getClassLoader().getResource(APP_VERSION_FILENAME); <END> String version = "UNKNOWN"; InputStream is = null; try { is = url.openStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String line; while ((line = br.readLine()) != null) { if (!line.startsWith("#")) { String[] pairs = Pattern.compile("=").split(line); if (pairs[0].equals("version")) { version = pairs[1]; } } } } catch (IOException ex) { Exceptions.printStackTrace(ex); } finally { IOUtils.closeQuietly(is); } return version; }</code><technical_language>do of this ourselves. class Properties, same, in line "load(InputStream is)"</technical_language>

Target:
public static String getAppVersion() { return APP_VERSION; }
Source:
<code>public HTableDescriptor generateDefaultSIGovernedTable(String tableName){ HTableDescriptor desc=new HTableDescriptor(TableName.valueOf(namespace,tableName)); <START> desc.setPriority(110); <END> desc.addFamily(createDataFamily()); return desc; }</code><technical_language>constant</technical_language>

Target:
public HTableDescriptor generateDefaultSIGovernedTable(String tableName){ HTableDescriptor desc=new HTableDescriptor(TableName.valueOf(namespace,tableName)); desc.setPriority(TABLE_PRIORITY); desc.addFamily(createDataFamily()); return desc; }
Source:
<code>public void onEvent(StatusUpdateEvent event, long sequence, boolean endOfBatch) throws Exception { TaskStatus status = event.getStatus(); this.schedulerState.updateTask(status); TaskID taskId = status.getTaskId(); NodeTask task = schedulerState.getTask(taskId); if (task == null) { LOGGER.warn("Task: not found, status: {}", taskId.getValue(), status.getState()); schedulerState.removeTask(taskId); return; } LOGGER.info("Status Update for task: | state: {}", taskId.getValue(), status.getState()); TaskState state = status.getState(); switch (state) { case TASK_STAGING: schedulerState.makeTaskStaging(taskId); break; case TASK_STARTING: schedulerState.makeTaskStaging(taskId); break; case TASK_RUNNING: schedulerState.makeTaskActive(taskId); break; case TASK_FINISHED: offerLifecycleManager.declineOutstandingOffers(task.getHostname()); schedulerState.removeTask(taskId); break; case TASK_FAILED: offerLifecycleManager.declineOutstandingOffers(task.getHostname()); if (taskIsKillable(taskId)) { schedulerState.removeTask(taskId); LOGGER.info("Removed killable, failed task with id {}", taskId); } else { schedulerState.makeTaskPending(taskId); <START> } <END> break; case TASK_KILLED: offerLifecycleManager.declineOutstandingOffers(task.getHostname()); schedulerState.removeTask(taskId); LOGGER.info("Removed killed task with id {}", taskId); break; case TASK_LOST: offerLifecycleManager.declineOutstandingOffers(task.getHostname()); if (taskIsKillable(taskId)) { schedulerState.removeTask(taskId); LOGGER.info("Removed killable, lost task with id {}", taskId); } else { schedulerState.makeTaskPending(taskId); LOGGER.info("Marked as pending lost task with id {}", taskId); } break; default: LOGGER.error("Invalid state: {}", state); break; } }</code><technical_language>this if/else block is replicated modulo a log statement. Private method</technical_language>

Target:
public void onEvent(StatusUpdateEvent event, long sequence, boolean endOfBatch) throws Exception { TaskStatus status = event.getStatus(); this.schedulerState.updateTask(status); TaskID taskId = status.getTaskId(); NodeTask task = schedulerState.getTask(taskId); if (task == null) { LOGGER.warn("Task: not found, status: {}", taskId.getValue(), status.getState()); schedulerState.removeTask(taskId); return; } LOGGER.info("Status Update for task: | state: {}", taskId.getValue(), status.getState()); TaskState state = status.getState(); switch (state) { case TASK_STAGING: schedulerState.makeTaskStaging(taskId); break; case TASK_STARTING: schedulerState.makeTaskStaging(taskId); break; case TASK_RUNNING: schedulerState.makeTaskActive(taskId); break; case TASK_FINISHED: cleanupTask(taskId, task, "finished"); break; case TASK_FAILED: cleanupFailedTask(taskId, task, "failed"); break; case TASK_KILLED: cleanupTask(taskId, task, "killed"); break; case TASK_LOST: cleanupFailedTask(taskId, task, "lost"); break; default: LOGGER.error("Invalid state: {}", state); break; } }
Source:
<code>public PatchScript call() throws OrmException, NoSuchChangeException { validatePatchSetId(psa); validatePatchSetId(psb); control = changeControlFactory.validateFor(changeId); change = control.getChange(); ReviewDb db = schemaFactory.open(); <START> patchSet = db.patchSets().get(patchSetId); <END> if (patchSet == null) { throw new NoSuchChangeException(changeId); } projectKey = change.getProject(); aId = psa != null ? toObjectId(db, psa) : null; bId = toObjectId(db, psb); try { git = repoManager.openRepository(projectKey.get()); } catch (RepositoryNotFoundException e) { log.error("Repository " + projectKey + " not found", e); throw new NoSuchChangeException(changeId, e); } final String fileName = patchKey.getFileName(); try { final PatchList list = listFor(keyFor(settings.getWhitespace())); final PatchScriptBuilder b = newBuilder(list); final PatchListEntry contentWS = list.get(fileName); final CommentDetail comments = allComments(db); final PatchListEntry contentActual; if (settings.getWhitespace() == Whitespace.IGNORE_NONE) { contentActual = contentWS; } else { contentActual = listFor(keyFor(Whitespace.IGNORE_NONE)).get(fileName); } try { return b.toPatchScript(contentWS, comments, contentActual); } catch (IOException e) { log.error("File content unavailable", e); throw new NoSuchChangeException(changeId, e); } } finally { git.close(); db.close(); } }</code><technical_language>in a try/finally block possibly leak database connection. Right if patch set null (missing in database) leak connection, creating easy DOS attack</technical_language>

Target:
public PatchScript call() throws OrmException, NoSuchChangeException { validatePatchSetId(psa); validatePatchSetId(psb); control = changeControlFactory.validateFor(changeId); change = control.getChange(); ReviewDb db = null; try { db = schemaFactory.open(); patchSet = db.patchSets().get(patchSetId); if (patchSet == null) { throw new NoSuchChangeException(changeId); } projectKey = change.getProject(); aId = psa != null ? toObjectId(db, psa) : null; bId = toObjectId(db, psb); try { git = repoManager.openRepository(projectKey.get()); } catch (RepositoryNotFoundException e) { log.error("Repository " + projectKey + " not found", e); throw new NoSuchChangeException(changeId, e); } final String fileName = patchKey.getFileName(); try { final PatchList list = listFor(keyFor(settings.getWhitespace())); final PatchScriptBuilder b = newBuilder(list); final PatchListEntry contentWS = list.get(fileName); final CommentDetail comments = allComments(db); final PatchListEntry contentActual; if (settings.getWhitespace() == Whitespace.IGNORE_NONE) { contentActual = contentWS; } else { contentActual = listFor(keyFor(Whitespace.IGNORE_NONE)).get(fileName); } try { return b.toPatchScript(contentWS, comments, contentActual); } catch (IOException e) { log.error("File content unavailable", e); throw new NoSuchChangeException(changeId, e); } } finally { git.close(); } } finally { if (db != null) { db.close(); } } }