auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public boolean get(URIish uri, CredentialItem... items) throws UnsupportedCredentialItem { for (CredentialItem i : items) { if (i instanceof CredentialItem.Username) { ((CredentialItem.Username) i).setValue(username); continue; } if (i instanceof CredentialItem.Password) { ((CredentialItem.Password) i).setValue(password); continue; } if (i instanceof CredentialItem.StringType) { if (i.getPromptText().equals("Password: ")) { ((CredentialItem.StringType) i).setValue(new String( password)); continue; } } if(i instanceof CredentialItem.YesNoType) { ((CredentialItem.YesNoType)i).setValue(true); return true; } throw new UnsupportedCredentialItem(uri, i.getClass().getName() + ":" + i.getPromptText()); } return true; }

Target:
public boolean get(URIish uri, CredentialItem... items) throws UnsupportedCredentialItem { for (CredentialItem i : items) { if (i instanceof CredentialItem.Password) { ((CredentialItem.Password) i).setValue(password); continue; } if (i instanceof CredentialItem.StringType && PASSWORD_PROMPT.equals(i.getPromptText())) { ((CredentialItem.StringType) i).setValue(new String(password)); continue; } if (i instanceof CredentialItem.Username) { ((CredentialItem.Username) i).setValue(username); continue; } if (i instanceof CredentialItem.YesNoType) { ((CredentialItem.YesNoType) i).setValue(true); return true; } throw new UnsupportedCredentialItem(uri, i.getClass().getName() + ":" + i.getPromptText()); } return true; }
Source:
public RabbitMQConsumer(RabbitMQStore store) { if (store == null) { log.error("Cannot initialize."); return; } this.store = store; cachedMessage = new CachedMessage(); }

Target:
public RabbitMQConsumer(RabbitMQStore store) { if (store == null) { log.error("Cannot initialize consumer: " + getId()); return; } this.store = store; cachedMessage = new CachedMessage(); }
Source:
public void createTable(HTableDescriptor desc, byte[][] splitKeys) throws IOException { CreateTableRequest createReq = CreateTableRequest.of(desc.getTableName().getNameAsString()); for (HColumnDescriptor column : desc.getColumnFamilies()) { String columnName = column.getNameAsString(); createReq.addFamily(columnName, buildGarbageCollectionRule(column)); } if (splitKeys != null) { for (byte[] splitKey : splitKeys) { createReq.addSplit(ByteString.copyFrom(splitKey)); } } createTable(desc.getTableName(), createReq); }

Target:
public void createTable(HTableDescriptor desc, byte[][] splitKeys) throws IOException { createTable(desc.getTableName(), TableAdapter.adapt(desc, splitKeys)); }
Source:
public void testCaseSensitiveField() { String indexName = "machine"; Map<String, Object> docAsSource = new HashMap<>(); docAsSource.put("ProductionCount", 32L); docAsSource.put("Name", "A Big Machine"); addElasticDocumentToIndex(indexName, docAsSource); embeddedElasticsearchNode.getClient().admin().indices().refresh(refreshRequest(indexName)).actionGet(); MaterializedResult actualColumns = computeActual("SELECT name, ProductionCount FROM telemetry.Machine").toTestTypes(); MaterializedResult.Builder builder = resultBuilder(getQueryRunner().getDefaultSession(), VARCHAR, BIGINT); for (MaterializedRow row : actualColumns.getMaterializedRows()) { builder.row(row.getField(0), row.getField(1)); } MaterializedResult actualResult = builder.build(); builder = resultBuilder(getQueryRunner().getDefaultSession(), VARCHAR, BIGINT); MaterializedResult expectedColumns = builder .row("A Big Machine", 32L).build(); assertEquals(actualResult, expectedColumns, format("%s != %s", actualResult, expectedColumns)); }

Target:
public void testCaseSensitiveField() { String indexName = "machine"; String tableName = "telemetry.Machine"; Map<String, Object> source = new HashMap<>(); source.put("ProductionCount", 32L); source.put("Name", "A Big Machine"); embeddedElasticsearchNode.getClient().prepareIndex(indexName.toLowerCase(ENGLISH), "doc").setSource(source).get(); embeddedElasticsearchNode.getClient().admin().indices().refresh(refreshRequest(indexName)).actionGet(); MaterializedResult actualColumns = computeActual("SELECT name, ProductionCount FROM " + tableName).toTestTypes(); MaterializedResult.Builder builder = resultBuilder(getQueryRunner().getDefaultSession(), VARCHAR, BIGINT); for (MaterializedRow row : actualColumns.getMaterializedRows()) { builder.row(row.getField(0), row.getField(1)); } MaterializedResult actualResult = builder.build(); builder = resultBuilder(getQueryRunner().getDefaultSession(), VARCHAR, BIGINT); MaterializedResult expectedColumns = builder .row("A Big Machine", 32L).build(); assertEquals(actualResult, expectedColumns, format("%s != %s", actualResult, expectedColumns)); }
Source:
public SearchServiceClientBuilder addPolicy(HttpPipelinePolicy policy) { this.policies.add(policy); return this; }

Target:
public SearchServiceClientBuilder addPolicy(HttpPipelinePolicy policy) { Objects.requireNonNull(policy); this.policies.add(policy); return this; }
Source:
private void processConfigData(byte[] data) throws Exception { Properties properties = new Properties(); properties.load(new ByteArrayInputStream(data)); QuorumMaj newConfig = new QuorumMaj(properties); currentConfig.set(newConfig); if ( log.isInfoEnabled() ) { log.info("New config event received: " + properties.toString()); } String connectionString = configToConnectionString(newConfig); if ( connectionString.trim().length() > 0 ) { ensembleProvider.setConnectionString(connectionString); } else { log.debug("Ignoring new config as it is empty"); } }

Target:
private void processConfigData(byte[] data) throws Exception { Properties properties = new Properties(); properties.load(new ByteArrayInputStream(data)); log.info("New config event received: {}", properties); QuorumMaj newConfig = new QuorumMaj(properties); currentConfig.set(newConfig); String connectionString = configToConnectionString(newConfig); if ( connectionString.trim().length() > 0 ) { ensembleProvider.setConnectionString(connectionString); } else { log.debug("Ignoring new config as it is empty"); } }
Source:
public void testRepoManifestCopyfile() throws Exception { Repository localDb = createWorkRepository(); StringBuilder xmlContent = new StringBuilder(); xmlContent.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n") .append("<manifest>") .append("<remote name=\"remote1\" fetch=\".\" />") .append("<default revision=\"master\" remote=\"remote1\" />") .append("<project path=\"foo\" name=\"") .append(defaultUri) .append("\">") .append("<copyfile src=\"hello.txt\" dest=\"Hello\" />") .append("</project>") .append("</manifest>"); JGitTestUtil.writeTrashFile(localDb, "manifest.xml", xmlContent.toString()); RepoCommand command = new RepoCommand(localDb); command.setPath(localDb.getWorkTree() + "/manifest.xml") .setURI(rootUri) .call(); File hello = new File(localDb.getWorkTree() + "/foo/hello.txt"); assertTrue(hello.exists()); BufferedReader reader = new BufferedReader(new FileReader(hello)); String content = reader.readLine(); assertTrue(content.startsWith("world")); hello = new File(localDb.getWorkTree() + "/Hello"); assertTrue(hello.exists()); reader = new BufferedReader(new FileReader(hello)); content = reader.readLine(); assertTrue(content.startsWith("world")); }

Target:
public void testRepoManifestCopyfile() throws Exception { Repository localDb = createWorkRepository(); StringBuilder xmlContent = new StringBuilder(); xmlContent.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n") .append("<manifest>") .append("<remote name=\"remote1\" fetch=\".\" />") .append("<default revision=\"master\" remote=\"remote1\" />") .append("<project path=\"foo\" name=\"") .append(defaultUri) .append("\">") .append("<copyfile src=\"hello.txt\" dest=\"Hello\" />") .append("</project>") .append("</manifest>"); JGitTestUtil.writeTrashFile(localDb, "manifest.xml", xmlContent.toString()); RepoCommand command = new RepoCommand(localDb); command.setPath(localDb.getWorkTree().getAbsolutePath() + "/manifest.xml") .setURI(rootUri) .call(); File hello = new File(localDb.getWorkTree(), "foo/hello.txt"); assertTrue("The original file exists", hello.exists()); BufferedReader reader = new BufferedReader(new FileReader(hello)); String content = reader.readLine(); reader.close(); assertEquals("The original file has expected content", "world", content); hello = new File(localDb.getWorkTree(), "Hello"); assertTrue("The destination file exists", hello.exists()); reader = new BufferedReader(new FileReader(hello)); content = reader.readLine(); reader.close(); assertEquals("The destination file has expected content", "world", content); }
Source:
public Builder entryPoint(final String entrypoint) { if (entrypoint != null && !entrypoint.isEmpty()) { return entryPoint(entrypoint.split(" ")); } return this; }

Target:
public Builder entryPoint(final String entrypoint) { if (entrypoint != null && !entrypoint.isEmpty()) { return entryPoint(entrypoint.split(" ")); } else { this.entrypoint = null; } return this; }
Source:
public void mergeAndStore(final Path metadataBasePath, final Metadata mergeMetadata) { doInLock(metadataBasePath, path -> { if (Files.exists(metadataBasePath)) { try { final Metadata metadata = readMetadata(metadataBasePath); mergeAndStore(metadataBasePath, metadata, mergeMetadata); return; } catch (Exception e) { logger.error("Unable to merge the metadata to " + metadataBasePath + " by source metadata" + ReflectionToStringBuilder.toString(mergeMetadata) + " Continuing with storing new metadata", e); } } try { Files.createDirectories(metadataBasePath); } catch (IOException e) { throw Throwables.propagate(e); } storeMetadata(metadataBasePath, null, mergeMetadata, MetadataType.ARTIFACT_ROOT_LEVEL); }); }

Target:
public void mergeAndStore(final Path metadataBasePath, final Metadata mergeMetadata) { doInLock(metadataBasePath, path -> { if (Files.exists(metadataBasePath)) { try { final Metadata metadata = readMetadata(metadataBasePath); mergeAndStore(metadataBasePath, metadata, mergeMetadata); return; } catch (Exception e) { logger.error("Unable to merge the metadata to " + metadataBasePath + " by source metadata " + ReflectionToStringBuilder.toString(mergeMetadata) + ". Continuing with storing new metadata ...", e); } } try { Files.createDirectories(metadataBasePath); } catch (IOException e) { throw Throwables.propagate(e); } storeMetadata(metadataBasePath, null, mergeMetadata, MetadataType.ARTIFACT_ROOT_LEVEL); }); }
Source:
void doIt( Object obj ) throws Exception; } public static <E extends Exception> void forAll( ActionAble actionable, Object... accessors ) throws E { List<E> error = Arrays.stream( accessors ).map( accessor -> { try { actionable.doIt( accessor ); return null; } catch ( Throwable t ) { return (E) t; } } ).filter( Objects::nonNull ).collect( Collectors.toList() ); if ( !error.isEmpty() ) { throw error.get(0); } }

Target:
void doIt( Object obj ) throws Exception; } public static <E extends Exception> void forAll( ActionAble actionable, Object... subjects ) throws E { List<E> error = Arrays.stream( subjects ).map( accessor -> { try { actionable.doIt( accessor ); return null; } catch ( Throwable t ) { return (E) t; } } ).filter( Objects::nonNull ).collect( Collectors.toList() ); if ( !error.isEmpty() ) { throw error.get(0); } }
Source:
private void updateStringValuesToDatabase(Connection dbConnection, String sqlStmt, Object... params) throws UserStoreException { PreparedStatement prepStmt = null; boolean localConnection = false; try { if (dbConnection == null) { localConnection = true; dbConnection = getDBConnection(); } prepStmt = dbConnection.prepareStatement(sqlStmt); if (params != null && params.length > 0) { for (int i = 0; i < params.length; i++) { Object param = params[i]; if (param == null) { throw new UserStoreException("Invalid data provided"); } else if (param instanceof String) { prepStmt.setString(i + 1, (String) param); } else if (param instanceof Integer) { prepStmt.setInt(i + 1, (Integer) param); } else if (param instanceof Date) { prepStmt.setTimestamp(i + 1,new Timestamp(System.currentTimeMillis())); } else if (param instanceof Boolean) { prepStmt.setBoolean(i + 1, (Boolean) param); } } } int count = prepStmt.executeUpdate(); if(count == 0) { log.info("No rows were updated"); } if (log.isDebugEnabled()) { log.debug("Executed querry is " + sqlStmt + " and number of updated rows :: " + count); } if (localConnection) { dbConnection.commit(); } } catch (SQLException e) { throw new UserStoreException("Error occurred while updating String values to database", e); } finally { if (localConnection) { DatabaseUtil.closeAllConnections(dbConnection); } DatabaseUtil.closeAllConnections(null, prepStmt); } }

Target:
private void updateStringValuesToDatabase(Connection dbConnection, String sqlStmt, Object... params) throws UserStoreException { PreparedStatement prepStmt = null; boolean localConnection = false; try { if (dbConnection == null) { localConnection = true; dbConnection = getDBConnection(); } prepStmt = dbConnection.prepareStatement(sqlStmt); if (params != null && params.length > 0) { for (int i = 0; i < params.length; i++) { Object param = params[i]; if (param == null) { throw new UserStoreException("Invalid data provided"); } else if (param instanceof String) { prepStmt.setString(i + 1, (String) param); } else if (param instanceof Integer) { prepStmt.setInt(i + 1, (Integer) param); } else if (param instanceof Date) { prepStmt.setTimestamp(i + 1,new Timestamp(System.currentTimeMillis())); } else if (param instanceof Boolean) { prepStmt.setBoolean(i + 1, (Boolean) param); } } } int count = prepStmt.executeUpdate(); if(count == 0) { log.info("No rows were updated"); } if (log.isDebugEnabled()) { log.debug("Executed querry is " + sqlStmt + " and number of updated rows :: " + count); } if (localConnection) { dbConnection.commit(); } } catch (SQLException e) { String errorMessage = "Error occurred while updating String values to database"; if (log.isDebugEnabled()) { log.debug(errorMessage, e); } throw new UserStoreException(errorMessage, e); } finally { if (localConnection) { DatabaseUtil.closeAllConnections(dbConnection); } DatabaseUtil.closeAllConnections(null, prepStmt); } }
Source:
public TableStatistics(Estimate rowCount, Map<ColumnHandle, ColumnStatistics> columnStatistics) { this.rowCount = requireNonNull(rowCount, "rowCount can not be null"); this.columnStatistics = unmodifiableMap(requireNonNull(columnStatistics, "columnStatistics can not be null")); }

Target:
public TableStatistics(Estimate rowCount, Map<ColumnHandle, ColumnStatistics> columnStatistics) { this.rowCount = requireNonNull(rowCount, "rowCount can not be null"); if (!rowCount.isUnknown() && rowCount.getValue() < 0) { throw new IllegalArgumentException(format("rowCount must be greater than or equal to 0: %s", rowCount.getValue())); } this.columnStatistics = unmodifiableMap(requireNonNull(columnStatistics, "columnStatistics can not be null")); }
Source:
public Response resetEmulatedMachine(Action action) { VdcQueryReturnValue result = runQuery(VdcQueryType.GetVdsGroupById, new IdQueryParameters(guid)); if (result != null && result.getSucceeded() && result.getReturnValue() != null) { VdsGroupOperationParameters param = new VdsGroupOperationParameters((VDSGroup)result.getReturnValue()); param.setForceResetEmulatedMachine(true); return doAction(VdcActionType.UpdateVdsGroup, param, action); } else { throw new WebApplicationException(Response.status(Response.Status.INTERNAL_SERVER_ERROR) .entity("Couldn't locate a cluster with the specified id.") .build()); } }

Target:
public Response resetEmulatedMachine(Action action) { VdcQueryReturnValue result = runQuery(VdcQueryType.GetVdsGroupById, new IdQueryParameters(guid)); if (result != null && result.getSucceeded() && result.getReturnValue() != null) { VdsGroupOperationParameters param = new VdsGroupOperationParameters((VDSGroup)result.getReturnValue()); param.setForceResetEmulatedMachine(true); return doAction(VdcActionType.UpdateVdsGroup, param, action); } else { throw new WebApplicationException(Response.status(Response.Status.NOT_FOUND).build()); } }
Source:
protected void doHeaders(RenderRequest request, RenderResponse response) { try { doDispatch(request, response); } catch (IOException ex) { logger.error("Exception rendering headers for portlet " + getPortletName() + ". Aborting doHeaders", ex); } catch (PortletException ex) { logger.error("Exception rendering headers for portlet " + getPortletName() + ". Aborting doHeaders", ex); } }

Target:
protected void doHeaders(RenderRequest request, RenderResponse response) { try { doDispatch(request, response); } catch (IOException | PortletException ex) { logger.error("Exception rendering headers for portlet " + getPortletName() + ". Aborting doHeaders", ex); } }
Source:
public Opt<Identity> enter(final Request request) throws IOException { final String decoded = new String( DatatypeConverter.parseBase64Binary( PATTERN.split( new RqHeaders.Smart( new RqHeaders.Base(request) ) .single("authorization") )[1] ), StandardCharsets.UTF_8 ).trim(); final String user = decoded.split(":")[0]; final Opt<Identity> identity = this.entry.enter( user, decoded.substring(user.length() + 1) ); if (!identity.has()) { throw new RsForward( new RsWithHeader( new RsFlash("access denied", Level.WARNING), String.format( "WWW-Authenticate: Basic ream=\"%s\"", this.realm ) ), HttpURLConnection.HTTP_UNAUTHORIZED, new RqHref.Base(request).href() ); } return identity; }

Target:
public Opt<Identity> enter(final Request request) throws IOException { final String decoded = new String( DatatypeConverter.parseBase64Binary( AUTH.split( new RqHeaders.Smart( new RqHeaders.Base(request) ).single("authorization") )[1] ), StandardCharsets.UTF_8 ).trim(); final String user = decoded.split(":")[0]; final Opt<Identity> identity = this.entry.enter( user, decoded.substring(user.length() + 1) ); if (!identity.has()) { throw new RsForward( new RsWithHeader( new RsFlash("access denied", Level.WARNING), String.format( "WWW-Authenticate: Basic ream=\"%s\"", this.realm ) ), HttpURLConnection.HTTP_UNAUTHORIZED, new RqHref.Base(request).href() ); } return identity; }
Source:
private void handleIO(SelectionKey sk) { MemcachedNode qa=(MemcachedNode)sk.attachment(); try { getLogger().debug( "Handling IO for: %s (r=%s, w=%s, c=%s, op=%s)", sk, sk.isReadable(), sk.isWritable(), sk.isConnectable(), sk.attachment()); if(sk.isConnectable()) { getLogger().info("Connection state changed for %s", sk); final SocketChannel channel=qa.getChannel(); if(channel.finishConnect()) { connected(qa); addedQueue.offer(qa); if(qa.getWbuf().hasRemaining()) { handleWrites(sk, qa); } } else { assert !channel.isConnected() : "connected"; } } else { if(sk.isValid() && sk.isReadable()) { handleReads(sk, qa); } if(sk.isValid() && sk.isWritable()) { handleWrites(sk, qa); } } } catch(ClosedChannelException e) { if(!shutDown) { getLogger().info("Closed channel and not shutting down. " + "Queueing reconnect on %s", qa, e); lostConnection(qa, ReconnDelay.DEFAULT, "closed channel"); } } catch(ConnectException e) { getLogger().info("Reconnecting due to failure to connect to %s", qa, e); queueReconnect(qa, ReconnDelay.DEFAULT, "failure to connect"); } catch (OperationException e) { qa.setupForAuth("due to authentication failure"); getLogger().info("Reconnection due to exception " + "handling a memcached operation on %s. " + "This may be due to an authentication failure.", qa, e); lostConnection(qa, ReconnDelay.IMMEDIATE, "due to authentication failure"); } catch(Exception e) { qa.setupForAuth("due to exception"); getLogger().info("Reconnecting due to exception on %s", qa, e); lostConnection(qa, ReconnDelay.DEFAULT, "due to exception"); } qa.fixupOps(); }

Target:
private void handleIO(SelectionKey sk) { MemcachedNode qa=(MemcachedNode)sk.attachment(); try { getLogger().debug( "Handling IO for: %s (r=%s, w=%s, c=%s, op=%s)", sk, sk.isReadable(), sk.isWritable(), sk.isConnectable(), sk.attachment()); if(sk.isConnectable()) { getLogger().info("Connection state changed for %s", sk); final SocketChannel channel=qa.getChannel(); if(channel.finishConnect()) { connected(qa); addedQueue.offer(qa); if(qa.getWbuf().hasRemaining()) { handleWrites(sk, qa); } } else { assert !channel.isConnected() : "connected"; } } else { if(sk.isValid() && sk.isReadable()) { handleReads(sk, qa); } if(sk.isValid() && sk.isWritable()) { handleWrites(sk, qa); } } } catch(ClosedChannelException e) { if(!shutDown) { getLogger().info("Closed channel and not shutting down. " + "Queueing reconnect on %s", qa, e); lostConnection(qa, ReconnDelay.DEFAULT, "closed channel"); } } catch(ConnectException e) { getLogger().info("Reconnecting due to failure to connect to %s", qa, e); queueReconnect(qa, ReconnDelay.DEFAULT, "failure to connect"); } catch (OperationException e) { qa.setupForAuth("authentication failure"); getLogger().info("Reconnection due to exception " + "handling a memcached operation on %s. " + "This may be due to an authentication failure.", qa, e); lostConnection(qa, ReconnDelay.IMMEDIATE, "authentication failure"); } catch(Exception e) { qa.setupForAuth("due to exception"); getLogger().info("Reconnecting due to exception on %s", qa, e); lostConnection(qa, ReconnDelay.DEFAULT, "exception" + e); } qa.fixupOps(); }
Source:
public Map<String, RoleManagementRules> loadPerunRolesManagement() { Map<String, RoleManagementRules> rolesManagementRules = new HashMap<>(); JsonNode rootNode = loadConfigurationFile(); JsonNode rolesNodes = rootNode.get("perun_roles_management"); Iterator<String> roleNames =rolesNodes.fieldNames(); while(roleNames.hasNext()) { String roleName = roleNames.next(); JsonNode roleNode = rolesNodes.get(roleName); List<Map<String, String>> privilegedRoles = new ArrayList<>(); JsonNode privilegedRolesNode = roleNode.get("privileged_roles"); for (JsonNode privilegedRoleNode : privilegedRolesNode) { Map<String, String> innerRoleMap = createmapFromJsonNode(privilegedRoleNode); privilegedRoles.add(innerRoleMap); } Map<String, String> entitiesToManage = createmapFromJsonNode(roleNode.get("entities_to_manage")); Map<String, String> objectsToAssign = createmapFromJsonNode(roleNode.get("assign_to_objects")); rolesManagementRules.put(roleName, new RoleManagementRules(roleName, privilegedRoles, entitiesToManage, objectsToAssign)); } return rolesManagementRules; }

Target:
public Map<String, RoleManagementRules> loadPerunRolesManagement() { Map<String, RoleManagementRules> rolesManagementRules = new HashMap<>(); try { JsonNode rootNode = loadConfigurationFile(); JsonNode rolesNodes = rootNode.get("perun_roles_management"); Iterator<String> roleNames = rolesNodes.fieldNames(); while (roleNames.hasNext()) { String roleName = roleNames.next(); JsonNode roleNode = rolesNodes.get(roleName); List<Map<String, String>> privilegedRoles = new ArrayList<>(); JsonNode privilegedRolesNode = roleNode.get("privileged_roles"); for (JsonNode privilegedRoleNode : privilegedRolesNode) { Map<String, String> innerRoleMap = createmapFromJsonNode(privilegedRoleNode); privilegedRoles.add(innerRoleMap); } Map<String, String> entitiesToManage = createmapFromJsonNode(roleNode.get("entities_to_manage")); Map<String, String> objectsToAssign = createmapFromJsonNode(roleNode.get("assign_to_objects")); rolesManagementRules.put(roleName, new RoleManagementRules(roleName, privilegedRoles, entitiesToManage, objectsToAssign)); } } catch(RuntimeException e) { throw new InternalErrorException("The configuration file " + configurationPath.getFilename() + " has invalid syntax.", e); } return rolesManagementRules; }
Source:
public static boolean isInitialized() { waitInitialized(); return sCameraX.mInitialized.get(); }

Target:
public static boolean isInitialized() { synchronized (sInitDeinitLock) { return sInstance != null && sInstance.mInitialized.get(); } }
Source:
public <C> void dispatch(CommandMessage<C> command) { if (NoOpMessageMonitor.INSTANCE.equals(messageMonitor)) { CommandMessage<? extends C> interceptedCommand = intercept(command); Member destination = commandRouter.findDestination(interceptedCommand) .orElseThrow(() -> new NoHandlerForCommandException( "No node known to accept " + interceptedCommand.getCommandName())); try { connector.send(destination, interceptedCommand); } catch (Exception e) { destination.suspect(); throw new CommandDispatchException(DISPATCH_ERROR_MESSAGE + ": " + e.getMessage(), e); } } else { dispatch(command, null); } }

Target:
public <C> void dispatch(CommandMessage<C> command) { if (NoOpMessageMonitor.INSTANCE.equals(messageMonitor)) { CommandMessage<? extends C> interceptedCommand = intercept(command); Member destination = commandRouter.findDestination(interceptedCommand) .orElseThrow(() -> new NoHandlerForCommandException( format("No node known to accept [%s]", interceptedCommand.getCommandName()))); try { connector.send(destination, interceptedCommand); } catch (Exception e) { destination.suspect(); throw new CommandDispatchException(DISPATCH_ERROR_MESSAGE + ": " + e.getMessage(), e); } } else { dispatch(command, null); } }
Source:
static public boolean compareDoubleWithAccuracy(final double lhs, final double rhs, final double accuracy) { if (accuracy <= 0) throw new IllegalArgumentException("Accuracy must be positive."); return abs(lhs - rhs) / (abs(lhs) + abs(rhs) + EPSILON) < accuracy; }

Target:
public static boolean compareDoubleWithAccuracy(final double lhs, final double rhs, final double accuracy) { if (accuracy <= 0) throw new IllegalArgumentException("Accuracy must be positive."); return abs(lhs - rhs) / (abs(lhs) + abs(rhs) + EPSILON) < accuracy; }
Source:
public static void register(AggregationImplModule mod) { final BinaryOperator<Long> add = Math::addExact; final BinaryOperator<Long> subsctact = Math::subtractExact; mod.register(new SumAggregation<Float>(DataTypes.FLOAT, (n1, n2) -> n1 + n2, (n1, n2) -> n1 - n2)); mod.register(new SumAggregation<Double>(DataTypes.DOUBLE, (n1, n2) -> n1 + n2, (n1, n2) -> n1 - n2)); mod.register(new SumAggregation<>(DataTypes.BYTE, DataTypes.LONG, add, subsctact)); mod.register(new SumAggregation<>(DataTypes.SHORT, DataTypes.LONG, add, subsctact)); mod.register(new SumAggregation<>(DataTypes.INTEGER, DataTypes.LONG, add, subsctact)); mod.register(new SumAggregation<>(DataTypes.LONG, add, subsctact)); }

Target:
public static void register(AggregationImplModule mod) { final BinaryOperator<Long> add = Math::addExact; final BinaryOperator<Long> substract = Math::subtractExact; mod.register(new SumAggregation<Float>(DataTypes.FLOAT, (n1, n2) -> n1 + n2, (n1, n2) -> n1 - n2)); mod.register(new SumAggregation<Double>(DataTypes.DOUBLE, (n1, n2) -> n1 + n2, (n1, n2) -> n1 - n2)); mod.register(new SumAggregation<>(DataTypes.BYTE, DataTypes.LONG, add, substract)); mod.register(new SumAggregation<>(DataTypes.SHORT, DataTypes.LONG, add, substract)); mod.register(new SumAggregation<>(DataTypes.INTEGER, DataTypes.LONG, add, substract)); mod.register(new SumAggregation<>(DataTypes.LONG, add, substract)); }
Source:
public void addPartition(String partitionIdStr) { PartitionId partitionId = partitionIdMap.get(partitionIdStr); if (partitionId != null) { if (assignedPartitionIds.add(partitionId)) { for (VirtualReplicatorClusterListener listener : listeners) { listener.onPartitionAdded(partitionId); } logger.info("Partition is added to current VCR: {}. Assigned partitions: {}", partitionIdStr, vcrInstanceName, assignedPartitionIds); } else { logger.info("Partition exists on current VCR: {}", partitionIdStr, vcrInstanceName); } } else { logger.error("Partition not in clusterMap on add.", partitionIdStr); metrics.partitionIdNotInClusterMapOnAdd.inc(); } }

Target:
public void addPartition(String partitionIdStr) { PartitionId partitionId = partitionIdMap.get(partitionIdStr); if (partitionId != null) { if (assignedPartitionIds.add(partitionId)) { for (VirtualReplicatorClusterListener listener : listeners) { listener.onPartitionAdded(partitionId); } logger.info("Partition is added to current VCR: {}. Number of assigned partitions: {}", partitionIdStr, vcrInstanceName, assignedPartitionIds.size()); logger.debug("Assigned Partitions: {}", assignedPartitionIds); } else { logger.info("Partition exists on current VCR: {}", partitionIdStr, vcrInstanceName); } } else { logger.error("Partition not in clusterMap on add.", partitionIdStr); metrics.partitionIdNotInClusterMapOnAdd.inc(); } }
Source:
boolean match(String algorithm) { String normalizedName = algorithm.replaceAll("-", "").toLowerCase(Locale.ROOT); return normalizedName.contains(name().toLowerCase(Locale.ROOT)); }

Target:
boolean match(String algorithm) { return "DSA".equals(algorithm); }
Source:
public static boolean confirmHardReset(Shell shell, final Repository repo) { String question = UIText.ResetTargetSelectionDialog_ResetConfirmQuestion; ILaunchConfiguration launch = LaunchFinder .getRunningLaunchConfiguration(Collections.singleton(repo), null); if (launch != null) { question = MessageFormat.format(question, "\n\n" + MessageFormat.format( UIText.LaunchFinder_RunningLaunchMessage, launch.getName())); } else { question = MessageFormat.format(question, ""); } MessageDialog messageDialog = new MessageDialog(shell, UIText.ResetTargetSelectionDialog_ResetQuestion, null, question, MessageDialog.QUESTION, 0, UIText.CommandConfirmationHardResetDialog_resetButtonLabel, IDialogConstants.NO_LABEL); return messageDialog.open() == 0; }

Target:
public static boolean confirmHardReset(Shell shell, final Repository repo) { String question = UIText.ResetTargetSelectionDialog_ResetConfirmQuestion; ILaunchConfiguration launch = LaunchFinder .getRunningLaunchConfiguration(Collections.singleton(repo), null); if (launch != null) { question = MessageFormat.format(question, "\n\n" + MessageFormat.format( UIText.LaunchFinder_RunningLaunchMessage, launch.getName())); } else { question = MessageFormat.format(question, ""); } MessageDialog messageDialog = new MessageDialog(shell, UIText.ResetTargetSelectionDialog_ResetQuestion, null, question, MessageDialog.QUESTION, 0, UIText.CommandConfirmationHardResetDialog_resetButtonLabel, IDialogConstants.NO_LABEL); return messageDialog.open() == Window.OK; }
Source:
public void visitFormatSpecifier(FormatSpecifier formatSpecifier) { scan(formatSpecifier.columnToken()); scan(formatSpecifier.formatExpressions()); }

Target:
public void visitFormatSpecifier(FormatSpecifier formatSpecifier) { scan(formatSpecifier.formatExpressions()); }
Source:
private StudentProfileAttributes extractProfileData() { StudentProfileAttributes editedProfile = StudentProfileAttributes.builder().build(); editedProfile.googleId = account.googleId; editedProfile.shortName = getRequestParamValue(Const.ParamsNames.STUDENT_SHORT_NAME); editedProfile.email = getRequestParamValue(Const.ParamsNames.STUDENT_PROFILE_EMAIL); editedProfile.institute = getRequestParamValue(Const.ParamsNames.STUDENT_PROFILE_INSTITUTION); editedProfile.nationality = getRequestParamValue(Const.ParamsNames.STUDENT_NATIONALITY); if ("".equals(editedProfile.nationality)) { editedProfile.nationality = getRequestParamValue("existingNationality"); } String value = Const.ParamsNames.STUDENT_GENDER; if ("male".equals(value) || "female".equals(value) || "other".equals(value)) { editedProfile.gender = Gender.valueOf(getRequestParamValue(Const.ParamsNames.STUDENT_GENDER)); } else { editedProfile.gender = Gender.none; } editedProfile.moreInfo = getRequestParamValue(Const.ParamsNames.STUDENT_PROFILE_MOREINFO); editedProfile.pictureKey = ""; preprocessParameters(editedProfile); validatePostParameters(editedProfile); return editedProfile; }

Target:
private StudentProfileAttributes extractProfileData() { StudentProfileAttributes editedProfile = StudentProfileAttributes.builder(account.googleId).build(); editedProfile.shortName = getRequestParamValue(Const.ParamsNames.STUDENT_SHORT_NAME); editedProfile.email = getRequestParamValue(Const.ParamsNames.STUDENT_PROFILE_EMAIL); editedProfile.institute = getRequestParamValue(Const.ParamsNames.STUDENT_PROFILE_INSTITUTION); editedProfile.nationality = getRequestParamValue(Const.ParamsNames.STUDENT_NATIONALITY); if ("".equals(editedProfile.nationality)) { editedProfile.nationality = getRequestParamValue("existingNationality"); } editedProfile.gender = Gender.parseToGender(getRequestParamValue(Const.ParamsNames.STUDENT_GENDER)); editedProfile.moreInfo = getRequestParamValue(Const.ParamsNames.STUDENT_PROFILE_MOREINFO); editedProfile.pictureKey = ""; preprocessParameters(editedProfile); validatePostParameters(editedProfile); return editedProfile; }
Source:
public void run(StreamGraphBuilder app) { try { StreamGraph streamGraph = new StreamGraphImpl(this, config); app.init(streamGraph, config); ExecutionPlanner planner = new ExecutionPlanner(config); ProcessorGraph processorGraph = planner.plan(streamGraph); processorGraph.getProcessors().forEach(processor -> { Config processorConfig = processor.generateConfig(); log.info("Starting processor with config {}", processor.getId(), config); JobRunner runner = new JobRunner(processorConfig); runner.run(true); }); } catch (Throwable t) { throw new SamzaException("Fail to run application", t); } }

Target:
public void run(StreamGraphBuilder app) { try { StreamGraph streamGraph = new StreamGraphImpl(this, config); app.init(streamGraph, config); ExecutionPlanner planner = new ExecutionPlanner(config); ProcessorGraph processorGraph = planner.plan(streamGraph); processorGraph.getProcessorNodes().forEach(processor -> { Config processorConfig = processor.generateConfig(); log.info("Starting processor with config {}", processor.getId(), config); JobRunner runner = new JobRunner(processorConfig); runner.run(true); }); } catch (Throwable t) { throw new SamzaException("Fail to run application", t); } }
Source:
public static boolean install(List<ConnectorDescriptor> descriptors, IRunnableContext context) { try { IRunnableWithProgress runner = createInstallJob(descriptors); context.run(true, true, runner); new DiscoveryFeedbackJob(descriptors).schedule(); recordInstalled(descriptors); } catch (InvocationTargetException e) { IStatus status = new Status(IStatus.ERROR, DiscoveryUi.ID_PLUGIN, NLS.bind( Messages.ConnectorDiscoveryWizard_installProblems, new Object[] { e.getCause().getMessage() }), e.getCause()); StatusManager.getManager().handle(status, StatusManager.SHOW | StatusManager.BLOCK | StatusManager.LOG); return false; } catch (InterruptedException e) { return false; } return true; }

Target:
public static boolean install(List<ConnectorDescriptor> descriptors, IRunnableContext context) { try { IRunnableWithProgress runner = createInstallJob(descriptors); context.run(true, true, runner); new DiscoveryFeedbackJob(descriptors).schedule(); recordInstalled(descriptors); } catch (InvocationTargetException e) { IStatus status = new Status(IStatus.ERROR, JBossCentralActivator.PLUGIN_ID, NLS.bind( Messages.ConnectorDiscoveryWizard_installProblems, new Object[] { e.getCause().getMessage() }), e.getCause()); StatusManager.getManager().handle(status, StatusManager.SHOW | StatusManager.BLOCK | StatusManager.LOG); return false; } catch (InterruptedException e) { return false; } return true; }
Source:
private void waitForFutureCompletion( GroupByQuery query, ListenableFuture<?> future, IncrementalIndex<?> closeOnFailure ) { try { queryWatcher.registerQuery(query, future); final long timeout = QueryContexts.getTimeout(query); if (QueryContexts.isNoTimeout(timeout)) { future.get(); } else { future.get(timeout, TimeUnit.MILLISECONDS); } } catch (InterruptedException e) { log.warn(e, "Query interrupted, cancelling pending results, query id [%s]", query.getId()); future.cancel(true); closeOnFailure.close(); throw new QueryInterruptedException(e); } catch (CancellationException e) { closeOnFailure.close(); throw new QueryInterruptedException(e); } catch (TimeoutException e) { closeOnFailure.close(); log.info("Query timeout, cancelling pending results for query id [%s]", query.getId()); future.cancel(true); throw new QueryInterruptedException(e); } catch (ExecutionException e) { closeOnFailure.close(); throw Throwables.propagate(e.getCause()); } }

Target:
private void waitForFutureCompletion( GroupByQuery query, ListenableFuture<?> future, IncrementalIndex<?> closeOnFailure ) { try { queryWatcher.registerQuery(query, future); if (QueryContexts.hasTimeout(query)) { future.get(QueryContexts.getTimeout(query), TimeUnit.MILLISECONDS); } else { future.get(); } } catch (InterruptedException e) { log.warn(e, "Query interrupted, cancelling pending results, query id [%s]", query.getId()); future.cancel(true); closeOnFailure.close(); throw new QueryInterruptedException(e); } catch (CancellationException e) { closeOnFailure.close(); throw new QueryInterruptedException(e); } catch (TimeoutException e) { closeOnFailure.close(); log.info("Query timeout, cancelling pending results for query id [%s]", query.getId()); future.cancel(true); throw new QueryInterruptedException(e); } catch (ExecutionException e) { closeOnFailure.close(); throw Throwables.propagate(e.getCause()); } }
Source:
public static void addMembers(AccountGroup.UUID groupUUID, Set<String> members, final AsyncCallback<NativeList<MemberInfo>> cb) { if (members.size() == 1) { addMember(groupUUID, members.iterator().next(), new AsyncCallback<MemberInfo>() { @Override public void onSuccess(MemberInfo result) { cb.onSuccess(NativeList.of(result)); } @Override public void onFailure(Throwable caught) { cb.onFailure(caught); } }); } else { MemberInput input = MemberInput.create(); for (String member : members) { input.add_member(member); } new RestApi(membersBase(groupUUID) + ".add").data(input).put(cb); } }

Target:
public static void addMembers(AccountGroup.UUID groupUUID, Set<String> members, final AsyncCallback<NativeList<MemberInfo>> cb) { if (members.size() == 1) { addMember(groupUUID, members.iterator().next(), new AsyncCallback<MemberInfo>() { @Override public void onSuccess(MemberInfo result) { cb.onSuccess(NativeList.of(result)); } @Override public void onFailure(Throwable caught) { cb.onFailure(caught); } }); } else { MemberInput input = MemberInput.create(); for (String member : members) { input.add_member(member); } new RestApi(membersBase(groupUUID) + ".add").data(input).post(cb); } }
Source:
private Predicate<Diff> resourceAttachmentMoveDiff(final String name) { return new Predicate<Diff>() { public boolean apply(Diff input) { if (input.getMatch().toString().contains(name)) { return true; } else { return false; } } }; }

Target:
private Predicate<Diff> resourceAttachmentMoveDiff(final String name) { return new Predicate<Diff>() { public boolean apply(Diff input) { if (input instanceof ResourceAttachmentChange && DifferenceKind.MOVE.equals(input.getKind())) { final ResourceAttachmentChange change = (ResourceAttachmentChange) input; final EObject left = change.getMatch().getLeft(); if (left instanceof Diagram) { return name.equals(((Diagram) left).getName()); } } return false; } }; }
Source:
public void removeListener() { if (!stereotypeList.isEmpty()) { for (Stereotype stereotype : stereotypeList) { Node compartment = helper.getStereotypeCompartment(hostView, stereotype); if (null != compartment && null != stereotype) { getDiagramEventBroker().removeNotificationListener(compartment, this); EList<Property> properties = stereotype.allAttributes(); for (Property property : properties) { getDiagramEventBroker().removeNotificationListener(helper.getStereotypeProperty(hostView, stereotype, property), this); } } } } }

Target:
public void removeListener() { if (!stereotypeList.isEmpty()) { for (Stereotype stereotype : stereotypeList) { Node compartment = helper.getStereotypeCompartment(hostView, stereotype); if (null != compartment && null != stereotype) { unsubscribe(compartment); EList<Property> properties = stereotype.allAttributes(); for (Property property : properties) { unsubscribe(helper.getStereotypeProperty(hostView, stereotype, property)); } } } } }
Source:
public void testBlobIdFlag() throws Exception { boolean[] isEncryptedValues = {true, false}; if (version >= BLOB_ID_V3) { for (BlobIdType type : BlobIdType.values()) { for (boolean isEncrypted : isEncryptedValues) { BlobId blobId = new BlobId(version, type, referenceDatacenterId, referenceAccountId, referenceContainerId, referencePartitionId, isEncrypted, null); BlobId blobIdSerDed = new BlobId(new DataInputStream(new ByteArrayInputStream(blobId.toBytes())), referenceClusterMap); assertEquals("The type should match the original's type", type, blobIdSerDed.getType()); assertEquals("The isEncrypted should match the original", version == BLOB_ID_V3 ? false : isEncrypted, BlobId.isEncrypted(blobId.getID())); } } } if (version >= BLOB_ID_V5) { for (BlobDataType dataType : BlobDataType.values()) { BlobId blobId = new BlobId(version, BlobIdType.NATIVE, referenceDatacenterId, referenceAccountId, referenceContainerId, referencePartitionId, false, dataType); BlobId blobIdSerDed = new BlobId(new DataInputStream(new ByteArrayInputStream(blobId.toBytes())), referenceClusterMap); assertEquals("The data type should match the original's", dataType, blobIdSerDed.getBlobDataType()); } } }

Target:
public void testBlobIdFlag() throws Exception { boolean[] isEncryptedValues = {true, false}; if (version >= BLOB_ID_V3) { for (BlobIdType type : BlobIdType.values()) { for (boolean isEncrypted : isEncryptedValues) { BlobId blobId = new BlobId(version, type, referenceDatacenterId, referenceAccountId, referenceContainerId, referencePartitionId, isEncrypted, referenceDataType); BlobId blobIdSerDed = new BlobId(new DataInputStream(new ByteArrayInputStream(blobId.toBytes())), referenceClusterMap); assertEquals("The type should match the original's type", type, blobIdSerDed.getType()); assertEquals("The isEncrypted should match the original", version == BLOB_ID_V3 ? false : isEncrypted, BlobId.isEncrypted(blobId.getID())); } } } if (version >= BLOB_ID_V5) { for (BlobDataType dataType : BlobDataType.values()) { BlobId blobId = new BlobId(version, BlobIdType.NATIVE, referenceDatacenterId, referenceAccountId, referenceContainerId, referencePartitionId, false, dataType); BlobId blobIdSerDed = new BlobId(new DataInputStream(new ByteArrayInputStream(blobId.toBytes())), referenceClusterMap); assertEquals("The data type should match the original's", dataType, blobIdSerDed.getBlobDataType()); } } }
Source:
protected void assertExceptionIsThrown(String sql, String expectedMsgPattern) { final SqlNode sqlNode; final SqlParserUtil.StringAndPos sap = SqlParserUtil.findPos(sql); try { sqlNode = SqlParserFactory.parse(sap.sql); } catch (Throwable e) { checkParseEx(e, expectedMsgPattern, sap.sql); return; } Throwable thrown = null; try { m_validator.validate(sqlNode); } catch (Throwable ex) { thrown = ex; } SqlTests.checkEx(thrown, expectedMsgPattern, sap, SqlTests.Stage.VALIDATE); }

Target:
protected void assertExceptionIsThrown(String sql, String expectedMsgPattern) { final SqlNode sqlNode; final SqlParserUtil.StringAndPos sap = SqlParserUtil.findPos(sql); try { sqlNode = SqlParserFactory.parse(sap.sql); } catch (Throwable e) { throw mapException(e, expectedMsgPattern, sap.sql); } Throwable thrown = null; try { m_validator.validate(sqlNode); } catch (Throwable ex) { thrown = ex; } SqlTests.checkEx(thrown, expectedMsgPattern, sap, SqlTests.Stage.VALIDATE); }
Source:
public synchronized Rewriter apply(Module module) { TermContext initializingContext = TermContext.builder(new GlobalContext(fs, javaOptions, globalOptions, krunOptions, kem, smtOptions, hookProvider, files, Stage.REWRITING)) .freshCounter(0).build(); Definition evaluatedDef = initializeDefinition.invoke(module, kem, initializingContext.global()); GlobalContext rewritingContext = new GlobalContext(fs, javaOptions, globalOptions, krunOptions, kem, smtOptions, hookProvider, files, Stage.REWRITING); rewritingContext.setDefinition(evaluatedDef); return new SymbolicRewriterGlue(module, evaluatedDef, kompileOptions, javaOptions, initializingContext.getCounterValue(), rewritingContext, kem); }

Target:
public synchronized Rewriter apply(Module module) { TermContext initializingContext = TermContext.builder(new GlobalContext(fs, javaOptions, globalOptions, krunOptions, kem, smtOptions, hookProvider, files, Stage.INITIALIZING)) .freshCounter(0).build(); Definition evaluatedDef = initializeDefinition.invoke(module, kem, initializingContext.global()); GlobalContext rewritingContext = new GlobalContext(fs, javaOptions, globalOptions, krunOptions, kem, smtOptions, hookProvider, files, Stage.REWRITING); rewritingContext.setDefinition(evaluatedDef); return new SymbolicRewriterGlue(module, evaluatedDef, kompileOptions, javaOptions, initializingContext.getCounterValue(), rewritingContext, kem); }
Source:
public static ZonedDateTime parse(String dateString) { int n = 0; for (DateTimeFormatter df : DATE_TIME_FORMATTERS) { try { return toZonedDateTime(df.parse(dateString)); } catch (DateTimeParseException dte) { n++; continue; } } if (IS_NUMERIC_P.matcher(dateString) .matches()) { long ldate = Long.parseLong(dateString); return Instant.ofEpochMilli(ldate) .atZone(UTC_ZONE_ID); } return null; }

Target:
public static ZonedDateTime parse(String dateString) { for (DateTimeFormatter df : DATE_TIME_FORMATTERS) { try { return toZonedDateTime(df.parse(dateString)); } catch (DateTimeParseException dte) { continue; } } if (IS_NUMERIC_P.matcher(dateString) .matches()) { long ldate = Long.parseLong(dateString); return Instant.ofEpochMilli(ldate) .atZone(UTC_ZONE_ID); } return null; }
Source:
public void testTimeout() { EvaluationException e = assertThrows(EvaluationException.class, () -> simpleEval("for(i=0;i<256;i++){for(j=0;j<256;j++){for(k=0;k<256;k++){for(l=0;l<256;l++){ln(pi)}}}}"), "Loop was not stopped."); assertTrue(e.getMessage().contains("Calculations exceeded time limit")); }

Target:
public void testTimeout() { ExpressionTimeoutException e = assertThrows(ExpressionTimeoutException.class, () -> simpleEval("for(i=0;i<256;i++){for(j=0;j<256;j++){for(k=0;k<256;k++){for(l=0;l<256;l++){ln(pi)}}}}"), "Loop was not stopped."); assertTrue(e.getMessage().contains("Calculations exceeded time limit")); }
Source:
private Predicate<String> createPredicate() { if(includeLists != null) { return e -> includeLists.contains(e); } else if (excludeLists != null) { return e -> !excludeLists.contains(e); } else { return e -> true; } }

Target:
private Predicate<String> createPredicate() { if (includeLists.isPresent()) { return e -> includeLists.get().contains(e); } else if (excludeLists.isPresent()) { return e -> !excludeLists.get().contains(e); } else { return e -> true; } }