auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static void createAndWaitForStream(AmazonKinesisClient kinesisClient, String streamName, int shardCount) { StreamStatus streamStatus = getStreamState(kinesisClient, streamName); if (streamStatus != null) { if (streamStatus == StreamStatus.ACTIVE) { return; } else if (streamStatus == StreamStatus.DELETING) { waitForStreamState(kinesisClient, streamName, null); createStream(streamName, shardCount, kinesisClient); } } else { createStream(streamName, shardCount, kinesisClient); } waitForStreamState(kinesisClient, streamName, StreamStatus.ACTIVE); }

Target:
public static void createAndWaitForStream(AmazonKinesisClient kinesisClient, String streamName, int shardCount) { StreamStatus streamStatus = getStreamState(kinesisClient, streamName); if (streamStatus != null) { if (streamStatus == StreamStatus.ACTIVE) { return; } if (streamStatus == StreamStatus.DELETING) { waitForStreamState(kinesisClient, streamName, null); createStream(streamName, shardCount, kinesisClient); } } else { createStream(streamName, shardCount, kinesisClient); } waitForStreamState(kinesisClient, streamName, StreamStatus.ACTIVE); }
Source:
private Pair<String, String> composeVmNames(VirtualMachineTO vmSpec) { String vmInternalCSName = null; String vmNameOnVcenter = null; if(vmSpec != null) { vmInternalCSName = vmNameOnVcenter = vmSpec.getName(); if (_instanceNameFlag == true) { String[] tokens = vmInternalCSName.split("-"); assert (tokens.length >= 3); vmNameOnVcenter = String.format("%s-%s-%s-%s", tokens[0], tokens[1], tokens[2], vmSpec.getHostName()); } } return new Pair<String, String>(vmInternalCSName, vmNameOnVcenter); }

Target:
protected Pair<String, String> composeVmNames(VirtualMachineTO vmSpec) throws CloudRuntimeException { String vmInternalCSName = ""; String vmNameOnVcenter = ""; if(vmSpec == null) { throw new CloudRuntimeException("vmSpec is null"); } vmInternalCSName = vmNameOnVcenter = vmSpec.getName(); if (_instanceNameFlag && vmSpec.getType() == VirtualMachine.Type.User) { String[] tokens = vmInternalCSName.split("-"); if(tokens.length<3) throw new InvalidParameterValueException("Invalid vmInternalCSName format: "+vmInternalCSName+" expected format : *-*-* (e.g -> i-x-y)"); vmNameOnVcenter = String.format("%s-%s-%s-%s", tokens[0], tokens[1], tokens[2], vmSpec.getHostName()); } return new Pair<String, String>(vmInternalCSName, vmNameOnVcenter); }
Source:
public void onResponse(Object response) { operations.addAndGet(performanceUpdateFrequency); }

Target:
public void onResponse(Object response) { operations.addAndGet(1); }
Source:
public static PcapFile getPcapFile(Path filePath) throws IOException, BadPcapFileException { if (Files.notExists(filePath) || !Files.isRegularFile(filePath) || Files.size(filePath) < PcapFileValues.GLOBAL_HEADER_SIZE) { throw new BadPcapFileException("Bad Pcap File."); } if (!Files.isReadable(filePath)) { throw new BadPcapFileException("File is not readable."); } FileChannel fileChannel = (FileChannel) checkNotNull(Files.newByteChannel(filePath)); ByteBuffer header = ByteBuffer.allocate(PcapFileValues.PCAPNG_BLOCK_HEADER_SIZE); fileChannel.read(header); header.flip(); int blockType = header.getInt(); if (blockType == PcapFileValues.PCAPNG_SHB) { return new PcapNgFile(filePath); } return new PcapOldFile(filePath); }

Target:
public static PcapFile getPcapFile(Path filePath) throws IOException, BadPcapFileException { if (Files.notExists(filePath) || !Files.isRegularFile(filePath) || Files.size(filePath) < PcapFileValues.GLOBAL_HEADER_SIZE) { throw new BadPcapFileException("Bad Pcap File."); } if (!Files.isReadable(filePath)) { throw new BadPcapFileException("File is not readable."); } try { FileChannel fileChannel = (FileChannel) checkNotNull(Files.newByteChannel(filePath)); ByteBuffer header = ByteBuffer.allocate(PcapFileValues.PCAPNG_BLOCK_HEADER_SIZE); fileChannel.read(header); header.flip(); int blockType = header.getInt(); if (blockType == PcapFileValues.PCAPNG_SHB) { return new PcapNgFile(filePath); } return new PcapOldFile(filePath); } catch (IOException e) { e.printStackTrace(); return new PcapOldFile(filePath); } }
Source:
private ChannelSftp openChannel() throws JSchException { if (channel == null || !channel.isConnected()) { JSch jsch = new JSch(); int port = uri.getPort() <= 0 ? 22 : uri.getPort(); com.jcraft.jsch.Session session = jsch.getSession(username, uri.getHost(), port); session.setConfig("StrictHostKeyChecking", "no"); session.setTimeout(retryPause); session.setPassword(password); session.connect(); channel = (ChannelSftp) session.openChannel("sftp"); channel.connect(); keepChannelOpen = false; } return channel; }

Target:
private ChannelSftp openChannel() throws JSchException { if (channel == null || !channel.isConnected()) { JSch jsch = new JSch(); int port = uri.getPort() <= 0 ? 22 : uri.getPort(); com.jcraft.jsch.Session session = jsch.getSession(username, uri.getHost(), port); session.setConfig("StrictHostKeyChecking", "no"); session.setTimeout(timeout); session.setPassword(password); session.connect(); channel = (ChannelSftp) session.openChannel("sftp"); channel.connect(); keepChannelOpen = false; } return channel; }
Source:
Mono<Response<DocumentResultCollection<RecognizeEntitiesResult>>> recognizeBatchEntitiesWithResponse( List<TextDocumentInput> textInputs, TextAnalyticsRequestOptions options, Context context) { Objects.requireNonNull(textInputs, "'textInputs' cannot be null."); final MultiLanguageBatchInput batchInput = new MultiLanguageBatchInput() .setDocuments(Transforms.toMultiLanguageInput(textInputs)); return service.entitiesRecognitionGeneralWithRestResponseAsync( batchInput, options == null ? null : options.getModelVersion(), options == null ? null : options.showStatistics(), context) .doOnSubscribe(ignoredValue -> logger.info("A batch of named entities input - {}", textInputs.toString())) .doOnSuccess(response -> logger.info("A batch of named entities output - {}", response.getValue())) .doOnError(error -> logger.warning("Failed to named entities - {}", error)) .map(response -> new SimpleResponse<>(response, toDocumentResultCollection(response.getValue()))); }

Target:
Mono<Response<DocumentResultCollection<RecognizeEntitiesResult>>> recognizeBatchEntitiesWithResponse( List<TextDocumentInput> textInputs, TextAnalyticsRequestOptions options, Context context) { Objects.requireNonNull(textInputs, "'textInputs' cannot be null."); final MultiLanguageBatchInput batchInput = new MultiLanguageBatchInput() .setDocuments(Transforms.toMultiLanguageInput(textInputs)); return service.entitiesRecognitionGeneralWithRestResponseAsync( batchInput, options == null ? null : options.getModelVersion(), options == null ? null : options.showStatistics(), context) .doOnSubscribe(ignoredValue -> logger.info("A batch of named entities input - {}", textInputs.toString())) .doOnSuccess(response -> logger.info("A batch of named entities output - {}", response.getValue())) .doOnError(error -> logger.warning("Failed to recognize named entities - {}", error)) .map(response -> new SimpleResponse<>(response, toDocumentResultCollection(response.getValue()))); }
Source:
private MediaSource buildMediaSource(Uri uri) { return new ExtractorMediaSource.Factory( new DefaultHttpDataSourceFactory(getString(R.string.application_name))) .createMediaSource(uri); }

Target:
private MediaSource buildMediaSource(Uri uri) { return new ExtractorMediaSource.Factory( new DefaultHttpDataSourceFactory(Identifier.getUserAgent(this))) .createMediaSource(uri); }
Source:
private static String getCustomImage(Label label) { Pattern r = Pattern.compile(CUSTOM_IMAGE_SEPARATOR + "([\\w\\.\\-/:]+[\\w])"); Matcher m = r.matcher(label.toString()); if (m.find()) { return m.group(1); } return null; }

Target:
private static String getCustomImage(Label label) { Matcher m = CUSTOM_IMAGE_FROM_LABEL_PATTERN.matcher(label.toString()); if (m.find()) { return m.group(1); } return null; }
Source:
private void renameStatisticsFile() { File defaultFile = new File(getPathToDefaultStatisticsResultsFile()); File lnpStatisticsFile = new File(getPathToTestStatisticsResultsFile()); if (!defaultFile.renameTo(lnpStatisticsFile)) { log.warning("Failed in renaming file."); } }

Target:
private void renameStatisticsFile() { File defaultFile = new File(TestProperties.LNP_TEST_RESULTS_FOLDER + "/statistics.json"); File lnpStatisticsFile = new File(getPathToTestStatisticsResultsFile()); if (lnpStatisticsFile.exists()) { lnpStatisticsFile.delete(); } if (!defaultFile.renameTo(lnpStatisticsFile)) { log.warning("Failed to rename generated statistics.json file."); } }
Source:
@Override protected void log(int priority, String tag, @NonNull String message, Throwable t) { switch (priority) { case Log.VERBOSE: case Log.DEBUG: break; case Log.INFO: Log.i(AnkiDroidApp.TAG, message, t); break; case Log.WARN: Log.w(AnkiDroidApp.TAG, message, t); break; case Log.ERROR: case Log.ASSERT: Log.e(AnkiDroidApp.TAG, message, t); break; } }

Target:
protected void log(int priority, String tag, @NonNull String message, Throwable t) { switch (priority) { case Log.VERBOSE: case Log.DEBUG: break; case Log.INFO: Log.i(AnkiDroidApp.TAG, message, t); break; case Log.WARN: Log.w(AnkiDroidApp.TAG, getTag() + "/ " + message, t); break; case Log.ERROR: case Log.ASSERT: Log.e(AnkiDroidApp.TAG, getTag() + "/ " + message, t); break; } }
Source:
public Map<String, ? extends Machine> getInternalMachines() { Map<String, MachineImpl> machines = new HashMap<>(); String workspaceId = identity.getWorkspaceId(); try (OpenShiftClient client = clientFactory.create()) { List<Pod> pods = client.pods().inNamespace(workspaceId).list().getItems(); for (Pod pod : pods) { for (ContainerStatus status : pod.getStatus().getContainerStatuses()) { machines.put(pod.getMetadata().getName() + "/" + status.getName(), new MachineImpl(new HashMap<>(), new HashMap<>())); } } List<Route> routes = client.routes().inNamespace(workspaceId).list().getItems(); List<Service> services = client.services().inNamespace(workspaceId).list().getItems(); for (Route route : routes) { String serviceName = route.getSpec().getTo().getName(); Service service = services.stream() .filter(s -> s.getMetadata().getName().equals(serviceName)) .findAny() .get(); List<Pod> servicesPods = client.pods() .inNamespace(workspaceId) .withLabels(service.getSpec().getSelector()) .list() .getItems(); for (Pod servicesPod : servicesPods) { for (Container container : servicesPod.getSpec().getContainers()) { for (ContainerPort containerPort : container.getPorts()) { for (ServicePort servicePort : service.getSpec().getPorts()) { if (containerPort.getContainerPort().equals(servicePort.getPort())) { String portName = route.getSpec().getPort().getTargetPort().getStrVal(); machines.get(servicesPod.getMetadata().getName() + "/" + container.getName()) .getServers() .put(portName, new ServerImpl("http://" + route.getSpec().getHost(), ServerStatus.UNKNOWN)); } } } } } } } catch (RuntimeException ignored) { } return machines; }

Target:
public Map<String, ? extends Machine> getInternalMachines() { Map<String, MachineImpl> machines = this.machines.entrySet() .stream() .collect(toMap(Map.Entry::getKey, e -> new MachineImpl(e.getValue()))); String workspaceId = identity.getWorkspaceId(); try (OpenShiftClient client = clientFactory.create()) { List<Route> routes = client.routes().inNamespace(workspaceId).list().getItems(); List<Service> services = client.services().inNamespace(workspaceId).list().getItems(); for (Route route : routes) { String serviceName = route.getSpec().getTo().getName(); Service service = services.stream() .filter(s -> s.getMetadata().getName().equals(serviceName)) .findAny() .get(); List<Pod> servicesPods = client.pods() .inNamespace(workspaceId) .withLabels(service.getSpec().getSelector()) .list() .getItems(); for (Pod servicesPod : servicesPods) { for (Container container : servicesPod.getSpec().getContainers()) { for (ContainerPort containerPort : container.getPorts()) { for (ServicePort servicePort : service.getSpec().getPorts()) { if (containerPort.getContainerPort().equals(servicePort.getPort())) { String portName = route.getSpec().getPort().getTargetPort().getStrVal(); machines.get(servicesPod.getMetadata().getName() + "/" + container.getName()) .getServers() .put(portName, new ServerImpl("http://" + route.getSpec().getHost(), ServerStatus.UNKNOWN)); } } } } } } } catch (RuntimeException e) { LOG.error("Error occurs while resolving machines in workspace " + identity.getWorkspaceId(), e); return emptyMap(); } return machines; }
Source:
public DatagramWriter(boolean secureClose) { byteStream = secureClose ? new ByteArrayOutputStream() { @Override public void close() throws IOException { Bytes.clear(buf); } } : new ByteArrayOutputStream(); resetCurrentByte(); }

Target:
public DatagramWriter(boolean secureClose) { byteStream = secureClose ? new ByteArrayOutputStream() { @Override public void close() throws IOException { Bytes.clear(buf); super.close(); } } : new ByteArrayOutputStream(); resetCurrentByte(); }
Source:
private String getClientId() { return ( (ClientMessageBusImpl) clientMessageBus ).getClientId(); }

Target:
String getClientId() { return clientMessageBus.getClientId(); }
Source:
public String decode(byte[] wbxmlBody) { try { int i = 4; if (false == ((wbxmlBody[i] & WBXML_TOKEN_MASK) == 0x05)) { return null; } if (false == ((wbxmlBody[i] & WBXML_TOKEN_WITH_ATTRS) == WBXML_TOKEN_WITH_ATTRS)) { return null; } i++; if ((wbxmlBody[i] & WBXML_TOKEN_MASK) == 0x05) { i += 8; } if (false == ((wbxmlBody[i] & WBXML_TOKEN_MASK) == 0x06 || (wbxmlBody[i] & WBXML_TOKEN_MASK) == 0x07)) { return null; } if (wbxmlBody[i + 1] != WBXML_INLINE_STRING) { return null; } i += 2; int j = i; while (wbxmlBody[j] != 0) { j++; } String value = new String(wbxmlBody, i, j-i); return value; } catch (ArrayIndexOutOfBoundsException e) { if (Email.DEBUG) { Log.d(Email.LOG_TAG, "ArrayIndexOutOfBoundsException while handling " + "CONTENT_MIME_TYPE_B_EMN"); } } catch (Exception e) { if (Email.DEBUG) { Log.d(Email.LOG_TAG, "Exception while handling CONTENT_MIME_TYPE_B_EMN " + e); } } return null; }

Target:
public String decode(byte[] wbxmlBody) { try { int i = 4; if ((wbxmlBody[i] & WBXML_TOKEN_MASK) != WBXML_TAG_EMN) { return null; } if ((wbxmlBody[i] & WBXML_TOKEN_WITH_ATTRS) != WBXML_TOKEN_WITH_ATTRS) { return null; } i++; if ((wbxmlBody[i] & WBXML_TOKEN_MASK) == WBXML_ATTR_TIMESTAMP) { i++; if (wbxmlBody[i] == WBXML_ATTR_OPAQUE_DATA) { i++; i+= wbxmlBody[i] + 1; } } if ((wbxmlBody[i] & WBXML_TOKEN_MASK) == WBXML_ATTR_MAILBOX && (wbxmlBody[i] & WBXML_TOKEN_MASK) == WBXML_ATTR_MAILBOX_AT) { return null; } if (wbxmlBody[i + 1] != WBXML_INLINE_STRING) { return null; } i += 2; int j = i; while (wbxmlBody[j] != WBXML_ATTR_NULL ) { j++; } if (i == j) return null; String emailAddress = new String(wbxmlBody, i, j-i); i = j + 1; String extension = ExtensionEncoded(wbxmlBody[i]); if (extension != null) { emailAddress += extension; } return emailAddress; } catch (ArrayIndexOutOfBoundsException e) { if (Email.DEBUG) { Log.d(Email.LOG_TAG, "ArrayIndexOutOfBoundsException while handling " + "CONTENT_MIME_TYPE_B_EMN"); } } catch (Exception e) { if (Email.DEBUG) { Log.d(Email.LOG_TAG, "Exception while handling CONTENT_MIME_TYPE_B_EMN " + e); } } return null; }
Source:
public void fillDigest(MessageDigest digest) throws IOException { final DigestWriter digestWriter = new DigestWriter( digest ); for ( JsonObject bodyPart : bodyParts ) { gson.toJson( bodyPart, digestWriter ); digestWriter.insertNewline(); } this.contentLength = digestWriter.getContentLenght(); }

Target:
public void fillDigest(MessageDigest digest) throws IOException { final DigestWriter digestWriter = new DigestWriter( digest ); for ( JsonObject bodyPart : bodyParts ) { gson.toJson( bodyPart, digestWriter ); digestWriter.insertNewline(); } hintContentLenght( digestWriter.getContentLength() ); }
Source:
public void decorate(Object element, IDecoration decoration) { if (Activator.getDefault() == null) return; if (!PlatformUI.isWorkbenchRunning()) return; final IResource resource = getResource(element); if (resource == null) { decorateResourceMapping(element, decoration); } else { try { decorateResource(resource, decoration); } catch(CoreException e) { handleException(resource, e); } } }

Target:
public void decorate(Object element, IDecoration decoration) { if (Activator.getDefault() == null) return; if (!PlatformUI.isWorkbenchRunning()) return; final IResource resource = getResource(element); if (resource == null) decorateResourceMapping(element, decoration); else { try { decorateResource(resource, decoration); } catch(CoreException e) { handleException(resource, e); } } }
Source:
Registration register() throws JMException { instance = server.registerMBean(StandbyCommand.this, ObjectNameFactory.getObjectName(StandbyCommand.class.getName())); return this; }

Target:
protected Registration register() throws JMException { instance = server.registerMBean(StandbyCommand.this, ObjectNameFactory.getObjectName(StandbyCommand.class.getName())); return this; }
Source:
private Map<Text,Text> createSplitDirectoryMap(SortedSet<Text> splits, SortedSet<Text> dirs) { Map<Text,Text> data = new HashMap<>(); Iterator<Text> s = splits.iterator(); Iterator<Text> d = dirs.iterator(); while (s.hasNext() && d.hasNext()) { data.put(s.next(), d.next()); } return data; }

Target:
private Map<Text,Text> createSplitDirectoryMap(SortedSet<Text> splits, SortedSet<Text> dirs) { Preconditions.checkArgument(splits.size() == dirs.size()); Map<Text,Text> data = new HashMap<>(); Iterator<Text> s = splits.iterator(); Iterator<Text> d = dirs.iterator(); while (s.hasNext() && d.hasNext()) { data.put(s.next(), d.next()); } return data; }
Source:
public void tearDown() { File test_scripts_folder = new File(filepathPrefix); if(test_scripts_folder.exists()) { for (String entry : test_scripts_folder.list()) { if(!new File(test_scripts_folder.getPath(), entry).delete()) { fail("Failed to delete file " + entry); } } if(!test_scripts_folder.delete()) { fail("Failed to deleter folder " + test_scripts_folder.getPath()); } } }

Target:
public void tearDown() { File test_scripts_folder = new File(filepathPrefix); if(test_scripts_folder.exists()) { for (String entry : test_scripts_folder.list()) { if(!new File(test_scripts_folder.getPath(), entry).delete()) { fail("Failed to delete file " + entry); } } if(!test_scripts_folder.delete()) { fail("Failed to delete folder " + test_scripts_folder.getPath()); } } }
Source:
public void addCoreColumn(Term term, String value) { if (coreIdTerm != null && coreIdTerm.equals(term)) { throw new IllegalStateException("You cannot add a term that was specified as coreId term"); } List<Term> coreTerms = terms.get(coreRowType); if (!coreTerms.contains(term)) { if (useHeaders && recordNum>1){ throw new IllegalStateException("You cannot add new terms after the first row when headers are enabled"); } coreTerms.add(term); } try { coreRow.put(term, value); } catch (NullPointerException e) { throw new IllegalStateException("No core record has been created yet. Call newRecord() at least once"); } }

Target:
public void addCoreColumn(Term term, String value) { if (coreIdTerm != null && coreIdTerm.equals(term)) { throw new IllegalStateException("You cannot add a term that was specified as coreId term"); } List<Term> coreTerms = terms.get(coreRowType); if (!coreTerms.contains(term)) { if (recordNum>1){ throw new IllegalStateException("You cannot add new terms after the first row when headers are enabled"); } coreTerms.add(term); } try { coreRow.put(term, value); } catch (NullPointerException e) { throw new IllegalStateException("No core record has been created yet. Call newRecord() at least once"); } }
Source:
protected Function<GitHubRepositoryName, GHHook> createHookSubscribedTo(final List<GHEvent> events) { return new Function<GitHubRepositoryName, GHHook>() { @Override public GHHook apply(GitHubRepositoryName name) { Validate.notNull(name); try { GHRepository repo = checkNotNull( from(name.resolve()).firstMatch(withAdminAccess()).orNull(), "There is no admin access to manage hooks on %s", name ); Validate.notEmpty(events, "Events list for hook can't be empty"); Set<GHHook> hooks = from(fetchHooks().apply(repo)) .filter(webhookFor(endpoint)) .toSet(); Set<GHEvent> alreadyRegistered = from(hooks) .transformAndConcat(eventsFromHook()).toSet(); if (hooks.size() == 1 && isEqualCollection(alreadyRegistered, events)) { LOGGER.debug("Hook already registered for events {}", events); return null; } Set<GHEvent> merged = from(alreadyRegistered).append(events).toSet(); from(hooks) .filter(deleteWebhook()) .filter(log("Replaced hook")).toList(); return createWebhook(endpoint, merged).apply(repo); } catch (Throwable t) { LOGGER.warn("Failed to add GitHub webhook for {}", name, t); } return null; } }; }

Target:
protected Function<GitHubRepositoryName, GHHook> createHookSubscribedTo(final List<GHEvent> events) { return new Function<GitHubRepositoryName, GHHook>() { @Override public GHHook apply(GitHubRepositoryName name) { name = Validate.notNull(name); try { GHRepository repo = checkNotNull( from(name.resolve()).firstMatch(withAdminAccess()).orNull(), "There is no admin access to manage hooks on %s", name ); Validate.notEmpty(events, "Events list for hook can't be empty"); Set<GHHook> hooks = from(fetchHooks().apply(repo)) .filter(webhookFor(endpoint)) .toSet(); Set<GHEvent> alreadyRegistered = from(hooks) .transformAndConcat(eventsFromHook()).toSet(); if (hooks.size() == 1 && isEqualCollection(alreadyRegistered, events)) { LOGGER.debug("Hook already registered for events {}", events); return null; } Set<GHEvent> merged = from(alreadyRegistered).append(events).toSet(); from(hooks) .filter(deleteWebhook()) .filter(log("Replaced hook")).toList(); return createWebhook(endpoint, merged).apply(repo); } catch (Throwable t) { LOGGER.warn("Failed to add GitHub webhook for due to {}", name, t); } return null; } }; }
Source:
public void customWithUriVars() throws Exception { MockHttpServletRequest request = logout().logoutUrl("/uri-logout/{var1}/{var2}", "val1", "val2").buildRequest( servletContext); CsrfToken token = (CsrfToken) request.getAttribute(CsrfRequestPostProcessor.TestCsrfTokenRepository.TOKEN_ATTR_NAME); assertThat(request.getMethod()).isEqualTo("POST"); assertThat(request.getParameter(token.getParameterName())).isEqualTo( token.getToken()); assertThat(request.getRequestURI()).isEqualTo("/uri-logout/val1/val2"); }

Target:
public void customWithUriVars() { MockHttpServletRequest request = logout().logoutUrl("/uri-logout/{var1}/{var2}", "val1", "val2").buildRequest( servletContext); CsrfToken token = (CsrfToken) request.getAttribute(CsrfRequestPostProcessor.TestCsrfTokenRepository.TOKEN_ATTR_NAME); assertThat(request.getMethod()).isEqualTo("POST"); assertThat(request.getParameter(token.getParameterName())).isEqualTo( token.getToken()); assertThat(request.getRequestURI()).isEqualTo("/uri-logout/val1/val2"); }
Source:
protected BigInteger inSatoshis(Object qty) { BigInteger satoshis; if (qty instanceof Long || qty instanceof Integer) satoshis = BigInteger.valueOf(((Number)qty).longValue()); else if (qty instanceof BigInteger) satoshis = (BigInteger)qty; else if (qty instanceof BigDecimal) satoshis = ((BigDecimal)qty).movePointRight(Coin.NUM_COIN_DECIMALS). setScale(0,BigDecimal.ROUND_HALF_UP).unscaledValue(); else if (qty instanceof Double || qty instanceof Float) { return inSatoshis(BigDecimal.valueOf((Double)qty)); } else if (qty instanceof Coin) satoshis = BigInteger.valueOf(((Coin)qty).value); else throw new IllegalArgumentException("Cannot format a " + qty.getClass().getSimpleName() + " as a Bicoin value"); return satoshis; }

Target:
private static BigInteger inSatoshis(Object qty) { BigInteger satoshis; if (qty instanceof Long || qty instanceof Integer) satoshis = BigInteger.valueOf(((Number)qty).longValue()); else if (qty instanceof BigInteger) satoshis = (BigInteger)qty; else if (qty instanceof BigDecimal) satoshis = ((BigDecimal)qty).movePointRight(Coin.SMALLEST_UNIT_EXPONENT). setScale(0,BigDecimal.ROUND_HALF_UP).unscaledValue(); else if (qty instanceof Coin) satoshis = BigInteger.valueOf(((Coin)qty).value); else throw new IllegalArgumentException("Cannot format a " + qty.getClass().getSimpleName() + " as a Bicoin value"); return satoshis; }
Source:
private List<String> validateFilterOption( String moduleName, String filterOption, String testGroup) { Set<String> testSources = new HashSet<>(); List<String> testOptions = new ArrayList<>(); List<String> errors = new ArrayList<>(); List<Filters> results = new ArrayList<>(); for (TestInfo test : getTestInfos(moduleName, testGroup)) { for (TestOption options : test.getOptions()) { if (options.getName().equals(filterOption)) { testOptions.add(options.getValue()); testSources.addAll(test.getSources()); results.add(checkOptionType(options.getValue())); } } } if (!(results.isEmpty() || results.stream().allMatch(results.get(0)::equals))) { errors.add( String.format( "Test: %s uses \"%s\" %s for REGREX, %s for ClassOrMethod, %s for " + "Package. Options: %s, TEST_MAPPING file path: %s, test group: %s", moduleName, filterOption, Collections.frequency(results, Filters.REGREX), Collections.frequency(results, Filters.CLASSORMETHOD), Collections.frequency(results, Filters.PACKAGE), testOptions, testSources, testGroup)); } return errors; }

Target:
private List<String> validateFilterOption( String moduleName, String filterOption, String testGroup) { List<String> errors = new ArrayList<>(); Set<Filters> filterTypes = new HashSet<>(); Map<Filters, Set<TestInfo>> filterTestInfos = new HashMap<>(); for (TestInfo test : getTestInfos(moduleName, testGroup)) { for (TestOption options : test.getOptions()) { if (options.getName().equals(filterOption)) { Filters optionType = getOptionType(options.getValue()); filterTestInfos.computeIfAbsent(optionType, k -> new HashSet<>()).add(test); } } } filterTypes = filterTestInfos.keySet(); if (!(filterTypes.isEmpty() || filterTypes.size() == 1)) { errors.add( String.format( "Mixed filter types found. Test: %s , TestGroup: %s, Details:\n" + "%s", moduleName, testGroup, getDetailedErrors(filterOption, filterTestInfos))); } return errors; }
Source:
public FunctionCheckedException<CassandraClient, Map<String, String>, Exception> getHostnamesByIp() { return client -> { KsDef systemPalantir; try { systemPalantir = client.describe_keyspace(SYSTEM_PALANTIR_KEYSPACE); } catch (NotFoundException e) { logger.debug("Did not find keyspace with hostnames by ip, moving on without them"); return ImmutableMap.of(); } if (systemPalantir.getCf_defs().stream().noneMatch(cfDef -> cfDef.name.equals(HOSTNAMES_BY_IP_TABLE))) { logger.debug("Did not find table with hostnames by ip, moving on without them"); return ImmutableMap.of(); } CqlQuery query = CqlQuery.builder() .safeQueryFormat("SELECT * FROM \"%s\".\"%s\";") .addArgs( SafeArg.of("keyspace", SYSTEM_PALANTIR_KEYSPACE), SafeArg.of("table", HOSTNAMES_BY_IP_TABLE)) .build(); return client.execute_cql3_query(query, Compression.NONE, ConsistencyLevel.LOCAL_ONE).getRows().stream() .collect(ImmutableMap.toImmutableMap( row -> getNamedColumnValue(row, IP_COLUMN), row -> getNamedColumnValue(row, HOSTNAME_COLUMN))); }; }

Target:
public FunctionCheckedException<CassandraClient, Map<String, String>, Exception> getHostnamesByIp() { return client -> { KsDef systemPalantir; try { systemPalantir = client.describe_keyspace(SYSTEM_PALANTIR_KEYSPACE); } catch (NotFoundException e) { logger.debug("Did not find keyspace with hostnames by ip, moving on without them"); return ImmutableMap.of(); } if (isCfNotPresent(systemPalantir, HOSTNAMES_BY_IP_TABLE)) { logger.debug("Did not find table with hostnames by ip, moving on without them"); return ImmutableMap.of(); } CqlQuery query = CqlQuery.builder() .safeQueryFormat("SELECT * FROM \"%s\".\"%s\";") .addArgs( SafeArg.of("keyspace", SYSTEM_PALANTIR_KEYSPACE), SafeArg.of("table", HOSTNAMES_BY_IP_TABLE)) .build(); return client.execute_cql3_query(query, Compression.NONE, ConsistencyLevel.LOCAL_ONE).getRows().stream() .collect(ImmutableMap.toImmutableMap( row -> getNamedColumnValue(row, IP_COLUMN), row -> getNamedColumnValue(row, HOSTNAME_COLUMN))); }; }
Source:
private static ChunkManager createChunkManager(Configuration config, boolean sync) { ChunkManager manager = null; boolean persist = config.getBoolean(HDDS_CONTAINER_PERSISTDATA, HDDS_CONTAINER_PERSISTDATA_DEFAULT); if (persist == false) { boolean scrubber = config.getBoolean( HddsConfigKeys.HDDS_CONTAINERSCRUB_ENABLED, HddsConfigKeys.HDDS_CONTAINERSCRUB_ENABLED_DEFAULT); if (scrubber) { LOG.warn("Failed to set " + HDDS_CONTAINER_PERSISTDATA + " to false." + " Please set " + HddsConfigKeys.HDDS_CONTAINERSCRUB_ENABLED + " also to false to enable non-persistent containers."); persist = true; } } if (persist == true) { manager = new ChunkManagerImpl(sync); } else { LOG.warn(HDDS_CONTAINER_PERSISTDATA + " is set to false. All user data will be discarded."); manager = new ChunkManagerNullImpl(sync); } return manager; }

Target:
private static ChunkManager createChunkManager(Configuration config, boolean sync) { ChunkManager manager = null; boolean persist = config.getBoolean(HDDS_CONTAINER_PERSISTDATA, HDDS_CONTAINER_PERSISTDATA_DEFAULT); if (!persist) { boolean scrubber = config.getBoolean( HddsConfigKeys.HDDS_CONTAINERSCRUB_ENABLED, HddsConfigKeys.HDDS_CONTAINERSCRUB_ENABLED_DEFAULT); if (scrubber) { LOG.warn("Failed to set " + HDDS_CONTAINER_PERSISTDATA + " to false." + " Please set " + HddsConfigKeys.HDDS_CONTAINERSCRUB_ENABLED + " also to false to enable non-persistent containers."); persist = true; } } if (persist) { manager = new ChunkManagerImpl(sync); } else { LOG.warn(HDDS_CONTAINER_PERSISTDATA + " is set to false. This should be used only for testing." + " All user data will be discarded."); manager = new ChunkManagerDummyImpl(sync); } return manager; }
Source:
public void serializeRecordedEvents(List<RecordedEvent> events, String filePath) { GsonPersistedDataSerializer serializationContext = new GsonPersistedDataSerializer(); PersistedData data = recordedEventListTypeHandler.serialize(events, serializationContext); try (Writer writer = new FileWriter(filePath)) { Gson gson = new GsonBuilder().create(); gson.toJson(data, writer); } catch (IOException e) { logger.error("Error while serializing recorded events", e); } }

Target:
public void serializeRecordedEvents(List<RecordedEvent> events, String filePath) { GsonPersistedDataSerializer serializationContext = new GsonPersistedDataSerializer(); GsonPersistedData data = (GsonPersistedData) recordedEventListTypeHandler.serialize(events, serializationContext); try (Writer writer = new FileWriter(filePath)) { Gson gson = new GsonBuilder().create(); gson.toJson(data.getElement(), writer); } catch (IOException e) { logger.error("Error while serializing recorded events", e); } }
Source:
private static Collection<CountrySpecification> getCountrySpecifications(Collection<String> shipsToCountries) { Set<String> countryCodes = new HashSet<>(); String wildcard = "*"; List<String> wildCardCodes; for (String countryCode : shipsToCountries) { if (wildcard.equals(countryCode)) { wildCardCodes = new ArrayList<>(Arrays.asList(Locale.getISOCountries())); wildCardCodes.removeAll(Arrays.asList(UNSUPPORTED_COUNTRIES_FOR_SHIPPING)); countryCodes.addAll(wildCardCodes); } else { countryCodes.add(countryCode); } } List<CountrySpecification> countrySpecifications = new ArrayList<>(countryCodes.size()); for (String countryCode : countryCodes) { countrySpecifications.add(new CountrySpecification(countryCode)); } return countrySpecifications; }

Target:
private static Collection<CountrySpecification> getCountrySpecifications(Collection<String> shipsToCountries) { Set<String> countryCodes = new HashSet<>(shipsToCountries); String wildcard = "*"; if (countryCodes.remove(wildcard)) { List<String> wildCardCodes = new ArrayList<>(Arrays.asList(Locale.getISOCountries())); wildCardCodes.removeAll(Arrays.asList(UNSUPPORTED_COUNTRIES_FOR_SHIPPING)); countryCodes.addAll(wildCardCodes); } List<CountrySpecification> countrySpecifications = new ArrayList<>(countryCodes.size()); for (String countryCode : countryCodes) { countrySpecifications.add(new CountrySpecification(countryCode)); } return countrySpecifications; }
Source:
public EntityManager createEntityManager() { return new OgmEntityManager( this, hibernateEmf.createEntityManager().unwrap( EntityManagerImpl.class ) ); }

Target:
public EntityManager createEntityManager() { return new OgmEntityManager( this, (EntityManagerImpl) hibernateEmf.createEntityManager() ); }
Source:
public void before() throws Exception { DOWNLOAD_CACHE.before(); Path tmpPath = tmp.getRoot().toPath(); LOG.info("The current temporary path: {}", tmpPath); Path currentModulePath = Paths.get("").toAbsolutePath(); Path flinkHomePath = currentModulePath.getParent().getParent().toAbsolutePath(); Path hadoopClasspath = Paths.get(flinkHomePath.toString(), "/flink-yarn-tests/target/yarn.classpath"); File hadoopClasspathFile = new File(hadoopClasspath.toString()); if (!hadoopClasspathFile.exists()) { throw new FileNotFoundException(HBASE_E2E_SQL); } String classPathContent = FileUtils.readFileUtf8(hadoopClasspathFile); hadoopClasspathJars = Arrays.stream(classPathContent.split(":")) .map(jar -> Paths.get(jar)) .collect(Collectors.toList()); }

Target:
public void before() throws Exception { DOWNLOAD_CACHE.before(); Path tmpPath = tmp.getRoot().toPath(); LOG.info("The current temporary path: {}", tmpPath); File hadoopClasspathFile = new File(hadoopClasspath.toAbsolutePath().toString()); if (!hadoopClasspathFile.exists()) { throw new FileNotFoundException("File that contains hadoop classpath " + hadoopClasspath.toString() + " does not exist."); } String classPathContent = FileUtils.readFileUtf8(hadoopClasspathFile); hadoopClasspathJars = Arrays.stream(classPathContent.split(":")) .map(jar -> Paths.get(jar)) .collect(Collectors.toList()); }
Source:
public ContainerPlan cloneWithScheduledResource(Resource resource) { return new ContainerPlan(getId(), getInstances(), getRequiredResource(), resource); }

Target:
private ContainerPlan cloneWithScheduledResource(Resource resource) { return new ContainerPlan(getId(), getInstances(), getRequiredResource(), resource); }
Source:
public void testExecuteAndPostProcess() throws Exception{ FeedbackSessionsDb fsDb = new FeedbackSessionsDb(); FeedbackSessionAttributes fs = dataBundle.feedbackSessions.get("session1InCourse1"); String[] submissionParams = new String[]{ Const.ParamsNames.COURSE_ID, fs.courseId, Const.ParamsNames.FEEDBACK_SESSION_NAME, fs.feedbackSessionName, }; InstructorAttributes instructor = dataBundle.instructors.get("instructor1OfCourse1"); gaeSimulation.loginAsInstructor(instructor.googleId); assertNotNull(fsDb.getFeedbackSession(fs.courseId, fs.feedbackSessionName)); Action a = gaeSimulation.getActionObject(uri, submissionParams); RedirectResult r = (RedirectResult) a.executeAndPostProcess(); assertNull(fsDb.getFeedbackSession(fs.courseId, fs.feedbackSessionName)); assertEquals(Const.ActionURIs.INSTRUCTOR_FEEDBACKS_PAGE + "?error=false" + "&user=idOfInstructor1OfCourse1", r.getDestinationWithParams()); assertEquals(Const.StatusMessages.FEEDBACK_SESSION_DELETED, r.getStatusMessage()); assertEquals(false, r.isError); }

Target:
public void testExecuteAndPostProcess() throws Exception{ FeedbackSessionsDb fsDb = new FeedbackSessionsDb(); FeedbackSessionAttributes fs = dataBundle.feedbackSessions.get("session1InCourse1"); String[] submissionParams = new String[]{ Const.ParamsNames.COURSE_ID, fs.courseId, Const.ParamsNames.FEEDBACK_SESSION_NAME, fs.feedbackSessionName, }; InstructorAttributes instructor = dataBundle.instructors.get("instructor1OfCourse1"); gaeSimulation.loginAsInstructor(instructor.googleId); assertNotNull(fsDb.getFeedbackSession(fs.courseId, fs.feedbackSessionName)); Action a = gaeSimulation.getActionObject(uri, submissionParams); RedirectResult r = (RedirectResult) a.executeAndPostProcess(); assertNull(fsDb.getFeedbackSession(fs.courseId, fs.feedbackSessionName)); assertEquals(Const.ActionURIs.INSTRUCTOR_FEEDBACKS_PAGE + "?error=false&user=idOfInstructor1OfCourse1", r.getDestinationWithParams()); assertEquals(Const.StatusMessages.FEEDBACK_SESSION_DELETED, r.getStatusMessage()); assertEquals(false, r.isError); }
Source:
public GitBlitUrlsConfig(Config config) { canonicalWebUrlString = config.getString("gerrit", null, "canonicalWebUrl"); sshdListenAddressString = config.getString("sshd", null, "listenAddress"); httpdListenUrlString = config.getString("httpd", null, "listenUrl"); downloadSchemes = config.getStringList("download", null, "scheme"); }

Target:
public GitBlitUrlsConfig(Config config) { canonicalWebUrlString = config.getString("gerrit", null, "canonicalWebUrl"); sshdListenAddressString = config.getString("sshd", null, "listenAddress"); httpdListenUrlString = config.getString("httpd", null, "listenUrl"); downloadSchemes = Arrays.asList(config.getStringList("download", null, "scheme")); }
Source:
public void testConstructAccountAndContainerFromArguments() throws JSONException { List<Container> containers = new ArrayList<>(); for (int i = 0; i < 2; i++) { containers.add(new Container(refContainerIds.get(i), refContainerNames.get(i), refContainerStatuses.get(i), refContainerDescriptions.get(i), refContainerPrivacies.get(i), refAccountId)); } Account accountFromArguments = new Account(refAccountId, refAccountName, refAccountStatus, containers); assertAccountAgainstReference(accountFromArguments, true, true); }

Target:
public void testConstructAccountAndContainerFromArguments() throws JSONException { List<Container> containers = new ArrayList<>(); for (int i = 0; i < CONTAINER_COUNT; i++) { containers.add(new ContainerBuilder(refContainerIds.get(i), refContainerNames.get(i), refContainerStatuses.get(i), refContainerDescriptions.get(i), refContainerPrivacyValues.get(i), refAccountId).build()); } Account accountFromArguments = new AccountBuilder(refAccountId, refAccountName, refAccountStatus, containers).build(); assertAccountAgainstReference(accountFromArguments, true, true); }
Source:
public void insertFile(DrawableFile f) { try { DrawableTransaction trans = beginTransaction(); CaseDbTransaction caseDbTransaction = this.tskCase.beginTransaction(); insertFile(f, trans, caseDbTransaction); commitTransaction(trans, true); caseDbTransaction.commit(); } catch (TskCoreException ex) { LOGGER.log(Level.SEVERE, "Error inserting file", ex); } }

Target:
public void insertFile(DrawableFile f) { DrawableTransaction trans = null; CaseDbTransaction caseDbTransaction = null; try { trans = beginTransaction(); caseDbTransaction = tskCase.beginTransaction(); insertFile(f, trans, caseDbTransaction); commitTransaction(trans, true); caseDbTransaction.commit(); } catch (TskCoreException ex) { if (null != trans) { rollbackTransaction(trans); } if (null != caseDbTransaction) { try { caseDbTransaction.rollback(); } catch (TskCoreException ex2) { LOGGER.log(Level.SEVERE, "Error in trying to rollback transaction", ex2); } } LOGGER.log(Level.SEVERE, "Error inserting file", ex); } }
Source:
@Override public boolean test(Map<Object, Object> ctx) throws Exception { Integer origin = firstKey.get(); int key = ThreadLocalRandom.current().nextInt(origin, origin + keysNumbPerThread); try (Transaction tx = txs.txStart(args.txConcurrency(), args.txIsolation())) { IgniteCache<Integer, Object> cache = cacheForOperation(); cache.put(key, new SampleValue(key)); tx.suspend(); ex.submit(new Callable<Object>() { @Override public Object call() { tx.resume(); tx.commit(); return null; } }).get(); } return true; }

Target:
@Override public boolean test(Map<Object, Object> ctx) throws Exception { Integer origin = firstKey.get(); int key = ThreadLocalRandom.current().nextInt(origin, origin + keysNumbPerThread); try (Transaction tx = txs.txStart(args.txConcurrency(), args.txIsolation())) { IgniteCache<Integer, Object> cache = cacheForOperation(); cache.put(key, new SampleValue(key)); tx.suspend(); ex.submit(new Callable<Void>() { @Override public Void call() { tx.resume(); tx.commit(); return null; } }).get(); } return true; }
Source:
public String getLocalName() { if (localName == null) { if (getSemanticElement() instanceof Diagram) { Diagram diagram = (Diagram) getSemanticElement(); String type = diagram.getType(); String humanType = NotationTypesMap.instance.getHumanReadableType(diagram); if (humanType != null) { localName = humanType; } else { localName = type; } } else if (getNotationElement() instanceof BasicCompartment) { localName = "Compartment"; } else if (helper.isFloatingLabel(getNotationElement())) { localName = "Label"; } else if (getSemanticElement() instanceof CSSConnectorImpl) { String type = ((CSSConnectorImpl) semanticElement).getType(); if (null != type) { localName = type; } } else { localName = getSemanticElement().eClass().getName(); } } return localName; }

Target:
public String getLocalName() { if (localName == null) { if (getSemanticElement() instanceof Diagram) { Diagram diagram = (Diagram) getSemanticElement(); String type = diagram.getType(); String humanType = NotationTypesMap.instance.getHumanReadableType(diagram); if (humanType != null) { localName = humanType; } else { localName = type; } } else if (getNotationElement() instanceof BasicCompartment) { localName = "Compartment"; } else if (helper.isFloatingLabel(getNotationElement())) { localName = "Label"; } else { localName = getSemanticElement().eClass().getName(); } } return localName; }
Source:
public void testPrimaryKeyValidation() { final TableSchema pkSchema = TableSchema.builder() .field(NAME, DataTypes.STRING().notNull()) .field(COUNT, DataTypes.DECIMAL(38, 18)) .field(TIME, DataTypes.TIMESTAMP(3)) .field(COMPUTED_COLUMN_NAME, COMPUTED_COLUMN_DATATYPE, COMPUTED_COLUMN_EXPRESSION) .watermark(TIME, WATERMARK_EXPRESSION, WATERMARK_DATATYPE) .primaryKey(NAME) .build(); Map<String, String> options1 = getModifiedOptions( getBasicSinkOptions(), options -> options.put( String.format( "%s.%s", TestFormatFactory.IDENTIFIER, TestFormatFactory.CHANGELOG_MODE.key()), "I;UA;UB;D")); createTableSink(pkSchema, options1); try { createTableSink(pkSchema, getBasicSinkOptions()); fail(); } catch (Throwable t) { String error = "The Kafka table 'default.default.sinkTable' with 'test-format' format" + " doesn't support defining PRIMARY KEY constraint on the table, because it can't" + " guarantee the semantic of primary key."; assertEquals(error, t.getCause().getMessage()); } try { createTableSource(pkSchema, getBasicSourceOptions()); fail(); } catch (Throwable t) { String error = "The Kafka table 'default.default.scanTable' with 'test-format' format" + " doesn't support defining PRIMARY KEY constraint on the table, because it can't" + " guarantee the semantic of primary key."; assertEquals(error, t.getCause().getMessage()); } }

Target:
public void testPrimaryKeyValidation() { final TableSchema pkSchema = TableSchema.builder() .field(NAME, DataTypes.STRING().notNull()) .field(COUNT, DataTypes.DECIMAL(38, 18)) .field(TIME, DataTypes.TIMESTAMP(3)) .field(COMPUTED_COLUMN_NAME, COMPUTED_COLUMN_DATATYPE, COMPUTED_COLUMN_EXPRESSION) .watermark(TIME, WATERMARK_EXPRESSION, WATERMARK_DATATYPE) .primaryKey(NAME) .build(); Map<String, String> sinkOptions = getModifiedOptions( getBasicSinkOptions(), options -> options.put( String.format( "%s.%s", TestFormatFactory.IDENTIFIER, TestFormatFactory.CHANGELOG_MODE.key()), "I;UA;UB;D")); createTableSink(pkSchema, sinkOptions); try { createTableSink(pkSchema, getBasicSinkOptions()); fail(); } catch (Throwable t) { String error = "The Kafka table 'default.default.sinkTable' with 'test-format' format" + " doesn't support defining PRIMARY KEY constraint on the table, because it can't" + " guarantee the semantic of primary key."; assertEquals(error, t.getCause().getMessage()); } Map<String, String> sourceOptions = getModifiedOptions( getBasicSourceOptions(), options -> options.put( String.format( "%s.%s", TestFormatFactory.IDENTIFIER, TestFormatFactory.CHANGELOG_MODE.key()), "I;UA;UB;D")); createTableSource(pkSchema, sourceOptions); try { createTableSource(pkSchema, getBasicSourceOptions()); fail(); } catch (Throwable t) { String error = "The Kafka table 'default.default.scanTable' with 'test-format' format" + " doesn't support defining PRIMARY KEY constraint on the table, because it can't" + " guarantee the semantic of primary key."; assertEquals(error, t.getCause().getMessage()); } }
Source:
public Reading(ConvertiblePair convertiblePair, Function<? super S, ? extends T> function) { super(convertiblePair, function); }

Target:
Reading(ConvertiblePair convertiblePair, Function<? super S, ? extends T> function) { super(convertiblePair, function); }
Source:
private Mono<PagedResponse<CustomFormModelInfo>> listFirstPageModelInfo(Context context) { return service.listCustomModelsSinglePageAsync(context) .doOnRequest(ignoredValue -> logger.info("Listing all model information")) .doOnSuccess(response -> logger.info("Listed all models")) .doOnError(error -> logger.warning("Failed to list all models", error)) .map(res -> new PagedResponseBase<>( res.getRequest(), res.getStatusCode(), res.getHeaders(), toCustomFormModelInfo(res.getValue()), res.getContinuationToken(), null)); }

Target:
private Mono<PagedResponse<CustomFormModelInfo>> listFirstPageModelInfo(Context context) { return service.listCustomModelsSinglePageAsync(context) .doOnRequest(ignoredValue -> logger.info("Listing information for all models")) .doOnSuccess(response -> logger.info("Listed all models")) .doOnError(error -> logger.warning("Failed to list all models information", error)) .map(res -> new PagedResponseBase<>( res.getRequest(), res.getStatusCode(), res.getHeaders(), toCustomFormModelInfo(res.getValue()), res.getContinuationToken(), null)); }
Source:
public double calculatePacketLoss( NetworkStatistics previousStats, NetworkStatistics currentStats, String switchName, String portId, long previousTimestamp, long currentTimestamp) throws Exception { long currentReceiveErrors = getPortReceiveErrors(currentStats, switchName, portId); long previousReceiveErrors = getPortReceiveErrors(currentStats, switchName, portId); long currentReceivedPackets = getPortReceivedPackets(currentStats, switchName, portId); long previousReceivedPackets = getPortReceivedPackets(currentStats, switchName, portId); if (currentReceivedPackets == previousReceivedPackets) return 0; return (currentReceiveErrors - previousReceiveErrors) / (currentReceivedPackets - previousReceivedPackets); }

Target:
public double calculatePacketLoss( NetworkStatistics previousStats, NetworkStatistics currentStats, String switchName, String portId, long previousTimestamp, long currentTimestamp) throws Exception { long currentReceiveErrors = getPortReceiveErrors(currentStats, switchName, portId); long previousReceiveErrors = getPortReceiveErrors(previousStats, switchName, portId); long currentReceivedPackets = getPortReceivedPackets(currentStats, switchName, portId); long previousReceivedPackets = getPortReceivedPackets(previousStats, switchName, portId); if (currentReceivedPackets == previousReceivedPackets) return 0; return (currentReceiveErrors - previousReceiveErrors) / (currentReceivedPackets - previousReceivedPackets); }
Source:
public Map<String, String> getOutputFormatConfiguration() { Map<String, String> configuration = new HashMap<>(); if (conf.schema != null) { configuration.put(SCHEMA_KEY, conf.schema); } if (conf.compressionCodec != null && !conf.containsMacro("compressionCodec") && !"none".equalsIgnoreCase(conf.compressionCodec)) { configuration.put(MAPRED_OUTPUT_COMPRESS, "true"); if (CODEC_SNAPPY.equalsIgnoreCase(conf.compressionCodec)) { configuration.put(AVRO_OUTPUT_CODEC, CODEC_SNAPPY); } else if (CODEC_DEFLATE.equalsIgnoreCase(conf.compressionCodec)) { configuration.put(AVRO_OUTPUT_CODEC, CODEC_DEFLATE); } else { throw new IllegalArgumentException("Unsupported compression codec " + conf.compressionCodec); } } return configuration; }

Target:
public Map<String, String> getOutputFormatConfiguration() { Map<String, String> configuration = new HashMap<>(); if (conf.schema != null) { configuration.put(SCHEMA_KEY, conf.schema); } if (conf.compressionCodec != null && !conf.containsMacro("compressionCodec") && !"none".equalsIgnoreCase(conf.compressionCodec)) { try { CodecFactory.fromString(conf.compressionCodec.toLowerCase()); configuration.put(MAPRED_OUTPUT_COMPRESS, "true"); configuration.put(AVRO_OUTPUT_CODEC, conf.compressionCodec.toLowerCase()); } catch (Exception e) { throw new IllegalArgumentException("Unsupported compression codec " + conf.compressionCodec); } } return configuration; }