auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void handleFailure(Exception exception) { root.set(null); noFilesFound.set(true); searchInProgress.set(false); successfulSearch.set(false); final boolean permissionProblem = exception instanceof IOException && exception.getCause() instanceof FileSystemException && exception.getCause().getMessage().endsWith("Operation not permitted"); if (permissionProblem) { dialogService.showErrorDialogAndWait(String.format(Localization.lang("JabRef does not have permission to access %s"), exception.getCause().getMessage())); } else { dialogService.showErrorDialogAndWait(exception); } }

Target:
private void handleFailure(Exception exception) { final boolean permissionProblem = exception instanceof IOException && exception.getCause() instanceof FileSystemException && exception.getCause().getMessage().endsWith("Operation not permitted"); if (permissionProblem) { dialogService.showErrorDialogAndWait(String.format(Localization.lang("JabRef does not have permission to access %s"), exception.getCause().getMessage())); } else { dialogService.showErrorDialogAndWait(exception); } }
Source:
public void shutdown() { listenerToRequest.clear(); locationEngine.setRequest(null); }

Target:
public void shutdown() { listenerToRequest.clear(); intentToRequest.clear(); locationEngine.setRequest(null); }
Source:
private static void readEvalPrintLoop() { System.err.println("Welcome to Starlark (java.starlark.net)"); String line; LineReader reader = buildLineReader(); try { while ((line = prompt(reader)) != null) { ParserInput input = ParserInput.fromString(line, "<stdin>"); try { Object result = Starlark.execFile(input, OPTIONS, module, thread); if (result != Starlark.NONE) { System.out.println(Starlark.repr(result)); } } catch (SyntaxError.Exception ex) { for (SyntaxError error : ex.errors()) { System.err.println(error); } } catch (EvalException ex) { System.err.println(ex.getMessageWithStack()); } catch (InterruptedException ex) { System.err.println("Interrupted"); } } } finally { try { reader.getTerminal().close(); } catch (IOException unused) { } } }

Target:
private static int readEvalPrintLoop() { System.err.println("Welcome to Starlark (java.starlark.net)"); String line; LineReader reader = buildLineReader(); if (reader == null) { return 1; } try { while ((line = prompt(reader)) != null) { ParserInput input = ParserInput.fromString(line, "<stdin>"); try { Object result = Starlark.execFile(input, OPTIONS, module, thread); if (result != Starlark.NONE) { System.out.println(Starlark.repr(result)); } } catch (SyntaxError.Exception ex) { for (SyntaxError error : ex.errors()) { System.err.println(error); } } catch (EvalException ex) { System.err.println(ex.getMessageWithStack()); } catch (InterruptedException ex) { System.err.println("Interrupted"); } } return 0; } catch (IOError e) { System.err.println("I/O error: " + e.getMessage()); return 1; } finally { try { reader.getTerminal().close(); } catch (IOException unused) { } } }
Source:
public static void hideSubreddit(final Activity activity, String Subreddit) { HiddenSubreddits.add(Subreddit.toLowerCase()); final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity); final SharedPreferences.Editor editor = prefs.edit(); editor.putString(activity.getString(R.string.pref_all_filter_key), StringUtils.join(HiddenSubreddits, ',')); editor.commit(); IsEmpty = false; }

Target:
public void hideSubreddit(final Activity activity, String Subreddit) { hiddenSubreddits.add(Subreddit.toLowerCase()); final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity); final SharedPreferences.Editor editor = prefs.edit(); editor.putString(activity.getString(R.string.pref_all_filter_key), StringUtils.join(hiddenSubreddits, ',')); editor.commit(); }
Source:
public MediaItem getMediaItem() { return MediaItem.fromUri(stream.getUrl()); }

Target:
public MediaItem getMediaItem() { return source.getMediaItem(); }
Source:
public AmqpBodyType getBodyType() { return bodyType; }

Target:
public AmqpBodyType getBodyType() { return AmqpBodyType.DATA; }
Source:
private Vector3f getViewPosition(Vector3f out) { ClientComponent clientComponent = getClientEntity().getComponent(ClientComponent.class); if (clientComponent == null) { return out; } LocationComponent location = clientComponent.camera.getComponent(LocationComponent.class); if (location == null) { return getPosition(); } return location.getWorldPosition(out); }

Target:
public Vector3f getViewPosition(Vector3f out) { ClientComponent clientComponent = getClientEntity().getComponent(ClientComponent.class); if (clientComponent == null) { return out; } LocationComponent location = clientComponent.camera.getComponent(LocationComponent.class); if (location == null) { return getPosition(); } return location.getWorldPosition(out); }
Source:
public static String javaVersion(final String def) { final String javaVersionProperty = SafePropertyAccessor.getProperty("java.version", def); if (javaVersionProperty.equals("0")) return "1.7.0"; return javaVersionProperty; }

Target:
public static String javaVersion(final String def) { final String javaVersionProperty = SafePropertyAccessor.getProperty("java.version", def); if ("0".equals(javaVersionProperty)) return "1.7.0"; return javaVersionProperty; }
Source:
public void afterScript(String script, WebDriver driver) { waitProcessing(driver); }

Target:
public void afterScript(String script, WebDriver driver) { if (script.contains(".click(")) waitPageLoading(driver); }
Source:
public final String getESResultJson(final String esQueryJson, final String url) { StringBuilder stringBuilder = new StringBuilder(); try { HttpClient httpClient = new DefaultHttpClient(); String encodedJson = URLEncoder.encode(esQueryJson, UTF_8); StringBuilder esGetURL = new StringBuilder(url).append(encodedJson).append(UID); Settings currentSettings = new Settings(); HttpGet getRequest; if (!currentSettings.getOptOutCheckBoxValue()) { esGetURL = new StringBuilder(esGetURL).append(windowObjects.getBeagleId()); String versionInfo = windowObjects.getOsInfo() + " " + windowObjects.getApplicationVersion() + " " + windowObjects.getPluginVersion(); getRequest = new HttpGet(esGetURL.toString()); getRequest.setHeader(USER_AGENT, versionInfo); } else { esGetURL = new StringBuilder(esGetURL).append(OPTED_OUT); getRequest = new HttpGet(esGetURL.toString()); } HttpResponse response = httpClient.execute(getRequest); if (response.getStatusLine().getStatusCode() != HTTP_OK_STATUS) { throw new RuntimeException(FAILED_HTTP_ERROR + response.getStatusLine().getStatusCode() + " " + response.getStatusLine().getReasonPhrase()); } BufferedReader bufferedReader = new BufferedReader( new InputStreamReader((response.getEntity().getContent()), UTF_8)); String output; while ((output = bufferedReader.readLine()) != null) { stringBuilder.append(output); } bufferedReader.close(); httpClient.getConnectionManager().shutdown(); } catch (RuntimeException e) { throw e; } catch (Exception e) { handleHttpException(e); } return stringBuilder.toString(); }

Target:
public final String getESResultJson(final String esQueryJson, final String url) { StringBuilder stringBuilder = new StringBuilder(); try { HttpClient httpClient = new DefaultHttpClient(); String encodedJson = URLEncoder.encode(esQueryJson, StandardCharsets.UTF_8.name()); StringBuilder esGetURL = new StringBuilder(url).append(encodedJson).append(UID); Settings currentSettings = new Settings(); HttpGet getRequest; if (!currentSettings.getOptOutCheckBoxValue()) { esGetURL = new StringBuilder(esGetURL).append(windowObjects.getBeagleId()); String versionInfo = windowObjects.getOsInfo() + " " + windowObjects.getApplicationVersion() + " " + windowObjects.getPluginVersion(); getRequest = new HttpGet(esGetURL.toString()); getRequest.setHeader(USER_AGENT, versionInfo); } else { esGetURL = new StringBuilder(esGetURL).append(OPTED_OUT); getRequest = new HttpGet(esGetURL.toString()); } HttpResponse response = httpClient.execute(getRequest); if (response.getStatusLine().getStatusCode() != HTTP_OK_STATUS) { throw new RuntimeException(FAILED_HTTP_ERROR + response.getStatusLine().getStatusCode() + " " + response.getStatusLine().getReasonPhrase()); } BufferedReader bufferedReader = new BufferedReader( new InputStreamReader((response.getEntity().getContent()), StandardCharsets.UTF_8.name())); String output; while ((output = bufferedReader.readLine()) != null) { stringBuilder.append(output); } bufferedReader.close(); httpClient.getConnectionManager().shutdown(); } catch (RuntimeException e) { throw e; } catch (Exception e) { return handleHttpException(e); } return stringBuilder.toString(); }
Source:
public void testForOwnerTag() { List<AutoScalingGroup> asgList = createASGList(); String[] asgNames = {ASG1, ASG2}; AWSClient awsMock = createMockAWSClient(asgList, asgNames); List<Cluster> list = Lists.newArrayList(); for (AutoScalingGroup asg : asgList) { List<String> instances = Lists.newArrayList(); instances.add(INSTANCE_ID); com.netflix.simianarmy.conformity.AutoScalingGroup conformityAsg = new com.netflix.simianarmy.conformity.AutoScalingGroup( asg.getAutoScalingGroupName(), instances.toArray(new String[instances.size()])); Cluster cluster = new Cluster(asg.getAutoScalingGroupName(), REGION, conformityAsg); List<TagDescription> tagDescriptions = asg.getTags(); for (TagDescription tagDescription : tagDescriptions) { if ( tagDescription.getKey() != null) { if ( OWNER_TAG_KEY.equalsIgnoreCase(tagDescription.getKey()) ) { String value = tagDescription.getValue(); if (value != null) { cluster.setOwnerEmail(value); } } } } list.add(cluster); } Assert.assertNotNull(list.get(0).getOwnerEmail()); Assert.assertTrue(list.get(0).getOwnerEmail().equalsIgnoreCase(OWNER_TAG_VALUE)); Assert.assertEquals(list.get(1).getOwnerEmail(), null); }

Target:
public void testForOwnerTag() { Properties properties = new Properties(); BasicConformityMonkeyContext ctx = new BasicConformityMonkeyContext(); List<AutoScalingGroup> asgList = createASGList(); String[] asgNames = {ASG1, ASG2}; AWSClient awsMock = createMockAWSClient(asgList, asgNames); Map<String, AWSClient> regionToAwsClient = Maps.newHashMap(); regionToAwsClient.put("us-east-1", awsMock); AWSClusterCrawler clusterCrawler = new AWSClusterCrawler(regionToAwsClient, new BasicConfiguration(properties)); List<Cluster> clusters = clusterCrawler.clusters(asgNames); Assert.assertTrue(OWNER_TAG_VALUE.equalsIgnoreCase(clusters.get(0).getOwnerEmail())); Assert.assertNull(clusters.get(1).getOwnerEmail()); }
Source:
public void processChild(final ConfigurationNode config, final int index, final BlockDestroyAction.Builder builder) { final BlockDestroyAction.Entry.Builder entry = builder.entry(index); entry.apply(this.action.parse(config.getNode(BlockDestroyActionConfig.APPLY))); entry.drop(this.drop.parse(config.getNode(BlockDestroyActionConfig.DROP))); final List<ItemAcceptable> with = new ArrayList<>(this.with(config.getNode(BlockDestroyActionConfig.WITH))); with.addAll(tool(config.getNode(BlockDestroyActionConfig.TOOL))); entry.with(with); }

Target:
public void processChild(final ConfigurationNode config, final int index, final BlockDestroyAction.Builder builder) { final BlockDestroyAction.Entry.Builder entry = builder.entry(index); entry.apply(this.action.parse(config.getNode(BlockDestroyActionConfig.APPLY))); entry.drop(this.drop.parse(config.getNode(BlockDestroyActionConfig.DROP))); final List<ItemAcceptable> with = new ArrayList<>(this.with(config.getNode(BlockDestroyActionConfig.WITH))); with.addAll(this.tool(config.getNode(BlockDestroyActionConfig.TOOL))); entry.with(with); }
Source:
protected void doPublish(PatchSetPublishDetail publishDetail) { TaskAttribute comment = getTaskData().getRoot().getAttribute(TaskAttribute.COMMENT_NEW); String editorCommentText = comment != null ? comment.getValue() : ""; PublishDialog dialog = new PublishDialog(getShell(), getTask(), publishDetail, addedDrafts, editorCommentText); openOperationDialog(dialog); if (dialog.getReturnCode() == Window.OK && comment != null) { comment.clearValues(); getTaskEditorPage().doSave(new NullProgressMonitor()); try { TasksUi.getTaskDataManager().discardEdits(getTask()); } catch (CoreException e) { TasksUiInternal.displayStatus("Unable to clear status for task " + getTask().getTaskId() + ". Unexpected behavior may result.", e.getStatus()); } } }

Target:
protected void doPublish(PatchSetPublishDetail publishDetail) { TaskAttribute comment = getTaskData().getRoot().getAttribute(TaskAttribute.COMMENT_NEW); String editorCommentText = comment != null ? comment.getValue() : ""; PublishDialog dialog = new PublishDialog(getShell(), getTask(), publishDetail, addedDrafts, editorCommentText); openOperationDialog(dialog); if (dialog.getReturnCode() == Window.OK && comment != null) { comment.clearValues(); getTaskEditorPage().doSave(new NullProgressMonitor()); try { TasksUi.getTaskDataManager().discardEdits(getTask()); } catch (CoreException e) { Status status = new Status(IStatus.ERROR, GerritUiPlugin.PLUGIN_ID, "Error while clearing task status.", e); TasksUiInternal.displayStatus("Clear outgoing task status failed", status); } } }
Source:
public void onMessage(IOSMessage message) { if (message instanceof ReportSetupMessage) { ReportSetupMessage reportSetupMessage = ReportSetupMessage.class.cast(message); handle(reportSetupMessage); } else if (message instanceof ReportConnectedApplicationsMessage) { ReportConnectedApplicationsMessage reportConnectedApplicationsMessage = ReportConnectedApplicationsMessage.class .cast(message); handle(reportConnectedApplicationsMessage); } else if (message instanceof ApplicationSentListingMessage) { ApplicationSentListingMessage applicationSentListingMessage = ApplicationSentListingMessage.class.cast(message); handle(applicationSentListingMessage); } else if (message instanceof ApplicationDataMessage) { } else if (message instanceof ApplicationConnectedMessage) { ApplicationConnectedMessage applicationConnectedMessage = ApplicationConnectedMessage.class.cast(message); handle(applicationConnectedMessage); } }

Target:
public void onMessage(IOSMessage message) { handleReportSetupMessage(message); handleReportConnectedApplicationsMessage(message); handleApplicationSentListingMessage(message); handleApplicationDataMessage(message); handleApplicationConnectedMessage(message); }
Source:
private void fetchClasses() { fWaitingForSession = false; fFetchingClasses = true; fHardwareOs.getResourceClasses(fContext, new DataRequestMonitor<IGDBHardwareAndOS2.IResourceClass[]>(fSession.getExecutor(), null) { @Override @ConfinedToDsfExecutor("fExecutor") protected void handleCompleted() { if (isSuccess()) { fResourceClasses = getData(); if (fResourceClasses.length == 0) fSupported = false; } else { fSupported = false; } fFetchingClasses = false; notifyUI(); super.handleCompleted(); } }); }

Target:
private void fetchClasses() { fWaitingForSession = false; fFetchingClasses = true; fHardwareOs.getResourceClasses(fContext, new DataRequestMonitor<IGDBHardwareAndOS2.IResourceClass[]>(fSession.getExecutor(), null) { @Override @ConfinedToDsfExecutor("fExecutor") protected void handleCompleted() { if (isSuccess()) { fResourceClasses = getData(); if (fResourceClasses.length == 0) fSupported = false; } else { fSupported = false; } fFetchingClasses = false; notifyUI(); } }); }
Source:
public Element createRootElement(Document doc, Jsr107Configuration configuration) { Element rootElement = doc.createElementNS(NAMESPACE.toString(), JSR_NAMESPACE_PREFIX + COLON + DEFAULT_ELEMENT_NAME); rootElement.setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI, "xmlns:" + JSR_NAMESPACE_PREFIX, NAMESPACE.toString()); rootElement.setAttribute(JSR_107_COMPLIANT_ATOMICS_ATTRIBUTE, String.valueOf(configuration.isJsr107CompliantAtomics())); ConfigurationElementState managementState = configuration.isEnableManagementAll(); ConfigurationElementState statisticsState = configuration.isEnableStatisticsAll(); if (ConfigurationElementState.ENABLED == managementState || ConfigurationElementState.DISABLED == managementState) { rootElement.setAttribute(ENABLE_MANAGEMENT_ALL_ATTRIBUTE, String.valueOf(configuration.isEnableManagementAll() .asBoolean())); } if (ConfigurationElementState.ENABLED == statisticsState || ConfigurationElementState.DISABLED == statisticsState) { rootElement.setAttribute(ENABLE_STATISTICS_ALL_ATTRIBUTE, String.valueOf(configuration.isEnableStatisticsAll() .asBoolean())); } if (configuration.getDefaultTemplate() != null) { rootElement.setAttribute(DEFAULT_TEMPLATE_ATTRIBUTE, configuration.getDefaultTemplate()); } processCaches(doc, rootElement, configuration); return rootElement; }

Target:
protected Element createRootElement(Document doc, Jsr107Configuration configuration) { Element rootElement = doc.createElementNS(NAMESPACE.toString(), JSR_NAMESPACE_PREFIX + COLON + DEFAULT_ELEMENT_NAME); rootElement.setAttribute(JSR_107_COMPLIANT_ATOMICS_ATTRIBUTE, String.valueOf(configuration.isJsr107CompliantAtomics())); ConfigurationElementState managementState = configuration.isEnableManagementAll(); ConfigurationElementState statisticsState = configuration.isEnableStatisticsAll(); if (ConfigurationElementState.ENABLED == managementState || ConfigurationElementState.DISABLED == managementState) { rootElement.setAttribute(ENABLE_MANAGEMENT_ALL_ATTRIBUTE, String.valueOf(managementState.asBoolean())); } if (ConfigurationElementState.ENABLED == statisticsState || ConfigurationElementState.DISABLED == statisticsState) { rootElement.setAttribute(ENABLE_STATISTICS_ALL_ATTRIBUTE, String.valueOf(statisticsState.asBoolean())); } if (configuration.getDefaultTemplate() != null) { rootElement.setAttribute(DEFAULT_TEMPLATE_ATTRIBUTE, configuration.getDefaultTemplate()); } processCaches(doc, rootElement, configuration); return rootElement; }
Source:
public void execute() { try { launch.launch(launchMode.getIdentifier(), new NullProgressMonitor()); } catch (CoreException e) { DebugUIPlugin.log(e); } }

Target:
public void execute() { DebugUITools.launch(launch, launchMode.getIdentifier()); }
Source:
public XBeeDevice(XBeeDevice localXBeeDevice, XBee64BitAddress xbee64BitAddress) { if (localXBeeDevice == null) throw new NullPointerException("Local XBee device cannot be null."); if (xbee64BitAddress == null) throw new NullPointerException("XBee 64 bit address of the remote device cannot be null."); this.localXBeeDevice = localXBeeDevice; this.connectionInterface = localXBeeDevice.getConnectionInterface(); this.xbee64BitAddress = xbee64BitAddress; this.logger = LoggerFactory.getLogger(XBeeDevice.class); logger.debug(toString() + "Using the connection interface {}.", connectionInterface.getClass().getSimpleName(), connectionInterface.toString()); }

Target:
public XBeeDevice(XBeeDevice localXBeeDevice, XBee64BitAddress xbee64BitAddress) { if (localXBeeDevice == null) throw new NullPointerException("Local XBee device cannot be null."); if (xbee64BitAddress == null) throw new NullPointerException("XBee 64 bit address of the remote device cannot be null."); if (localXBeeDevice.isRemote()) throw new IllegalArgumentException("The given local XBee device is remote."); this.localXBeeDevice = localXBeeDevice; this.connectionInterface = localXBeeDevice.getConnectionInterface(); this.xbee64BitAddress = xbee64BitAddress; this.logger = LoggerFactory.getLogger(XBeeDevice.class); logger.debug(toString() + "Using the connection interface {}.", connectionInterface.getClass().getSimpleName(), connectionInterface.toString()); }
Source:
public boolean hasId(String id) throws BuildException { if (id == null) return false; if (applicableValuesList == null) { if (superClass != null) { return superClass.hasId(id); } else { return false; } } if (getValueType() != ENUMERATED && getValueType() != TREE) { throw new BuildException(ManagedMakeMessages.getResourceString("Option.error.bad_value_type")); } return applicableValuesList.contains(id); }

Target:
public boolean hasId(String id) throws BuildException { if (id == null) return false; if (applicableValuesList == null) { if (superClass != null) { return superClass.hasId(id); } else { return false; } } checkEnumOrTree(); return applicableValuesList.contains(id); }
Source:
public NewVnicProfileModel(EntityModel sourceModel, Version dcCompatibilityVersion, boolean customPropertiesVisible, Guid dcId) { super(sourceModel, dcCompatibilityVersion, customPropertiesVisible); setTitle(ConstantsManager.getInstance().getConstants().vnicProfileTitle()); setHashName("new_vnic_profile"); this.dcId = dcId; if (dcId != null) { initNetworkQoSList(dcId, null); } getPortMirroring().setEntity(false); }

Target:
public NewVnicProfileModel(EntityModel sourceModel, Version dcCompatibilityVersion, boolean customPropertiesVisible, Guid dcId) { super(sourceModel, dcCompatibilityVersion, customPropertiesVisible, dcId); setTitle(ConstantsManager.getInstance().getConstants().vnicProfileTitle()); setHashName("new_vnic_profile"); initNetworkQoSList(null); getPortMirroring().setEntity(false); }
Source:
public static String sanitizeDefaultPort(String url) { String scheme = url.substring(0, url.indexOf("://")); int portIndex = url.indexOf(':', scheme.length() + 3); if(portIndex >= 0) { int port = Integer.parseInt(url.substring(portIndex + 1)); if(isDefaultPort(port, scheme)) { return url.substring(0, portIndex); } } return url; }

Target:
public static String sanitizeDefaultPort(String url) { int afterSchemeIndex = url.indexOf("://"); if(afterSchemeIndex < 0) { return url; } String scheme = url.substring(0, afterSchemeIndex); int fromIndex = scheme.length() + 3; int ipv6StartIndex = url.indexOf('[', fromIndex); if (ipv6StartIndex > 0) { fromIndex = url.indexOf(']', ipv6StartIndex); } int portIndex = url.indexOf(':', fromIndex); if(portIndex >= 0) { int port = Integer.parseInt(url.substring(portIndex + 1)); if(isDefaultPort(port, scheme)) { return url.substring(0, portIndex); } } return url; }
Source:
public DatalakeDrStatusResponse getBackupStatusByBackupId(String datalakeName, String backupId, String actorCrn) { checkNotNull(datalakeName); checkNotNull(actorCrn); checkNotNull(backupId); actorCrn = "crn:altus:iam:us-west-1:9d74eee4-1cad-45d7-b645-7ccf9edbb73d:user:8d1e890c-8a2e-4cf9-96bd-d50478bc027e"; datalakeName = "biglauer-az-dr-4-dl"; try (ManagedChannelWrapper channelWrapper = makeWrapper()) { BackupDatalakeStatusRequest.Builder builder = BackupDatalakeStatusRequest.newBuilder() .setDatalakeName(datalakeName); return statusConverter.convert( newStub(channelWrapper.getChannel(), UUID.randomUUID().toString(), actorCrn) .backupDatalakeStatus(builder.build()) ); } }

Target:
public DatalakeDrStatusResponse getBackupStatusByBackupId(String datalakeName, String backupId, String actorCrn) { if (!datalakeDrConfig.isConfigured()) { return missingConnectorResponse(); } checkNotNull(datalakeName); checkNotNull(actorCrn); checkNotNull(backupId); try (ManagedChannelWrapper channelWrapper = makeWrapper()) { BackupDatalakeStatusRequest.Builder builder = BackupDatalakeStatusRequest.newBuilder() .setDatalakeName(datalakeName) .setBackupId(backupId); return statusConverter.convert( newStub(channelWrapper.getChannel(), UUID.randomUUID().toString(), actorCrn) .backupDatalakeStatus(builder.build()) ); } }
Source:
private static TreeSet<Integer> parseCpuPinningNumbers(final String text) { try { TreeSet<Integer> include = new TreeSet<Integer>(); TreeSet<Integer> exclude = new TreeSet<Integer>(); String[] splitText = text.split(","); for (String section : splitText) { if (section.startsWith("^")) { exclude.add(Integer.parseInt(section.substring(1))); } else if (section.contains("-")) { String[] numbers = section.split("-"); int start = Integer.parseInt(numbers[0]); int end = Integer.parseInt(numbers[1]); for (int i = start; i <= end; i++) { include.add(i); } } else { include.add(Integer.parseInt(section)); } } include.removeAll(exclude); return include; } catch (NumberFormatException ex) { return null; } }

Target:
private TreeSet<Integer> parseCpuPinningNumbers(final String text) { try { TreeSet<Integer> include = new TreeSet<Integer>(); TreeSet<Integer> exclude = new TreeSet<Integer>(); String[] splitText = text.split(","); for (String section : splitText) { if (section.startsWith("^")) { exclude.add(Integer.parseInt(section.substring(1))); } else if (section.contains("-")) { String[] numbers = section.split("-"); int start = Integer.parseInt(numbers[0]); int end = Integer.parseInt(numbers[1]); for (int i = start; i <= end; i++) { include.add(i); } } else { include.add(Integer.parseInt(section)); } } include.removeAll(exclude); return include; } catch (NumberFormatException ex) { return null; } }
Source:
public CliCommandBuilder setController(final String protocol, final String hostname, final int port) { setController(String.format("%s://%s:%d", protocol, hostname, port)); return this; }

Target:
public CliCommandBuilder setController(final String protocol, final String hostname, final int port) { setController(formatAddress(protocol, hostname, port)); return this; }
Source:
public void call(final Subscriber<? super Account> subscriber) { if (Thread.currentThread() == handler.getLooper().getThread()) subscribe(subscriber); else handler.post(new Runnable() { @Override public void run() { subscribe(subscriber); } }); }

Target:
public void call(final Subscriber<? super Account> subscriber) { if (Thread.currentThread() == handler.getLooper().getThread()) { subscribe(subscriber); } else { handler.post(new Runnable() { @Override public void run() { subscribe(subscriber); } }); } }
Source:
public void testDeserializeEnvelope() { assertEquals(deserializeEnvelope(geometryFromText("MULTIPOINT (20 20, 25 25)")), new Envelope(20, 20, 25, 25)); assertEquals(deserializeEnvelope(geometryFromText("MULTILINESTRING ((1 1, 5 1), (2 4, 4 4))")), new Envelope(1, 1, 5, 4)); assertEquals(deserializeEnvelope(geometryFromText("POLYGON ((0 0, 0 4, 4 0))")), new Envelope(0, 0, 4, 4)); assertEquals(deserializeEnvelope(geometryFromText("MULTIPOLYGON (((0 0 , 0 2, 2 2, 2 0)), ((2 2, 2 4, 4 4, 4 2)))")), new Envelope(0, 0, 4, 4)); assertEquals(deserializeEnvelope(geometryFromText("GEOMETRYCOLLECTION (POINT (3 7), LINESTRING (4 6, 7 10))")), new Envelope(3, 6, 7, 10)); assertEquals(deserializeEnvelope(geometryFromText("POLYGON EMPTY")), null); assertEquals(deserializeEnvelope(geometryFromText("POINT (1 2)")), new Envelope(1, 2, 1, 2)); assertEquals(deserializeEnvelope(geometryFromText("POINT EMPTY")), null); assertEquals(deserializeEnvelope(geometryFromText("GEOMETRYCOLLECTION (GEOMETRYCOLLECTION (POINT (2 7), LINESTRING (4 6, 7 10)), POINT (3 7), LINESTRING (4 6, 7 10))")), new Envelope(2, 6, 7, 10)); }

Target:
public void testDeserializeEnvelope() { assertDeserializeEnvelope("MULTIPOINT (20 20, 25 25)", new Envelope(20, 20, 25, 25)); assertDeserializeEnvelope("MULTILINESTRING ((1 1, 5 1), (2 4, 4 4))", new Envelope(1, 1, 5, 4)); assertDeserializeEnvelope("POLYGON ((0 0, 0 4, 4 0))", new Envelope(0, 0, 4, 4)); assertDeserializeEnvelope("MULTIPOLYGON (((0 0 , 0 2, 2 2, 2 0)), ((2 2, 2 4, 4 4, 4 2)))", new Envelope(0, 0, 4, 4)); assertDeserializeEnvelope("GEOMETRYCOLLECTION (POINT (3 7), LINESTRING (4 6, 7 10))", new Envelope(3, 6, 7, 10)); assertDeserializeEnvelope("POLYGON EMPTY", null); assertDeserializeEnvelope("POINT (1 2)", new Envelope(1, 2, 1, 2)); assertDeserializeEnvelope("POINT EMPTY", null); assertDeserializeEnvelope("GEOMETRYCOLLECTION (GEOMETRYCOLLECTION (POINT (2 7), LINESTRING (4 6, 7 10)), POINT (3 7), LINESTRING (4 6, 7 10))", new Envelope(2, 6, 7, 10)); }
Source:
private RelNode possiblyWrapRootWithOuterLimitFromContext( RelRoot root ) { Object outerLimitObj = plannerContext.getQueryContext().get(PlannerContext.CTX_SQL_OUTER_LIMIT); Long outerLimit = DimensionHandlerUtils.convertObjectToLong(outerLimitObj, true); if (outerLimit == null) { return root.rel; } if (root.rel instanceof Sort) { Sort innerSort = (Sort) root.rel; final int offset = Calcites.getOffset(innerSort); final int innerLimit = Calcites.getFetch(innerSort); final int fetch = Calcites.collapseFetch( innerLimit, Ints.checkedCast(outerLimit), 0 ); if (fetch == innerLimit) { return root.rel; } root.rel.getCluster().getPlanner().setImportance(innerSort, 0.0); return LogicalSort.create( innerSort.getInput(), innerSort.collation, offset > 0 ? makeBigIntLiteral(offset) : null, makeBigIntLiteral(fetch) ); } return LogicalSort.create( root.rel, root.collation, null, makeBigIntLiteral(outerLimit) ); }

Target:
private RelNode possiblyWrapRootWithOuterLimitFromContext( RelRoot root ) { Object outerLimitObj = plannerContext.getQueryContext().get(PlannerContext.CTX_SQL_OUTER_LIMIT); Long outerLimit = DimensionHandlerUtils.convertObjectToLong(outerLimitObj, true); if (outerLimit == null) { return root.rel; } if (root.rel instanceof Sort) { Sort innerSort = (Sort) root.rel; final int offset = Calcites.getOffset(innerSort); final int innerLimit = Calcites.getFetch(innerSort); final int fetch = Calcites.collapseFetch( innerLimit, Ints.checkedCast(outerLimit), 0 ); if (fetch == innerLimit) { return root.rel; } return LogicalSort.create( innerSort.getInput(), innerSort.collation, offset > 0 ? makeBigIntLiteral(offset) : null, makeBigIntLiteral(fetch) ); } return LogicalSort.create( root.rel, root.collation, null, makeBigIntLiteral(outerLimit) ); }
Source:
public void initialize(Context context) { context.registerSyntaxNodeConsumer(Tree.Kind.FILE_INPUT, ctx -> { previousTokenLine = -1; pattern = Pattern.compile(legalCommentPattern); ignoreList = new ArrayList<>(); }); context.registerSyntaxNodeConsumer(Tree.Kind.TOKEN, ctx -> { PyToken pyToken = (PyToken) ctx.syntaxNode(); if (ignoreList.contains(pyToken.token())) { return; } ignoreList.add(pyToken.token()); for (Trivia trivia : pyToken.trivia()) { if (trivia.getToken().getLine() == previousTokenLine) { String comment = trivia.getToken().getValue(); if (!pattern.matcher(comment).matches()) { ctx.addIssue(new PyTokenImpl(trivia.getToken()), MESSAGE); } } } previousTokenLine = pyToken.line(); }); }

Target:
public void initialize(Context context) { Pattern pattern = Pattern.compile(legalCommentPattern); context.registerSyntaxNodeConsumer(Tree.Kind.FILE_INPUT, ctx -> previousTokenLine = -1); context.registerSyntaxNodeConsumer(Tree.Kind.TOKEN, ctx -> { Token pyToken = (Token) ctx.syntaxNode(); for (Trivia trivia : pyToken.trivia()) { if (previousTokenLine == trivia.getToken().getLine()) { String comment = trivia.getToken().getValue(); if (!pattern.matcher(comment).matches()) { ctx.addIssue(new TokenImpl(trivia.getToken()), MESSAGE); } } } previousTokenLine = pyToken.line(); }); }
Source:
public void dateIsGood() throws Exception { metadata.setMetadata(setValidUntil(THE_FUTURE, ISO_ZERO_SECONDS, entityXml)); assertThat("Expected metadata to be valid", not(metadata.isMetadataValid())); }

Target:
public void dateIsGood() { metadata.setMetadata(setValidUntil(THE_FUTURE, ISO_ZERO_SECONDS, entityXml)); initializeMetadata(); assertThat("Expected metadata to be valid", not(metadata.isMetadataValid())); }
Source:
public String getFromHttpSession(String key) { HttpServletRequest request = this.getThreadLocalRequest(); HttpSession session = request.getSession(); Object value = session.getAttribute(key); assert value instanceof String : "Retrieving non string value from session"; return (String)value; }

Target:
public String getFromHttpSession(String key) { HttpServletRequest request = this.getThreadLocalRequest(); HttpSession session = request.getSession(); Object value = session.getAttribute(UI_PREFIX + key); String result = null; if (value instanceof String) { result = (String)value; } else { log.error("Retrieving non string value from session"); } return result; }
Source:
private void createTooltipShell(Shell parent) { final Display display = parent.getDisplay(); if (fTipShell != null && !fTipShell.isDisposed()) { fTipShell.dispose(); } fTipShell = new Shell(parent, SWT.ON_TOP | SWT.TOOL); fTipShell.addDisposeListener(e -> Display.getDefault().removeFilter(SWT.MouseMove, fListener)); GridLayout gridLayout = new GridLayout(); gridLayout.numColumns = 2; gridLayout.marginWidth = 2; gridLayout.marginHeight = 2; fTipShell.setLayout(gridLayout); fTipShell.setBackground(display.getSystemColor(SWT.COLOR_INFO_BACKGROUND)); fTipComposite = new Composite(fTipShell, SWT.NONE); fTipComposite.setLayout(new GridLayout(3, false)); setupControl(fTipComposite); }

Target:
private void createTooltipShell(Shell parent) { final Display display = parent.getDisplay(); if (fTipShell != null && !fTipShell.isDisposed()) { fTipShell.dispose(); } fTipShell = new Shell(parent, SWT.ON_TOP | SWT.TOOL); fTipShell.addDisposeListener(e -> e.display.removeFilter(SWT.MouseMove, fListener)); fTipShell.addDisposeListener(e -> e.display.removeFilter(SWT.FocusOut, fListener)); GridLayout gridLayout = new GridLayout(); gridLayout.numColumns = 2; gridLayout.marginWidth = 2; gridLayout.marginHeight = 2; fTipShell.setLayout(gridLayout); fTipShell.setBackground(display.getSystemColor(SWT.COLOR_INFO_BACKGROUND)); fTipComposite = new Composite(fTipShell, SWT.NONE); fTipComposite.setLayout(new GridLayout(3, false)); setupControl(fTipComposite); }
Source:
@Test public void testJsonType() { tester.setFor(SqlStdOperatorTable.JSON_TYPE); tester.checkString("json_type('1')", "INTEGER", "VARCHAR(20) NOT NULL"); tester.checkString("json_type('11.45')", "DOUBLE", "VARCHAR(20) NOT NULL"); tester.checkString("json_type('true')", "BOOLEAN", "VARCHAR(20) NOT NULL"); tester.checkString("json_type('\"hello\"')", "STRING", "VARCHAR(20) NOT NULL"); tester.checkString("json_type(null)", "NULL", "VARCHAR(20) NOT NULL"); tester.checkString("json_type(cast(null as varchar(1)))", "NULL", "VARCHAR(20) NOT NULL"); tester.checkString("json_type(timestamp '2016-02-24 12:42:25')", "LONG", "VARCHAR(20) NOT NULL"); tester.checkString("json_type('[\"foo\",null]')", "ARRAY", "VARCHAR(20) NOT NULL"); tester.checkString("json_type('{\"foo\":100}')", "OBJECT", "VARCHAR(20) NOT NULL"); tester.checkString("json_type('{}')", "OBJECT", "VARCHAR(20) NOT NULL"); tester.checkString("json_type(cast(2 as float))", "DOUBLE", "VARCHAR(20) NOT NULL"); }

Target:
@Test public void testJsonType() { tester.setFor(SqlStdOperatorTable.JSON_TYPE); tester.checkString("json_type('\"1\"')", "STRING", "VARCHAR(20) NOT NULL"); tester.checkString("json_type('1')", "INTEGER", "VARCHAR(20) NOT NULL"); tester.checkString("json_type('11.45')", "DOUBLE", "VARCHAR(20) NOT NULL"); tester.checkString("json_type('true')", "BOOLEAN", "VARCHAR(20) NOT NULL"); tester.checkString("json_type('null')", "NULL", "VARCHAR(20) NOT NULL"); tester.checkString("json_type(cast(null as varchar(1)))", "NULL", "VARCHAR(20) NOT NULL"); tester.checkString("json_type('{\"a\": [10, true]}')", "OBJECT", "VARCHAR(20) NOT NULL"); tester.checkString("json_type('{}')", "OBJECT", "VARCHAR(20) NOT NULL"); tester.checkString("json_type('[10, true]')", "ARRAY", "VARCHAR(20) NOT NULL"); tester.checkString("json_type('\"2019-01-27 21:24:00\"')", "STRING", "VARCHAR(20) NOT NULL"); }
Source:
void shutdown() throws InterruptedException { compactionManager.disable(); for (Map.Entry<PartitionId, BlobStore> partitionAndStore : stores.entrySet()) { try { partitionAndStore.getValue().shutdown(); } catch (Exception e) { logger.error( "Exception while shutting down store for partition " + partitionAndStore.getKey() + " on disk " + disk); } } longLivedTaskScheduler.shutdown(); if (!longLivedTaskScheduler.awaitTermination(30, TimeUnit.SECONDS)) { logger.error("Could not terminate long live tasks after DiskManager shutdown"); } compactionManager.awaitTermination(); diskIOScheduler.close(); }

Target:
void shutdown() throws InterruptedException { long startTimeMs = time.milliseconds(); try { compactionManager.disable(); diskIOScheduler.disable(); final AtomicInteger numFailures = new AtomicInteger(0); List<Thread> shutdownThreads = new ArrayList<>(); for (final Map.Entry<PartitionId, BlobStore> partitionAndStore : stores.entrySet()) { Thread thread = Utils.newThread("store-shutdown-" + partitionAndStore.getKey(), new Runnable() { @Override public void run() { try { partitionAndStore.getValue().shutdown(); } catch (Exception e) { numFailures.incrementAndGet(); metrics.totalStoreShutdownFailures.inc(); logger.error("Exception while shutting down store on disk {}", partitionAndStore.getKey(), disk, e); } } }, false); thread.start(); shutdownThreads.add(thread); } for (Thread shutdownThread : shutdownThreads) { shutdownThread.join(); } if (numFailures.get() > 0) { logger.error( "Could not shutdown " + numFailures.get() + " out of " + stores.size() + " stores on the disk " + disk); } compactionManager.awaitTermination(); longLivedTaskScheduler.shutdown(); if (!longLivedTaskScheduler.awaitTermination(30, TimeUnit.SECONDS)) { logger.error("Could not terminate long live tasks after DiskManager shutdown"); } } finally { metrics.diskShutdownTimeMs.update(time.milliseconds() - startTimeMs); } }
Source:
protected byte[] applyMessage(RuntimeEnvironment env) throws Exception { String ret = null; String msgtext = getText(); switch (msgtext) { case "get-repo-type": List<String> types = new ArrayList<>(); for (String tag: getTags()) { boolean found = false; for (RepositoryInfo ri : env.getRepositories()) { if (ri.getDirectoryNameRelative().equals(tag)) { types.add(ri.getType()); found = true; break; } } if (!found) { types.add("N/A"); } } ret = types.stream().collect(Collectors.joining("\n")).toString(); break; } return ret.getBytes(); }

Target:
protected byte[] applyMessage(RuntimeEnvironment env) throws Exception { String ret = null; String msgtext = getText(); switch (msgtext) { case "get-repo-type": List<String> types = new ArrayList<>(16); for (String tag: getTags()) { boolean found = false; for (RepositoryInfo ri : env.getRepositories()) { if (ri.getDirectoryNameRelative().equals(tag)) { types.add(tag + ":" + ri.getType()); found = true; break; } } if (!found) { types.add(tag + ":N/A"); } } ret = types.stream().collect(Collectors.joining("\n")); break; } return ret.getBytes(); }
Source:
public static void restoreDefaults() throws Exception { registryManager.removeAllRegistryEntries(); LogManager.resetConfiguration(); try { String logFile = CarbonUtils.getCarbonConfigDirPath() + RegistryConstants.PATH_SEPARATOR + "log4j.properties"; Log4jConfigurer.initLogging(logFile); } catch (FileNotFoundException e) { String msg = "Cannot restore default logging configuration." + " log4j.properties file not found in the classpath"; throw new LogViewerException(msg, e); } }

Target:
public static void restoreDefaults() throws Exception { registryManager.removeAllRegistryEntries(); LogManager.resetConfiguration(); try { String logFile = CarbonUtils.getCarbonConfigDirPath() + RegistryConstants.PATH_SEPARATOR + "log4j.properties"; Log4jConfigurer.initLogging(logFile); } catch (FileNotFoundException e) { String msg = "Cannot restore default logging configuration." + " log4j.properties file is not found in the classpath"; throw new LogViewerException(msg, e); } }
Source:
public static String bytesToBigDecimal(byte[] bytes) { int scale = 0; for (int i = 0; i < 4; i++) { scale += (((int) bytes[i]) << (8 * (3 - i))); } byte[] vals = new byte[bytes.length - 4]; System.arraycopy(bytes, 4, vals, 0, vals.length); BigInteger unscaled = new BigInteger(vals); BigDecimal number = new BigDecimal(unscaled, scale); return number.toString(); }

Target:
public static String bytesToBigDecimal(byte[] bytes) { BigDecimal number = bytesToBigDecimalObject(bytes); return number.toString(); }
Source:
public TimeGraphEntry(@NonNull TimeGraphEntryModel model) { setModel(model); }

Target:
public TimeGraphEntry(@NonNull TimeGraphEntryModel model) { fModel = model; fStartTime = model.getStartTime(); fEndTime = model.getEndTime(); }
Source:
public JWE verifyAndDecodeJwe(String jweStr, JWEAlgorithmProvider algorithmProvider, JWEEncryptionProvider encryptionProvider) throws JWEException { try { String[] parts = jweStr.split("\\."); if (parts.length != 5) { throw new IllegalStateException("Not a JWE String"); } this.base64Header = parts[0]; this.base64Cek = parts[1]; this.initializationVector = Base64Url.decode(parts[2]); this.encryptedContent = Base64Url.decode(parts[3]); this.authenticationTag = Base64Url.decode(parts[4]); this.header = getHeader(); if (algorithmProvider == null) { throw new IllegalArgumentException("No provider for alg "); } if (encryptionProvider == null) { throw new IllegalArgumentException("No provider for enc "); } keyStorage.setEncryptionProvider(encryptionProvider); byte[] decodedCek = algorithmProvider.decodeCek(Base64Url.decode(base64Cek), keyStorage.getDecryptionKey()); keyStorage.setCEKBytes(decodedCek); encryptionProvider.verifyAndDecodeJwe(this); return this; } catch (Exception e) { throw new JWEException(e); } }

Target:
public JWE verifyAndDecodeJwe(String jweStr, JWEAlgorithmProvider algorithmProvider, JWEEncryptionProvider encryptionProvider) throws JWEException { try { setupJWEHeader(jweStr); return getProcessedJWE(algorithmProvider, encryptionProvider); } catch (Exception e) { throw new JWEException(e); } }
Source:
private static String generateAuthenticateHead( final String user, final String pass ) { final String auth = String.format("%s:%s", user, pass); final String encoded = DatatypeConverter.printBase64Binary( auth.getBytes() ); return String.format("Authorization: Basic %s", encoded); }

Target:
private static String generateAuthenticateHead( final String user, final String pass ) { return String.format( "Authorization: Basic %s", DatatypeConverter.printBase64Binary( String.format("%s:%s", user, pass).getBytes() ) ); }
Source:
private static boolean canMatchPacket(final ITmfEvent event) { ITmfEventField content = event.getContent(); return ((content.getFieldValue(Long.class, TcpEventStrings.SEQ) == null) || (content.getFieldValue(Long.class, TcpEventStrings.ACKSEQ) == null) || (content.getFieldValue(Long.class, TcpEventStrings.FLAGS) == null)); }

Target:
private static boolean canMatchPacket(final ITmfEvent event) { ITmfEventField content = event.getContent(); return !((content.getFieldValue(Long.class, TcpEventStrings.SEQ) == null) || (content.getFieldValue(Long.class, TcpEventStrings.ACKSEQ) == null) || (content.getFieldValue(Long.class, TcpEventStrings.FLAGS) == null)); }
Source:
private int[][] sanitizeInput(int[][] input) { int teamSize = input.length; int[][] output = new int[teamSize][teamSize]; for (int i = 0; i < teamSize; i++) { for (int j = 0; j < teamSize; j++) { int points = input[i][j]; if (points == Const.POINTS_NOT_SUBMITTED) { output[i][j] = NA; } else if (points == Const.POINTS_NOT_SURE) { output[i][j] = NSU; } else { output[i][j] = points; } } } return output; }

Target:
private int[][] sanitizeInput(int[][] input) { int teamSize = input.length; int[][] output = new int[teamSize][teamSize]; for (int i = 0; i < teamSize; i++) { for (int j = 0; j < teamSize; j++) { int points = input[i][j]; boolean pointsNotGiven = points == Const.POINTS_NOT_SUBMITTED; output[i][j] = pointsNotGiven ? NA : points; } } return output; }
Source:
public void exportValues(StringBuilder result) { Formatter formatter = new Formatter(result); final Student student = getStudent(); formatter.format("%s: %s\n", BundleUtil.getString(Bundle.ACADEMIC, "label.ingression"), getIngressionType() == null ? " - " : getIngressionType().getFullDescription().getContent(Locale.getDefault())); formatter.format("%s: %d\n", BundleUtil.getString(Bundle.ACADEMIC, "label.studentNumber"), student.getNumber()); formatter.format("%s: %s\n", BundleUtil.getString(Bundle.ACADEMIC, "label.Student.Person.name"), student.getPerson() .getName()); formatter.format("%s: %s\n", BundleUtil.getString(Bundle.ACADEMIC, "label.degree"), getDegree().getPresentationName()); formatter.close(); }

Target:
public void exportValues(StringBuilder result) { Formatter formatter = new Formatter(result); final Student student = getStudent(); formatter.format("%s: %s\n", BundleUtil.getString(Bundle.ACADEMIC, "label.ingression"), getIngressionType() == null ? " - " : getIngressionType().getDescription().getContent()); formatter.format("%s: %d\n", BundleUtil.getString(Bundle.ACADEMIC, "label.studentNumber"), student.getNumber()); formatter.format("%s: %s\n", BundleUtil.getString(Bundle.ACADEMIC, "label.Student.Person.name"), student.getPerson() .getName()); formatter.format("%s: %s\n", BundleUtil.getString(Bundle.ACADEMIC, "label.degree"), getDegree().getPresentationName()); formatter.close(); }
Source:
public void testConstructor() { int leaderEpoch = 5; long endOffset = 10L; EpochEndOffset epochEndOffset = new EpochEndOffset(Errors.FENCED_LEADER_EPOCH, leaderEpoch, endOffset); verify(leaderEpoch, endOffset, true, Errors.FENCED_LEADER_EPOCH, false, epochEndOffset); }

Target:
public void testConstructor() { int leaderEpoch = 5; long endOffset = 10L; EpochEndOffset epochEndOffset = new EpochEndOffset(Errors.FENCED_LEADER_EPOCH, leaderEpoch, endOffset); assertEquals(leaderEpoch, epochEndOffset.leaderEpoch()); assertEquals(endOffset, epochEndOffset.endOffset()); assertTrue(epochEndOffset.hasError()); assertEquals(Errors.FENCED_LEADER_EPOCH, epochEndOffset.error()); assertFalse(epochEndOffset.hasUndefinedEpochOrOffset()); }
Source:
protected String getProcessVariables() { Diagram diagram = canvasSessionManager.getCurrentSession().getCanvasHandler().getDiagram(); Node selectedElement = getSelectedElement(); String variables = VariableUtils.encodeProcessVariables(diagram, selectedElement); StringBuilder sb = new StringBuilder(); if (!variables.isEmpty()) { sb.append(variables); } String dataObjects = findDataObjects().stream() .map(this::dataObjectToProcessVariableFormat) .collect(Collectors.joining(",")); if (!dataObjects.isEmpty()) { sb.append(dataObjects); } return sb.toString(); }

Target:
protected String getProcessVariables() { Diagram diagram = canvasSessionManager.getCurrentSession().getCanvasHandler().getDiagram(); Node selectedElement = getSelectedElement(); String variables = VariableUtils.encodeProcessVariables(diagram, selectedElement); StringBuilder sb = new StringBuilder(); if (!variables.isEmpty()) { sb.append(variables); } String dataObjects = findDataObjects().stream() .map(AssignmentsEditorWidget::dataObjectToProcessVariableFormat) .collect(Collectors.joining(",")); if (!dataObjects.isEmpty()) { sb.append(dataObjects); } return sb.toString(); }
Source:
private Pair<Double, Double> totalCost(final int numWorker, final int numTotalDataInstances, final double numPullsPerMiniBatch, final int availableEvaluators, final List<EvaluatorSummary> workers, final List<EvaluatorSummary> servers) { final double avgNumMiniBatchesPerWorker = Math.ceil((double) numTotalDataInstances / numWorker / miniBatchSize); final double workerThroughputSum = workers.subList(0, numWorker).stream() .mapToDouble(worker -> worker.throughput) .sum(); final double compCost = numTotalDataInstances / workerThroughputSum; final int numServer = availableEvaluators - numWorker; final double serverThroughputSum = servers.subList(0, numServer).stream() .mapToDouble(server -> server.throughput) .sum(); final double commCost = numPullsPerMiniBatch / serverThroughputSum / numServerThreads * numWorker * avgNumMiniBatchesPerWorker; final double totalCost = compCost + commCost; final String costInfo = String.format("{\"numServer\": %d, \"numWorker\": %d, \"totalCost\": %f, " + "\"compCost\": %f, \"commCost\": %f}", numServer, numWorker, totalCost, compCost, commCost); LOG.log(Level.INFO, "CostInfo {0} {1}", new Object[]{System.currentTimeMillis(), costInfo}); return new Pair<>(compCost, commCost); }

Target:
private Pair<Double, Double> totalCost(final int numWorker, final int numTotalDataInstances, final double numPullsPerMiniBatch, final int availableEvaluators, final List<EvaluatorSummary> workers, final List<EvaluatorSummary> servers) { final double avgNumMiniBatchesPerWorker = Math.ceil((double) numTotalDataInstances / numWorker / miniBatchSize); final double workerThroughputSum = workers.subList(0, numWorker).stream() .mapToDouble(worker -> worker.throughput) .sum(); final double compCost = numTotalDataInstances / workerThroughputSum; final int numServer = availableEvaluators - numWorker; final double serverThroughputSum = servers.subList(0, numServer).stream() .mapToDouble(server -> server.throughput) .sum() * serverNumThreads; final double commCost = numPullsPerMiniBatch / serverThroughputSum * numWorker * avgNumMiniBatchesPerWorker; final double totalCost = compCost + commCost; final String costInfo = String.format("{\"numServer\": %d, \"numWorker\": %d, \"totalCost\": %f, " + "\"compCost\": %f, \"commCost\": %f}", numServer, numWorker, totalCost, compCost, commCost); LOG.log(Level.INFO, "CostInfo {0} {1}", new Object[]{System.currentTimeMillis(), costInfo}); return new Pair<>(compCost, commCost); }