auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public ResponseEntity formLogin(Authentication authentication) { if (authentication == null || !authentication.isAuthenticated()) { throw new InsufficientAuthenticationException("unauthorized"); } if (!(authentication instanceof UsernamePasswordAuthenticationToken)) { return toResponseEntityError("Unsupported authentication class " + authentication.getClass().getName()); } String token; try { Object principal = authentication.getPrincipal(); String subject; if (principal instanceof UserDetails) { subject = ((UserDetails) principal).getUsername(); } else { subject = principal.toString(); } <START> Integer timeout = configurationManagementService.getConfiguration().getSessionConfiguration().getTimeoutSeconds(); <END> token = securityTokenProvider.getToken(subject, Collections.emptyMap(), timeout); } catch (JoseException e) { logger.error("Unable to create JWT token.", e); return toResponseEntityError("Unable to create JWT token.", HttpStatus.BAD_REQUEST); } return ResponseEntity.ok().body(new LoginOutput(token, authentication.getAuthorities())); }</code><technical_language>Cosmetic: add a shortcut method getSessionTimeoutSeconds() ConfigurationManager configurationManager.getSessionTimeoutSeconds() instead of injecting configurationManagementService again. Controllers extend BaseController injects ConfigurationManager</technical_language>

Target:
public ResponseEntity formLogin(Authentication authentication) { if (authentication == null || !authentication.isAuthenticated()) { throw new InsufficientAuthenticationException("unauthorized"); } if (!(authentication instanceof UsernamePasswordAuthenticationToken)) { return toResponseEntityError("Unsupported authentication class " + authentication.getClass().getName()); } String token; try { Object principal = authentication.getPrincipal(); String subject; if (principal instanceof UserDetails) { subject = ((UserDetails) principal).getUsername(); } else { subject = principal.toString(); } Integer timeout = configurationManager.getSessionTimeoutSeconds(); token = securityTokenProvider.getToken(subject, Collections.emptyMap(), timeout); } catch (JoseException e) { logger.error("Unable to create JWT token.", e); return toResponseEntityError("Unable to create JWT token.", HttpStatus.BAD_REQUEST); } return ResponseEntity.ok().body(new LoginOutput(token, authentication.getAuthorities())); }
Source:
<code><START> private synchronized Object getLock( final List<String> key ) { <END> Object lock = syncMap.putIfAbsent( key, new Object() ); if ( lock == null ) { lock = syncMap.get( key ); } return lock; }</code><technical_language>need sync, need check if "lock" returned is null. "putIfAbsent" call return null. If map lock, add object parameter map return you. If is lock in map, return that, discard "new Object()"</technical_language>

Target:
private synchronized ReentrantReadWriteLock getLock( final List<String> key ) { ReentrantReadWriteLock lock = new ReentrantReadWriteLock( true ); ReentrantReadWriteLock existing = syncMap.putIfAbsent(key, lock); return existing != null ? existing : lock; }
Source:
<code>public synchronized void onRecordsReceived(@NotNull final ConsumerRecords<?, ?> records, @NotNull final Map<MetricName, ? extends Metric> metrics) { final Instant receivedTime = Instant.now(); for (final TopicPartition topicPartition : records.partitions()) { final KafkaPositionKey key = _ownedKeys.get(topicPartition); if (key == null) { return; } final KafkaPositionValue value = (KafkaPositionValue) _positions.get(key); if (value == null) { return; } long consumerOffset = Long.MIN_VALUE; <START> Instant lastRecordPolledTimestamp = null; <END> for (final ConsumerRecord<?, ?> record : records.records(topicPartition)) { long recordOffset = record.offset(); if (consumerOffset <= recordOffset) { consumerOffset = recordOffset + 1; lastRecordPolledTimestamp = Instant.ofEpochMilli(record.timestamp()); } } value.setLastNonEmptyPollTime(receivedTime); value.setConsumerOffset(consumerOffset); value.setLastRecordPolledTimestamp(lastRecordPolledTimestamp); Long consumerLag = getLagMetric(metrics, topicPartition); if (consumerLag != null) { final long brokerOffset = consumerOffset + consumerLag; value.setLastBrokerQueriedTime(receivedTime); value.setBrokerOffset(brokerOffset); } if (!_needingInit.isEmpty()) { _needingInit.remove(topicPartition); } } }</code><technical_language>Oh, lucky you: I remembered another one. is this "return" "continue"? (Ditto for below.) Some other topicPartition ownedKey, it? If not, semantics of null key null here</technical_language>

Target:
public synchronized void onRecordsReceived(@NotNull final ConsumerRecords<?, ?> records, @NotNull final Map<MetricName, ? extends Metric> metrics) { final Instant receivedTime = Instant.now(); for (final TopicPartition topicPartition : records.partitions()) { final KafkaPositionKey key = _ownedKeys.computeIfAbsent(topicPartition, s -> new KafkaPositionKey(topicPartition.topic(), topicPartition.partition(), BrooklinInstanceInfo.getInstanceName(), _datastreamTaskPrefix, _datastreamTaskName, _connectorTaskStartTime)); final KafkaPositionValue value = (KafkaPositionValue) _positions.computeIfAbsent(key, s -> new KafkaPositionValue()); records.records(topicPartition).stream() .max(Comparator.comparingLong(ConsumerRecord::offset)) .ifPresent(record -> { value.setLastNonEmptyPollTime(receivedTime); value.setConsumerOffset(record.offset() + 1); value.setLastRecordReceivedTimestamp(Instant.ofEpochMilli(record.timestamp())); }); getLagMetric(metrics, topicPartition).ifPresent(consumerLag -> Optional.ofNullable(value.getConsumerOffset()).ifPresent(consumerOffset -> { final long brokerOffset = consumerOffset + consumerLag; value.setLastBrokerQueriedTime(receivedTime); value.setBrokerOffset(brokerOffset); })); _needingInit.remove(topicPartition); } }
Source:
<code>boolean isEmptySpace(World world, BlockPos pos, TileEntity tile) { BlockState state = world.getBlockState(pos); VoxelShape shape = state.getCollisionShape(world, pos); if (shape != cachedDownShape) { <START> cachedOpenBelow = VoxelShapes.compare(REQ_SPACE, shape, IBooleanFunction.AND); <END> cachedDownShape = shape; } return cachedOpenBelow; }</code><technical_language>I missing a ! here, this false for shape = VoxelShapes.empty()</technical_language>

Target:
boolean isEmptySpace(World world, BlockPos pos, TileEntity tile) { if(tile instanceof IConveyorTile) return true; BlockState state = world.getBlockState(pos); VoxelShape shape = state.getCollisionShape(world, pos); if (shape != cachedDownShape) { cachedOpenBelow = !VoxelShapes.compare(REQUIRED_SPACE, shape, IBooleanFunction.AND); cachedDownShape = shape; } return cachedOpenBelow; }
Source:
<code>public List<RevCommit> getBaseCommits(final int aIdx, final int bIdx) throws IncorrectObjectTypeException, IOException { if (sourceCommits[aIdx] == null) throw new IncorrectObjectTypeException(sourceObjects[aIdx], Constants.TYPE_COMMIT); if (sourceCommits[bIdx] == null) throw new IncorrectObjectTypeException(sourceObjects[bIdx], Constants.TYPE_COMMIT); walk.reset(); walk.setRevFilter(RevFilter.MERGE_BASE); walk.markStart(sourceCommits[aIdx]); walk.markStart(sourceCommits[bIdx]); List<RevCommit> bases = new ArrayList<RevCommit>(); int commitIdx = 0; for (RevCommit base : walk) { if (commitIdx < MAX_BASES) { bases.add(base); commitIdx++; } else { throw new IOException(MessageFormat.format( JGitText.get().mergeRecursiveTooManyMergeBasesFor, <START> "TOO_MANY_BASES", sourceCommits[aIdx].name(), <END> sourceCommits[bIdx].name(), Integer.valueOf(commitIdx), base.name())); } } return bases; }</code><technical_language>"too bases" repeated translated</technical_language>

Target:
public List<RevCommit> getBaseCommits(final int aIdx, final int bIdx) throws IncorrectObjectTypeException, IOException { if (sourceCommits[aIdx] == null) throw new IncorrectObjectTypeException(sourceObjects[aIdx], Constants.TYPE_COMMIT); if (sourceCommits[bIdx] == null) throw new IncorrectObjectTypeException(sourceObjects[bIdx], Constants.TYPE_COMMIT); walk.reset(); walk.setRevFilter(RevFilter.MERGE_BASE); walk.markStart(sourceCommits[aIdx]); walk.markStart(sourceCommits[bIdx]); List<RevCommit> bases = new ArrayList<RevCommit>(); int commitIdx = 0; for (RevCommit base : walk) { if (commitIdx < MAX_BASES) { bases.add(base); commitIdx++; } else { throw new IOException(MessageFormat.format( JGitText.get().mergeRecursiveTooManyMergeBasesFor, Integer.valueOf(MAX_BASES), sourceCommits[aIdx].name(), sourceCommits[bIdx].name(), Integer.valueOf(commitIdx), base.name())); } } return bases; }
Source:
<code>private void toggleHtmlMode() { mEditorFragmentListener.onTrackableEvent(TrackableEvent.HTML_BUTTON_TAPPED); mEditorFragmentListener.onHtmlModeToggledInToolbar(); <START> mHtmlModeEnabled = !mHtmlModeEnabled; <END> mWPAndroidGlueCode.toggleEditorMode(); }</code><technical_language>nitpick: wondering move this line top of method: this listeners tracking happen fact (when point)</technical_language>

Target:
private void toggleHtmlMode() { mHtmlModeEnabled = !mHtmlModeEnabled; mEditorFragmentListener.onTrackableEvent(TrackableEvent.HTML_BUTTON_TAPPED); mEditorFragmentListener.onHtmlModeToggledInToolbar(); mWPAndroidGlueCode.toggleEditorMode(); }
Source:
<code>private List<SchemaTableName> listTables(ConnectorSession session, SchemaTablePrefix prefix) { if (prefix.getTableName() == null) { return listTables(session, prefix.getSchemaName()); } <START> return ImmutableList.of(new SchemaTableName(prefix.getSchemaName(), prefix.getTableName())); <END> }</code><technical_language>if schemaName is null here</technical_language>

Target:
private List<SchemaTableName> listTables(ConnectorSession session, SchemaTablePrefix prefix) { if (prefix.getSchemaName() == null || prefix.getTableName() == null) { return listTables(session, prefix.getSchemaName()); } return ImmutableList.of(new SchemaTableName(prefix.getSchemaName(), prefix.getTableName())); }
Source:
<code>public void testSetAndGetExtendedResourcesWithoutYarnSupport() { <START> assumeTrue(HadoopUtils.isMaxHadoopVersion(3, 0)); final Resource resource = Resource.newInstance(100, 1); ResourceInformationReflector.INSTANCE.setResourceInformation(resource, RESOURCE_NAME, RESOURCE_VALUE); final Map<String, Long> externalResourcesResult = ResourceInformationReflector.INSTANCE.getExternalResources(resource); <END> assertTrue(externalResourcesResult.isEmpty()); }</code><technical_language>this test pass if Hadoop version is 2.10+ 3.0? contradict testSetAndGetExtendedResourcesWithYarnSupport</technical_language>

Target:
public void testSetAndGetExtendedResourcesWithoutYarnSupport() { assumeTrue(HadoopUtils.isMaxHadoopVersion(2, 10)); final Resource resource = Resource.newInstance(100, 1); ResourceInformationReflector.INSTANCE.setResourceInformation(resource, RESOURCE_NAME, RESOURCE_VALUE); final Map<String, Long> externalResourcesResult = ResourceInformationReflector.INSTANCE.getExternalResources(resource); assertTrue(externalResourcesResult.isEmpty()); }
Source:
<code>public void changeSessionIdThenPreserveParameters() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest("GET", ""); String id = request.getSession().getId(); request.getSession(); request.setServletPath("/login"); request.setMethod("POST"); request.setParameter("username", "user"); request.setParameter("password", "password"); HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository(); CsrfToken token = repository.generateToken(request); repository.saveToken(token, request, response); request.setParameter(token.getParameterName(), token.getToken()); loadConfig(SessionManagementDefaultSessionFixationServlet31Config.class); springSecurityFilterChain.doFilter(request, response, chain); <START> Assert.assertNotEquals(id, request.getSession().getId()); <END> Assert.assertEquals(request.getParameter(token.getParameterName()), token.getToken()); Assert.assertEquals(request.getParameter("username"), "user"); Assert.assertEquals(request.getParameter("password"), "password"); }</code><technical_language>do a favor please AssertJ instead? assertThat(request.getSession().getId()).isEqualTo(id)</technical_language>

Target:
public void changeSessionIdThenPreserveParameters() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest("GET", ""); String id = request.getSession().getId(); request.getSession(); request.setServletPath("/login"); request.setMethod("POST"); request.setParameter("username", "user"); request.setParameter("password", "password"); HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository(); CsrfToken token = repository.generateToken(request); repository.saveToken(token, request, response); request.setParameter(token.getParameterName(), token.getToken()); request.getSession().setAttribute("attribute1", "value1"); loadConfig(SessionManagementDefaultSessionFixationServlet31Config.class); springSecurityFilterChain.doFilter(request, response, chain); assertThat(!request.getSession().getId().equals(id)); assertThat(request.getSession().getAttribute("attribute1").equals("value1")); }
Source:
<code>public void unsetMavenWorkspaceRepository(MavenWorkspaceRepository mavenWorkspaceRepository) { <START> this.mavenWorkspaceRepository = null; <END> }</code><technical_language>correct thing: java if (this.mavenWorkspaceRepository == mavenWorkspaceRepository) { this.mavenWorkspaceRepository = null; } properly handle replacement</technical_language>

Target:
public void unsetMavenWorkspaceRepository(MavenWorkspaceRepository mavenWorkspaceRepository) { if (this.mavenWorkspaceRepository == mavenWorkspaceRepository) { this.mavenWorkspaceRepository = null; } }
Source:
<code>private void createImageForMemoryDump() { VDSReturnValue retVal = Backend .getInstance() .getResourceManager() .RunVdsCommand( VDSCommandType.CreateImage, new CreateImageVDSCommandParameters( storagePoolId, storageDomainId, imageGroupId, getVm().getTotalMemorySizeInBytes(), <START> VolumeType.Preallocated, <END> VolumeFormat.RAW, volumeId, "", getStoragePool().getcompatibility_version().toString())); if (!retVal.getSucceeded()) { throw new VdcBLLException(VdcBllErrors.VolumeCreationError, "CreateAllSnapshotsFromVmCommand::executeVmCommand: Failed to create image for memory!"); } Guid guid = createTask(retVal.getCreationInfo(), VdcActionType.CreateAllSnapshotsFromVm, VdcObjectType.Storage, getStorageDomainId().getValue()); getTaskIdList().add(guid); }</code><technical_language>sparse</technical_language>

Target:
private void createImageForMemoryDump() { VDSReturnValue retVal = Backend .getInstance() .getResourceManager() .RunVdsCommand( VDSCommandType.CreateImage, new CreateImageVDSCommandParameters( storagePoolId, storageDomainId, memoryDumpImageGroupId, getVm().getTotalMemorySizeInBytes(), VolumeType.Preallocated, VolumeFormat.RAW, memoryDumpVolumeId, "", getStoragePool().getcompatibility_version().toString())); if (!retVal.getSucceeded()) { throw new VdcBLLException(VdcBllErrors.VolumeCreationError, "CreateAllSnapshotsFromVmCommand::executeVmCommand: Failed to create image for memory!"); } Guid guid = createTask(retVal.getCreationInfo(), VdcActionType.CreateAllSnapshotsFromVm, VdcObjectType.Storage, getStorageDomainId().getValue()); getTaskIdList().add(guid); }
Source:
<code>public void onNext(final StartTime startTime) { LOG.log(Level.INFO, "StartTime: {0}", startTime); final EventHandler<AllocatedEvaluator> evalAllocHandlerForServer = getEvalAllocHandlerForServer(); final List<EventHandler<ActiveContext>> contextActiveHandlersForServer = new ArrayList<>(2); contextActiveHandlersForServer.add(getFirstContextActiveHandlerForServer()); contextActiveHandlersForServer.add(getSecondContextActiveHandlerForServer()); evaluatorManager.allocateEvaluators(initServerCount, evalAllocHandlerForServer, contextActiveHandlersForServer); final EventHandler<AllocatedEvaluator> evalAllocHandlerForWorker = getEvalAllocHandlerForWorker(); final List<EventHandler<ActiveContext>> contextActiveHandlersForWorker = new ArrayList<>(2); contextActiveHandlersForWorker.add(getFirstContextActiveHandlerForWorker()); contextActiveHandlersForWorker.add(getSecondContextActiveHandlerForWorker()); evaluatorManager.allocateEvaluators(dataLoadingService.getNumberOfPartitions(), evalAllocHandlerForWorker, contextActiveHandlersForWorker); workerEM.getNetworkSetup().registerConnectionFactory(identifierFactory.getNewInstance(driverId)); serverEM.getNetworkSetup().registerConnectionFactory(identifierFactory.getNewInstance(driverId)); <START> psNetworkSetup.registerConnectionFactory(identifierFactory.getNewInstance(driverId)); <END> }</code><technical_language>call identifierFactory.getNewInstance(driverId) repeatedly? reuse them..</technical_language>

Target:
public void onNext(final StartTime startTime) { LOG.log(Level.INFO, "StartTime: {0}", startTime); final EventHandler<AllocatedEvaluator> evalAllocHandlerForServer = getEvalAllocHandlerForServer(); final List<EventHandler<ActiveContext>> contextActiveHandlersForServer = new ArrayList<>(2); contextActiveHandlersForServer.add(getFirstContextActiveHandlerForServer()); contextActiveHandlersForServer.add(getSecondContextActiveHandlerForServer()); evaluatorManager.allocateEvaluators(initServerCount, evalAllocHandlerForServer, contextActiveHandlersForServer); final EventHandler<AllocatedEvaluator> evalAllocHandlerForWorker = getEvalAllocHandlerForWorker(); final List<EventHandler<ActiveContext>> contextActiveHandlersForWorker = new ArrayList<>(2); contextActiveHandlersForWorker.add(getFirstContextActiveHandlerForWorker()); contextActiveHandlersForWorker.add(getSecondContextActiveHandlerForWorker()); evaluatorManager.allocateEvaluators(dataLoadingService.getNumberOfPartitions(), evalAllocHandlerForWorker, contextActiveHandlersForWorker); final Identifier driverId = identifierFactory.getNewInstance(driverIdStr); workerEMWrapper.getNetworkSetup().registerConnectionFactory(driverId); serverEMWrapper.getNetworkSetup().registerConnectionFactory(driverId); psNetworkSetup.registerConnectionFactory(driverId); }
Source:
<code>public Iterator<Row> getTransitiveClosureOver(Row startingPoint, Relationships.Direction direction, String... relationshipNames) { String startingCP = startingPoint.getString(Statements.CP); if (startingCP == null) { return Collections.<Row>emptyList().iterator(); } Observable<Row> closureContent = getRelationshipTables(direction) .flatMap(table -> { <START> Statement q = select().all().from(table).where(in(Statements.NAME, Arrays.asList(relationshipNames))); <END> return session.execute(q); }) .map(relationships -> computeTransitiveClosure(startingCP, relationships)) .flatMap(this::loadEntities); return closureContent.toBlocking().getIterator(); }</code><technical_language>compute transitive closure deleting stuff - delete entity, delete contains, adding feedId in case</technical_language>

Target:
public Iterator<Row> getTransitiveClosureOver(Row startingPoint, Relationships.Direction direction, String... relationshipNames) { String startingCP = startingPoint.getString(Statements.CP); if (startingCP == null) { return Collections.<Row>emptyList().iterator(); } TransitiveClosureProcessor runner = new TransitiveClosureProcessor( cp -> getRelationshipOtherEnds(cp, direction, Arrays.asList(relationshipNames))); return runner.process(startingCP) .toList() .flatMap(listCP -> loadEntities(listCP).toList() .map(unsorted -> reorderEntities(unsorted, listCP))) .toBlocking() .first() .iterator(); }
Source:
<code>protected SshAction<Session> newSessionAction() { return new SshAction<Session>() { private Session session = null; @Override public void clear() throws TransportException, ConnectionException { closeWhispering(session, this); session = null; } @Override public Session create() throws Exception { checkConnected(); <START> sshClientConnection.ssh.getConnection().setMaxPacketSize(256 * 1024); <END> session = sshClientConnection.ssh.startSession(); if (allocatePTY) { session.allocatePTY(TERM, 80, 24, 0, 0, Collections.<PTYMode, Integer> emptyMap()); } return session; } @Override public String toString() { return "Session()"; } }; }</code><technical_language>sense a configKey</technical_language>

Target:
protected SshAction<Session> newSessionAction() { return new SshAction<Session>() { private Session session = null; @Override public void clear() throws TransportException, ConnectionException { closeWhispering(session, this); session = null; } @Override public Session create() throws Exception { checkConnected(); sshClientConnection.ssh.getConnection().setMaxPacketSize(maxPacketSize); session = sshClientConnection.ssh.startSession(); if (allocatePTY) { session.allocatePTY(TERM, 80, 24, 0, 0, Collections.<PTYMode, Integer> emptyMap()); } return session; } @Override public String toString() { return "Session()"; } }; }
Source:
<code>private static URL[] getUrls(ClassLoader classLoader, boolean wasWrappedJar) { URL[] urls = getClassLoaderUrls(classLoader); <START> if (urls != null) { if (wasWrappedJar && urls.length == 1) { <END> try { String jarClassPath = new JarInputStream(urls[0].openStream()).getManifest().getMainAttributes().getValue("Class-Path"); String[] urlStrings = jarClassPath.split(" "); URL[] newUrls = new URL[urlStrings.length]; for (int i = 0; i < urlStrings.length; i++) { newUrls[i] = new URL(urlStrings[i]); } return newUrls; } catch (Exception e) { return null; } } } return urls; }</code><technical_language>nit: merge together: if (wasWrappedJar && urls != null && urls.length ==1). This reduce for block ident urls parameters together, is easier read</technical_language>

Target:
private static URL[] getUrls(ClassLoader classLoader, boolean wasWrappedJar) { URL[] urls = getClassLoaderUrls(classLoader); if (wasWrappedJar && urls != null && urls.length == 1) { try { String jarClassPath = new JarInputStream(urls[0].openStream()).getManifest().getMainAttributes().getValue("Class-Path"); String[] urlStrings = jarClassPath.split(" "); URL[] newUrls = new URL[urlStrings.length]; for (int i = 0; i < urlStrings.length; i++) { newUrls[i] = new URL(urlStrings[i]); } return newUrls; } catch (Exception e) { e.printStackTrace(); return null; } } return urls; }
Source:
<code>public void updateCustomizedViews(String customizedStateType, List<CustomizedView> customizedViews) { for (CustomizedView cv : customizedViews) { <START> if (_customizedViewCacheMap.containsKey(customizedStateType)) { <END> _customizedViewCacheMap.get(customizedStateType).getCustomizedViewCache().setProperty(cv); } else { CustomizedViewCache customizedViewCache = new CustomizedViewCache(getClusterName(), customizedStateType); customizedViewCache.getCustomizedViewCache().setProperty(cv); _customizedViewCacheMap.put(customizedStateType, customizedViewCache); } } }</code><technical_language>nit, move this condition out of loop checking adding key if exists. in loop, need set property</technical_language>

Target:
public void updateCustomizedViews(String customizedStateType, List<CustomizedView> customizedViews) { if (!_customizedViewCacheMap.containsKey(customizedStateType)) { CustomizedViewCache customizedViewCache = new CustomizedViewCache(getClusterName(), customizedStateType); _customizedViewCacheMap.put(customizedStateType, customizedViewCache); } for (CustomizedView cv : customizedViews) { _customizedViewCacheMap.get(customizedStateType).getCustomizedViewCache().setProperty(cv); } }
Source:
<code>public int hashCode() { <START> return 123456789; <END> }</code><technical_language>this hash code? in order avoid other people wondering in future, replace System.identityHashCode( this ) (which is default Object.hashCode() implementation returns)</technical_language>

Target:
public int hashCode() { return System.identityHashCode( this ); }
Source:
<code>private static ImageResource getPoolVmImageResource(VmType vmType, boolean nextRunConfigurationExists) { switch (vmType) { case Desktop: return nextRunConfigurationExists ? resources.manyDesktopsChangesImage() : resources.manyDesktopsImage(); case Server: return nextRunConfigurationExists ? resources.manyServersChangesImage() : resources.manyServersImage(); <START> default: return null; <END> } }</code><technical_language>Consider logging unexpected state</technical_language>

Target:
private static ImageResource getPoolVmImageResource(VmType vmType, boolean nextRunConfigurationExists) { switch (vmType) { case Desktop: return nextRunConfigurationExists ? resources.manyDesktopsChangesImage() : resources.manyDesktopsImage(); case Server: return nextRunConfigurationExists ? resources.manyServersChangesImage() : resources.manyServersImage(); default: log.severe("Invalid VmType."); return null; } }
Source:
<code>public TableInstance<RelationalTableDefinition> createImmutable(RelationalTableDefinition tableDefinition, TableHandle tableHandle) { TableName tableName = createImmutableTableName(tableHandle); <START> checkArgument(tableName.getSchema().isPresent(), "Cassandra does not like you when you don't have keyspace defined"); <END> if (!queryExecutor.tableExists(tableName.getSchema().get(), tableName.getInternalNameInDatabase())) { queryExecutor.executeQuery(tableDefinition.getCreateTableDDL(tableName.getNameInDatabase())); RelationalDataSource dataSource = tableDefinition.getDataSource(); insertData(tableName, dataSource); } return new CassandraTableInstance(tableName, tableDefinition); }</code><technical_language>nice message</technical_language>

Target:
public TableInstance<RelationalTableDefinition> createImmutable(RelationalTableDefinition tableDefinition, TableHandle tableHandle) { TableName tableName = createImmutableTableName(tableHandle); checkArgument(tableName.getSchema().isPresent(), "Cassandra requires table with schema"); if (!queryExecutor.tableExists(tableName.getSchema().get(), tableName.getSchemalessNameInDatabase())) { executeQueryIgnoreTypeError(tableDefinition.getCreateTableDDL(tableName.getNameInDatabase())); RelationalDataSource dataSource = tableDefinition.getDataSource(); insertData(tableName, dataSource); } return new CassandraTableInstance(tableName, tableDefinition); }
Source:
<code><START> public static synchronized DoorsColumnType fromString(String value) { <END> if (value.contains("Verification Criteria")) { value = "Verification Criteria"; } if (rawStringToDataType.isEmpty()) { for (DoorsColumnType enumStatus : DoorsColumnType.values()) { DoorsColumnType.rawStringToDataType.put(enumStatus.columnType, enumStatus); } } DoorsColumnType returnVal = rawStringToDataType.get(value); return returnVal != null ? returnVal : OTHER; }</code><technical_language>Remove synchronized lazy loading of map structure, add values static map enum element construction</technical_language>

Target:
public static DoorsColumnType fromString(String value) { if (value.contains("Verification Criteria")) { value = "Verification Criteria"; } DoorsColumnType returnVal = rawStringToDataType.get(value); return returnVal != null ? returnVal : OTHER; }
Source:
<code>public HaplotypeProbabilitiesFromSequence(final HaplotypeProbabilitiesFromSequence other) { <START> this(other.getHaplotype() , other.obsAllele1,other.obsAllele2,other.obsAlleleOther); <END> }</code><technical_language>whitespace suggestion this(other.getHaplotype(), other.obsAllele1, other.obsAllele2, other.obsAlleleOther);</technical_language>

Target:
public HaplotypeProbabilitiesFromSequence(final HaplotypeProbabilitiesFromSequence other) { super(other); obsAllele1 = other.obsAllele1; obsAllele2 = other.obsAllele2; obsAlleleOther = other.obsAlleleOther; }
Source:
<code>public void invalidationDoesNotProceedIfTimelockPingUnsuccessful() { when(timestampManagementService.ping()).thenThrow(EXCEPTION); TimeLockMigrator migrator = TimeLockMigrator.create(timestampManagementService, invalidator); <START> assertThatThrownBy(migrator::migrate).isInstanceOf(AtlasDbDependencyException.class); <END> verify(invalidator, never()).backupAndInvalidate(); }</code><technical_language>nit: hasCause(EXCEPTION) well</technical_language>

Target:
public void invalidationDoesNotProceedIfTimelockPingUnsuccessful() { when(timestampManagementService.ping()).thenThrow(EXCEPTION); TimeLockMigrator migrator = TimeLockMigrator.create(timestampManagementService, invalidator); assertThatThrownBy(migrator::migrate).isInstanceOf(AtlasDbDependencyException.class) .hasCause(EXCEPTION); verify(timestampManagementService).ping(); verify(invalidator, never()).backupAndInvalidate(); }
Source:
<code>protected NamedValue<?> parseNamedValueType(NamedValuePropertyType namedValueProperty) throws OwsExceptionReport { if (namedValueProperty.isSetNamedValue()) { NamedValueType namedValue = namedValueProperty.getNamedValue(); NamedValue<?> sosNamedValue = parseNamedValueValue(namedValue.getValue()); ReferenceType referenceType = (ReferenceType) CodingHelper.decodeXmlObject(namedValue.getName()); sosNamedValue.setName(referenceType); return sosNamedValue; } else if (namedValueProperty.isSetHref()) { <START> NamedValue<?> sosNamedValue = new NamedValue<ReferenceType>(); <END> ReferenceType referenceType = new ReferenceType(namedValueProperty.getHref()); if (namedValueProperty.isSetTitle()) { referenceType.setTitle(namedValueProperty.getTitle()); } sosNamedValue.setName(referenceType); return sosNamedValue; } else { throw new UnsupportedDecoderInputException(this, namedValueProperty); } }</code><technical_language><?>? actual type is right there..</technical_language>

Target:
protected NamedValue<?> parseNamedValueType(NamedValuePropertyType namedValueProperty) throws OwsExceptionReport { if (namedValueProperty.isSetNamedValue()) { NamedValueType namedValue = namedValueProperty.getNamedValue(); NamedValue<?> sosNamedValue = parseNamedValueValue(namedValue.getValue()); ReferenceType referenceType = (ReferenceType) CodingHelper.decodeXmlObject(namedValue.getName()); sosNamedValue.setName(referenceType); return sosNamedValue; } else if (namedValueProperty.isSetHref()) { NamedValue<ReferenceType> sosNamedValue = new NamedValue<ReferenceType>(); ReferenceType referenceType = new ReferenceType(namedValueProperty.getHref()); if (namedValueProperty.isSetTitle()) { referenceType.setTitle(namedValueProperty.getTitle()); } sosNamedValue.setName(referenceType); return sosNamedValue; } else { throw new UnsupportedDecoderInputException(this, namedValueProperty); } }
Source:
<code>public void modified(final Map<Object, Object> config) { runtimeConfiguration = new ISYActiveBindingConfig(config); <START> setProperlyConfigured(true); <END> if (this.insteonClient != null) { this.insteonClient.stop(); } this.insteonClient = new InsteonClient(runtimeConfiguration.getUser(), runtimeConfiguration.getPassword(), this); Errors.addErrorListener(new ErrorHandler()); if (runtimeConfiguration.isUseUpnp()) { this.logger.info("ISY: using UPNP to communicate with ISY"); this.insteonClient.start(); } else { this.logger.info("ISY: using URL to communicate with ISY"); try { this.insteonClient.start(runtimeConfiguration.getUuid(), String.format("http://%s:%s", runtimeConfiguration.getIpAddress(), runtimeConfiguration.getPort())); } catch (Exception e) { throw new RuntimeException(e); } } }</code><technical_language>This end of method</technical_language>

Target:
public void modified(final Map<Object, Object> config) { runtimeConfiguration = new ISYActiveBindingConfig(config); if (this.insteonClient != null) { this.insteonClient.stop(); } this.insteonClient = new InsteonClient(runtimeConfiguration.getUser(), runtimeConfiguration.getPassword(), this); Errors.addErrorListener(new ErrorHandler()); if (runtimeConfiguration.isUseUpnp()) { this.logger.info("ISY: using UPNP to communicate with ISY"); this.insteonClient.start(); } else { this.logger.info("ISY: using URL to communicate with ISY"); try { this.insteonClient.start(runtimeConfiguration.getUuid(), String.format("http://%s:%s", runtimeConfiguration.getIpAddress(), runtimeConfiguration.getPort())); } catch (Exception e) { throw new RuntimeException(e); } } setProperlyConfigured(true); }
Source:
<code>protected boolean isShowCrossReferenceInfo() { IPreferenceStore store = TraditionalRenderingPlugin.getDefault().getPreferenceStore(); boolean prefShowInfo = store.getBoolean(TraditionalRenderingPreferenceConstants.MEM_CROSS_REFERENCE_INFO); <START> return (!fIsDisplayLittleEndian && prefShowInfo); <END> }</code><technical_language>getter instead of accessing variable: isDisplayLittleEndian()</technical_language>

Target:
protected boolean isShowCrossReferenceInfo() { IPreferenceStore store = TraditionalRenderingPlugin.getDefault().getPreferenceStore(); boolean prefShowInfo = store.getBoolean(TraditionalRenderingPreferenceConstants.MEM_CROSS_REFERENCE_INFO); return (!isDisplayLittleEndian() && prefShowInfo); }
Source:
<code>private synchronized void loadAccounts() { if (accountFile == null || !accountFile.exists()) return; if (accountFile.length() == 0) return; LOG.debug("loading accounts from file: " + accountFile.getAbsolutePath()); FileInputStream dataIn = null; try { dataIn = new FileInputStream(accountFile); byte[] encryptedAccountData = IOUtils.toByteArray(dataIn); XStream xStream = createXStream(); <START> Pair<XMPPAccount, Set<XMPPAccount>> accountData = <END> (ImmutablePair<XMPPAccount, Set<XMPPAccount>>) xStream.fromXML( new ByteArrayInputStream(Crypto.decrypt(encryptedAccountData, secretKey))); activeAccount = accountData.getLeft(); accounts = accountData.getRight(); } catch (RuntimeException e) { LOG.error("internal error while loading account data", e); return; } catch (Exception e) { LOG.error("could not load account data", e); return; } finally { IOUtils.closeQuietly(dataIn); } accounts.remove(activeAccount); accounts.add(activeAccount); LOG.debug("loaded " + accounts.size() + " account(s)"); }</code><technical_language>if point a garbage file 100 MBytes in size</technical_language>

Target:
private synchronized void loadAccounts() { if (accountFile == null || !accountFile.exists()) return; LOG.debug("loading accounts from file: " + accountFile.getAbsolutePath()); FileInputStream dataIn = null; try { long accountFileSize = accountFile.length(); if (accountFileSize <= 0 || accountFileSize > MAX_ACCOUNT_DATA_SIZE) throw new IOException( "account data seems malformed, refused to load " + accountFileSize + " bytes into memory"); dataIn = new FileInputStream(accountFile); byte[] encryptedAccountData = IOUtils.toByteArray(dataIn); XStream xStream = createXStream(); AccountStoreInformation accountData = (AccountStoreInformation) xStream.fromXML( new ByteArrayInputStream(Crypto.decrypt(encryptedAccountData, secretKey))); accounts = new HashSet<>(accountData.configuredAccounts); activeAccount = accountData.configuredAccounts.get(accountData.activeAccountIndex); } catch (RuntimeException e) { LOG.error("internal error while loading account data", e); return; } catch (Exception e) { LOG.error("could not load account data", e); return; } finally { IOUtils.closeQuietly(dataIn); } accounts.remove(activeAccount); accounts.add(activeAccount); LOG.debug("loaded " + accounts.size() + " account(s)"); }
Source:
<code>protected String getLaunchCommand(JBossServer jbossServer) throws CoreException { String programArguments = getLaunchProgramArgs(); String vmArguments = getLaunchVMArgs(); String jar = getJar(jbossServer.getServer()); <START> String command = "java " + vmArguments + " -jar " + jar + " " + IJBossRuntimeConstants.SPACE + programArguments + "&"; <END> return command; }</code><technical_language>" " + IJBossRuntimeConstants.SPACE 2 spaces right</technical_language>

Target:
protected String getLaunchCommand(JBossServer jbossServer) throws CoreException { String programArguments = getLaunchProgramArgs(); String vmArguments = getLaunchVMArgs(); String jar = getJar(jbossServer.getServer()); String command = "java " + vmArguments + " -jar " + jar + IJBossRuntimeConstants.SPACE + programArguments + "&"; return command; }
Source:
<code>private boolean executePresendScript(ExtendedEmailPublisherContext context, MimeMessage msg) throws RuntimeException { boolean cancel = false; String script = ContentBuilder.transformText(presendScript, context, getRuntimeMacros(context)); if (StringUtils.isNotBlank(script)) { debug(context.getListener().getLogger(), "Executing pre-send script"); ClassLoader cl = Jenkins.getInstance().getPluginManager().uberClassLoader; ScriptSandbox sandbox = null; CompilerConfiguration cc = new CompilerConfiguration(); cc.setScriptBaseClass(EmailExtScript.class.getCanonicalName()); cc.addCompilationCustomizers(new ImportCustomizer().addStarImports( "jenkins", "jenkins.model", "hudson", "hudson.model")); expandClasspath(context, cc); if (getDescriptor().isSecurityEnabled()) { debug(context.getListener().getLogger(), "Setting up sandbox for pre-send script"); cc.addCompilationCustomizers(new SandboxTransformer()); sandbox = new ScriptSandbox(); } Binding binding = new Binding(); binding.setVariable("build", context.getBuild()); <START> binding.setVariable("run", context.getRun()); <END> binding.setVariable("msg", msg); binding.setVariable("listener", context.getListener()); binding.setVariable("logger", context.getListener().getLogger()); binding.setVariable("cancel", cancel); binding.setVariable("trigger", context.getTrigger()); binding.setVariable("triggered", ImmutableMultimap.copyOf(context.getTriggered())); GroovyShell shell = new GroovyShell(cl, binding, cc); StringWriter out = new StringWriter(); PrintWriter pw = new PrintWriter(out); if (sandbox != null) { sandbox.register(); } try { shell.evaluate(script); cancel = ((Boolean) shell.getVariable("cancel")); debug(context.getListener().getLogger(), "Pre-send script set cancel to %b", cancel); } catch (SecurityException e) { context.getListener().getLogger().println("Pre-send script tried to access secured objects: " + e.getMessage()); } catch (Throwable t) { t.printStackTrace(pw); context.getListener().getLogger().println(out.toString()); } debug(context.getListener().getLogger(), out.toString()); } return !cancel; }</code><technical_language>Is needed? term "build" is widely accepted, including for a WorkflowRun. is need for a presendScript for Workflow</technical_language>

Target:
private boolean executePresendScript(ExtendedEmailPublisherContext context, MimeMessage msg) throws RuntimeException { return executeScript(presendScript, "pre-send", context, msg, null, null); }
Source:
<code>protected List<File> getFilesFromProperty(String property) { List<File> result = Lists.newArrayList(); String fileList = settings.getString(property); if (StringUtils.isNotEmpty(fileList)) { Iterable<String> fileNames = Splitter.on(SEPARATOR).omitEmptyStrings().split(fileList); for (String pathPattern : fileNames) { boolean isLibraryProperty = property.endsWith("libraries"); <START> List<File> libraryFilesForPattern = getFilesForPattern(fs.baseDir(), pathPattern, isLibraryProperty); <END> if (validateLibraries && libraryFilesForPattern.isEmpty() && hasJavaSources) { LOG.error("Invalid value for " + property); String message = "No files nor directories matching '" + pathPattern + "'"; throw new IllegalStateException(message); } result.addAll(libraryFilesForPattern); } } return result; }</code><technical_language>baseDir change loop execution, more interesting a variable initialized "for" statement instead of accessing time. remark for isLibraryProperty</technical_language>

Target:
protected List<File> getFilesFromProperty(String property) { List<File> result = Lists.newArrayList(); String fileList = settings.getString(property); if (StringUtils.isNotEmpty(fileList)) { Iterable<String> fileNames = Splitter.on(SEPARATOR).omitEmptyStrings().split(fileList); File baseDir = fs.baseDir(); boolean isLibraryProperty = property.endsWith("libraries"); for (String pathPattern : fileNames) { List<File> libraryFilesForPattern = getFilesForPattern(baseDir, pathPattern, isLibraryProperty); if (validateLibraries && libraryFilesForPattern.isEmpty() && hasJavaSources()) { LOG.error("Invalid value for " + property); String message = "No files nor directories matching '" + pathPattern + "'"; throw new IllegalStateException(message); } result.addAll(libraryFilesForPattern); } } return result; }
Source:
<code>public void refresh() { if (getManagedForm() == null || getManagedForm().getForm().isDisposed()) { return; } try { showEditorBusy(true); boolean hasIncoming = false; if (getTask() != null) { hasIncoming = getTask().getSynchronizationState().isIncoming(); } if (model != null) { doSave(new NullProgressMonitor()); refreshInput(); } else { initModel(getTaskEditor().getTaskEditorInput()); } if (taskData != null) { try { setReflow(false); Menu menu = editorComposite.getMenu(); CommonUiUtil.setMenu(editorComposite, null); if (!shouldAutoRefresh) { for (Control control : editorComposite.getChildren()) { control.dispose(); } } else { } if (focusTracker != null) { focusTracker.reset(); } lastSelection = null; if (!shouldAutoRefresh) { for (IFormPart part : getManagedForm().getParts()) { <START> part.dispose(); <END> getManagedForm().removePart(part); } } editorComposite.setMenu(menu); if (!shouldAutoRefresh) { createFormContentInternal(); } getTaskEditor().setMessage(null, 0); if (hasIncoming) { getTaskEditor().setActivePage(getId()); } setSubmitEnabled(true); } finally { setReflow(true); } } updateOutlinePage(); updateHeaderMessage(); getManagedForm().dirtyStateChanged(); getTaskEditor().updateHeaderToolBar(); } finally { showEditorBusy(false); } reflow(); }</code><technical_language>I if change task editor parts override dispose dispose controls, need loop line 1468. allow section control lifecycle of controls defining a refresh method default disposes recreates controls, overridden AbstractTaskEditorAttributeSection refresh editors. need register editors page, keeping page decoupled editors. attribute section decide refresh editors recreate section depending editors support refresh() changed attributes</technical_language>

Target:
public void refresh() { if (getManagedForm() == null || getManagedForm().getForm().isDisposed()) { return; } try { showEditorBusy(true); boolean hasIncoming = false; if (getTask() != null) { hasIncoming = getTask().getSynchronizationState().isIncoming(); } if (model != null) { doSave(new NullProgressMonitor()); refreshInput(); } else { initModel(getTaskEditor().getTaskEditorInput()); } if (taskData != null) { try { setReflow(false); Menu menu = editorComposite.getMenu(); CommonUiUtil.setMenu(editorComposite, null); if (focusTracker != null) { focusTracker.reset(); } lastSelection = null; editorComposite.setMenu(menu); if (!shouldAutoRefresh) { createFormContentInternal(); } getTaskEditor().setMessage(null, 0); if (hasIncoming) { getTaskEditor().setActivePage(getId()); } setSubmitEnabled(true); } finally { setReflow(true); } } updateOutlinePage(); updateHeaderMessage(); getManagedForm().dirtyStateChanged(); getTaskEditor().updateHeaderToolBar(); } finally { showEditorBusy(false); } reflow(); }
Source:
<code><START> public ListenableFuture<?> submit(final Runnable runnable) <END> { final Runnable wrappedPrioritizedRunnable = new PrioritizedRunnable() { @Override public int getPriority() { if (runnable instanceof PrioritizedRunnable) { return ((PrioritizedRunnable) runnable).getPriority(); } else { return 0; } } @Override public void run() { final Long threadUserTime; if (threadMXBean.isThreadCpuTimeEnabled()) { threadUserTime = threadMXBean.getCurrentThreadUserTime(); } else { threadUserTime = null; } runnable.run(); if (threadUserTime != null) { emitter.emit( metricBuilder .setDimension("priority", String.format("%d", getPriority())) .build("exec/cpu", threadMXBean.getCurrentThreadUserTime() - threadUserTime) ); } } }; emitMetrics(); return delegate.submit(wrappedPrioritizedRunnable); }</code><technical_language>change in method execute submit</technical_language>

Target:
public ListenableFuture<?> submit(final Runnable runnable) { return submit(runnable, (Object) null); }
Source:
<code>boolean deletcContentFromCollection(Collection collection, Session session, Path contentTargetPath, String uri) throws IOException { boolean deleted; Path uriPath = Paths.get(uri); CMSLogEvent event = info().collectionID(collection).uri(contentTargetPath); if (isDataVisualisationFile(contentTargetPath)) { <START> event.log("deleting data viz zip form collection content"); <END> deleted = collection.deleteDataVisContent(session, Paths.get(uri)); } else if (Files.isDirectory(contentTargetPath)) { event.log("deleting directory form collection content"); deleted = collection.deleteContentDirectory(session.getEmail(), uri); } else if (Content.isDataJsonFile(uri)) { event.log("deleting data.json and related files from collection content"); deleted = collection.deleteFileAndRelated(uri); } else { event.log("deleting single file from colleciton content"); deleted = collection.deleteFile(uri); } return deleted; }</code><technical_language>suggestion event.log("deleting data zip collection content");</technical_language>

Target:
boolean deletcContentFromCollection(Collection collection, Session session, Path contentTargetPath, String uri) throws IOException { boolean deleted; Path uriPath = Paths.get(uri); CMSLogEvent event = info().collectionID(collection).uri(contentTargetPath); if (isDataVisualisationFile(contentTargetPath)) { event.log("deleting data viz zip from collection content"); deleted = collection.deleteDataVisContent(session, Paths.get(uri)); } else if (Files.isDirectory(contentTargetPath)) { event.log("deleting directory from collection content"); deleted = collection.deleteContentDirectory(session.getEmail(), uri); } else if (Content.isDataJsonFile(uri)) { event.log("deleting data.json and related files from collection content"); deleted = collection.deleteFileAndRelated(uri); } else { event.log("deleting single file from colleciton content"); deleted = collection.deleteFile(uri); } return deleted; }
Source:
<code>public void testMultiThreadRemoveDisjointRanges() throws InterruptedException { final int numThreads = 8; final int removesPerThread = 100000; final int totalNumberOfRemoves = numThreads * removesPerThread; final CountDownLatch countDownLatch = new CountDownLatch(numThreads); for (int i = 0; i < totalNumberOfRemoves; i++) { <START> assertTrue(MSG_FALSE_RESULT, partitionManager.registerPartition(EVAL_ID, DATA_TYPE, 3 * i, 3 * i + 1)); <END> } final Runnable[] threads = new Runnable[numThreads]; for (int index = 0; index < numThreads; index++) { threads[index] = new RemoveThread(countDownLatch, partitionManager, index, numThreads, removesPerThread, IndexParity.ALL_INDEX); } TestUtils.runConcurrently(threads); final boolean allThreadsFinished = countDownLatch.await(60, TimeUnit.SECONDS); assertTrue(MSG_THREADS_NOT_FINISHED, allThreadsFinished); assertEquals(MSG_SIZE_ASSERTION, 0, partitionManager.getRangeSet(EVAL_ID, DATA_TYPE).size()); }</code><technical_language>fine assertion, coefficient change for</technical_language>

Target:
public void testMultiThreadRemoveDisjointRanges() throws InterruptedException { final int numThreads = 8; final int removesPerThread = 100000; final long rangeTerm = 3; final long rangeLength = 2; final int initialOffset = 0; final int totalNumberOfRemoves = numThreads * removesPerThread; final CountDownLatch countDownLatch = new CountDownLatch(numThreads); for (int i = 0; i < totalNumberOfRemoves; i++) { final int rangeStart = (int) (initialOffset + rangeTerm * i); final int rangeEnd = (int) (rangeStart + rangeLength - 1); assertTrue(MSG_REGISTER_UNEXPECTED_RESULT, partitionManager.register(EVAL_ID_PREFIX, DATA_TYPE_PREFIX, rangeStart, rangeEnd)); } final Runnable[] threads = new Runnable[numThreads]; for (int index = 0; index < numThreads; index++) { threads[index] = new RemoveThread(countDownLatch, partitionManager, index, numThreads, removesPerThread, IndexParity.ALL_INDEX, EVAL_ID_PREFIX, DATA_TYPE_PREFIX, rangeTerm, rangeLength, initialOffset); } TestUtils.runConcurrently(threads); final boolean allThreadsFinished = countDownLatch.await(60, TimeUnit.SECONDS); assertTrue(MSG_THREADS_NOT_FINISHED, allThreadsFinished); assertEquals(MSG_SIZE_ASSERTION, 0, partitionManager.getRangeSet(EVAL_ID_PREFIX, DATA_TYPE_PREFIX).size()); }
Source:
<code><START> PieChart getGlobalPC() { <END> return fGlobalPC; }</code><technical_language>needs synchronized</technical_language>

Target:
synchronized PieChart getGlobalPC() { return fGlobalPC; }