auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public long consumeUntil(BufferedDataOutputStreamPlus writer, long len) throws IOException { long copied = 0; while (copied < len) { int position = buffer.position(); int remaining = buffer.remaining(); if (remaining == 0) { try { reBuffer(); } catch (EOFException e) { throw new EOFException("EOF after " + copied + " bytes out of " + len); } position = buffer.position(); remaining = buffer.remaining(); if (remaining == 0) return copied == 0 ? -1 : copied; } int toCopy = (int) Math.min(len - copied, remaining); ByteBuffer dup = buffer.duplicate(); if (toCopy < remaining) dup.limit(dup.position() + toCopy); int result = writer.applyToChannel(c -> c.write(dup)); buffer.position(position + result); copied += result; } return copied; }

Target:
public long consumeUntil(BufferedDataOutputStreamPlus writer, long len) throws IOException { long copied = 0; while (copied < len) { if (buffer.remaining() == 0) { try { reBuffer(); } catch (EOFException e) { throw new EOFException("EOF after " + copied + " bytes out of " + len); } if (buffer.remaining() == 0 && copied < len) throw new AssertionError("reBuffer() failed to return data"); } int originalLimit = buffer.limit(); int toCopy = (int) Math.min(len - copied, buffer.remaining()); buffer.limit(buffer.position() + toCopy); int written = writer.applyToChannel(c -> c.write(buffer)); buffer.limit(originalLimit); copied += written; } return copied; }
Source:
public DslComponent(Scope scope, String componentId) { this.componentId = componentId; this.scope = scope; }

Target:
public DslComponent(Scope scope, String componentId) { Preconditions.checkNotNull(scope, "scope"); this.componentId = componentId; this.scope = scope; }
Source:
private static Duration getFsTimestampResolution(Path file) { Path dir = Files.isDirectory(file) ? file : file.getParent(); if (!dir.toFile().canWrite()) { return FALLBACK_TIMESTAMP_RESOLUTION; } FileStore s; try { s = Files.getFileStore(dir); FileStoreAttributeCache c = attributeCache.get(s); if (c != null) { return c.getFsTimestampResolution(); } Lock lock = locks.computeIfAbsent(s, l -> new ReentrantLock()); if (lock.tryLock()) { try { CompletableFuture<FileStoreAttributeCache> f = CompletableFuture .supplyAsync(() -> new FileStoreAttributeCache( s, dir)); f.exceptionally(e -> { Throwable cause = e.getCause(); if (!(cause instanceof NoSuchFileException)) { LOG.error(e.getLocalizedMessage(), e); } return null; }); f.thenAccept(cache -> { if (cache != null) { attributeCache.put(s, cache); } }); if (background.get()) { if (LOG.isDebugEnabled()) { f.thenAccept( cache -> LOG.debug(cache.toString())); } } else { FileStoreAttributeCache cache = f.get(); if (LOG.isDebugEnabled()) { LOG.debug(cache.toString()); } return cache.getFsTimestampResolution(); } } finally { lock.unlock(); locks.remove(s); } } return FALLBACK_TIMESTAMP_RESOLUTION; } catch (Exception e) { LOG.error(e.getLocalizedMessage(), e); return FALLBACK_TIMESTAMP_RESOLUTION; } }

Target:
private static Duration getFsTimestampResolution(Path file) { Path dir = Files.isDirectory(file) ? file : file.getParent(); if (!dir.toFile().canWrite()) { return FALLBACK_TIMESTAMP_RESOLUTION; } try { FileStore s = Files.getFileStore(dir); FileStoreAttributeCache c = attributeCache.get(s); if (c != null) { return c.getFsTimestampResolution(); } Lock lock = locks.computeIfAbsent(s, l -> new ReentrantLock()); CompletableFuture<Optional<Duration>> f = CompletableFuture .supplyAsync(() -> { if (!lock.tryLock()) { return Optional.empty(); } Optional<Duration> resolution; try { resolution = measureTimestampResolution(s, dir); if (resolution.isPresent()) { FileStoreAttributeCache cache = new FileStoreAttributeCache( resolution.get()); attributeCache.put(s, cache); if (LOG.isDebugEnabled()) { LOG.debug(cache.toString()); } } } finally { lock.unlock(); } return resolution; }); if (!background.get()) { Optional<Duration> d = f.get(); if (d.isPresent()) { return d.get(); } } } catch (IOException | InterruptedException | ExecutionException e) { LOG.error(e.getMessage(), e); } return FALLBACK_TIMESTAMP_RESOLUTION; }
Source:
private void addHeaderIfRequired(HttpServletResponse response) { Collection<String> cookies = response.getHeaders("Set-Cookie"); for( String cookie : cookies) { if(cookie.contains(DEFAULT_SESSION_ID_NAME)){ response.addHeader("Cache-Control", "no-cache"); return; } } }

Target:
private void addHeaderIfRequired(HttpServletResponse response) { boolean cacheControlHeaderNeeded = false; Collection<String> cookies = response.getHeaders("Set-Cookie"); for( String cookie : cookies) { if(cookie.contains(sessionIdName)){ cacheControlHeaderNeeded = true; break; } } String location = response.getHeader("Location"); if(location != null && location.contains(sessionIdName.toLowerCase())) { cacheControlHeaderNeeded = true; } if(cacheControlHeaderNeeded) { response.addHeader("Cache-Control", "no-cache"); } }
Source:
private boolean isServerBlocked(TerracottaServer server) { try (Connection connection = tryDiagnosticConnection(server)) { try (Diagnostics diagnostics = fetchDiagnosticEntity(connection)) { return Boolean.parseBoolean(diagnostics.invoke("ConsistencyManager", "isBlocked")); } } catch (Exception e) { e.printStackTrace(); return false; } }

Target:
private boolean isServerBlocked(TerracottaServer server) { try (DiagnosticService diagnosticService = DiagnosticServiceFactory.fetch( InetSocketAddress.createUnresolved(server.getHostName(), server.getTsaPort()), getClass().getSimpleName(), getConnectionTimeout(), getConnectionTimeout(), null, objectMapperFactory)) { return diagnosticService.isBlocked(); } catch (Exception e) { return false; } }
Source:
public void received(Channel channel, Object message) throws RemotingException { channel.setAttribute(KEY_READ_TIMESTAMP, System.currentTimeMillis()); final ExchangeChannel exchangeChannel = HeaderExchangeChannel.getOrAddChannel(channel); try { if (message instanceof Request) { Request request = (Request) message; if (request.isEvent()) { handlerEvent(channel, request); } else { if (request.isTwoWay()) { handleRequest(exchangeChannel, request); } else { handler.received(exchangeChannel, request.getData()); } } } else if (message instanceof Response) { handleResponse(channel, (Response) message); } else if (message instanceof String) { if (isClientSide(channel)) { Exception e = new Exception("Dubbo client can not supported string message: " + message + " in channel: " + channel + ", url: " + channel.getUrl()); logger.error(e.getMessage(), e); } else { if (TelnetHandlerAdapter.isEnableTelnet()){ String echo = handler.telnet(channel, (String) message); if (echo != null && echo.length() > 0) { channel.send(echo); } }else{ channel.send("telnet disabled"); channel.close(); } } } else { handler.received(exchangeChannel, message); } } finally { HeaderExchangeChannel.removeChannelIfDisconnected(channel); } }

Target:
public void received(Channel channel, Object message) throws RemotingException { channel.setAttribute(KEY_READ_TIMESTAMP, System.currentTimeMillis()); final ExchangeChannel exchangeChannel = HeaderExchangeChannel.getOrAddChannel(channel); try { if (message instanceof Request) { Request request = (Request) message; if (request.isEvent()) { handlerEvent(channel, request); } else { if (request.isTwoWay()) { handleRequest(exchangeChannel, request); } else { handler.received(exchangeChannel, request.getData()); } } } else if (message instanceof Response) { handleResponse(channel, (Response) message); } else if (message instanceof String) { if (isClientSide(channel)) { Exception e = new Exception("Dubbo client can not supported string message: " + message + " in channel: " + channel + ", url: " + channel.getUrl()); logger.error(e.getMessage(), e); } else { boolean enableTelnet = channel.getUrl().getParameter(Constants.TELNET_ENABLED, true); if (enableTelnet) { String echo = handler.telnet(channel, (String) message); if (StringUtils.isNotEmpty(echo)) { channel.send(echo); } } else { channel.send("telnet disabled\r\n"); } } } else { handler.received(exchangeChannel, message); } } finally { HeaderExchangeChannel.removeChannelIfDisconnected(channel); } }
Source:
public void init(Map<String, String> conf) { if (conf != null) { stormApiRootUrl = conf.get(TopologyLayoutConstants.STORM_API_ROOT_URL_KEY); } client = ClientBuilder.newClient(new ClientConfig()); }

Target:
public void init(Map<String, String> conf) throws ConfigException { if (conf != null) { stormApiRootUrl = conf.get(TopologyLayoutConstants.STORM_API_ROOT_URL_KEY); } client = ClientBuilder.newClient(new ClientConfig()); }
Source:
public byte[] encode(LwM2mNode node, ContentFormat format, LwM2mPath path, LwM2mModel model) throws CodecException { Validate.notNull(node); if (format == null) { throw new CodecException("Content format is mandatory. [%s]", path); } LOG.debug("Encoding node for path and format {}", node, path, format); byte[] encoded; switch (format.getCode()) { case ContentFormat.TLV_CODE: case ContentFormat.OLD_TLV_CODE: encoded = LwM2mNodeTlvEncoder.encode(node, path, model, converter); break; case ContentFormat.TEXT_CODE: encoded = LwM2mNodeTextEncoder.encode(node, path, model, converter); break; case ContentFormat.OPAQUE_CODE: encoded = LwM2mNodeOpaqueEncoder.encode(node, path, model, converter); break; case ContentFormat.JSON_CODE: case ContentFormat.OLD_JSON_CODE: encoded = LwM2mNodeJsonEncoder.encode(node, path, model, converter); break; case ContentFormat.SENML_JSON_CODE: encoded = LwM2mNodeSenMLJsonEncoder.encodeToJson(node, path, model, converter); break; default: throw new CodecException("Cannot encode %s:%s with format %s.", path, node, format); } LOG.trace("Encoded node {}: {}", node, encoded); return encoded; }

Target:
public byte[] encode(LwM2mNode node, ContentFormat format, LwM2mPath path, LwM2mModel model) throws CodecException { Validate.notNull(node); if (format == null) { throw new CodecException("Content format is mandatory. [%s]", path); } LOG.debug("Encoding node for path and format {}", node, path, format); byte[] encoded; switch (format.getCode()) { case ContentFormat.TLV_CODE: case ContentFormat.OLD_TLV_CODE: encoded = LwM2mNodeTlvEncoder.encode(node, path, model, converter); break; case ContentFormat.TEXT_CODE: encoded = LwM2mNodeTextEncoder.encode(node, path, model, converter); break; case ContentFormat.OPAQUE_CODE: encoded = LwM2mNodeOpaqueEncoder.encode(node, path, model, converter); break; case ContentFormat.JSON_CODE: case ContentFormat.OLD_JSON_CODE: encoded = LwM2mNodeJsonEncoder.encode(node, path, model, converter); break; default: throw new CodecException("Cannot encode %s:%s with format %s.", path, node, format); } LOG.trace("Encoded node {}: {}", node, encoded); return encoded; }
Source:
public void after() { underTest.stop(); db.executeUpdateSql("delete from metrics"); db.commit(); }

Target:
public void after() { underTest.stop(); }
Source:
public int read(char[] cbuf, int off, int len) throws IOException { int i = 0; try { for (i = 0; i < len; i++) { byte firstByte = input.readByte(); char c = Bits.readUtf8Char(input, firstByte); cbuf[i] = c; } } catch (EOFException e) { if (i == 0) { return -1; } } return i; }

Target:
public int read(char[] cbuf, int off, int len) throws IOException { if (off < 0 || (off + len) > cbuf.length) { throw new IndexOutOfBoundsException(); } int i = 0; try { for (i = 0; i < len; i++) { byte firstByte = input.readByte(); char c = Bits.readUtf8Char(input, firstByte); cbuf[off + i] = c; } } catch (EOFException e) { if (i == 0) { return -1; } } return i; }
Source:
public void test_number_of_keywords() { assertThat(Identifiers.KEYWORDS.size(), is(96)); }

Target:
public void test_number_of_keywords() { assertThat(Identifiers.KEYWORDS.size(), is(95)); }
Source:
public void run() { try (Jedis j = pool.getResource()) { Set<byte[]> endpoints_expired = j.zrangeByScore(EXP_EP, Double.NEGATIVE_INFINITY, System.currentTimeMillis()); for (byte[] endpoint : endpoints_expired) { Registration r = deserializeReg(j.get(toEndpointKey(endpoint))); if (!r.isAlive(gracePeriod)) { Deregistration dereg = removeRegistration(j, r.getId(), true); if (dereg != null) expirationListener.registrationExpired(dereg.getRegistration(), dereg.getObservations()); } } } catch (Exception e) { LOG.warn("Unexpected Exception while registration cleaning", e); } }

Target:
public void run() { try (Jedis j = pool.getResource()) { Set<byte[]> endpointsExpired = j.zrangeByScore(EXP_EP, Double.NEGATIVE_INFINITY, System.currentTimeMillis(), 0, cleanLimit); for (byte[] endpoint : endpointsExpired) { Registration r = deserializeReg(j.get(toEndpointKey(endpoint))); if (!r.isAlive(gracePeriod)) { Deregistration dereg = removeRegistration(j, r.getId(), true); if (dereg != null) expirationListener.registrationExpired(dereg.getRegistration(), dereg.getObservations()); } } } catch (Exception e) { LOG.warn("Unexpected Exception while registration cleaning", e); } }
Source:
public PhoneBuilder setWhitelistedCountries( @NonNull List<String> whitelistedCountries) { if (getParams().containsKey(ExtraConstants.BLACKLISTED_COUNTRIES)) { throw new IllegalStateException( "You can either whitelist or blacklist country codes for phone " + "authentication."); } String message = "Invalid argument: The whitelist is %s. For this case, " + "don't use this method."; Preconditions.checkNotNull(whitelistedCountries, String.format(message, "null")); Preconditions.checkArgument(!whitelistedCountries.isEmpty(), String.format(message, "empty")); addCountriesToBundle(whitelistedCountries, ExtraConstants.WHITELISTED_COUNTRIES); return this; }

Target:
public PhoneBuilder setWhitelistedCountries( @NonNull List<String> whitelistedCountries) { if (getParams().containsKey(ExtraConstants.BLACKLISTED_COUNTRIES)) { throw new IllegalStateException( "You can either whitelist or blacklist country codes for phone " + "authentication."); } String message = "Invalid argument: Only non-%s whitelists are valid. " + "To specify no whitelist, do not call this method."; Preconditions.checkNotNull(whitelistedCountries, String.format(message, "null")); Preconditions.checkArgument(!whitelistedCountries.isEmpty(), String.format(message, "empty")); addCountriesToBundle(whitelistedCountries, ExtraConstants.WHITELISTED_COUNTRIES); return this; }
Source:
public void testValidateAllClustersLevel() { storagePoolWithVersionHigherThanCluster(); List<VDSGroup> clusterList = createClusterList(); VDSGroup secondCluster = new VDSGroup(); secondCluster.setcompatibility_version(VERSION_1_2); secondCluster.setname("secondCluster"); clusterList.add(secondCluster); VDSGroup thirdCluster = new VDSGroup(); thirdCluster.setcompatibility_version(VERSION_1_1); thirdCluster.setname("thirdCluster"); clusterList.add(thirdCluster); when(vdsDao.getAllForStoragePool(any(Guid.class))).thenReturn(clusterList); assertFalse(cmd.checkAllClustersLevel()); List<String> messages = cmd.getReturnValue().getCanDoActionMessages(); assertTrue(messages.contains(VdcBllMessages.ERROR_CANNOT_UPDATE_STORAGE_POOL_COMPATIBILITY_VERSION_BIGGER_THAN_CLUSTERS.toString())); assertTrue(messages.get(0).contains("firstCluster")); assertTrue(!messages.get(0).contains("secondCluster")); assertTrue(messages.get(0).contains("thirdCluster")); }

Target:
public void testValidateAllClustersLevel() { storagePoolWithVersionHigherThanCluster(); List<VDSGroup> clusterList = createClusterList(); VDSGroup secondCluster = new VDSGroup(); secondCluster.setcompatibility_version(VERSION_1_2); secondCluster.setname("secondCluster"); clusterList.add(secondCluster); VDSGroup thirdCluster = new VDSGroup(); thirdCluster.setcompatibility_version(VERSION_1_1); thirdCluster.setname("thirdCluster"); clusterList.add(thirdCluster); when(vdsDao.getAllForStoragePool(any(Guid.class))).thenReturn(clusterList); assertFalse(cmd.checkAllClustersLevel()); List<String> messages = cmd.getReturnValue().getCanDoActionMessages(); assertTrue(messages.contains(VdcBllMessages.ERROR_CANNOT_UPDATE_STORAGE_POOL_COMPATIBILITY_VERSION_BIGGER_THAN_CLUSTERS.toString())); assertTrue(messages.get(0).contains("firstCluster")); assertFalse(messages.get(0).contains("secondCluster")); assertTrue(messages.get(0).contains("thirdCluster")); }
Source:
public void serialize() throws Exception { String xml = serializer.serialize(header); System.out.println(xml); XMLAssert.assertXpathExists("/subscriptionHeader/contentUri", xml); XMLAssert.assertXpathExists("/subscriptionHeader/packageHeader", xml); XMLAssert.assertXpathExists("/subscriptionHeader/packageHeader/name", xml); }

Target:
public void serialize() throws Exception { String xml = serializer.serialize(header); XMLAssert.assertXpathExists("/subscriptionHeader/contentUri", xml); XMLAssert.assertXpathExists("/subscriptionHeader/packageHeader", xml); XMLAssert.assertXpathExists("/subscriptionHeader/packageHeader/name", xml); }
Source:
public void recordPublicIpHostname(String publicIpId, String hostnameOrPublicIpAddress) { String old = publicIpIdToHostname.put(publicIpId, hostnameOrPublicIpAddress); if (old!=null && !old.equals(hostnameOrPublicIpAddress)) log.warn("Changing hostname recorded against public IP "+publicIpId+"; from "+old+" to "+hostnameOrPublicIpAddress); }

Target:
public void recordPublicIpHostname(String publicIpId, String hostnameOrPublicIpAddress) { synchronized (publicIpIdToHostname) { String old = publicIpIdToHostname.put(publicIpId, hostnameOrPublicIpAddress); if (old!=null && !old.equals(hostnameOrPublicIpAddress)) log.warn("Changing hostname recorded against public IP "+publicIpId+"; from "+old+" to "+hostnameOrPublicIpAddress); } }
Source:
private boolean stopVms() { boolean allDown = true; for (VM vm : getCachedVmsInPool()) { if (!vm.isDown()) { CommandCoordinatorUtil.executeAsyncCommand( VdcActionType.StopVm, withRootCommandInfo(new StopVmParameters(vm.getId(), StopVmTypeEnum.NORMAL), getActionType()), cloneContextAndDetachFromParent()); allDown = false; } } return allDown; }

Target:
private void stopVms() { allVmsDown = true; for (VM vm : getCachedVmsInPool()) { if (!vm.isDown()) { CommandCoordinatorUtil.executeAsyncCommand( VdcActionType.StopVm, withRootCommandInfo(new StopVmParameters(vm.getId(), StopVmTypeEnum.NORMAL), getActionType()), cloneContextAndDetachFromParent()); allVmsDown = false; } else { removeVm(vm); } } }
Source:
private Mac getHMAC() throws NoSuchAlgorithmException, CloneNotSupportedException, InvalidKeyException { lock.readLock().lock(); try { if (hmac != null && !isKeyExpired()) { return (Mac) hmac.clone(); } } finally { lock.readLock().unlock(); } lock.writeLock().lock(); try { if (hmac == null) { hmac = Mac.getInstance("HmacSHA256"); hmac.init(generateSecretKey()); } if (isKeyExpired()) { hmac.init(generateSecretKey()); } return (Mac) hmac.clone(); } finally { lock.writeLock().unlock(); } }

Target:
private Mac getHMAC() throws NoSuchAlgorithmException, CloneNotSupportedException, InvalidKeyException { lock.readLock().lock(); try { if (hmac != null && !isKeyExpired()) { return (Mac) hmac.clone(); } } finally { lock.readLock().unlock(); } lock.writeLock().lock(); try { if (hmac == null) { hmac = Mac.getInstance("HmacSHA256"); hmac.init(generateSecretKey()); } else if (isKeyExpired()) { hmac.init(generateSecretKey()); } return (Mac) hmac.clone(); } finally { lock.writeLock().unlock(); } }
Source:
public FbStatus(final Condition<Integer> check) { this(check, new Fallback() { @Override public Iterator<Response> route(final RqFallback req) throws IOException { final Response res = new RsWithStatus(req.code()); final String message = res .head().iterator().next().substring("HTTP/1.1 ".length()); return Collections.<Response>singleton( new RsFluent(res) .withHeader("Content-Type", "text/plain") .withBody( String.format( "%s: %s", message, req.throwable().getLocalizedMessage() ) ) ).iterator(); } }); }

Target:
public FbStatus(final Condition<Integer> check) { this(check, new Fallback() { @Override public Iterator<Response> route(final RqFallback req) throws IOException { final Response res = new RsWithStatus(req.code()); return Collections.<Response>singleton( new RsWithType( new RsWithBody( res, String.format( "%s: %s", res.head().iterator().next().split("\\s", 2)[1], req.throwable().getLocalizedMessage() ) ), "text/plain" ) ).iterator(); } }); }
Source:
public void execScript(String id, String serviceName, String script) { String execCreate = null; try { String sOrigAbsolutePath = TEST_SCRIPT_DIRECTORY + "/" + script; String sNewAbsolutePath = "/opt/hawkular-apm-test-local"; String[] commands = new String[]{"bash", "-c", "mkdir " + sNewAbsolutePath + " && " + "cp " + sOrigAbsolutePath + " " + sNewAbsolutePath + " && " + "chmod +x " + sNewAbsolutePath + "/" + script + " && " + sNewAbsolutePath + "/" + script}; execCreate = dockerClient.execCreate(id, commands, DockerClient.ExecCreateParam.attachStdout(), DockerClient.ExecCreateParam.attachStderr()); LogStream logStream = dockerClient.execStart(execCreate); } catch (DockerException | InterruptedException ex) { throw new EnvironmentException("Could not execute command", ex); } }

Target:
public void execScript(String id, String serviceName, String script) { log.info(String.format("Executing script: %s, in container: %s", script, id)); String[] commands = null; try { commands = new String[] { "bash", "-c", scriptExecCommand(script) }; ExecCreateCmdResponse exec = dockerClient.execCreateCmd(id) .withCmd(commands) .withAttachStdout(true) .withAttachStderr(true) .exec(); dockerClient.execStartCmd(exec.getId()) .exec(new ExecStartResultCallback(System.out, System.err)) .awaitCompletion(); } catch (DockerException | InterruptedException ex) { log.severe(String.format("Could not execute command: %s", Arrays.toString(commands))); throw new EnvironmentException("Could not execute command " + Arrays.toString(commands), ex); } }
Source:
public Integer[] transform(InputRow inputRow) { int id; if (IdType.ROWID.equals(idType)) { id = inputRow.getId(); } else { id = _counter.incrementAndGet(); } return new Integer[] { id }; }

Target:
public Integer[] transform(InputRow inputRow) { final int id; if (IdType.ROW_NUMBER == idType) { id = inputRow.getId(); } else { id = _counter.incrementAndGet(); } return new Integer[] { id }; }
Source:
public void setUp() throws Exception { executor = newFixedThreadPool(2); queryCanceller = new QueryCanceller(); query(format("DROP TABLE IF EXISTS %s", TABLE_NAME)); }

Target:
public void setUp() throws Exception { executor = newFixedThreadPool(2); queryCanceller = new QueryCanceller(serverAddress); }
Source:
public AuthenticationException(ADALError code, String details, HttpWebResponse response, Throwable throwable) { this(code, details, throwable); if (null == response) { return; } mServiceStatusCode = response.getStatusCode(); if (null != response.getResponseHeaders()) { mHttpResponseHeaders = response.getResponseHeaders(); } if (null != response.getBody()) { final String responseBodyStr = response.getBody(); try { mResponseBody = new HashMap<>(); final JSONObject jsonObject = new JSONObject(responseBodyStr); final Iterator<?> i = jsonObject.keys(); while (i.hasNext()) { final String key = (String) i.next(); mResponseBody.put(key, jsonObject.getString(key)); } } catch (final JSONException exc) { return; } } }

Target:
public AuthenticationException(ADALError code, String details, HttpWebResponse response, Throwable throwable) { this(code, details, throwable); setHttpResponse(response); }
Source:
private void updateBiosType() { ArchitectureType architecture = getArchitecture().getSelectedItem(); if (architecture == null || architecture.getFamily() != ArchitectureType.x86) { getBiosType().setIsChangeable(false, ConstantsManager.getInstance().getMessages().biosTypeSupportedForX86Only()); } else { getBiosType().updateChangeability(ConfigValues.BiosTypeSupported, getEffectiveVersion()); } if (!getBiosType().getIsChangable()) { getBiosType().setSelectedItem(BiosType.I440FX_SEA_BIOS); } else { if (!getIsNew() && architecture != null && architecture.equals(getEntity().getArchitecture()) && getEffectiveVersion().equals(getEntity().getCompatibilityVersion())) { getBiosType().setSelectedItem(getEntity().getBiosType()); } else if (getEffectiveVersion().greaterOrEquals(Version.v4_4)) { getBiosType().setSelectedItem(BiosType.Q35_SEA_BIOS); } } }

Target:
private void updateBiosType() { ArchitectureType architecture = getArchitecture().getSelectedItem(); if (architecture == null || architecture.getFamily() != ArchitectureType.x86) { getBiosType().setIsChangeable(false, ConstantsManager.getInstance().getMessages().biosTypeSupportedForX86Only()); } else { getBiosType().updateChangeability(ConfigValues.BiosTypeSupported, getEffectiveVersion()); } if (!getBiosType().getIsChangable()) { getBiosType().setSelectedItem(BiosType.I440FX_SEA_BIOS); return; } if (getIsEdit() && architecture.equals(getEntity().getArchitecture()) && getEffectiveVersion().equals(getEntity().getCompatibilityVersion())) { getBiosType().setSelectedItem(getEntity().getBiosType()); return; } if (getEffectiveVersion().greaterOrEquals(Version.v4_4)) { getBiosType().setSelectedItem(BiosType.Q35_SEA_BIOS); } }
Source:
public void configure(Binder binder) { JsonConfigProvider.bind(binder, "druid.pusher", DataSegmentPusherProvider.class); JsonConfigProvider.bind(binder, "druid.pusher.local", LocalDataSegmentPusherConfig.class); JsonConfigProvider.bind(binder, "druid.pusher.s3", S3DataSegmentPusherConfig.class); binder.bind(Configuration.class).toInstance(new Configuration()); JsonConfigProvider.bind(binder, "druid.pusher.hdfs", HdfsDataSegmentPusherConfig.class); JsonConfigProvider.bind(binder, "druid.pusher.cassandra", CassandraDataSegmentConfig.class); binder.bind(DataSegmentPusher.class).toProvider(DataSegmentPusherProvider.class); }

Target:
public void configure(Binder binder) { JsonConfigProvider.bind(binder, "druid.pusher", DataSegmentPusherProvider.class); JsonConfigProvider.bind(binder, "druid.pusher.s3", S3DataSegmentPusherConfig.class); binder.bind(Configuration.class).toInstance(new Configuration()); JsonConfigProvider.bind(binder, "druid.pusher.hdfs", HdfsDataSegmentPusherConfig.class); JsonConfigProvider.bind(binder, "druid.pusher.cassandra", CassandraDataSegmentConfig.class); binder.bind(DataSegmentPusher.class).toProvider(DataSegmentPusherProvider.class); }
Source:
public boolean removeAttributeWithoutCheck(PerunSession sess, Facility facility, AttributeDefinition attribute) throws InternalErrorException, WrongAttributeAssignmentException { getAttributesManagerImpl().checkNamespace(sess, attribute, NS_FACILITY_ATTR); if (getAttributesManagerImpl().isCoreAttribute(sess, attribute)) throw new WrongAttributeAssignmentException(attribute); boolean changed = getAttributesManagerImpl().removeAttribute(sess, facility, attribute); if (changed) { try { getAttributesManagerImpl().changedAttributeHook(sess, facility, new Attribute(attribute)); } catch (WrongAttributeValueException | WrongReferenceAttributeValueException ex) { throw new InternalErrorException(ex); } log.info("{} removed attribute: from facility {}",sess.getLogId(), attribute.getName(), facility.getName()); getPerunBl().getAuditer().log(sess, "{} removed for {}.", new AttributeDefinition(attribute), facility); } return changed; }

Target:
public boolean removeAttributeWithoutCheck(PerunSession sess, Facility facility, AttributeDefinition attribute) throws InternalErrorException, WrongAttributeAssignmentException { getAttributesManagerImpl().checkNamespace(sess, attribute, NS_FACILITY_ATTR); if (getAttributesManagerImpl().isCoreAttribute(sess, attribute)) throw new WrongAttributeAssignmentException(attribute); boolean changed = getAttributesManagerImpl().removeAttribute(sess, facility, attribute); if (changed) { try { getAttributesManagerImpl().changedAttributeHook(sess, facility, new Attribute(attribute)); } catch (WrongAttributeValueException | WrongReferenceAttributeValueException ex) { throw new InternalErrorException(ex); } log.info("{} removed attribute: from facility {}.",sess.getLogId(), attribute.getName(), facility.getId()); getPerunBl().getAuditer().log(sess, "{} removed for {}.", new AttributeDefinition(attribute), facility); } return changed; }
Source:
private String toHQL(CandidateFact fact) throws SemanticException { findDimStorageTables(); if (storageTableToQuery.isEmpty()) { return ""; } String qfmt = getQueryFormat(); Object[] queryTreeStrings = getQueryTreeStrings(fact); if (LOG.isDebugEnabled()) { LOG.debug("qfmt:" + qfmt + " Query strings: " + Arrays.toString(queryTreeStrings)); } String baseQuery = String.format(qfmt, queryTreeStrings); String insertString = ""; ASTNode destTree = qb.getParseInfo().getDestForClause(clauseName); if (destTree != null && ((ASTNode)(destTree.getChild(0))) .getToken().getType() != TOK_TMP_FILE) { insertString = "INSERT OVERWRITE" + HQLParser.getString( qb.getParseInfo().getDestForClause(clauseName)); } return insertString + baseQuery; }

Target:
private String toHQL(CandidateFact fact) throws SemanticException { findDimStorageTables(); String qfmt = getQueryFormat(); Object[] queryTreeStrings = getQueryTreeStrings(fact); if (LOG.isDebugEnabled()) { LOG.debug("qfmt:" + qfmt + " Query strings: " + Arrays.toString(queryTreeStrings)); } String baseQuery = String.format(qfmt, queryTreeStrings); String insertString = ""; ASTNode destTree = qb.getParseInfo().getDestForClause(clauseName); if (destTree != null && ((ASTNode)(destTree.getChild(0))) .getToken().getType() != TOK_TMP_FILE) { insertString = "INSERT OVERWRITE" + HQLParser.getString( qb.getParseInfo().getDestForClause(clauseName)); } return insertString + baseQuery; }
Source:
public void testSamSequenceTruncation(final String filename) { final SamReader reader = SamReaderFactory.makeDefault().open(new File(TEST_DATA_DIR, filename)); for (final SAMSequenceRecord sequence : reader.getFileHeader().getSequenceDictionary().getSequences()) { Assert.assertFalse(sequence.getSequenceName().contains(" "), sequence.getSequenceName()); } for (final SAMRecord rec : reader) { Assert.assertFalse(rec.getReferenceName().contains(" ")); } }

Target:
public void testSamSequenceTruncation(final String filename) { final SamReader reader = SamReaderFactory.makeDefault().open(new File(TEST_DATA_DIR, filename)); for (final SAMSequenceRecord sequence : reader.getFileHeader().getSequenceDictionary().getSequences()) { Assert.assertFalse(sequence.getSequenceName().contains(" "), sequence.getSequenceName()); } for (final SAMRecord rec : reader) { Assert.assertFalse(rec.getReferenceName().contains(" ")); } CloserUtil.close(reader); }
Source:
protected void openDialog(EditableConfiguration config, boolean isCurrent, boolean editBlockFirst) { config.setIsComponent(false); final String configName = getConfigDisplayName(config, isCurrent); final String subTitle = "Editing the " + configName + " configuration"; EditConfigDialog dialog = new EditConfigDialog(shell, title, subTitle, config, false, configurationViewModels, editBlockFirst); if (dialog.open() == Window.OK) { if (dialog.doAsComponent()) { server.saveAsComponent().uncheckedWrite(dialog.getComponent()); } else { if (isCurrent) { if (dialog.calledSwitchConfigOnSaveAs()) { if (dialog.switchConfigOnSaveAs()) { server.setCurrentConfig().uncheckedWrite(dialog.getConfig()); } else { server.saveAs().uncheckedWrite(dialog.getConfig()); } } else { server.setCurrentConfig().uncheckedWrite(dialog.getConfig()); } } else { if (dialog.switchConfigOnSaveAs()) { server.setCurrentConfig().uncheckedWrite(dialog.getConfig()); } else { server.saveAs().uncheckedWrite(dialog.getConfig()); } } } } }

Target:
protected void openDialog(EditableConfiguration config, boolean isCurrent, boolean editBlockFirst) { config.setIsComponent(false); final String configName = getConfigDisplayName(config, isCurrent); final String subTitle = "Editing the " + configName + " configuration"; EditConfigDialog dialog = new EditConfigDialog(shell, title, subTitle, config, false, configurationViewModels, editBlockFirst); if (dialog.open() == Window.OK) { server.ifDoAsComponentChooseSave(config, isCurrent, dialog.doAsComponent(), dialog.switchConfigOnSaveAs(), dialog.calledSwitchConfigOnSaveAs()); } }
Source:
public long getWorkflowIdByWorkflowVersionId(long workflowVersionId) { return ((BigInteger) namedQuery("Workflow.getWorkflowIdByWorkflowVersionId") .setParameter("workflowVersionId", workflowVersionId).getSingleResult()).longValueExact(); }

Target:
public Optional<Long> getWorkflowIdByWorkflowVersionId(long workflowVersionId) { try { BigInteger workflowBigIntId = ((BigInteger)namedQuery("Workflow.getWorkflowIdByWorkflowVersionId") .setParameter("workflowVersionId", workflowVersionId).getSingleResult()); return Optional.of(workflowBigIntId.longValueExact()); } catch (NoResultException nre) { LOG.error("Could get workflow based on workflow version id " + workflowVersionId + ". Error is " + nre.getMessage(), nre); return Optional.empty(); } }
Source:
private void handleTerminatedState(String testID) { ScheduledFuture timeoutTaskFuture = timeoutTasks.remove(testID); timeoutTaskFuture.cancel(true); testTasks.remove(testID); runningQueue.remove(testID); }

Target:
void handleTerminatedState(String testID) { ScheduledFuture timeoutTaskFuture = timeoutTasks.remove(testID); if (timeoutTaskFuture != null) { timeoutTaskFuture.cancel(true); } testTasks.remove(testID); runningQueue.remove(testID); }
Source:
public void checkClientTrusted(X509Certificate[] chain, String authType, SSLEngine engine) throws CertificateException { x509ExtendedTrustManager.checkServerTrusted(chain, authType, engine); if (clientHostnameVerificationEnabled) { try { performHostVerification(InetAddress.getByName(engine.getPeerHost()), chain[0]); } catch (UnknownHostException e) { throw new CertificateException("failed to verify host", e); } } }

Target:
public void checkClientTrusted(X509Certificate[] chain, String authType, SSLEngine engine) throws CertificateException { x509ExtendedTrustManager.checkServerTrusted(chain, authType, engine); if (clientHostnameVerificationEnabled) { try { performHostVerification(InetAddress.getByName(engine.getPeerHost()), chain[0]); } catch (UnknownHostException e) { throw new CertificateException("Failed to verify host", e); } } }
Source:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ((Application)getApplication()).inject(this); setContentView(R.layout.authentication_confirmation); _progressView = findViewById(R.id.progress); final AuthenticationChallenge challenge = getIntent().getParcelableExtra(CHALLENGE); RequestOptions requestOptions = new RequestOptions() .priority(Priority.IMMEDIATE); Glide.with(this) .asBitmap() .load(challenge.getIdentityProvider().getLogoURL()) .apply(requestOptions) .into(new SimpleTarget<Bitmap>() { @Override public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) { if (resource != null) { _displayCardWithIcon(challenge, new BitmapDrawable(getResources(), resource)); } else { _displayCardWithIcon(challenge, getResources().getDrawable(R.drawable.ic_launcher)); } } }); }

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ((Application)getApplication()).inject(this); setContentView(R.layout.authentication_confirmation); _progressView = findViewById(R.id.progress); final AuthenticationChallenge challenge = getIntent().getParcelableExtra(CHALLENGE); if (challenge == null) { throw new RuntimeException(this.getClass().getName() + " can only start if you provide it a challenge in the intent!"); } RequestOptions requestOptions = new RequestOptions() .priority(Priority.IMMEDIATE); Glide.with(this) .asBitmap() .load(challenge.getIdentityProvider().getLogoURL()) .apply(requestOptions) .into(new SimpleTarget<Bitmap>() { @Override public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) { if (resource != null) { _displayCardWithIcon(challenge, new BitmapDrawable(getResources(), resource)); } else { _displayCardWithIcon(challenge, getResources().getDrawable(R.drawable.ic_launcher)); } } }); }
Source:
public boolean isSuccessStatusCode() { return this.responseStatus >= 200 && this.responseStatus <= 299; }

Target:
public boolean isSuccessStatusCode() { return this.statusCode >= 200 && this.statusCode <= 299; }
Source:
public TalonOfPainTriggeredAbility() { super(Zone.BATTLEFIELD, new TalonOfPainEffect()); }

Target:
public TalonOfPainTriggeredAbility() { super(Zone.BATTLEFIELD, new AddCountersSourceEffect(CounterType.CHARGE.createInstance())); }
Source:
public void theGetActualMeterReadsRequestIsReceived() throws Throwable { this.correlationUidPattern = Pattern.compile(this.organisationId.getOrganisationId() + "\\|\\|\\|\\S{17}\\|\\|\\|\\S{17}"); this.testCase = this.wsdlProjectFactory.createWsdlTestCase(SOAP_PROJECT_XML, TEST_SUITE_XML, TEST_CASE_XML); final TestCaseResult runTestStepByName = this.testCaseRunner.runWsdlTestCase(this.testCase, this.deviceId.getDeviceId(), this.organisationId.getOrganisationId(), this.correlationUid, TEST_CASE_NAME_REQUEST); final TestStepResult runTestStepByNameResult = runTestStepByName.getRunTestStepByName(); final WsdlTestCaseRunner wsdlTestCaseRunner = runTestStepByName.getResults(); Assert.assertEquals(TestStepStatus.OK, runTestStepByNameResult.getStatus()); for (final TestStepResult tcr : wsdlTestCaseRunner.getResults()) { this.response = ((MessageExchange) tcr).getResponseContent(); this.correlationUidMatcher = this.correlationUidPattern.matcher(this.response); } this.correlationUidMatcher.find(); this.correlationUid = this.correlationUidMatcher.group(); }

Target:
public void theGetActualMeterReadsRequestIsReceived() throws Throwable { this.correlationUidPattern = Pattern.compile(this.organisationId.getOrganisationId() + "\\|\\|\\|\\S{17}\\|\\|\\|\\S{17}"); this.testCase = this.wsdlProjectFactory.createWsdlTestCase(SOAP_PROJECT_XML, TEST_SUITE_XML, TEST_CASE_XML); PROPERTIES_MAP.put("DeviceIdentificationE", this.deviceId.getDeviceId()); PROPERTIES_MAP.put("OrganisationIdentification", this.organisationId.getOrganisationId()); final TestCaseResult runTestStepByName = this.testCaseRunner.runWsdlTestCase(this.testCase, PROPERTIES_MAP, TEST_CASE_NAME_REQUEST); final TestStepResult runTestStepByNameResult = runTestStepByName.getRunTestStepByName(); final WsdlTestCaseRunner wsdlTestCaseRunner = runTestStepByName.getResults(); assertEquals(TestStepStatus.OK, runTestStepByNameResult.getStatus()); for (final TestStepResult tcr : wsdlTestCaseRunner.getResults()) { this.response = ((MessageExchange) tcr).getResponseContent(); this.correlationUidMatcher = this.correlationUidPattern.matcher(this.response); } this.correlationUidMatcher.find(); this.correlationUid = this.correlationUidMatcher.group(); }
Source:
public void newSegmentAdded() { if (!m_pbd.isCursorOpen(CURSOR_NAME)) { return; } if (m_pbd.getUsageSpecificLog().isDebugEnabled()) { m_pbd.getUsageSpecificLog().debug("Processing newSegmentAdded for PBD " + m_pbd.getNonce()); } scheduleTaskFor(m_pbd.getNonce(), ()->deleteOldSegments(), MIN_DELAY); }

Target:
public void newSegmentAdded() { if (!m_pbd.isCursorOpen(CURSOR_NAME)) { return; } if (m_pbd.getUsageSpecificLog().isDebugEnabled()) { m_pbd.getUsageSpecificLog().debug("Processing newSegmentAdded for PBD " + m_pbd.getNonce()); } scheduleTaskFor(m_pbd.getNonce(), this::deleteOldSegments, MIN_DELAY); }
Source:
private static void write(TBase<?, ?> tbase, OutputStream to, BlockCipher.Encryptor encryptor, byte[] AAD) throws IOException { if (null == encryptor) { try { tbase.write(protocol(to)); return; } catch (TException e) { throw new IOException("can not write " + tbase, e); } } TMemoryBuffer thriftMemoryBuffer = new TMemoryBuffer(100); try { tbase.write(new InterningProtocol(new TCompactProtocol(thriftMemoryBuffer))); } catch (TException e) { throw new IOException("can not write " + tbase, e); } byte[] encryptedBuffer = encryptor.encrypt(thriftMemoryBuffer.getArray(), AAD); to.write(encryptedBuffer); }

Target:
private static void write(TBase<?, ?> tbase, OutputStream to, BlockCipher.Encryptor encryptor, byte[] AAD) throws IOException { if (null == encryptor) { try { tbase.write(protocol(to)); return; } catch (TException e) { throw new IOException("can not write " + tbase, e); } } try (TMemoryBuffer thriftMemoryBuffer = new TMemoryBuffer(INIT_MEM_ALLOC_ENCR_BUFFER)) { tbase.write(new InterningProtocol(new TCompactProtocol(thriftMemoryBuffer))); byte[] encryptedBuffer = encryptor.encrypt(thriftMemoryBuffer.getArray(), AAD); to.write(encryptedBuffer); } catch (TException e) { throw new IOException("can not write " + tbase, e); } }
Source:
static Configuration getFinalQueryConf(GrillDriver driver, Configuration queryConf) { Configuration conf = new Configuration(driver.getConf()); for (Map.Entry<String, String> entry : queryConf) { if(entry.getKey().equals("cube.query.driver.supported.storages")){ continue; } conf.set(entry.getKey(), entry.getValue()); } return conf; }

Target:
static Configuration getFinalQueryConf(GrillDriver driver, Configuration queryConf) { Configuration conf = new Configuration(driver.getConf()); for (Map.Entry<String, String> entry : queryConf) { if(entry.getKey().equals("cube.query.driver.supported.storages")){ CubeGrillDriver.LOG.warn("cube.query.driver.supported.storages value : " + entry.getValue() + " from query conf ignored/"); continue; } conf.set(entry.getKey(), entry.getValue()); } return conf; }
Source:
public void testCramSort(String file, String fileReference, SAMFileHeader.SortOrder order) throws Exception { final CRAMFileReader cramFileReader = getCramFileReader(file, fileReference); final SAMRecordIterator samRecordIterator = cramFileReader.getIterator().assertSorted(order); while (samRecordIterator.hasNext()) { samRecordIterator.next(); } }

Target:
public void testCramSort(String file, String fileReference, SAMFileHeader.SortOrder order) throws Exception { final CRAMFileReader cramFileReader = getCramFileReader(file, fileReference); final SAMRecordIterator samRecordIterator = cramFileReader.getIterator().assertSorted(order); Assert.assertTrue(samRecordIterator.hasNext()); while (samRecordIterator.hasNext()) { Assert.assertNotNull(samRecordIterator.next()); } }
Source:
public Collection<Object> createComponents(Client client, ClusterService clusterService, ThreadPool threadPool, ResourceWatcherService resourceWatcherService, ScriptService scriptService, NamedXContentRegistry xContentRegistry, Environment environment, NodeEnvironment nodeEnvironment, NamedWriteableRegistry namedWriteableRegistry, IndexNameExpressionResolver expressionResolver, Supplier<RepositoriesService> repositoriesServiceSupplier) { List<Object> components = new ArrayList<>(); final SSLService sslService = createSSLService(environment, resourceWatcherService); setLicenseService(new LicenseService(settings, clusterService, getClock(), environment, resourceWatcherService, getLicenseState())); components.add(sslService); components.add(getLicenseService()); components.add(getLicenseState()); if (DiscoveryNode.isDataNode(environment.settings())) { AsyncTaskIndexService<AsyncSearchResponse> indexService = new AsyncTaskIndexService<>(XPackPlugin.ASYNC_RESULTS_INDEX, clusterService, threadPool.getThreadContext(), client, ASYNC_SEARCH_ORIGIN, AsyncSearchResponse::new, namedWriteableRegistry); AsyncTaskMaintenanceService maintenanceService = new AsyncTaskMaintenanceService(clusterService, nodeEnvironment.nodeId(), settings, threadPool, indexService); components.add(maintenanceService); } return components; }

Target:
public Collection<Object> createComponents(Client client, ClusterService clusterService, ThreadPool threadPool, ResourceWatcherService resourceWatcherService, ScriptService scriptService, NamedXContentRegistry xContentRegistry, Environment environment, NodeEnvironment nodeEnvironment, NamedWriteableRegistry namedWriteableRegistry, IndexNameExpressionResolver expressionResolver, Supplier<RepositoriesService> repositoriesServiceSupplier) { List<Object> components = new ArrayList<>(); final SSLService sslService = createSSLService(environment, resourceWatcherService); setLicenseService(new LicenseService(settings, clusterService, getClock(), environment, resourceWatcherService, getLicenseState())); components.add(sslService); components.add(getLicenseService()); components.add(getLicenseState()); return components; }
Source:
public void testChannelSizeNotSizeInPropertiesPutSuccess() throws Exception { int actualBlobSizes[] = {0, chunkSize - 1, chunkSize, chunkSize + 1, chunkSize * 2, chunkSize * 2 + 1}; for (int actualBlobSize : actualBlobSizes) { requestAndResultsList.clear(); int sizeInBlobProperties = actualBlobSize == 0 ? 1 : random.nextInt(actualBlobSize); RequestAndResult requestAndResult = new RequestAndResult(sizeInBlobProperties); requestAndResult.putContent = new byte[actualBlobSize]; random.nextBytes(requestAndResult.putContent); requestAndResultsList.add(requestAndResult); submitPutsAndAssertSuccess(true); } }

Target:
public void testChannelSizeNotSizeInPropertiesPutSuccess() throws Exception { int actualBlobSizes[] = {0, chunkSize - 1, chunkSize, chunkSize + 1, chunkSize * 2, chunkSize * 2 + 1}; for (int actualBlobSize : actualBlobSizes) { int sizesInProperties[] = {actualBlobSize - 1, actualBlobSize + 1}; for (int sizeInProperties : sizesInProperties) { requestAndResultsList.clear(); RequestAndResult requestAndResult = new RequestAndResult(0); requestAndResult.putContent = new byte[actualBlobSize]; requestAndResult.putBlobProperties = new BlobProperties(sizeInProperties, "serviceId", "memberId", "contentType", false, Utils.Infinite_Time); random.nextBytes(requestAndResult.putContent); requestAndResultsList.add(requestAndResult); submitPutsAndAssertSuccess(true); } } }
Source:
public static double measureBaselineDivergence(Map<String, ResourceAssignment> baseline, Map<String, ResourceAssignment> bestPossibleAssignment) { MapDifference<String, ResourceAssignment> mapDifference = Maps.difference(baseline, bestPossibleAssignment); Map<String, ResourceAssignment> matchedAssignment = mapDifference.entriesInCommon(); Map<String, MapDifference.ValueDifference<ResourceAssignment>> differentAssignment = mapDifference.entriesDiffering(); int numMatchedPartitions = countResourceAssignmentPartitions(matchedAssignment.values()); int numTotalPartitions = numMatchedPartitions; numTotalPartitions += countResourceAssignmentPartitions(mapDifference.entriesOnlyOnLeft().values()); numTotalPartitions += countResourceAssignmentPartitions(mapDifference.entriesOnlyOnRight().values()); for (Map.Entry<String, MapDifference.ValueDifference<ResourceAssignment>> entry : differentAssignment.entrySet()) { ResourceAssignment left = entry.getValue().leftValue(); ResourceAssignment right = entry.getValue().rightValue(); Set<Partition> partitionUnion = Sets.union(Sets.newHashSet(left.getMappedPartitions()), Sets.newHashSet(right.getMappedPartitions())); numTotalPartitions += partitionUnion.size(); } return numTotalPartitions == 0 ? 0.0d : (double) numMatchedPartitions / (double) numTotalPartitions; }

Target:
public static double measureBaselineDivergence(Map<String, ResourceAssignment> baseline, Map<String, ResourceAssignment> bestPossibleAssignment) { int numMatchedReplicas = 0; int numTotalBestPossibleReplicas = 0; for (Map.Entry<String, ResourceAssignment> resourceEntry : bestPossibleAssignment.entrySet()) { String resourceKey = resourceEntry.getKey(); if (!baseline.containsKey(resourceKey)) { continue; } Map<String, Map<String, String>> bestPossiblePartitions = resourceEntry.getValue().getRecord().getMapFields(); Map<String, Map<String, String>> baselinePartitions = baseline.get(resourceKey).getRecord().getMapFields(); for (Map.Entry<String, Map<String, String>> partitionEntry : bestPossiblePartitions.entrySet()) { String partitionName = partitionEntry.getKey(); if (!baselinePartitions.containsKey(partitionName)) { continue; } Map<String, String> bestPossibleReplicas = partitionEntry.getValue(); Map<String, String> baselineReplicas = baselinePartitions.get(partitionName); for (Map.Entry<String, String> replicaEntry : bestPossibleReplicas.entrySet()) { String replicaName = replicaEntry.getKey(); if (!baselineReplicas.containsKey(replicaName)) { continue; } String bestPossibleReplica = replicaEntry.getValue(); String baselineReplica = baselineReplicas.get(replicaName); if (bestPossibleReplica.equals(baselineReplica)) { numMatchedReplicas++; } } numTotalBestPossibleReplicas += bestPossibleReplicas.size(); } } return numTotalBestPossibleReplicas == 0 ? 0.0d : (double) numMatchedReplicas / (double) numTotalBestPossibleReplicas; }
Source:
public String getUrl() { return client.getUrl(); }

Target:
public URL getUrl() { return client.getUrl(); }