auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public KeycloakResourceDefinition() { super(PathElement.pathElement(ModelDescriptionConstants.AUTHENTICATION, ModelDescriptionConstants.KEYCLOAK), ControllerResolver.getResolver("core.management.security-realm.authentication.keycloak"), new SecurityRealmChildAddHandler(true, false, new AttributeDefinition[0]), new SecurityRealmChildRemoveHandler(true), OperationEntry.Flag.RESTART_RESOURCE_SERVICES, OperationEntry.Flag.RESTART_RESOURCE_SERVICES); }

Target:
public KeycloakResourceDefinition() { super(PathElement.pathElement(ModelDescriptionConstants.AUTHENTICATION, ModelDescriptionConstants.KEYCLOAK), ControllerResolver.getResolver("core", "management", "security-realm", "authentication", "keycloak"), new SecurityRealmChildAddHandler(true, false, new AttributeDefinition[0]), new SecurityRealmChildRemoveHandler(true), OperationEntry.Flag.RESTART_RESOURCE_SERVICES, OperationEntry.Flag.RESTART_RESOURCE_SERVICES); }
Source:
public void register(ResultSet resultSet, Statement statement) { log.tracef( "Registering result set [%s]", resultSet ); if ( statement == null ) { try { statement = resultSet.getStatement(); } catch (SQLException e) { throw convert( e, "unable to access Statement from ResultSet" ); } } if ( statement != null ) { Set<ResultSet> resultSets = xref.get( statement ); if ( resultSets == null && log.isDebugEnabled() ) { log.debug( "ResultSet statement was not registered (on register)" ); } if ( resultSets == null || resultSets == Collections.EMPTY_SET ) { resultSets = new HashSet<ResultSet>(); xref.put( statement, resultSets ); } resultSets.add( resultSet ); } else { unassociatedResultSets.add( resultSet ); } }

Target:
public void register(ResultSet resultSet, Statement statement) { log.tracef( "Registering result set [%s]", resultSet ); if ( statement == null ) { try { statement = resultSet.getStatement(); } catch (SQLException e) { throw convert( e, "unable to access Statement from ResultSet" ); } } if ( statement != null ) { Set<ResultSet> resultSets = xref.get( statement ); if ( log.isDebugEnabled() && resultSets == null ) { log.debug( "ResultSet statement was not registered (on register)" ); } if ( resultSets == null || resultSets == Collections.EMPTY_SET ) { resultSets = new HashSet<ResultSet>(); xref.put( statement, resultSets ); } resultSets.add( resultSet ); } else { unassociatedResultSets.add( resultSet ); } }
Source:
public boolean removeNodeId(final String location, final InetAddress address, final int nodeId) { if (address == null) { LOG.warn("removeNodeId: null IP address"); return false; } LOG.debug("removeNodeId: removing IP address from cache: {}:{}", location, str(address)); m_lock.writeLock().lock(); try { return m_managedAddresses.remove(new Key(location, address), new Value(nodeId, PrimaryType.PRIMARY)) || m_managedAddresses.remove(new Key(location, address), new Value(nodeId, PrimaryType.SECONDARY)) || m_managedAddresses.remove(new Key(location, address), new Value(nodeId, PrimaryType.NOT_ELIGIBLE)); } finally { m_lock.writeLock().unlock(); } }

Target:
public boolean removeNodeId(final String location, final InetAddress address, final int nodeId) { if (address == null) { LOG.warn("removeNodeId: null IP address"); return false; } LOG.debug("removeNodeId: removing IP address from cache: {}:{}", location, str(address)); m_lock.writeLock().lock(); try { final Key key = new Key(location, address); return m_managedAddresses.remove(key, new Value(nodeId, PrimaryType.PRIMARY)) || m_managedAddresses.remove(key, new Value(nodeId, PrimaryType.SECONDARY)) || m_managedAddresses.remove(key, new Value(nodeId, PrimaryType.NOT_ELIGIBLE)); } finally { m_lock.writeLock().unlock(); } }
Source:
public void logsWhenRequestsTakeTooLong() { originalRequest = new RequestTime(0L, MAX_REQUEST_DURATION.toNanos() + 1, 0L); RequestTime nextRequest = new RequestTimeBuilder(originalRequest) .progressLocalClock(MAX_INTERVAL_SINCE_PREVIOUS_REQUEST.toNanos() + 2) .progressRemoteClock(1L) .build(); createComparer(originalRequest, nextRequest).compare(); verify(mockedEvents, times(1)).requestsTookTooLong(anyLong(), anyLong()); }

Target:
public void logsWhenRequestsTakeTooLong() { originalRequest = new RequestTime(0L, ClockSkewComparer.MAX_REQUEST_DURATION.toNanos() + 1, 0L); RequestTime nextRequest = new RequestTime.Builder(originalRequest) .progressLocalClock(ClockSkewComparer.MAX_REQUEST_DURATION.toNanos() + 2) .progressRemoteClock(1L) .build(); compare(originalRequest, nextRequest); verify(mockedEvents, times(1)).requestsTookTooLong(anyLong(), anyLong()); }
Source:
public void theActivityCalendarContainsADayProfile(final Map<String, String> parameters) throws Throwable { final ActivityCalendar activityCalendar = (ActivityCalendar) ScenarioContext.current() .get(PlatformSmartmeteringKeys.ACTIVITY_CALENDAR); final int dayId = Integer.parseInt(parameters.get(PlatformSmartmeteringKeys.DAY_PROFILE_DAY_ID)); final int actionCount = Integer.parseInt(parameters.get(PlatformSmartmeteringKeys.DAY_PROFILE_ACTION_COUNT)); final DayProfile profile = new DayProfile(dayId); for (int i = 1; i <= actionCount; i++) { final String start = parameters.get(PlatformSmartmeteringKeys.DAY_PROFILE_START_TIME + "_" + i); final int selector = Integer .parseInt(parameters.get(PlatformSmartmeteringKeys.DAY_PROFILE_SCRIPT_SELECTOR + "_" + i)); profile.getDayProfileActions().add(new DayProfileAction(start, selector)); } activityCalendar.getDayProfiles().put(dayId, profile); ScenarioContext.current().put(PlatformSmartmeteringKeys.ACTIVITY_CALENDAR, activityCalendar); }

Target:
public void theActivityCalendarContainsADayProfile(final Map<String, String> parameters) throws Throwable { final ActivityCalendar activityCalendar = (ActivityCalendar) ScenarioContext.current() .get(PlatformSmartmeteringKeys.ACTIVITY_CALENDAR); final int dayId = Integer.parseInt(parameters.get(PlatformSmartmeteringKeys.DAY_PROFILE_DAY_ID)); final int actionCount = Integer.parseInt(parameters.get(PlatformSmartmeteringKeys.DAY_PROFILE_ACTION_COUNT)); final DayProfile profile = new DayProfile(dayId); for (int i = 1; i <= actionCount; i++) { final String start = SettingsHelper.getStringValue(parameters, PlatformSmartmeteringKeys.DAY_PROFILE_START_TIME, i); final int selector = SettingsHelper.getIntegerValue(parameters, PlatformSmartmeteringKeys.DAY_PROFILE_SCRIPT_SELECTOR, i); profile.getDayProfileActions().add(new DayProfileAction(start, selector)); } activityCalendar.getDayProfiles().put(dayId, profile); ScenarioContext.current().put(PlatformSmartmeteringKeys.ACTIVITY_CALENDAR, activityCalendar); }
Source:
public void testTransformerEAP720() throws Exception { testTransformation(EAP_7_1_0); }

Target:
public void testTransformerEAP720() throws Exception { testTransformation(EAP_7_2_0_TEMP); }
Source:
public Startpoint readStartpoint(SystemStreamPartition ssp, TaskName taskName) { Preconditions.checkState(!stopped, "Underlying metadata store not available"); Preconditions.checkNotNull(ssp, "SystemStreamPartition cannot be null"); byte[] startpointBytes = readWriteStore.get(toReadWriteStoreKey(ssp, taskName)); if (ArrayUtils.isNotEmpty(startpointBytes)) { try { Startpoint startpoint = objectMapper.readValue(startpointBytes, Startpoint.class); if (Instant.now().minus(DEFAULT_EXPIRATION_DURATION).isBefore(Instant.ofEpochMilli(startpoint.getCreationTimestamp()))) { return startpoint; } LOG.warn("Stale Startpoint: was read. Ignoring.", startpoint); } catch (IOException ex) { throw new SamzaException(ex); } } return null; }

Target:
public Optional<Startpoint> readStartpoint(SystemStreamPartition ssp, TaskName taskName) { Preconditions.checkState(!stopped, "Underlying metadata store not available"); Preconditions.checkNotNull(ssp, "SystemStreamPartition cannot be null"); byte[] startpointBytes = readWriteStore.get(toReadWriteStoreKey(ssp, taskName)); if (ArrayUtils.isNotEmpty(startpointBytes)) { try { Startpoint startpoint = objectMapper.readValue(startpointBytes, Startpoint.class); if (Instant.now().minus(DEFAULT_EXPIRATION_DURATION).isBefore(Instant.ofEpochMilli(startpoint.getCreationTimestamp()))) { return Optional.of(startpoint); } LOG.warn("Creation timestamp: of startpoint: has crossed the expiration duration: {}. Ignoring it", startpoint.getCreationTimestamp(), startpoint, DEFAULT_EXPIRATION_DURATION); } catch (IOException ex) { throw new SamzaException(ex); } } return Optional.empty(); }
Source:
public AbstractDecimalSelectiveStreamReader( StreamDescriptor streamDescriptor, Optional<TupleDomainFilter> filter, Optional<Type> outputType, LocalMemoryContext systemMemoryContext, int valuesPerPosition) { checkArgument(filter.isPresent() || outputType.isPresent(), "filter must be present if output is not required"); this.streamDescriptor = requireNonNull(streamDescriptor, "streamDescriptor is null"); this.filter = filter.orElse(null); this.outputRequired = outputType.isPresent(); this.systemMemoryContext = requireNonNull(systemMemoryContext, "systemMemoryContext is null"); this.nonDeterministicFilter = this.filter != null && !this.filter.isDeterministic(); this.nullsAllowed = this.filter == null || this.nonDeterministicFilter || this.filter.testNull(); this.scale = streamDescriptor.getOrcType().getScale().get(); this.nullBlock = outputType.map(type -> type.createBlockBuilder(null, 1).appendNull().build()).orElse(null); this.valuesPerPosition = valuesPerPosition; }

Target:
public AbstractDecimalSelectiveStreamReader( StreamDescriptor streamDescriptor, Optional<TupleDomainFilter> filter, Optional<Type> outputType, LocalMemoryContext systemMemoryContext, int valuesPerPosition) { requireNonNull(filter, "filter is null"); requireNonNull(outputType, "outputType is null"); checkArgument(filter.isPresent() || outputType.isPresent(), "filter must be present if output is not required"); this.streamDescriptor = requireNonNull(streamDescriptor, "streamDescriptor is null"); this.filter = filter.orElse(null); this.outputRequired = outputType.isPresent(); this.systemMemoryContext = requireNonNull(systemMemoryContext, "systemMemoryContext is null"); this.nonDeterministicFilter = this.filter != null && !this.filter.isDeterministic(); this.nullsAllowed = this.filter == null || this.nonDeterministicFilter || this.filter.testNull(); this.scale = streamDescriptor.getOrcType().getScale().get(); this.nullBlock = outputType.map(type -> type.createBlockBuilder(null, 1).appendNull().build()).orElse(null); this.valuesPerPosition = valuesPerPosition; }
Source:
public void close() { if (this.runThread.compareAndSet(true, false)) { try { cursor.signalConsumers(); this.stopLatch.await(); } catch (InterruptedException e) { } } }

Target:
public void close() { if (this.runThread.compareAndSet(true, false)) { try { this.stopLatch.await(); } catch (InterruptedException e) { } } }
Source:
private void startLibosinfoServerVM() { try { ProcessBuilder builder = buildExternalJavaProcessCmd(); builder.redirectErrorStream(true); libosinfoRMIServer = builder.start(); } catch (Exception exception) { System.out.println("Can't start exernal VM."); } }

Target:
private void startLibosinfoServerVM() { try { ProcessBuilder builder = buildShellProcessCmd(); builder.redirectErrorStream(true); libosinfoRMIServer = builder.start(); } catch (Exception exception) { log.error("Can't start exernal VM."); } }
Source:
public ArrayList<Award> getAwards(){ return awards; }

Target:
public List<Award> getAwards(){ return Collections.unmodifiableList(awards); }
Source:
private void validateCascadedValues(Object value, ValidationContext<?> context, ValueContext<?, ?> valueContext, Cascadable cascadable, ValidationOrder validationOrder) { for ( TypeVariable<?> cascadingTypeParameter : cascadable.getCascadingTypeParameters() ) { List<TypeVariable<?>> cascadingTypeParametersOfValueType = getCorrespondingTypeParametersInSubType( value.getClass(), TypeHelper.getErasedReferenceType( cascadable.getCascadableType() ), cascadingTypeParameter ); for ( TypeVariable<?> cascadingTypeParameterOfValueType : cascadingTypeParametersOfValueType ) { ValueExtractorDescriptor extractor = valueExtractorManager.getTypeParameterValueExtractor( value.getClass(), cascadingTypeParameterOfValueType ); if ( extractor == null ) { continue; } CascadingValueReceiver receiver = new CascadingValueReceiver( context, valueContext, validationOrder ); ( (ValueExtractor) extractor.getValueExtractor() ).extractValues( value, receiver ); } } }

Target:
private void validateCascadedValues(Object value, ValidationContext<?> context, ValueContext<?, ?> valueContext, Cascadable cascadable, ValidationOrder validationOrder) { for ( TypeVariable<?> cascadingTypeParameter : cascadable.getCascadingTypeParameters() ) { List<TypeVariable<?>> cascadingTypeParametersOfValueType = getCorrespondingTypeParametersInSubType( value.getClass(), TypeHelper.getErasedReferenceType( cascadable.getCascadableType() ), cascadingTypeParameter ); for ( TypeVariable<?> cascadingTypeParameterOfValueType : cascadingTypeParametersOfValueType ) { ValueExtractorDescriptor extractor = valueExtractorManager.getValueExtractor( value.getClass(), cascadingTypeParameterOfValueType ); if ( extractor == null ) { continue; } CascadingValueReceiver receiver = new CascadingValueReceiver( context, valueContext, validationOrder ); ( (ValueExtractor) extractor.getValueExtractor() ).extractValues( value, receiver ); } } }
Source:
private static void log(Level level, Throwable ex, String msg, Object... data) { modLog.log(level, () -> data == null ? msg : String.format(msg, data), ex); }

Target:
private static void log(Level level, Throwable ex, String msg, Object... data) { LOGGER.log(level, () -> data == null ? msg : String.format(msg, data), ex); }
Source:
private void delete() { SceneElement element = getSelectedSceneElement(); Scene scene = getCurrentScene(); List list = scene.getChildren(); controller.command(new RemoveFromListCommand(list, element)); }

Target:
private void delete() { controller.action(RemoveFromScene.class, getCurrentScene(), getSelectedSceneElement()); }
Source:
protected FSDataInputStream setupStream(BlockMetadata.FileBlockMetadata block) throws IOException { String filePath = block.getFilePath(); if (filePath.startsWith("/")) { filePath = filePath.substring(1); } RECORD_READER_MODE recordReaderMode = RECORD_READER_MODE.valueOf(this.getMode()); if (recordReaderMode == RECORD_READER_MODE.FIXED_WIDTH_RECORD) { ((S3FixedWidthRecordReaderContext)readerContext).setFilePath(filePath); ((S3FixedWidthRecordReaderContext)readerContext).setFileLength(block.getFileLength()); } else if (recordReaderMode == RECORD_READER_MODE.DELIMITED_RECORD) { ((S3DelimitedRecordReaderContext)readerContext).setFilePath(filePath); ((S3DelimitedRecordReaderContext)readerContext).setFileLength(block.getFileLength()); } return null; }

Target:
protected FSDataInputStream setupStream(BlockMetadata.FileBlockMetadata block) throws IOException { return null; }
Source:
public static Expression rewrite(Expression expression, Map<Symbol, Type> symbolTypes, SymbolAllocator symbolAllocator) { checkState(!(expression instanceof GroupingOperation), "GroupingOperation should have been re-written to a FunctionCall before execution"); if (expression instanceof SymbolReference) { return expression; } return ExpressionTreeRewriter.rewriteWith(new Visitor(symbolTypes, symbolAllocator), expression, new Context()); }

Target:
public static Expression rewrite(Expression expression, Map<Symbol, Type> symbolTypes, SymbolAllocator symbolAllocator) { return ExpressionTreeRewriter.rewriteWith(new Visitor(symbolTypes, symbolAllocator), expression, new Context()); }
Source:
private static boolean sendToSlackUser(String authToken, String message, String user) { boolean success = false; logger.debug("sendToSlackUser authToken='{}', message='{}', user='{}'", authToken, message, user); SlackSession session = null; try { session = SlackSessionFactory.createWebSocketSlackSession(authToken); session.connect(); SlackUser slackUser = session.findUserByUserName(user); if (user == null) { logger.error("Could not find Slack user '{}'", user); } else { session.sendMessageToUser(slackUser, message, null); success = true; } } catch (IOException e) { logger.error("Error sending message to Slack user", e); } finally { try { if (session != null) { session.disconnect(); } } catch (IOException e) { logger.error("Error disonnecting Slack session", e); } } return success; }

Target:
private static boolean sendToSlackUser(String authToken, String message, String user) { boolean success = false; logger.debug("sendToSlackUser authToken='{}', message='{}', user='{}'", authToken, message, user); SlackSession session = null; try { session = SlackSessionFactory.createWebSocketSlackSession(authToken); session.connect(); SlackUser slackUser = session.findUserByUserName(user); if (user == null) { logger.error("Could not find Slack user '{}'", user); } else { session.sendMessageToUser(slackUser, message, null); success = true; } } catch (IOException e) { logger.error("Error sending message to Slack user", e); } finally { try { if (session != null) { session.disconnect(); } } catch (IOException e) { logger.error("Error disconnecting Slack session", e); } } return success; }
Source:
private Object serializeFieldValue(Schema fieldSchema, Object fieldValue) { Object output = fieldValue; switch (fieldSchema.getType()) { case ARRAY: case MAP: case RECORD: byte[] data = null; try { @SuppressWarnings("rawtypes") SpecificDatumWriter writer = getDatumWriter(fieldSchema); data = IOUtils.serialize(writer, fieldValue); } catch (IOException e) { LOG.error(e.getMessage(), e); } output = data; break; case UNION: if (fieldSchema.getTypes().size() == 2 && isNullable(fieldSchema)) { int schemaPos = getUnionSchema(fieldValue, fieldSchema); Schema unionSchema = fieldSchema.getTypes().get(schemaPos); output = serializeFieldValue(unionSchema, fieldValue); } else { data = null; try { @SuppressWarnings("rawtypes") SpecificDatumWriter writer = getDatumWriter(fieldSchema); data = IOUtils.serialize(writer, fieldValue); } catch (IOException e) { LOG.error(e.getMessage(), e); } output = data; } break; case FIXED: break; case ENUM: case STRING: output = fieldValue.toString(); break; case BYTES: output = ((ByteBuffer) fieldValue).array(); break; case INT: case LONG: case FLOAT: case DOUBLE: case BOOLEAN: output = fieldValue; break; case NULL: break; default: throw new AssertionError(fieldSchema.getType().name()); } return output; }

Target:
private Object serializeFieldValue(Schema fieldSchema, Object fieldValue) { Object output = fieldValue; switch (fieldSchema.getType()) { case ARRAY: case MAP: case RECORD: byte[] data = null; try { @SuppressWarnings("rawtypes") SpecificDatumWriter writer = getDatumWriter(fieldSchema); data = IOUtils.serialize(writer, fieldValue); } catch (IOException e) { LOG.error(e.getMessage(), e); } output = data; break; case UNION: if (fieldSchema.getTypes().size() == 2 && isNullable(fieldSchema)) { int schemaPos = getUnionSchema(fieldValue, fieldSchema); Schema unionSchema = fieldSchema.getTypes().get(schemaPos); output = serializeFieldValue(unionSchema, fieldValue); } else { data = null; try { @SuppressWarnings("rawtypes") SpecificDatumWriter writer = getDatumWriter(fieldSchema); data = IOUtils.serialize(writer, fieldValue); } catch (IOException e) { LOG.error(e.getMessage(), e); } output = data; } break; case FIXED: break; case ENUM: case STRING: output = fieldValue.toString(); break; case BYTES: output = ((ByteBuffer) fieldValue).array(); break; case INT: case LONG: case FLOAT: case DOUBLE: case BOOLEAN: case NULL: break; default: throw new AssertionError(fieldSchema.getType().name()); } return output; }
Source:
public void doSystemCancel(String chargeId, Long accountId) { final Optional<ChargeEntity> maybeCharge = chargeDao.findByExternalIdAndGatewayAccount(chargeId, accountId); if (maybeCharge.isPresent()) { doCancel(maybeCharge.get(), SYSTEM_CANCELLATION_FLOW); } else { throw new ChargeNotFoundRuntimeException(chargeId); } }

Target:
public Optional<ChargeEntity> doSystemCancel(String chargeId, Long accountId) { return chargeDao.findByExternalIdAndGatewayAccount(chargeId, accountId) .map(chargeEntity -> { doCancel(chargeEntity, SYSTEM_CANCELLATION_FLOW); return chargeEntity; }); }
Source:
public void run(PortBindings portBindings, Configuration conf, Map<String, String> parameters) throws Exception { String actionSetId = ProcessUtils.getParameterValue(EXPORT_ACTION_SETID, conf, parameters); Preconditions.checkArgument(StringUtils.isNotBlank(actionSetId) && !WorkflowRuntimeParameters.UNDEFINED_NONEMPTY_VALUE.equals(actionSetId), "unable to export document entities to action manager due to missing action set identifier, " + "no '%s' required parameter provided!", EXPORT_ACTION_SETID); FileSystemPath inputPath = new FileSystemPath(FileSystem.get(conf), portBindings.getInput().get(inputPort)); try (ActionManagerServiceFacade actionManager = buildActionManager(conf, parameters); CloseableIterator<T> it = DataStore.<T> getReader(inputPath)) { MDStoreFacade mdStore = buildMDStoreFacade(parameters); int counter = 0; while (it.hasNext()) { MDStoreIdWithEntityId mdStoreComplexId = deliverMDStoreWithEntityId(it.next()); String mdRecordId = convertToMDStoreEntityId(mdStoreComplexId.getEntityId()); try { String mdRecord = mdStore.deliverRecord(mdStoreComplexId.getMdStoreId(), mdRecordId); handleRecord(mdRecord, actionSetId, actionManager); counter++; } catch (DocumentNotFoundException e) { log.error("mdrecord: " + mdRecordId + " wasn't found in mdstore: " + mdStoreComplexId.getMdStoreId(), e); } catch (Exception e) { log.error("got exception when trying to retrieve " + "MDStore record for mdstore id " + mdStoreComplexId.getMdStoreId() + ", and document id: " + mdRecordId, e); throw e; } } log.warn("exported " + counter + " entities in total"); } }

Target:
public void run(PortBindings portBindings, Configuration conf, Map<String, String> parameters) throws Exception { String actionSetId = ProcessUtils.getParameterValue(EXPORT_ACTION_SETID, conf, parameters); Preconditions.checkArgument(StringUtils.isNotBlank(actionSetId) && !WorkflowRuntimeParameters.UNDEFINED_NONEMPTY_VALUE.equals(actionSetId), "unable to export document entities to action manager due to missing action set identifier, " + "no '%s' required parameter provided!", EXPORT_ACTION_SETID); FileSystemPath inputPath = new FileSystemPath(FileSystem.get(conf), portBindings.getInput().get(inputPort)); try (ActionManagerServiceFacade actionManager = buildActionManager(conf, parameters); CloseableIterator<T> it = DataStore.<T> getReader(inputPath)) { MDStoreFacade mdStore = buildMDStoreFacade(parameters); int counter = 0; while (it.hasNext()) { MDStoreIdWithEntityId mdStoreComplexId = convertIdentifier(it.next()); String mdRecordId = convertToMDStoreEntityId(mdStoreComplexId.getEntityId()); try { String mdRecord = mdStore.fetchRecord(mdStoreComplexId.getMdStoreId(), mdRecordId); handleRecord(mdRecord, actionSetId, actionManager); counter++; } catch (DocumentNotFoundException e) { log.error("mdrecord: " + mdRecordId + " wasn't found in mdstore: " + mdStoreComplexId.getMdStoreId(), e); } catch (Exception e) { log.error("got exception when trying to retrieve " + "MDStore record for mdstore id " + mdStoreComplexId.getMdStoreId() + ", and document id: " + mdRecordId, e); throw e; } } log.warn("exported " + counter + " entities in total"); } }
Source:
private ExecutionType getRandomExecutionType(Bundle bundle) throws Exception { ExecutionType current = bundle.getProcessObject().getOrder(); Random r = new Random(); ExecutionType[] values = ExecutionType.values(); int i; do { i = r.nextInt(values.length); } while (current.equals(values[i])); return values[i]; }

Target:
private ExecutionType getRandomExecutionType(Bundle bundle) throws Exception { ExecutionType current = bundle.getProcessObject().getOrder(); Random r = new Random(); ExecutionType[] values = ExecutionType.values(); int i; do { i = r.nextInt(values.length); } while (current == values[i]); return values[i]; }
Source:
private static byte[] reverse(final byte[] a) { final int length = a.length; int i = length / 2; while(i-- != 0) { final byte t = a[length - i - 1]; a[length - i - 1] = a[i]; a[i] = t; } return a; }

Target:
private static byte[] reverse(final byte[] a) { final int length = a.length; for (int i = length / 2; i-- != 0; ) { final byte t = a[length - i - 1]; a[length - i - 1] = a[i]; a[i] = t; } return a; }
Source:
protected void appendHeaderFooterToFile(Path filePath, String commandId, byte[] header, byte[] footer) { try { Path tmpPath = Files.move(filePath, createTemp("tmp" + commandId), StandardCopyOption.REPLACE_EXISTING); try (InputStream is = Files.newInputStream(tmpPath); FileOutputStream os = new FileOutputStream(filePath.toFile(), true)) { if (header.length > 0) { os.write(header); } IOUtils.copy(is, os); if (footer.length > 0) { os.write(footer); } os.flush(); } finally { Files.delete(tmpPath); } } catch (IOException e) { log.error("Unable to append header and footer", e); } }

Target:
protected void appendHeaderFooterToFile(Path filePath, String commandId, byte[] header, byte[] footer) { if (header.length == 0 && footer.length == 0) { return; } try { Path tmpPath = Files.move(filePath, createTemp("tmp" + commandId), StandardCopyOption.REPLACE_EXISTING); try (InputStream is = Files.newInputStream(tmpPath); FileOutputStream os = new FileOutputStream(filePath.toFile(), true)) { if (header.length > 0) { os.write(header); } IOUtils.copy(is, os); if (footer.length > 0) { os.write(footer); } os.flush(); } finally { Files.delete(tmpPath); } } catch (IOException e) { log.error("Unable to append header and footer", e); } }
Source:
protected boolean checkUserAndGroupsAuthorization(Guid userId, String groupIds, final ActionGroup actionGroup, final Guid object, final VdcObjectType type) { final NGuid permId = DbFacade.getInstance().getEntityPermissionsForUserAndGroups(userId, groupIds, actionGroup, object, type); if (permId != null) { if (log.isDebugEnabled()) { log.debugFormat("Found permission {0} for user when running {1}, on {2} with id {3}", permId, getActionType(), type.getVdcObjectTranslation(), object); } return true; } if (log.isDebugEnabled()) { log.debugFormat("No permission found for user when running action {0}, on object {1} for action group {2} with id {3}.", getActionType(), type.getVdcObjectTranslation(), actionGroup, object); } return false; }

Target:
protected boolean checkUserAndGroupsAuthorization(Guid userId, String groupIds, final ActionGroup actionGroup, final Guid object, final VdcObjectType type) { final NGuid permId = getDbFacade().getEntityPermissionsForUserAndGroups(userId, groupIds, actionGroup, object, type); if (permId != null) { if (log.isDebugEnabled()) { log.debugFormat("Found permission {0} for user when running {1}, on {2} with id {3}", permId, getActionType(), type.getVdcObjectTranslation(), object); } return true; } if (log.isDebugEnabled()) { log.debugFormat("No permission found for user when running action {0}, on object {1} for action group {2} with id {3}.", getActionType(), type.getVdcObjectTranslation(), actionGroup, object); } return false; }
Source:
private String getDeleteSql() { String sql = null; if (config.deleteEnabled) { switch (config.pkMode) { case RECORD_KEY: if (fieldsMetadata.keyFieldNames.isEmpty()) { throw new ConnectException("Require primary keys to support delete"); } sql = dbDialect.buildDeleteStatement( tableId, asColumns(fieldsMetadata.keyFieldNames) ); break; default: throw new ConnectException("Deletes are only supported for pk.mode record_key"); } } return sql; }

Target:
private String getDeleteSql() { String sql = null; if (config.deleteEnabled) { switch (config.pkMode) { case RECORD_KEY: if (fieldsMetadata.keyFieldNames.isEmpty()) { throw new ConnectException("Require primary keys to support delete"); } try { sql = dbDialect.buildDeleteStatement( tableId, asColumns(fieldsMetadata.keyFieldNames) ); } catch (UnsupportedOperationException e) { throw new ConnectException(String.format( "Deletes to table '%s' are not supported with the %s dialect.", tableId, dbDialect.name() )); } break; default: throw new ConnectException("Deletes are only supported for pk.mode record_key"); } } return sql; }
Source:
public void parsePom(InputStream inputStream) { try { MavenXpp3Reader reader = new MavenXpp3Reader(); Model model = reader.read(inputStream); if (dependencies == null) { dependencies = new LinkedList<>(); } if (repositories == null) { repositories = new LinkedList<>(); } parent = model.getParent(); setPropertiesFromModel(this, model); for (org.apache.maven.model.Dependency dependency : model.getDependencies()) { if (!"test".equalsIgnoreCase(dependency.getScope())) { dependencies.add(new Dependency(new DefaultArtifact( (dependency.getGroupId().contains("${")) ? parent.getGroupId() : dependency.getGroupId(), dependency.getArtifactId(), dependency.getClassifier(), "jar", dependency.getVersion() ), JavaScopes.RUNTIME)); } } for (Repository remoteRepository : model.getRepositories()) { repositories.add(new RemoteRepository(remoteRepository.getId(), "default", remoteRepository.getUrl())); } } catch (Exception e) { LOGGER.error("Error while reading POM file", e); } }

Target:
public void parsePom(InputStream inputStream) { try { MavenXpp3Reader reader = new MavenXpp3Reader(); Model model = reader.read(inputStream); if (dependencies == null) { dependencies = new LinkedList<>(); } if (repositories == null) { repositories = new LinkedList<>(); } parent = model.getParent(); setPropertiesFromModel(this, model); for (org.apache.maven.model.Dependency dependency : model.getDependencies()) { if (!"test".equalsIgnoreCase(dependency.getScope())) { dependencies.add(new Dependency(new DefaultArtifact( dependency.getGroupId(), dependency.getArtifactId(), dependency.getClassifier(), "jar", dependency.getVersion() ), JavaScopes.RUNTIME)); } } for (Repository remoteRepository : model.getRepositories()) { repositories.add(new RemoteRepository(remoteRepository.getId(), "default", remoteRepository.getUrl())); } } catch (Exception ex) { LOGGER.error("Error while reading POM file", ex); } }
Source:
public void test_getDeveloperDecertifications_CompletesWithoutError() throws EntityRetrievalException, JsonProcessingException, EntityCreationException{ SecurityContextHolder.getContext().setAuthentication(adminUser); DeveloperDecertificationResponse resp = searchViewController.getDeveloperDecertifications(); assertTrue("DeveloperDecertificationResponse should have size == 2 but has size " + resp.getDeveloperDecertificationResult().size(), resp.getDeveloperDecertificationResult().size() == 2); }

Target:
public void test_getDeveloperDecertifications_CompletesWithoutError() throws EntityRetrievalException, JsonProcessingException, EntityCreationException{ DeveloperDecertificationResponse resp = searchViewController.getDeveloperDecertifications(); assertTrue("DeveloperDecertificationResponse should have size == 2 but has size " + resp.getDeveloperDecertificationResult().size(), resp.getDeveloperDecertificationResult().size() == 2); }
Source:
public BigInteger getYear() { return year; }

Target:
public long getYear() { return year; }
Source:
public void testRequestNetworkCallback() { final TestNetworkCallback callback = new TestNetworkCallback(); try { mCm.requestNetwork(new NetworkRequest.Builder() .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) .build(), callback); Network internetNetwork = callback.waitForAvailable(); assertNotNull("Did not receive NetworkCallback.onAvailable for INTERNET", internetNetwork); } catch (InterruptedException e) { fail("Broadcast receiver or NetworkCallback wait was interrupted."); } finally { mCm.unregisterNetworkCallback(callback); } }

Target:
public void testRequestNetworkCallback() { final TestNetworkCallback callback = new TestNetworkCallback(); mCm.requestNetwork(new NetworkRequest.Builder() .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) .build(), callback); try { Network internetNetwork = callback.waitForAvailable(); assertNotNull("Did not receive NetworkCallback#onAvailable for INTERNET", internetNetwork); } catch (InterruptedException e) { fail("NetworkCallback wait was interrupted."); } finally { mCm.unregisterNetworkCallback(callback); } }
Source:
public void testDecimal() throws Exception { assertExpression("DECIMAL '12.34'", new DecimalLiteral("12.34")); assertExpression("DECIMAL '12.'", new DecimalLiteral("12.")); assertExpression("DECIMAL '12'", new DecimalLiteral("12")); assertExpression("DECIMAL '.34'", new DecimalLiteral(".34")); assertExpression("DECIMAL '+12.34'", new DecimalLiteral("+12.34")); assertExpression("DECIMAL '+12'", new DecimalLiteral("+12")); assertExpression("DECIMAL '-12.34'", new DecimalLiteral("-12.34")); assertExpression("DECIMAL '-12'", new DecimalLiteral("-12")); assertExpression("DECIMAL '+.34'", new DecimalLiteral("+.34")); assertExpression("DECIMAL '-.34'", new DecimalLiteral("-.34")); assertExpression("123.", new DecimalLiteral("123.")); assertExpression("123.0", new DecimalLiteral("123.0")); assertExpression(".5", new DecimalLiteral(".5")); assertExpression("123.5", new DecimalLiteral("123.5")); }

Target:
public void testDecimal() throws Exception { assertExpression("DECIMAL '12.34'", new DecimalLiteral("12.34")); assertExpression("DECIMAL '12.'", new DecimalLiteral("12.")); assertExpression("DECIMAL '12'", new DecimalLiteral("12")); assertExpression("DECIMAL '.34'", new DecimalLiteral(".34")); assertExpression("DECIMAL '+12.34'", new DecimalLiteral("+12.34")); assertExpression("DECIMAL '+12'", new DecimalLiteral("+12")); assertExpression("DECIMAL '-12.34'", new DecimalLiteral("-12.34")); assertExpression("DECIMAL '-12'", new DecimalLiteral("-12")); assertExpression("DECIMAL '+.34'", new DecimalLiteral("+.34")); assertExpression("DECIMAL '-.34'", new DecimalLiteral("-.34")); assertInvalidExpression("123.", "Unexpected decimal literal: 123."); assertInvalidExpression("123.0", "Unexpected decimal literal: 123.0"); assertInvalidExpression(".5", "Unexpected decimal literal: .5"); assertInvalidExpression("123.5", "Unexpected decimal literal: 123.5"); }
Source:
public void createsHostsConfiguration() throws IOException { Assume.assumeFalse(SystemUtils.IS_OS_WINDOWS); final File path = this.temp.newFolder(); final SSHD sshd = new SSHD(path); try { sshd.start(); final File key = this.temp.newFile(); FileUtils.write(key, sshd.key()); this.manifest(path, sshd.login(), sshd.port(), key); final String host = "host"; final int sport = 567; final String server = "server"; final File fhosts = this.hosts(path, host); new Nginx().update(host, 1234, server, sport); MatcherAssert.assertThat( FileUtils.readFileToString(fhosts), Matchers.equalTo( Joiner.on('\n').join( "upstream example_servers {", " server 10.0.0.1:80;", " server 10.0.0.2:80;", String.format(" server %s:%d;", server, sport), "}" ) ) ); } finally { sshd.stop(); } }

Target:
public void createsHostsConfiguration() throws IOException { Assume.assumeFalse(SystemUtils.IS_OS_WINDOWS); final SSHD sshd = new SSHD(temp); sshd.start(); final File key = File.createTempFile("ssh", "key", temp); FileUtils.write(key, sshd.key()); this.manifest(temp, sshd.login(), sshd.port(), key); final String host = "host"; final int sport = 567; final String server = "server"; final File fhosts = this.hosts(temp, host); try { new Nginx().update(host, 1234, server, sport); } finally { sshd.stop(); } MatcherAssert.assertThat( FileUtils.readFileToString(fhosts), Matchers.equalTo( Joiner.on('\n').join( "upstream example_servers {", " server 10.0.0.1:80;", " server 10.0.0.2:80;", String.format(" server %s:%d;", server, sport), "}" ) ) ); }
Source:
public boolean check(final String login) throws IOException { return false; }

Target:
public boolean check(final String login) throws IOException { throw new UnsupportedOperationException(); }
Source:
WebSocketConnection(final URI serverUri) { this.serverUri = serverUri; pingSender = Timers.fixedRateTimer("websocket-ping-sender") .period(45, TimeUnit.SECONDS) .delay(45, TimeUnit.SECONDS) .task( () -> { if (!client.isOutputClosed()) { client .sendPing(ByteBuffer.wrap("Ping".getBytes(StandardCharsets.UTF_8))) .exceptionally(logWebSocketError("Failed to send ping.")); } }); }

Target:
WebSocketConnection(final URI serverUri) { this.serverUri = serverUri; pingSender = Timers.fixedRateTimer("websocket-ping-sender") .period(45, TimeUnit.SECONDS) .delay(45, TimeUnit.SECONDS) .task( () -> { if (!client.isOutputClosed()) { client .sendPing(ByteBuffer.allocate(0)) .exceptionally(logWebSocketError(Level.INFO, "Failed to send ping.")); } }); }
Source:
public void testEventName() { ITmfTrace trace = initializeTrace(testTrace1); XmlStateSystemModule module = initializeModule(TmfXmlTestFiles.ATTRIBUTE_FILE); try { module.setTrace(trace); module.schedule(); module.waitForCompletion(); ITmfStateSystem ss = module.getStateSystem(); assertNotNull(ss); List<Integer> quarks = ss.getQuarks("*"); assertEquals(2, quarks.size()); for (Integer quark : quarks) { String name = ss.getAttributeName(quark); switch (name) { case "test": { int[] expectedStarts = { 1, 5, 7 }; ITmfStateValue[] expectedValues = { TmfStateValue.newValueInt(1), TmfStateValue.newValueInt(2) }; verifyStateIntervals("test", ss, quark, expectedStarts, expectedValues); } break; case "test1": { int[] expectedStarts = { 1, 3, 7, 7 }; ITmfStateValue[] expectedValues = { TmfStateValue.nullValue(), TmfStateValue.newValueInt(1), TmfStateValue.newValueInt(2) }; verifyStateIntervals("test1", ss, quark, expectedStarts, expectedValues); } break; default: fail("Wrong attribute name " + name); break; } } } catch (TmfAnalysisException | AttributeNotFoundException | StateSystemDisposedException e) { fail(e.getMessage()); } finally { module.dispose(); trace.dispose(); } }

Target:
public void testEventName() { ITmfTrace trace = initializeTrace(testTrace1); XmlStateSystemModule module = initializeModule(TmfXmlTestFiles.ATTRIBUTE_FILE); try { module.setTrace(trace); module.schedule(); module.waitForCompletion(); ITmfStateSystem ss = module.getStateSystem(); assertNotNull(ss); List<Integer> quarks = ss.getQuarks("*"); assertEquals(2, quarks.size()); for (Integer quark : quarks) { String name = ss.getAttributeName(quark); switch (name) { case "test": { final int[] expectedStarts = { 1, 5, 7 }; ITmfStateValue[] expectedValues = { TmfStateValue.newValueInt(1), TmfStateValue.newValueInt(2) }; verifyStateIntervals("test", ss, quark, expectedStarts, expectedValues); } break; case "test1": { final int[] expectedStarts = { 1, 3, 7, 7 }; ITmfStateValue[] expectedValues = { TmfStateValue.nullValue(), TmfStateValue.newValueInt(1), TmfStateValue.newValueInt(2) }; verifyStateIntervals("test1", ss, quark, expectedStarts, expectedValues); } break; default: fail("Wrong attribute name " + name); break; } } } catch (TmfAnalysisException | AttributeNotFoundException | StateSystemDisposedException e) { fail(e.getMessage()); } finally { module.dispose(); trace.dispose(); } }
Source:
private void createNonUIThreadControl(Composite composite, int columns) { PixelConverter pixelConverter= new PixelConverter(composite); String str= PreferencesMessages.CodeAssistAdvancedConfigurationBlock_nonUIThread; Button checkbox = addCheckBox(composite, str, PREF_CODEASSIST_NONUITHREAD_COMPUTATION, new String[] { Boolean.TRUE.toString(), Boolean.FALSE.toString() }, pixelConverter.convertWidthInCharsToPixels(7)); checkbox.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, false, columns, 1)); CompletionProposalComputerRegistry registry= CompletionProposalComputerRegistry.getDefault(); if (registry.computingCompletionRequiresUIThread()) { checkbox.setSelection(false); checkbox.setEnabled(false); Label label = new Label(composite, SWT.NONE); label.setText(NLS.bind(PreferencesMessages.CodeAssistAdvancedConfigurationBlock_nonUIThread_computersRequiringUIThread, registry.getComputersRequiringUIThreadNames().collect(Collectors.joining(",")))); GridData layoutData= new GridData(GridData.FILL, GridData.FILL, true, false, columns, 1); layoutData.horizontalIndent = 30; label.setLayoutData(layoutData); label.setEnabled(false); } }

Target:
private void createNonUIThreadControl(Composite composite, int columns) { PixelConverter pixelConverter= new PixelConverter(composite); String str= PreferencesMessages.CodeAssistAdvancedConfigurationBlock_nonUIThread; Button checkbox = addCheckBox(composite, str, PREF_CODEASSIST_NONUITHREAD_COMPUTATION, new String[] { Boolean.TRUE.toString(), Boolean.FALSE.toString() }, pixelConverter.convertWidthInCharsToPixels(7)); checkbox.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, false, columns, 1)); CompletionProposalComputerRegistry registry= CompletionProposalComputerRegistry.getDefault(); if (registry.computingCompletionRequiresUIThread()) { checkbox.setSelection(false); checkbox.setEnabled(false); Label label = new Label(composite, SWT.NONE); label.setText(Messages.format(PreferencesMessages.CodeAssistAdvancedConfigurationBlock_nonUIThread_computersRequiringUIThread, registry.getComputersRequiringUIThreadNames().collect(Collectors.joining(",")))); GridData layoutData= new GridData(GridData.FILL, GridData.FILL, true, false, columns, 1); layoutData.horizontalIndent = 30; label.setLayoutData(layoutData); label.setEnabled(false); } }
Source:
public void message(PubNub pubnub, PNMessageResult message) { Exchange exchange = new DefaultExchange(endpoint, endpoint.getExchangePattern()); Message inmessage = exchange.getIn(); inmessage.setBody(message); inmessage.setHeader(TIMETOKEN, message.getTimetoken()); inmessage.setHeader(CHANNEL, message.getChannel()); try { getProcessor().process(exchange); } catch (Exception e) { exchange.setException(e); getExceptionHandler().handleException("Error processing exchange", exchange, e); } }

Target:
public void message(PubNub pubnub, PNMessageResult message) { Exchange exchange = endpoint.createExchange(); Message inmessage = exchange.getIn(); inmessage.setBody(message); inmessage.setHeader(TIMETOKEN, message.getTimetoken()); inmessage.setHeader(CHANNEL, message.getChannel()); try { getProcessor().process(exchange); } catch (Exception e) { exchange.setException(e); getExceptionHandler().handleException("Error processing exchange", exchange, e); } }
Source:
public void onProjectCreated(CreateProjectEvent event) { final ProjectConfigDto projectConfig = event.getProjectConfig(); if (projectConfig == null) { return; } if (view.isGoIntoActivated()) { view.resetGoIntoMode(); } final ProjectNode node = nodeManager.wrap(projectConfig); view.addNode(null, node); view.select(node, false); if (!projectConfig.getProblems().isEmpty() || Constants.BLANK_ID.equals(projectConfig.getType())) { notificationManager.notify(locale.projectExplorerInvalidProjectDetected(), locale.projectExplorerDetectedUnconfiguredProject(), projectConfig); askUserToSetUpProject(projectConfig); } }

Target:
public void onProjectCreated(CreateProjectEvent event) { final ProjectConfigDto projectConfig = event.getProjectConfig(); if (projectConfig == null) { return; } if (view.isGoIntoActivated()) { view.resetGoIntoMode(); } final ProjectNode node = nodeManager.wrap(projectConfig); view.addNode(null, node); view.select(node, false); if (!projectConfig.getProblems().isEmpty()) { notificationManager.notify(locale.projectExplorerInvalidProjectDetected(), locale.projectExplorerDetectedUnconfiguredProject(), projectConfig); askUserToSetUpProject(projectConfig); } }
Source:
void migrateDatabase() { Flyway flyway = Flyway.configure() .dataSource(dataSource) .baselineOnMigrate(true) .load(); flyway.migrate(); }

Target:
void migrateDatabase() { if (dataSource == null){ throw new NullPointerException("Failed to migrate, cannot connect to database"); } Flyway flyway = Flyway.configure() .dataSource(dataSource) .baselineOnMigrate(true) .load(); flyway.migrate(); }
Source:
public String toString() { return "CdpLinkTopologyEntity{" + "id=" + id + ", nodeId=" + nodeId + ", cdpCacheIfIndex=" + cdpCacheIfIndex + ", cdpInterfaceName='" + cdpInterfaceName + '\'' + ", cdpCacheAddress='" + cdpCacheAddress + '\'' + ", cdpCacheDeviceId='" + cdpCacheDeviceId + '\'' + ", cdpCacheDevicePort='" + cdpCacheDevicePort + '\'' + '}'; }

Target:
public String toString() { return MoreObjects.toStringHelper(this) .add("id", id) .add("nodeId", nodeId) .add("cdpCacheIfIndex", cdpCacheIfIndex) .add("cdpInterfaceName", cdpInterfaceName) .add("cdpCacheAddress", cdpCacheAddress) .add("cdpCacheDeviceId", cdpCacheDeviceId) .add("cdpCacheDevicePort", cdpCacheDevicePort) .toString(); }
Source:
public static <T, S> Stream<S> map( List<T> values, Function<T, S> mapper, Executor executor, int concurrency) { int size = values.size(); if (size <= 1 || concurrency == 1) { return values.stream().map(mapper); } List<CompletableFuture<S>> futures = Lists.newArrayListWithCapacity(size); for (int i = 0; i < size; i++) { futures.add(new CompletableFuture<>()); } if (size < concurrency) { concurrency = size; } AtomicInteger nextValueToProcess = new AtomicInteger(0); for (int i = 0; i < concurrency; i++) { executor.execute(() -> { int currentValueToProcess; while ((currentValueToProcess = nextValueToProcess.getAndIncrement()) < size) { T value = values.get(currentValueToProcess); CompletableFuture<S> future = futures.get(currentValueToProcess); try { future.complete(mapper.apply(value)); } catch (Exception e) { future.completeExceptionally(e); } } }); } return streamAllUnchecked(futures); }

Target:
public static <T, S> Stream<S> map( List<T> values, Function<T, S> mapper, Executor executor, int concurrency) { int size = values.size(); if (size <= 1 || concurrency == 1) { return values.stream().map(mapper); } Map<T, CompletableFuture<S>> futuresByValue = values.stream() .collect(Collectors.toMap(Function.identity(), value -> new CompletableFuture<>())); Queue<T> valueQueue = new ConcurrentLinkedQueue<T>(values); if (size < concurrency) { concurrency = size; } for (int i = 0; i < concurrency; i++) { executor.execute(() -> runOperationsAndUpdateFutures(futuresByValue, valueQueue, mapper)); } return streamAllUnchecked(futuresByValue.values()); }