text:
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import {
  ErrorInfo,
  PerfEntry,
  PerfEvent,
  Resolution,
} from './type.js';
import {WaitableEvent} from './waitable_event.js';

const TOP_BAR_HEIGHT = 32;

const DEFAULT_WINDOW_WIDTH = 764;

/**
 * Gets default window size which minimizes the letterbox area for given preview
 * aspect ratio.
 *
 * @param aspectRatio Preview aspect ratio.
 */
export function getDefaultWindowSize(aspectRatio: number): Resolution {
  // For the call site from background.js cannot access letterbox space reserved
  // for controls on 3 sides around #preview-box directly from dom. The
  // letterbox size number is hard coded here.
  // TODO(b/172345161): Reference these number from left, right, bottom of
  // #preview-box's bounding client rect after background.js being removed.
  const bottom = 88;
  const left = 88;
  const right = 100;

  return new Resolution(
      DEFAULT_WINDOW_WIDTH,
      Math.round(
          (DEFAULT_WINDOW_WIDTH - (left + right)) / aspectRatio + bottom +
          TOP_BAR_HEIGHT));
}

/**
 * Class which is used to coordinate the setup of window between Tast side and
 * CCA side.
 */
export class AppWindow {
  /**
   * A waitable event which will resolve to the URL of the CCA instance just
   * launched.
   */
  private readonly readyOnCCASide = new WaitableEvent<string>();

  private readonly readyOnTastSide = new WaitableEvent();

  private readonly onClosed = new WaitableEvent();

  private inClosingItself = false;

  private readonly errors: ErrorInfo[] = [];

  private readonly perfs: PerfEntry[] = [];

  private readonly launchedTime = performance.now();

  /**
   * @param fromColdStart Whether this app is launched from a cold start. It is
   *     used for performance measurement.
   */
  constructor(private readonly fromColdStart: boolean) {}

  /**
   * Waits until the window is bound and returns the URL of the window.
   *
   * @return The URL of the window.
   */
  waitUntilWindowBound(): Promise<string> {
    return this.readyOnCCASide.wait();
  }

  /**
   * Binds the URL to the window.
   */
  bindUrl(url: string): void {
    this.readyOnCCASide.signal(url);
  }

  /**
   * Notifies the listener that the window setup is done on Tast side.
   */
  notifyReadyOnTastSide(): void {
    this.readyOnTastSide.signal();
  }

  /**
   * Waits until the setup for the window is done on Tast side.
   */
  waitUntilReadyOnTastSide(): Promise<void> {
    return this.readyOnTastSide.wait();
  }

  /**
   * Triggers when CCA is fully launched.
   */
  onAppLaunched(): void {
    const event = this.fromColdStart ?
        PerfEvent.LAUNCHING_FROM_LAUNCH_APP_COLD :
        PerfEvent.LAUNCHING_FROM_LAUNCH_APP_WARM;
    this.perfs.push({
      event: event,
      duration: (performance.now() - this.launchedTime),
    });
  }

  /**
   * Notifies the listener that the window is closed.
   */
  notifyClosed(): void {
    this.onClosed.signal();
  }

  /**
   * Waits until the window is closed.
   */
  waitUntilClosed(): Promise<void> {
    return this.onClosed.wait();
  }

  /**
   * Notifies the listener that the window is about to close itself.
   */
  notifyClosingItself(): void {
    this.inClosingItself = true;
  }

  /**
   * Check if it has received the signal that the window is about to close
   * itself.
   */
  isClosingItself(): boolean {
    return this.inClosingItself;
  }

  /**
   * Reports error and makes it visible on Tast side.
   *
   * @param errorInfo Information of the error.
   */
  reportError(errorInfo: ErrorInfo): void {
    this.errors.push(errorInfo);
  }

  /**
   * Gets all the errors.
   */
  getErrors(): ErrorInfo[] {
    return this.errors;
  }

  /**
   * Reports perf information and makes it visible on Tast side.
   *
   * @param perfEntry Information of the perf event.
   */
  reportPerf(perfEntry: PerfEntry): void {
    this.perfs.push(perfEntry);
  }

  /**
   * Gets all the perf information.
   */
  getPerfs(): PerfEntry[] {
    return this.perfs;
  }
}


text: Remove interpretN in favor of :+:

redpajama_set_name: RedPajamaGithub


text:
package gov.opm.scrd.services.impl.reporting;

import gov.opm.scrd.LoggingHelper;
import gov.opm.scrd.entities.application.Account;
import gov.opm.scrd.entities.application.User;
import gov.opm.scrd.entities.batchprocessing.AllDetails;
import gov.opm.scrd.entities.batchprocessing.InvoiceData;
import gov.opm.scrd.entities.batchprocessing.PaymentTransaction;
import gov.opm.scrd.entities.batchprocessing.PaymentTransactionCodes;
import gov.opm.scrd.entities.common.Helper;
import gov.opm.scrd.services.ExportType;
import gov.opm.scrd.services.ReportGenerationException;
import gov.opm.scrd.services.ReportService;
import gov.opm.scrd.services.impl.BaseReportService;

import java.io.ByteArrayOutputStream;
import java.math.BigDecimal;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;
import javax.persistence.PersistenceException;

import org.jboss.logging.Logger;

import com.lowagie.text.Cell;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Element;
import com.lowagie.text.HeaderFooter;
import com.lowagie.text.Phrase;
import com.lowagie.text.Table;

/**
 *

 * Creates the suspense resolution report as described in
 * http://apps.topcoder.com/forums/?module=Thread&threadID=810139&start=0.
 *

 *
 *

 * Thread Safety:  This class is effectively thread safe after configuration, the configuration is done
 * in a thread safe manner.
 *

 *
 * @author faeton, AleaActaEst, TCSASSEMBLER
 * @version 1.0
 */
@Stateless
@LocalBean
@TransactionManagement(TransactionManagementType.CONTAINER)
public class SuspenseResolutionReportService extends BaseReportService implements
    ReportService<SuspenseResolutionReportRequest, SuspenseResolutionReportResponse> {

    /**
     * Query used for inspected transactions.
     */
    private static final String QUERY_TRANSACTIONS = "SELECT a FROM PaymentTransaction a WHERE a.deleted = false "
        + "AND a.payTransTransactionDate >= :startDate AND a.payTransTransactionDate <= :endDate "
        + "AND a.resolvedSuspense = true";

    /**
     * Query used for transaction groups.
     */
    private static final String QUERY_GROUP = "SELECT a FROM PaymentTransaction a WHERE a.deleted = false "
        + "AND a.payTransTransactionDate <= :transactionDate ORDER BY a.payTransStatusDate";

    /**
     * Query used for getting the user.
     */
    private static final String QUERY_USER = "SELECT a FROM User a WHERE a.deleted = false "
        + "AND a.username = :username";

    /**
     *

     * Represents the class name.
     *

     */
    private static final String CLASS_NAME = SuspenseResolutionReportService.class.getName();

    /**
     * Default constructor.
     */
    public SuspenseResolutionReportService() {
    }

    /**
     * Generates the report for suspense resolution records.
     *
     * @param request the request object
     * @return the model for the requested report.
     * @throws IllegalArgumentException if the request is null.
     * @throws ReportGenerationException if there is any problem when generating response.
     */
    public SuspenseResolutionReportResponse getReport(SuspenseResolutionReportRequest request)
        throws ReportGenerationException {
        String signature = CLASS_NAME + "#getReport(SuspenseResolutionReportRequest request)";
        Logger logger = getLogger();
        LoggingHelper.logEntrance(logger, signature, new String[] {"request"}, new Object[] {request});
        Helper.checkNull(logger, signature, request, "request");
        Helper.checkNull(logger, signature, request.getStartDate(), "request.startDate");
        Helper.checkNull(logger, signature, request.getEndDate(), "request.endDate");

        try {
            SuspenseResolutionReportResponse response = new SuspenseResolutionReportResponse();
            response.setReportGenerationDate(new Date());
            response.setReportName(getReportName());
            response.setStartDate(request.getStartDate());
            response.setEndDate(request.getEndDate());
            response.setItems(new ArrayList<SuspenseResolutionReportResponseItem>());

            List<PaymentTransaction> transactions = getEntityManager()
                .createQuery(QUERY_TRANSACTIONS, PaymentTransaction.class)
                .setParameter("startDate", request.getStartDate()).setParameter("endDate", request.getEndDate())
                .getResultList();
            // for each PaymentTransaction [record] get the csd of the account to which it belongs
            for (PaymentTransaction record : transactions) {

                // Once we have this get all the other PaymentTransaction with the same csd WHERE their
                // payTransTransactionDate <= [record].payTransTransactionDate. Lets call this the GROUP.
                // In the group sort the records by payTransStatusDate.
                List<PaymentTransaction> group = getEntityManager().createQuery(QUERY_GROUP, PaymentTransaction.class)
                    .setParameter("transactionDate", record.getPayTransTransactionDate()).getResultList();

                SuspenseResolutionReportResponseItem item = new SuspenseResolutionReportResponseItem();
                item.setCsd(record.getScmClaimNumber());
                // The actual [record] will hold the "processed" amount as payTransPaymentAmount
                item.setProcessed(record.getPayTransPaymentAmount());
                // The first record in this group will hold the starting status of the payment as paymentStatusCode
                if (!group.isEmpty()) {
                    item.setStartedAs(String.valueOf(group.iterator().next().getPaymentStatusCode()));
                }
                // Use the AllDetails table to get a corresponding record for the payTransactionKey of the actual
                // [record].payTransactionKey, which will hold the type of payment as AllDetails.paymentType
                String key = String.valueOf(record.getPayTransactionKey());
                AllDetails detail = ReportHelper.getAllDetails(getEntityManager(), getLogger(), key);
                if (detail != null) {
                    item.setPayment(detail.getPaymentType());
                }

                for (PaymentTransaction groupItem : group) {
                    item.setTransactionDate(groupItem.getPayTransTransactionDate());
                    // In the group look for the record with payTransStatusCode == PaymentTransactionCodes.SUSPENDED
                    // and get the PaymentTransaction.payTransPaymentAmount which will give us the "suspense" amount
                    if (groupItem.getPaymentStatusCode() != null
                        && groupItem.getPaymentStatusCode() == PaymentTransactionCodes.SUSPENDED.getCode()) {
                        item.setSuspense(groupItem.getPayTransPaymentAmount());
                    }
                    // In the group look for the record with payTransStatusCode ==
                    // PaymentTransactionCodes.SUSPENSE_REFUND_COMPLETE and get the
                    // PaymentTransaction.payTransPaymentAmount which will give us the "resolved" amount
                    if (groupItem.getPaymentStatusCode() != null
                        && groupItem.getPaymentStatusCode() == PaymentTransactionCodes.SUSPENSE_REFUND_COMPLETE
                            .getCode()) {
                        item.setResolved(groupItem.getPayTransPaymentAmount());
                    }
                }

                InvoiceData invoice = ReportHelper.getInvoiceData(getEntityManager(), getLogger(), record);
                if (invoice != null) {
                    // From InvoiceData get the record matched on [record].payTransactionKey and get the
                    // accountBalanceNew
                    item.setAccount(invoice.getAccountBalanceNew());
                    // From InvoiceData get the record matched on [record].payTransactionKey and get the
                    // payTransStatusDescription
                    item.setResolution(invoice.getPayTransStatusDescription());
                }

                // TO get the user (i.e. supervisor) get the User from the Account for the csd. Once you have the
                // account User get the User.supervisor.
                Account account = ReportHelper.getAccountData(getEntityManager(), getLogger(), record);
                if (account == null) {
                    continue;
                }
                List<User> users = getEntityManager().createQuery(QUERY_USER, User.class)
                    .setParameter("username", account.getClaimOfficer()).getResultList();
                if (users.isEmpty()) {
                    // the report is grouped by supervisor, if there is no supervisor, we cannot group it
                    continue;
                }
                Long supervisorId = users.iterator().next().getSupervisorId();
                if (supervisorId == null) {
                    // the report is grouped by supervisor, if there is no supervisor, we cannot group it
                    continue;
                }
                User supervisor = getEntityManager().find(User.class, supervisorId);
                if (supervisor != null) {
                    item.setSupervisor(supervisor.getFirstName() + " " + supervisor.getLastName());
                }
                response.getItems().add(item);
            }

            LoggingHelper.logExit(logger, signature, new Object[] {response});
            return response;
        } catch (IllegalStateException e) {
            throw LoggingHelper.logException(logger, signature, new ReportGenerationException(
                "The entity manager has been closed.", e));
        } catch (PersistenceException e) {
            throw LoggingHelper.logException(logger, signature, new ReportGenerationException(
                "An error has occurred when accessing persistence.", e));
        }
    }

    /**
     * Renders the report using the given model.
     *
     * @param response the report model
     * @param exportType the file type to generate
     * @return the rendered report document
     * @throws IllegalArgumentException if any argument is null
     * @throws ReportGenerationException if there is any problem when generating response.
     */
    public byte[] exportReport(SuspenseResolutionReportResponse response, ExportType exportType)
        throws ReportGenerationException {
        String signature = CLASS_NAME
            + "#exportReport(SuspenseResolutionReportResponse response, ExportType exportType)";
        Logger logger = getLogger();

        LoggingHelper.logEntrance(logger, signature, new String[] {"response", "exportType"}, new Object[] {response,
            exportType});

        Helper.checkNull(logger, signature, response, "response");
        Helper.checkNull(logger, signature, exportType, "exportType");

        Document document = null;
        try {
            byte[] result = null;

            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            document = new Document();
            document.setMargins(ReportHelper.MARGIN_LR, ReportHelper.MARGIN_LR, ReportHelper.MARGIN_TB,
                ReportHelper.MARGIN_TB);

            // Associate it with output stream
            ReportHelper.initDocumentFormat(document, outputStream, exportType);

            HeaderFooter head = ReportHelper.generateHeaderNoBorder(document, response.getReportGenerationDate(),
                response.getReportName(), null);

            document.setHeader(head);
            document.open();

            // group by supervisor
            Map<String, List<SuspenseResolutionReportResponseItem>> grouped =
                new HashMap<String, List<SuspenseResolutionReportResponseItem>>();
            List<SuspenseResolutionReportResponseItem> items = response.getItems();
            if (items != null) {
                for (SuspenseResolutionReportResponseItem item : items) {
                    if (grouped.get(item.getSupervisor()) == null) {
                        grouped.put(item.getSupervisor(), new ArrayList<SuspenseResolutionReportResponseItem>());
                    }
                    grouped.get(item.getSupervisor()).add(item);
                }
            }

            if (items.isEmpty()) {
                // render empty body like in the screenshot
                renderItems(response, new ArrayList<SuspenseResolutionReportResponseItem>(), document, "");
            }

            Set<Entry<String, List<SuspenseResolutionReportResponseItem>>> entrySet = grouped.entrySet();
            for (Entry<String, List<SuspenseResolutionReportResponseItem>> entry : entrySet) {
                renderItems(response, entry.getValue(), document, entry.getKey());
            }

            document.close();
            result = outputStream.toByteArray();
            LoggingHelper.logExit(logger, signature, new Object[] {result});
            return result;
        } catch (DocumentException e) {
            throw LoggingHelper.logException(logger, signature, new ReportGenerationException(
                "An error has occurred when rendering the document.", e));
        } finally {
            // per reviewer, we should do this even if it does not make sense
            // since we needed to close it to build the PDF before return
            if (document != null) {
                document.close();
            }
        }
    }

    /**
     * Renders a table of records.
     *
     * @param response Response records
     * @param items Table details
     * @param document the current document
     * @param title The group title, currently not used
     * @throws DocumentException may be thrown by the iText library while rendering the elements
     */
    private void renderItems(SuspenseResolutionReportResponse response,
        List<SuspenseResolutionReportResponseItem> items, Document document, String title) throws DocumentException {

        // table styling
        Table table = new Table(10);
        table.setBorder(Table.NO_BORDER);
        Cell cell = new Cell();
        cell.setBorder(Cell.NO_BORDER);
        table.setDefaultCell(cell);
        table.setWidth(100);
        table.setPadding(1);

        // table header and column widths
        table.setWidths(new float[] {8, 8, 10, 10, 10, 22, 2, 2, 10, 10});

        // group header
        Cell groupHeaderCell = new Cell(new Phrase("Supervisor: " + title, ReportHelper.TABLE_HEADER_FONT));
        groupHeaderCell.setColspan(10);
        table.addCell(groupHeaderCell);

        table.addCell(ReportHelper.textLinedCell("CSD #", ReportHelper.TABLE_HEADER_FONT));
        table.addCell(ReportHelper.textLinedMoneyCell("Suspense", ReportHelper.TABLE_HEADER_FONT));
        table.addCell(ReportHelper.textLinedMoneyCell("Resolved", ReportHelper.TABLE_HEADER_FONT));
        table.addCell(ReportHelper.textLinedMoneyCell("Processed", ReportHelper.TABLE_HEADER_FONT));
        table.addCell(ReportHelper.textLinedCell("Started As", ReportHelper.TABLE_HEADER_FONT));
        table.addCell(ReportHelper.textLinedCell("Resolution", ReportHelper.TABLE_HEADER_FONT));
        table.addCell(new Phrase("     ", ReportHelper.TABLE_HEADER_FONT));
        table.addCell(new Phrase("     ", ReportHelper.TABLE_HEADER_FONT));
        table.addCell(ReportHelper.textLinedCell("Payment       ", ReportHelper.TABLE_HEADER_FONT));
        table.addCell(ReportHelper.textLinedMoneyCell("Account", ReportHelper.TABLE_HEADER_FONT));

        // process rows
        BigDecimal total = BigDecimal.ZERO;
        Date oldest = null;
        for (SuspenseResolutionReportResponseItem row : items) {
            table.addCell(new Phrase(row.getCsd(), ReportHelper.TABLE_DATA_FONT));
            table.addCell(ReportHelper.moneyCell(ReportHelper.formatMoney(row.getSuspense()),
                ReportHelper.TABLE_DATA_FONT));
            table.addCell(ReportHelper.moneyCell(ReportHelper.formatMoney(row.getResolved()),
                ReportHelper.TABLE_DATA_FONT));
            table.addCell(ReportHelper.moneyCell(ReportHelper.formatMoney(row.getProcessed()),
                ReportHelper.TABLE_DATA_FONT));
            table.addCell(new Phrase(row.getStartedAs(), ReportHelper.TABLE_DATA_FONT));
            table.addCell(new Phrase(row.getResolution(), ReportHelper.TABLE_DATA_FONT));
            table.addCell(new Phrase("     ", ReportHelper.TABLE_DATA_FONT));
            table.addCell(new Phrase("     ", ReportHelper.TABLE_DATA_FONT));
            table.addCell(new Phrase(row.getPayment(), ReportHelper.TABLE_DATA_FONT));
            table.addCell(ReportHelper.moneyCell(ReportHelper.formatMoney(row.getAccount()),
                ReportHelper.TABLE_DATA_FONT));

            total = total.add(row.getResolved() == null ? BigDecimal.ZERO : row.getResolved());

            if (row.getTransactionDate() != null) {
                if (oldest == null) {
                    oldest = row.getTransactionDate();
                } else if (oldest.before(row.getTransactionDate())) {
                    oldest = row.getTransactionDate();
                }
            }
        }

        // total row
        Cell spacerCell = new Cell("");
        spacerCell.setColspan(10);
        table.addCell(spacerCell);

        // add report note
        Cell note1Cell = new Cell(new Phrase("processed payments.", ReportHelper.TABLE_DATA_FONT));
        note1Cell.setColspan(10);
        table.addCell(note1Cell);

        String template = "employees resolved payments dated betwee {0} and {1}. The oldest one entered the";
        String longText = MessageFormat.format(template,
            ReportHelper.formatDate(response.getStartDate(), "MMMM dd, yyyy"),
            ReportHelper.formatDate(response.getEndDate(), "MMMM dd, yyyy"));
        Cell note2Cell = new Cell(new Phrase(longText, ReportHelper.TABLE_HEADER_FONT));
        note2Cell.setColspan(10);
        note2Cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(note2Cell);

        template = "Service Credit system on {0}.";
        String shortText = MessageFormat.format(template, ReportHelper.formatDate(oldest, "MMMM dd, yyyy"));
        Cell note3Cell = new Cell(new Phrase(shortText, ReportHelper.TABLE_HEADER_FONT));
        note3Cell.setColspan(10);
        note3Cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(note3Cell);

        // add total row
        Cell doubleUnderlinedCell = new Cell("     ");
        doubleUnderlinedCell.setBorder(Cell.BOTTOM);
        doubleUnderlinedCell.setBorderWidthBottom(2);
        doubleUnderlinedCell.setColspan(10);
        table.addCell(doubleUnderlinedCell);

        Cell singleUnderlinedCell = new Cell("     ");
        singleUnderlinedCell.setBorder(Cell.BOTTOM);
        singleUnderlinedCell.setBorderWidthBottom(1);
        singleUnderlinedCell.setColspan(10);
        table.addCell(singleUnderlinedCell);

        Cell totalTextCell = new Cell(new Phrase("Users Resolved Payments Totalling:", ReportHelper.TABLE_HEADER_FONT));
        totalTextCell.setColspan(8);
        totalTextCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        table.addCell(totalTextCell);

        Cell totalCell = new Cell(new Phrase(ReportHelper.formatMoney(total), ReportHelper.TABLE_HEADER_FONT));
        totalCell.setColspan(2);
        totalCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        table.addCell(totalCell);

        table.addCell(singleUnderlinedCell);

        spacerCell = new Cell("");
        spacerCell.setColspan(10);
        table.addCell(spacerCell);

        document.add(table);
    }

    /**
     * Renders the chart image.
     *
     * @param response the service response for rendering.
     * @return the byte array of the image.
     * @throws ReportGenerationException if there are any error.
     */
    @Override
    public byte[] renderChart(SuspenseResolutionReportResponse response) throws ReportGenerationException {
        return null;
    }
}


text:
namespace EasyCpp
{
	namespace VFS
	{
		Path::Path()
			: Path("/")
		{}

		Path::Path(const std::string & path)
		{
			auto vector = stringSplit<std::string>("/", path);
			if (path.length() == 0 || path[0] != '/')
				throw std::runtime_error("Invalid path");
			if (vector[vector.size() - 1] != "") {
				std::string filename = vector[vector.size() - 1];
				size_t extpos = filename.find_last_of('.');
				if (extpos != std::string::npos)
				{
					_filename = filename.substr(0, extpos);
					_extension = filename.substr(extpos + 1);
				}
				else _filename = filename;
				vector[vector.size() - 1] = "";
			}
			_dirname = implode<std::string>("/", vector);
			normalize();
		}

		Path::Path(const std::string & dirname, const std::string & basename)
		{
			std::regex fregex("^([^\\/]*)?$");
			if (!std::regex_match(basename, fregex))
				throw std::runtime_error("Not a valid filename");
			if (dirname.length() == 0 || dirname[0] != '/' || dirname[dirname.size() - 1] != '/')
				throw std::runtime_error("Invalid path");
			_dirname = dirname;
			std::string filename = basename;
			size_t extpos = filename.find_last_of('.');
			if (extpos != std::string::npos)
			{
				_filename = filename.substr(0, extpos);
				_extension = filename.substr(extpos + 1);
			}
			else _filename = filename;
			normalize();
		}

		Path::Path(const std::string & dirname, const std::string & filename, const std::string & extension)
		{
			std::regex fregex("^([^\\/\\.]*)?$");
			if (dirname.length() == 0 || dirname[0] != '/' || dirname[dirname.size() - 1] != '/')
				throw std::runtime_error("Invalid path");
			if (!std::regex_match(filename, fregex))
				throw std::runtime_error("Not a valid filename");
			if (!std::regex_match(extension, fregex))
				throw std::runtime_error("Not a valid extension");
			_dirname = dirname;
			_filename = filename;
			_extension = extension;
			normalize();
		}

		Path::~Path()
		{
		}

		std::string Path::getDirName() const
		{
			return _dirname;
		}

		std::string Path::getBaseName() const
		{
			std::string res = _filename;
			if (_extension != "")
				res += "." + _extension;
			return res;
		}

		std::string Path::getExtension() const
		{
			return _extension;
		}

		std::string Path::getFileName() const
		{
			return _filename;
		}

		std::string Path::getString() const
		{
			std::string bname = getBaseName();
			return getDirName() + (bname != "" ? bname : "");
		}

		bool Path::hasFile() const
		{
			return _filename != "" || _extension != "";
		}

		void Path::normalize()
		{
			std::vector<std::string> parts = stringSplit("/", _dirname);
			std::vector<std::string> out;
			for (const auto& e : parts)
			{
				if (e == "" || e == ".") {
				}
				else if (e == "..") {
					if (out.size() > 0) {
						out.erase(out.begin() + out.size() - 1);
					}
				}
				else {
					out.push_back(e);
				}
			}
			out.push_back("");
			_dirname = "/" + implode<std::string>("/", out);
		}

		const Path DLL_EXPORT operator+(Path const & lhs, Path const & rhs)
		{
			return Path(lhs.getString() + rhs.getString());
		}
	}
}


text:
package com.facebook.fbreact.specs;

import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.ReactModuleWithSpec;
import com.facebook.react.turbomodule.core.interfaces.TurboModule;
import javax.annotation.Nullable;

public abstract class NativeHeapCaptureSpec extends ReactContextBaseJavaModule implements ReactModuleWithSpec, TurboModule {
  public NativeHeapCaptureSpec(ReactApplicationContext reactContext) {
    super(reactContext);
  }

  @ReactMethod
  public abstract void captureComplete(String path, @Nullable String error);

  @ReactMethod
  public abstract void captureHeap(String path);
}


text:
package download

import (
	"context"
	"errors"
	"fmt"
	"reflect"
	"strings"
	"testing"
	"time"

	"github.com/open-policy-agent/opa/bundle"
	"github.com/open-policy-agent/opa/logging"
	"github.com/open-policy-agent/opa/logging/test"
	"github.com/open-policy-agent/opa/metrics"
	"github.com/open-policy-agent/opa/plugins"
)

func TestStartStop(t *testing.T) {
	ctx := context.Background()
	fixture := newTestFixture(t)

	updates := make(chan *Update)

	config := Config{}
	if err := config.ValidateAndInjectDefaults(); err != nil {
		t.Fatal(err)
	}

	d := New(config, fixture.client, "/bundles/test/bundle1").WithCallback(func(_ context.Context, u Update) {
		updates <- &u
	})

	d.Start(ctx)

	// Give time for some download events to occur
	time.Sleep(1 * time.Second)

	u1 := <-updates

	if u1.Bundle == nil || len(u1.Bundle.Modules) == 0 {
		t.Fatal("expected bundle with at least one module but got:", u1)
	}

	if !strings.HasSuffix(u1.Bundle.Modules[0].URL, u1.Bundle.Modules[0].Path) {
		t.Fatalf("expected URL to have path as suffix but got %v and %v", u1.Bundle.Modules[0].URL, u1.Bundle.Modules[0].Path)
	}

	if u1.Size == 0 {
		t.Fatal("expected non-0 size")
	}

	d.Stop(ctx)
}

func TestStartStopWithBundlePersistence(t *testing.T) {
	ctx := context.Background()
	fixture := newTestFixture(t)

	updates := make(chan *Update)

	config := Config{}
	if err := config.ValidateAndInjectDefaults(); err != nil {
		t.Fatal(err)
	}

	d := New(config, fixture.client, "/bundles/test/bundle1").WithCallback(func(_ context.Context, u Update) {
		updates <- &u
	}).WithBundlePersistence(true)

	d.Start(ctx)

	// Give time for some download events to occur
	time.Sleep(1 * time.Second)

	u1 := <-updates

	if u1.Bundle == nil || len(u1.Bundle.Modules) == 0 {
		t.Fatal("expected bundle with at least one module but got:", u1)
	}

	if !strings.HasSuffix(u1.Bundle.Modules[0].URL, u1.Bundle.Modules[0].Path) {
		t.Fatalf("expected URL to have path as suffix but got %v and %v", u1.Bundle.Modules[0].URL, u1.Bundle.Modules[0].Path)
	}

	if u1.Raw == nil {
		t.Fatal("expected bundle reader to be non-nil")
	}

	if u1.Size == 0 {
		t.Fatal("expected non-0 size")
	}

	r := bundle.NewReader(u1.Raw)

	b, err := r.Read()
	if err != nil {
		t.Fatal(err)
	}

	if !reflect.DeepEqual(b.Data, u1.Bundle.Data) {
		t.Fatal("expected the bundle object and reader to have the same data")
	}

	if len(b.Modules) != len(u1.Bundle.Modules) {
		t.Fatal("expected the bundle object and reader to have the same number of bundle modules")
	}

	d.Stop(ctx)
}

func TestStopWithMultipleCalls(t *testing.T) {
	ctx := context.Background()
	fixture := newTestFixture(t)

	updates := make(chan *Update)

	config := Config{}
	if err := config.ValidateAndInjectDefaults(); err != nil {
		t.Fatal(err)
	}

	d := New(config, fixture.client, "/bundles/test/bundle1").WithCallback(func(_ context.Context, u Update) {
		updates <- &u
	})

	d.Start(ctx)

	// Give time for some download events to occur
	time.Sleep(1 * time.Second)

	u1 := <-updates

	if u1.Bundle == nil || len(u1.Bundle.Modules) == 0 {
		t.Fatal("expected bundle with at least one module but got:", u1)
	}

	done := make(chan struct{})
	go func() {
		d.Stop(ctx)
		close(done)
	}()

	d.Stop(ctx)
	<-done

	if !d.stopped {
		t.Fatal("expected downloader to be stopped")
	}
}

func TestStartStopWithLazyLoadingMode(t *testing.T) {
	ctx := context.Background()
	fixture := newTestFixture(t)

	updates := make(chan *Update)

	config := Config{}
	if err := config.ValidateAndInjectDefaults(); err != nil {
		t.Fatal(err)
	}

	d := New(config, fixture.client, "/bundles/test/bundle1").WithCallback(func(_ context.Context, u Update) {
		updates <- &u
	}).WithLazyLoadingMode(true)

	d.Start(ctx)

	// Give time for some download events to occur
	time.Sleep(1 * time.Second)

	u1 := <-updates

	if u1.Bundle == nil || len(u1.Bundle.Modules) == 0 {
		t.Fatal("expected bundle with at least one module but got:", u1)
	}

	if !strings.HasSuffix(u1.Bundle.Modules[0].URL, u1.Bundle.Modules[0].Path) {
		t.Fatalf("expected URL to have path as suffix but got %v and %v", u1.Bundle.Modules[0].URL, u1.Bundle.Modules[0].Path)
	}

	if len(u1.Bundle.Raw) == 0 {
		t.Fatal("expected bundle to contain raw bytes")
	}

	if len(u1.Bundle.Data) != 0 {
		t.Fatal("expected the bundle object to contain no data")
	}

	d.Stop(ctx)
}

func TestStartStopWithDeltaBundleMode(t *testing.T) {
	ctx := context.Background()

	updates := make(chan *Update)

	config := Config{}

	if err := config.ValidateAndInjectDefaults(); err != nil {
		t.Fatal(err)
	}

	fixture := newTestFixture(t)

	d := New(config, fixture.client, "/bundles/test/bundle2").WithCallback(func(_ context.Context, u Update) {
		updates <- &u
	})

	d.Start(ctx)

	// Give time for some download events to occur
	time.Sleep(1 * time.Second)

	u1 := <-updates

	if u1.Bundle == nil || u1.Bundle.Manifest.Revision != deltaBundleMode {
		t.Fatal("expected delta bundle but got:", u1)
	}

	if u1.Size == 0 {
		t.Fatal("expected non-0 size")
	}

	d.Stop(ctx)
}

func TestStartStopWithLongPollNotSupported(t *testing.T) {
	ctx := context.Background()

	config := Config{}
	min := int64(1)
	max := int64(2)
	timeout := int64(1)
	config.Polling.MinDelaySeconds = &min
	config.Polling.MaxDelaySeconds = &max
	config.Polling.LongPollingTimeoutSeconds = &timeout

	if err := config.ValidateAndInjectDefaults(); err != nil {
		t.Fatal(err)
	}

	fixture := newTestFixture(t)
	fixture.d = New(config, fixture.client, "/bundles/test/bundle1").WithCallback(fixture.oneShot)
	defer fixture.server.stop()

	fixture.d.Start(ctx)

	// Give time for some download events to occur
	time.Sleep(5 * time.Second)

	fixture.d.Stop(ctx)
	if len(fixture.updates) < 2 {
		t.Fatalf("Expected at least 2 updates but got %v\n", len(fixture.updates))
	}
}

func TestStartStopWithLongPollSupportedByServer(t *testing.T) {
	ctx := context.Background()

	config := Config{}
	min := int64(1)
	max := int64(2)
	config.Polling.MinDelaySeconds = &min
	config.Polling.MaxDelaySeconds = &max

	// simulate scenario where server supports long polling but long polling timeout not provided
	config.Polling.LongPollingTimeoutSeconds = nil

	if err := config.ValidateAndInjectDefaults(); err != nil {
		t.Fatal(err)
	}

	fixture := newTestFixture(t)
	fixture.d = New(config, fixture.client, "/bundles/test/bundle1").WithCallback(fixture.oneShot)
	fixture.server.longPoll = true
	defer fixture.server.stop()

	fixture.d.Start(ctx)

	// Give time for some download events to occur
	time.Sleep(3 * time.Second)

	fixture.d.Stop(ctx)
	if len(fixture.updates) == 0 {
		t.Fatal("expected update but got none")
	}

	if *fixture.d.client.Config().ResponseHeaderTimeoutSeconds == 0 {
		t.Fatal("expected non-zero value for response header timeout")
	}
}

func TestStartStopWithLongPollSupported(t *testing.T) {
	ctx := context.Background()

	config := Config{}
	timeout := int64(1)
	config.Polling.LongPollingTimeoutSeconds = &timeout

	if err := config.ValidateAndInjectDefaults(); err != nil {
		t.Fatal(err)
	}

	fixture := newTestFixture(t)
	fixture.d = New(config, fixture.client, "/bundles/test/bundle1").WithCallback(fixture.oneShot)
	fixture.server.longPoll = true
	defer fixture.server.stop()

	fixture.d.Start(ctx)

	// Give time for some download events to occur
	time.Sleep(3 * time.Second)

	fixture.d.Stop(ctx)
	if len(fixture.updates) == 0 {
		t.Fatal("expected update but got none")
	}
}

func TestStartStopWithLongPollWithLongTimeout(t *testing.T) {
	ctx := context.Background()

	config := Config{}
	timeout := int64(3) // this will result in the test server sleeping for 3 seconds
	config.Polling.LongPollingTimeoutSeconds = &timeout

	if err := config.ValidateAndInjectDefaults(); err != nil {
		t.Fatal(err)
	}

	fixture := newTestFixture(t)
	fixture.d = New(config, fixture.client, "/bundles/test/bundle1").WithCallback(fixture.oneShot)
	fixture.server.longPoll = true
	defer fixture.server.stop()

	fixture.d.Start(ctx)

	time.Sleep(500 * time.Millisecond)

	if len(fixture.updates) != 0 {
		t.Fatalf("expected no update but got %v", len(fixture.updates))
	}

	fixture.d.Stop(ctx)

	if len(fixture.updates) != 1 {
		t.Fatalf("expected one update but got %v", len(fixture.updates))
	}

	if fixture.updates[0].Error == nil {
		t.Fatal("expected error but got nil")
	}
}

func TestEtagCachingLifecycle(t *testing.T) {

	ctx := context.Background()
	fixture := newTestFixture(t)
	fixture.d = New(Config{}, fixture.client, "/bundles/test/bundle1").WithCallback(fixture.oneShot)
	defer fixture.server.stop()

	// check etag on the downloader is empty
	if fixture.d.etag != "" {
		t.Fatalf("Expected empty downloader ETag but got %v", fixture.d.etag)
	}

	// simulate downloader error on first bundle download
	fixture.server.expCode = 500
	fixture.server.expEtag = "some etag value"
	err := fixture.d.oneShot(ctx)
	if err == nil {
		t.Fatal("Expected error but got nil")
	} else if len(fixture.updates) != 1 {
		t.Fatal("expected update")
	} else if fixture.d.etag != "" {
		t.Fatalf("Expected empty downloader ETag but got %v", fixture.d.etag)
	}

	// simulate successful bundle activation and check updated etag on the downloader
	fixture.server.expCode = 0
	err = fixture.d.oneShot(ctx)
	if err != nil {
		t.Fatal("Unexpected:", err)
	} else if len(fixture.updates) != 2 {
		t.Fatal("expected update")
	} else if fixture.d.etag != fixture.server.expEtag {
		t.Fatalf("Expected downloader ETag %v but got %v", fixture.server.expEtag, fixture.d.etag)
	}

	// simulate another successful bundle activation and check updated etag on the downloader
	fixture.server.expEtag = "some etag value - 2"
	err = fixture.d.oneShot(ctx)
	if err != nil {
		t.Fatal("Unexpected:", err)
	} else if len(fixture.updates) != 3 {
		t.Fatal("expected update")
	} else if fixture.d.etag != fixture.server.expEtag {
		t.Fatalf("Expected downloader ETag %v but got %v", fixture.server.expEtag, fixture.d.etag)
	}

	// simulate bundle activation error and check etag is set from the last successful activation
	fixture.mockBundleActivationError = true
	fixture.server.expEtag = "some newer etag value - 3"
	err = fixture.d.oneShot(ctx)
	if err != nil {
		t.Fatal("Unexpected:", err)
	} else if len(fixture.updates) != 4 {
		t.Fatal("expected update")
	} else if fixture.d.etag != "some etag value - 2" {
		t.Fatalf("Expected downloader ETag %v but got %v", "some etag value - 2", fixture.d.etag)
	}

	// simulate successful bundle activation and check updated etag on the downloader
	fixture.server.expCode = 0
	fixture.mockBundleActivationError = false
	err = fixture.d.oneShot(ctx)
	if err != nil {
		t.Fatal("Unexpected:", err)
	} else if len(fixture.updates) != 5 {
		t.Fatal("expected update")
	} else if fixture.d.etag != fixture.server.expEtag {
		t.Fatalf("Expected downloader ETag %v but got %v", fixture.server.expEtag, fixture.d.etag)
	}

	// simulate downloader error and check etag is set from the last successful activation
	fixture.server.expCode = 500
	err = fixture.d.oneShot(ctx)
	if err == nil {
		t.Fatal("Expected error but got nil")
	} else if len(fixture.updates) != 6 {
		t.Fatal("expected update")
	} else if fixture.d.etag != fixture.server.expEtag {
		t.Fatalf("Expected downloader ETag %v but got %v", fixture.server.expEtag, fixture.d.etag)
	}

	// simulate bundle activation error and check etag is set from the last successful activation
	fixture.mockBundleActivationError = true
	fixture.server.expCode = 0
	err = fixture.d.oneShot(ctx)
	if err != nil {
		t.Fatal("Unexpected:", err)
	} else if len(fixture.updates) != 7 {
		t.Fatal("expected update")
	} else if fixture.d.etag != fixture.server.expEtag {
		t.Fatalf("Expected downloader ETag %v but got %v", fixture.server.expEtag, fixture.d.etag)
	}
}

func TestOneShotWithBundleEtag(t *testing.T) {

	ctx := context.Background()
	fixture := newTestFixture(t)
	fixture.d = New(Config{}, fixture.client, "/bundles/test/bundle1").WithCallback(fixture.oneShot)
	fixture.server.expEtag = "some etag value"
	defer fixture.server.stop()

	// check etag on the downloader is empty
	if fixture.d.etag != "" {
		t.Fatalf("Expected empty downloader ETag but got %v", fixture.d.etag)
	}

	// simulate successful bundle activation and check updated etag on the downloader
	fixture.server.expCode = 0
	err := fixture.d.oneShot(ctx)
	if err != nil {
		t.Fatal("Unexpected:", err)
	}

	if fixture.d.etag != fixture.server.expEtag {
		t.Fatalf("Expected downloader ETag %v but got %v", fixture.server.expEtag, fixture.d.etag)
	}

	if fixture.updates[0].Bundle == nil {
		// 200 response on first request, bundle should be present
		t.Errorf("Expected bundle in response")
	}

	if fixture.updates[0].Bundle.Etag != fixture.server.expEtag {
		t.Fatalf("Expected bundle ETag %v but got %v", fixture.server.expEtag, fixture.updates[0].Bundle.Etag)
	}
}

func TestFailureAuthn(t *testing.T) {

	ctx := context.Background()
	fixture := newTestFixture(t)
	fixture.server.expAuth = "Bearer anothersecret"
	defer fixture.server.stop()

	d := New(Config{}, fixture.client, "/bundles/test/bundle1")

	err := d.oneShot(ctx)
	if err == nil {
		t.Fatal("expected error")
	}
}

func TestFailureNotFound(t *testing.T) {

	ctx := context.Background()
	fixture := newTestFixture(t)
	delete(fixture.server.bundles, "test/bundle1")
	defer fixture.server.stop()

	d := New(Config{}, fixture.client, "/bundles/test/non-existent")

	err := d.oneShot(ctx)
	if err == nil {
		t.Fatal("expected error")
	}
}

func TestFailureUnexpected(t *testing.T) {

	ctx := context.Background()
	fixture := newTestFixture(t)
	fixture.server.expCode = 500
	defer fixture.server.stop()

	d := New(Config{}, fixture.client, "/bundles/test/bundle1")

	err := d.oneShot(ctx)
	if err == nil {
		t.Fatal("expected error")
	}
	var hErr HTTPError
	if !errors.As(err, &hErr) {
		t.Fatal("expected HTTPError")
	}
	if hErr.StatusCode != 500 {
		t.Fatal("expected status code 500")
	}
}

func TestEtagInResponse(t *testing.T) {
	ctx := context.Background()
	fixture := newTestFixture(t)
	fixture.server.etagInResponse = true
	fixture.d = New(Config{}, fixture.client, "/bundles/test/bundle1").WithCallback(fixture.oneShot)
	defer fixture.server.stop()

	if fixture.d.etag != "" {
		t.Fatalf("Expected empty downloader ETag but got %v", fixture.d.etag)
	}

	fixture.server.expEtag = "some etag value"

	err := fixture.d.oneShot(ctx)
	if err != nil {
		t.Fatal("Unexpected:", err)
	} else if len(fixture.updates) != 1 {
		t.Fatal("expected update")
	} else if fixture.d.etag != fixture.server.expEtag {
		t.Fatalf("Expected downloader ETag %v but got %v", fixture.server.expEtag, fixture.d.etag)
	}

	if fixture.updates[0].Bundle == nil {
		// 200 response on first request, bundle should be present
		t.Errorf("Expected bundle in response")
	}

	err = fixture.d.oneShot(ctx)
	if err != nil {
		t.Fatal("Unexpected:", err)
	} else if len(fixture.updates) != 2 {
		t.Fatal("expected two updates")
	} else if fixture.d.etag != fixture.server.expEtag {
		t.Fatalf("Expected downloader ETag %v but got %v", fixture.server.expEtag, fixture.d.etag)
	}

	if fixture.updates[1].Bundle != nil {
		// 304 response on second request, bundle should _not_ be present
		t.Errorf("Expected no bundle in response")
	}
}

func TestTriggerManual(t *testing.T) {

	ctx := context.Background()
	fixture := newTestFixture(t)

	config := Config{}
	tr := plugins.TriggerManual
	config.Trigger = &tr

	if err := config.ValidateAndInjectDefaults(); err != nil {
		t.Fatal(err)
	}

	updates := make(chan *Update)

	d := New(config, fixture.client, "/bundles/test/bundle1").
		WithCallback(func(_ context.Context, u Update) {
			updates <- &u
		})

	d.Start(ctx)

	// execute a series of triggers and expect responses
	for i := 0; i < 10; i++ {

		// mutate the fixture server's bundle for this trigger
		exp := fmt.Sprintf("rev%d", i)
		b := fixture.server.bundles["test/bundle1"]
		b.Manifest.Revision = exp
		fixture.server.bundles["test/bundle1"] = b

		// trigger the downloader
		go func() {
			d.Trigger(ctx)
		}()

		// wait for the update
		u := <-updates

		if u.Bundle.Manifest.Revision != exp {
			t.Fatalf("expected revision %q but got %q", exp, u.Bundle.Manifest.Revision)
		}
	}

	d.Stop(ctx)
}

func TestTriggerManualWithTimeout(t *testing.T) {

	ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
	defer cancel()

	fixture := newTestFixture(t)

	config := Config{}
	tr := plugins.TriggerManual
	config.Trigger = &tr

	if err := config.ValidateAndInjectDefaults(); err != nil {
		t.Fatal(err)
	}

	d := New(config, fixture.client, "/bundles/test/bundle1").
		WithCallback(func(context.Context, Update) {
			time.Sleep(3 * time.Second) // this should cause the context deadline to exceed
		})

	d.Start(ctx)

	b := fixture.server.bundles["test/bundle1"]
	b.Manifest.Revision = "rev%0"
	fixture.server.bundles["test/bundle1"] = b

	// trigger the downloader
	done := make(chan struct{})
	go func() {
		// this call should block till the context deadline exceeds
		d.Trigger(ctx)
		close(done)
	}()
	<-done

	if ctx.Err() == nil {
		t.Fatal("Expected error but got nil")
	}

	exp := context.DeadlineExceeded
	if ctx.Err() != exp {
		t.Fatalf("Expected error %v but got %v", exp, ctx.Err())
	}

	d.Stop(context.Background())
}

func TestDownloadLongPollNotModifiedOn304(t *testing.T) {

	ctx := context.Background()
	config := Config{}
	timeout := int64(3) // this will result in the test server sleeping for 3 seconds
	config.Polling.LongPollingTimeoutSeconds = &timeout

	if err := config.ValidateAndInjectDefaults(); err != nil {
		t.Fatal(err)
	}

	fixture := newTestFixture(t)
	fixture.d = New(config, fixture.client, "/bundles/test/bundle1").WithCallback(fixture.oneShot)
	fixture.server.longPoll = true
	fixture.server.expEtag = "foo"
	fixture.d.etag = fixture.server.expEtag // not modified
	fixture.server.expCode = 0
	defer fixture.server.stop()

	resp, err := fixture.d.download(ctx, metrics.New())
	if err != nil {
		t.Fatal("Unexpected:", err)
	}
	if resp.longPoll != fixture.d.longPollingEnabled {
		t.Fatalf("Expected same value for longPoll and longPollingEnabled")
	}
}

func TestOneShotLongPollingSwitch(t *testing.T) {
	ctx := context.Background()
	config := Config{}
	timeout := int64(3) // this will result in the test server sleeping for 3 seconds
	config.Polling.LongPollingTimeoutSeconds = &timeout
	if err := config.ValidateAndInjectDefaults(); err != nil {
		t.Fatal(err)
	}
	fixture := newTestFixture(t)
	fixture.d = New(config, fixture.client, "/bundles/test/bundle1").WithCallback(fixture.oneShot)
	fixture.server.expCode = 0
	defer fixture.server.stop()

	fixture.server.longPoll = true
	err := fixture.d.oneShot(ctx)
	if err != nil {
		t.Fatal("Unexpected:", err)
	}
	if fixture.d.longPollingEnabled != fixture.server.longPoll {
		t.Fatalf("Expected same value for longPoll and longPollingEnabled")
	}

	fixture.server.longPoll = false
	err = fixture.d.oneShot(ctx)
	if err != nil {
		t.Fatal("Unexpected:", err)
	}
	if fixture.d.longPollingEnabled != fixture.server.longPoll {
		t.Fatalf("Expected same value for longPollingEnabled and longPoll")
	}
}

func TestOneShotNotLongPollingSwitch(t *testing.T) {
	ctx := context.Background()
	config := Config{}
	timeout := int64(3)
	config.Polling.LongPollingTimeoutSeconds = &timeout
	if err := config.ValidateAndInjectDefaults(); err != nil {
		t.Fatal(err)
	}
	fixture := newTestFixture(t)
	fixture.d = New(config, fixture.client, "/bundles/test/bundle1").WithCallback(fixture.oneShot)
	fixture.server.expCode = 0

	defer fixture.server.stop()

	fixture.server.longPoll = true
	err := fixture.d.oneShot(ctx)
	if err != nil {
		t.Fatal("Unexpected:", err)
	}
	if !fixture.d.longPollingEnabled {
		t.Fatal("Expected long polling to be enabled")
	}

	fixture.server.longPoll = false
	err = fixture.d.oneShot(ctx)
	if err != nil {
		t.Fatal("Unexpected:", err)
	}
	if fixture.d.longPollingEnabled {
		t.Fatal("Expected long polling to be disabled")
	}
}

func TestWarnOnNonBundleContentType(t *testing.T) {
	ctx := context.Background()
	fixture := newTestFixture(t)
	fixture.server.bundles["not-a-bundle"] = bundle.Bundle{}

	config := Config{}
	if err := config.ValidateAndInjectDefaults(); err != nil {
		t.Fatal(err)
	}

	d := New(config, fixture.client, "/bundles/not-a-bundle")
	logger := test.New()
	logger.SetLevel(logging.Debug)
	d.logger = logger

	d.Start(ctx)

	time.Sleep(1 * time.Second)

	d.Stop(ctx)

	expectLogged := "Content-Type response header set to text/html. " +
		"Expected one of [application/gzip application/octet-stream application/vnd.openpolicyagent.bundles]. " +
		"Possibly not a bundle being downloaded."
	var found bool
	for _, entry := range logger.Entries() {
		if entry.Message == expectLogged {
			found = true
			break
		}
	}

	if !found {
		t.Errorf("Expected log entry: %s", expectLogged)
	}
}


text:
namespace IntegrationTests
{
	using AspNet.Identity.MongoDB;
	using Microsoft.AspNet.Identity;
	using MongoDB.Driver;
	using NUnit.Framework;

	public class UserIntegrationTestsBase : AssertionHelper
	{
		protected MongoDatabase Database;
		protected MongoCollection<IdentityUser> Users;
		protected MongoCollection<IdentityRole> Roles;

		// note: for now we'll have interfaces to both the new and old apis for MongoDB, that way we don't have to update all the tests at once and risk introducing bugs
		protected IMongoDatabase DatabaseNewApi;
		private IMongoCollection<IdentityUser> _UsersNewApi;
		private IMongoCollection<IdentityRole> _RolesNewApi;

		[SetUp]
		public void BeforeEachTest()
		{
			var client = new MongoClient("mongodb://localhost:27017");
			var identityTesting = "identity-testing";

			Database = client.GetServer().GetDatabase(identityTesting);
			Users = Database.GetCollection<IdentityUser>("users");
			Roles = Database.GetCollection<IdentityRole>("roles");

			DatabaseNewApi = client.GetDatabase(identityTesting);
			_UsersNewApi = DatabaseNewApi.GetCollection<IdentityUser>("users");
			_RolesNewApi = DatabaseNewApi.GetCollection<IdentityRole>("roles");

			Database.DropCollection("users");
			Database.DropCollection("roles");
		}

		protected UserManager<IdentityUser> GetUserManager()
		{
			var store = new UserStore<IdentityUser>(_UsersNewApi);
			return new UserManager<IdentityUser>(store);
		}

		protected RoleManager<IdentityRole> GetRoleManager()
		{
			var store = new RoleStore<IdentityRole>(_RolesNewApi);
			return new RoleManager<IdentityRole>(store);
		}
	}
}


text:
  <title>accounts-saml-example-openidp</title>

	{{>samlDemo}}

<template name="samlDemo">
	{{loginButtons}}

	{{#unless currentUser}}
		Log in with OpenIDP
	{{/unless}}

Step 1

	Create a password based account.

Step 2

	Sign out / log out.  You should see both the login buttons control 'Sign In' and the custom saml login link 'Log in with OpenIDP'

Step 3

	Create OpenIDP account if you don't already have one with same email address as the password account. https://openidp.feide.no/

Step 4

	Click the link 'Log in with OpenIDP'. In the pop up window, log in with your OpenIDP credentials.

Step 5

	If all goes well, the popup should close by itself.  You should now be logged in just as if you had typed in your username and password.

</template>


text:
template<typename T>
static T* npc(T* t)
{
    if(!t) throw new ::java::lang::NullPointerException();
    return t;
}

poi::sl::draw::geom::AdjustValue::AdjustValue(const ::default_init_tag&)
    : super(*static_cast< ::default_init_tag* >(0))
{
    clinit();
}

poi::sl::draw::geom::AdjustValue::AdjustValue(::poi::sl::draw::binding::CTGeomGuide* gd)
    : AdjustValue(*static_cast< ::default_init_tag* >(0))
{
    ctor(gd);
}

void poi::sl::draw::geom::AdjustValue::ctor(::poi::sl::draw::binding::CTGeomGuide* gd)
{
    super::ctor(npc(gd)->getName(), npc(gd)->getFmla());
}

double poi::sl::draw::geom::AdjustValue::evaluate(Context* ctx)
{
    auto name = getName();
    auto adj = npc(ctx)->getAdjustValue(name);
    return (adj != nullptr) ? npc(adj)->evaluate(ctx) : super::evaluate(ctx);
}

extern java::lang::Class *class_(const char16_t *c, int n);

java::lang::Class* poi::sl::draw::geom::AdjustValue::class_()
{
    static ::java::lang::Class* c = ::class_(u"org.apache.poi.sl.draw.geom.AdjustValue", 39);
    return c;
}

java::lang::Class* poi::sl::draw::geom::AdjustValue::getClass0()
{
    return class_();
}


text:
package org.jetbrains.plugins.scala
package annotator
package quickfix

import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiFile
import org.jetbrains.plugins.scala.lang.psi.api.base.ScLiteral
import org.jetbrains.plugins.scala.lang.psi.impl.ScalaPsiElementFactory.createExpressionFromText

/**
 * @author Ye Xianjin
 */
class ConvertOctalToHexFix(literal: ScLiteral) extends IntentionAction {
  override val getText: String = "convert Octal string to Hex string"

  override def getFamilyName: String = "Change ScLiteral"

  override def startInWriteAction: Boolean = true

  override def isAvailable(project: Project, editor: Editor, file: PsiFile): Boolean =
    literal.isValid && literal.getManager.isInProject(file)

  // the input text should be legal octal string
  private def convertOctalToHex(text: String): String = {
    import scala.math.BigInt
    val endsWithL = text.endsWith("l") || text.endsWith("L")
    val textWithoutL = if (endsWithL) text.substring(0, text.length - 1) else text
    val hexString = "0x" + BigInt(textWithoutL, 8).toString(16)
    if (endsWithL) hexString + "L" else hexString
  }

  override def invoke(project: Project, editor: Editor, file: PsiFile): Unit = {
    if (!literal.isValid) return
    val text = literal.getText
    if (!(text.length >= 2 && text(0) == '0' && text(1).toLower != 'x')) return
    literal.replace(createExpressionFromText(convertOctalToHex(text))(literal.getManager))
  }
}


text:
#include <Furrovine++/Text/Encoding/TextEncodingUnit.h>

namespace Furrovine { namespace Text { namespace Encoding {

	struct ascii : public TextEncodingUnit<ascii, char> {
	public:

		template <typename TIterator>
		TIterator EncodeOneBytes( codepoint c, TIterator bytes ) const {
			if ( c <= 0x7F ) {
				*bytes++ = static_cast<byte>( c );
			}
			else {
				// TODO: encoder error
				*bytes++ = ReplacementCodeUnit;
			}

			return bytes;
		}

		template <typename TIterator>
		TIterator DecodeOneBytes( TIterator bytes, codepoint &c ) const {
			c = *bytes++;
			if ( c > 0x7F ) {
				// TODO: decoder error
				c = ReplacementCodePoint;
			}
			return bytes;
		}

		template <typename TIterator>
		TIterator ReverseDecodeOneBytes( TIterator forwardbytes, codepoint &c ) const {
			auto bytes = std::reverse_iterator<TIterator>( forwardbytes );
			c = *bytes++;
			if ( c > 0x7F ) {
				// TODO: decoder error
				c = ReplacementCodePoint;
			}
			return bytes;
		}

	};

}}}

#endif // FURROVINEASCII_H


text:
"""Module for defining constants used in the tool."""

import enum

class RecordType(enum.IntEnum):
  """Define SMBIOS record types."""
  BIOS_RECORD = 0
  SYSTEM_RECORD = 1
  BASEBOARD_RECORD = 2
  CHASSIS_RECORD = 3
  PROCESSOR_RECORD = 4
  CACHE_RECORD = 7
  PORT_CONNECTOR_RECORD = 8
  SYSTEM_SLOTS_RECORD = 9
  GROUP_ASSOCIATIONS_RECORD = 14
  PHYSICAL_MEMORY_ARRAY_RECORD = 16
  MEMORY_DEVICE_RECORD = 17
  MEMORY_ARRAY_MAPPED_ADDRESS_RECORD = 19
  MEMORY_DEVICE_MAPPED_ADDRESS_RECORD = 20
  SYSTEM_BOOT_INFO_RECORD = 32
  IPMI_DEVICE_INFO_RECORD = 38
  SYSTEM_POWER_SUPPLY_RECORD = 39
  GOOGLE_BRIDGE_DEVICE_RECORD = 160
  GOOGLE_LINK_DEVICE_RECORD = 161
  GOOGLE_CPU_LINK_RECORD = 162

class FieldValueEnums(enum.Enum):
  """List all enums used to verify field value of records."""
  CHASSIS_TYPES = ['Main Server Chassis', 'Rack Mount Chassis']
  CHASSIS_LOCK = ['Present', 'Not Present']
  PROCESSOR_TYPE = ['Central Processor']
  PROCESSOR_STATUS = ['Populated', 'Unpopulated', 'Enabled', 'Disabled']
  SYSTEM_SLOTS_CURRENT_USAGE = ['In Use', 'Available', 'Unknown']
  SYSTEM_SLOTS_LENGTH = ['Short', 'Long']
  PHYSICAL_MEMORY_ARRAY_LOCATION = ['System Board Or Motherboard']
  PHYSICAL_MEMORY_ARRAY_USE = ['System Memory']
  MEMORY_DEVICE_FORM_FACTOR = ['Unknown', 'DIMM']
  MEMORY_DEVICE_TYPES = ['Unknown', 'DDR4', 'LPDDR4', 'DDR5', 'Logical non-volatile device']
  IPMI_DEVICE_INTERFACE_TYPES = [
      'BT (Block Transfer)', 'KCS (Keyboard Control Style)'
  ]

class FieldValueRegexps(enum.Enum):
  """List all regex patterns used to verify field value of records."""
  NUMBER_REGEXP = r'\d+'
  NUMBER_WITH_UNKNOWN_REGEXP = r'\d+|unknown'
  HEX_REGEXP = r'0x[0-9A-Fa-f]+'
  SPEED_REGEXP = r'(Unknown)|(\d+ [KMG]T/s)'
  SIZE_REGEXP = r'(Unknown)|(No Module Installed)|(\d+ ([kmgtKMGT]B|bits))'
  VERSION_REGEXP = r'[\d.]+'
  DATE_REGEXP = r'\d{2}/\d{2}/\d{4}'
  DEVPATH_REGEXP = r'[\w/]*'
  OEM_FOR_GOOGLE_REGEXP = r'0x[0-9A-Fa-f]*67'
  VENDOR_FOR_GOOGLE_REGEXP = r'.*Google.*'
  SOCKET_DESIGNATION_REGEXP = r'(CPU|P)\d+'
  DEVICE_LOCATOR_REGEXP = r'(?:[^\d]*)\d+'
  BANK_LOCATOR_REGEXP = r'.*(Node|Channel).*'


text:
"""
Module for YamlTemplateReaderFactory
"""
from src.data.template.yaml.YamlTemplateFieldBuilder import YamlTemplateFieldBuilder
from src.data.template.yaml.YamlTemplateReader import YamlTemplateReader

__author__ = 'DWI'

class YamlTemplateReaderFactory(object):
    """
    Class for building TemplateReaders that read YAML files
    """

    def build(self):
        """
        Build a YAMLTemplateReader that is ready to use
        :return: a YAMLTemplateReader
        """
        return YamlTemplateReader(YamlTemplateFieldBuilder())


text:
package com.streamsets.pipeline.stage.processor.expression;

import com.streamsets.pipeline.api.GenerateResourceBundle;
import com.streamsets.pipeline.api.Label;

@GenerateResourceBundle
public enum Groups implements Label {
  EXPRESSIONS;

  @Override
  public String getLabel() {
    return "Expressions";
  }

}


text:
package tectonicus.world;

import java.util.LinkedHashMap;

import tectonicus.chunk.Chunk;
import tectonicus.chunk.ChunkCoord;

class GeometryCache
{
	private int maxSize;

	private LinkedHashMap<ChunkCoord, Chunk> chunks;

	public GeometryCache(final int maxSize)
	{
		this.maxSize = maxSize;

		chunks = new LinkedHashMap<ChunkCoord, Chunk>(16, 0.75f, true); // access-order (most recently accessed last)

		/*
		ChunkCoord c00 = new ChunkCoord(0, 0);
		ChunkCoord c11 = new ChunkCoord(1, 1);
		ChunkCoord c22 = new ChunkCoord(2, 2);
		ChunkCoord c33 = new ChunkCoord(3, 3);
		ChunkCoord c44 = new ChunkCoord(4, 4);

		Chunk ch00 = null;
		Chunk ch11 = null;
		Chunk ch22 = null;
		Chunk ch33 = null;
		try
		{
			ch00 = new Chunk(c00, null);
			ch11 = new Chunk(c11, null);
			ch22 = new Chunk(c22, null);
			ch33 = new Chunk(c33, null);
		}
		catch (Exception e) { e.printStackTrace(); }

		put(c00, ch00);
		assert (contains(c00));
		assert (!contains(c11));
		assert (size() == 1);

		put(c11, ch11);

		assert(contains(new ChunkCoord(1, 1)));
		assert(size() == 2);

		put(c22, ch22);
		assert(contains(c00));
		assert(contains(c11));
		assert(contains(c22));
		assert(size() == 3);

		trimToMaxSize();
		assert(contains(c22));
		assert(contains(c11));
		assert(!contains(c00));

		// Contains c11, c22

		touch(c11);
		put(c33, null);
		trimToMaxSize();

		assert(contains(c11));
		assert(contains(c33));
		assert(size() == 2);

		put(c00, null);
		put(c22, null);
		trimToMaxSize();

		System.out.println("ok");

		chunks.clear();
		*/
	}

	public void unloadAll()
	{
		for (Chunk c : chunks.values())
		{
			c.unloadGeometry();
		}
		chunks.clear();
	}

	public boolean contains(ChunkCoord coord)
	{
		return chunks.containsKey(coord);
	}

	public void put(ChunkCoord coord, Chunk chunk)
	{
		assert (chunk != null);

		chunks.put(coord, chunk);
		chunks.get(coord); // touch the new entry to pull it to the end of the list
	}

	public Chunk get(ChunkCoord coord)
	{
		return chunks.get(coord);
	}

	public int size()
	{
		return chunks.size();
	}

	public long getGeometryMemorySize()
	{
		long total = 0;
		for (Chunk c : chunks.values())
		{
			total += c.getGeometryMemorySize();
		}
		return total;
	}

	public void trimToMaxSize()
	{
		while (size() > maxSize)
		{
			Chunk oldestChunk = chunks.values().iterator().next();
			oldestChunk.unloadGeometry();
			chunks.remove(oldestChunk.getCoord());
		}
	}

	public void touch(ChunkCoord coord)
	{
		chunks.get(coord);
	}

}


text:
const html = require('choo/html')
const css = require('sheetify')

const prefix = css`
  :host .headline {
     margin: 0 2rem;
  }
  :host {
    flex-direction: column;
  }
  @media(min-width: 960px) {
    :host {
      flex-direction: row;
    }
  }
  :host .headline {
    margin: 2rem 1rem;
  }
`

module.exports = function (state, emit) {
  return html`

          Register yourself, organization or music group and publish your music metadata into the blockchain!
          Get started

  `
}


text:
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.chrome.browser.ntp.cards;

/**
 * A node in the tree that has a parent and can notify it about changes.
 *
 * This class mostly serves as a convenience base class for implementations of {@link TreeNode}.
 */
public abstract class ChildNode implements TreeNode {
    private final NodeParent mParent;

    protected ChildNode(NodeParent parent) {
        mParent = parent;
    }

    protected void notifyItemRangeChanged(int index, int count) {
        mParent.onItemRangeChanged(this, index, count);
    }

    protected void notifyItemRangeInserted(int index, int count) {
        mParent.onItemRangeInserted(this, index, count);
    }

    protected void notifyItemRangeRemoved(int index, int count) {
        mParent.onItemRangeRemoved(this, index, count);
    }

    protected void notifyItemChanged(int index) {
        notifyItemRangeChanged(index, 1);
    }

    protected void notifyItemInserted(int index) {
        notifyItemRangeInserted(index, 1);
    }

    protected void notifyItemRemoved(int index) {
        notifyItemRangeRemoved(index, 1);
    }
}


text:
package org.apache.axis2.transport.base.threads.watermark;

import java.util.concurrent.*;

/**
 * An {@link ExecutorService} that executes each submitted task using
 * one of possibly several pooled threads, but the execution happens differently
 * from the {@link ThreadPoolExecutor}. In this executor after all the core pool threads
 * are used queuing happens until the water mark. If the more tasks are submitted after
 * the queue is filled up to the water mark the number of threads increases to max.
 * If the number of tasks continue to increase the Queue begins to fill up. If the queue
 * is a bounded queue and the queue is completely filled a {@link RejectedExecutionHandler}
 * is executed if one specified. Otherwise the task is rejected.
 */
public class WaterMarkExecutor extends ThreadPoolExecutor {
    public WaterMarkExecutor(int core, int max, long keepAlive,
                             TimeUnit timeUnit, WaterMarkQueue<Runnable> queue) {
        super(core, max, keepAlive, timeUnit, queue, new WaterMarkRejectionHandler(null));
    }

    public WaterMarkExecutor(int core, int max, long keepAlive,
                             TimeUnit timeUnit, WaterMarkQueue<Runnable> queue,
                             ThreadFactory threadFactory) {
        super(core, max, keepAlive,
                timeUnit, queue, threadFactory, new WaterMarkRejectionHandler(null));
    }

    public WaterMarkExecutor(int core, int max,
                             long keepAlive, TimeUnit timeUnit,
                             WaterMarkQueue<Runnable> queue,
                             RejectedExecutionHandler rejectedExecutionHandler) {

        super(core, max, keepAlive, timeUnit,
                queue, new WaterMarkRejectionHandler(rejectedExecutionHandler));
    }

    public WaterMarkExecutor(int core, int max, long keepAlive,
                             TimeUnit timeUnit, WaterMarkQueue<Runnable> queue,
                             ThreadFactory threadFactory,
                             RejectedExecutionHandler rejectedExecutionHandler) {
        super(core, max, keepAlive, timeUnit,
                queue, threadFactory, new WaterMarkRejectionHandler(rejectedExecutionHandler));
    }
}


text:
package de.linearbits.swt.simplebrowser.tags;

import java.net.URL;
import java.util.List;
import java.util.Map;

import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StyleRange;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;

import de.linearbits.swt.simplebrowser.HTMLStyle;

/**
 * A generic HTML element
 * @author Fabian Prasser
 */
public abstract class HTMLElement {

    /** Is this a style element*/
    private final boolean style;
    /** Is this a container element*/
    private final boolean container;
    /** Is this element a content emitter*/
    private final boolean content;
    /** The associated tag*/
    private final String  tag;

    /**
     * Constructor
     * @param tag
     * @param container
     * @param style
     * @param content
     */
    protected HTMLElement(String tag, boolean container, boolean style, boolean content) {
        this.tag = tag;
        this.container = container;
        this.style = style;
        this.content = content;
    }

    /**
     * End of style for the given content
     * @param content
     * @return
     */
    public abstract StyleRange endStyle(StringBuilder content);

    /**
     * Returns the content
     * @return
     */
    public abstract String getContent();

    /**
     * Returns the tag
     */
    public String getTag() {
        return tag;
    }

    /**
     * Is this a container
     * @return
     */
    public boolean isContentContainer() {
        return container;
    }

    /**
     * Is this a content emitter
     * @return
     */
    public boolean isContentEmitter() {
        return content;
    }

    /**
     * Is this element a style
     * @return
     */
    public boolean isStyle() {
        return style;
    }

    /**
     * Creates a new instance
     * @return
     */
    public abstract HTMLElement newInstance();

    /**
     * Renders the element
     * @param parent
     * @param content
     * @param style
     * @param styles
     */
    public abstract void render(HTMLElement parent, String content, HTMLStyle style, List<StyleRange> styles);

    /**
     * Renders the element
     * @param base
     * @param previous
     * @param parent
     * @param attributes
     * @param style
     * @return
     */
    public Composite render(URL base, HTMLElement previous, Composite parent, Map<String, String> attributes, HTMLStyle style) {
        Composite container = new Composite(parent, SWT.NONE);
        container.setLayout(getDefaultLayout());
        container.setLayoutData(getDefaultLayoutData());
        applyStyle(container, style);
        return container;
    }

    /**
     * Start of style for the given content
     * @param content
     */
    public abstract void startStyle(StringBuilder content);

    /**
     * Apply the defined style to the given control
     * @param control
     * @param style
     */
    protected void applyStyle(Control control, HTMLStyle style) {
        control.setBackground(style.getBackground());
        control.setForeground(style.getForeground());
    }

    /**
     * Default layout
     * @return
     */
    protected GridLayout getDefaultLayout() {
        GridLayout layout = new GridLayout(1, true);
        layout.marginBottom = 0;
        layout.marginTop = 0;
        layout.marginLeft = 0;
        layout.marginRight = 0;
        layout.marginWidth = 0;
        layout.marginHeight = 0;
        return layout;
    }

    /**
     * Default layout data
     * @return
     */
    protected GridData getDefaultLayoutData() {
        GridData data = new GridData(GridData.FILL_HORIZONTAL);
        data.horizontalIndent = 0;
        data.verticalIndent = 0;
        return data;
    }
}


text:
The sample source codes on this page shows how to split protected PDF document in VB.NET. ByteScout PDF Extractor SDK: the SDK is designed to help developers with pdf tables and pdf data extraction from unstructured documents like pdf, tiff, scans, images, scanned and electronic forms. The library is powered by OCR, computer vision and AI to provide unique functionality like table detection, automatic table structure extraction, data restoration, data restructuring and reconstruction. Supports PDF, TIFF, PNG, JPG images as input and can output CSV, XML, JSON formatted data. Includes full set of utilities like pdf splitter, pdf merger, searchable pdf maker and other utilities. It can split protected PDF document in VB.NET.

You will save a lot of time on writing and testing code as you may just take the VB.NET code from ByteScout PDF Extractor SDK for split protected PDF document below and use it in your application. Follow the instructions from the scratch to work and copy the VB.NET code. Enjoy writing a code with ready-to-use sample VB.NET codes.

ByteScout free trial version is available for download from our website. It includes all these programming tutorials along with source code samples.

## REQUEST FREE TECH SUPPORT

[Click here to get in touch](https://bytescout.zendesk.com/hc/en-us/requests/new?subject=ByteScout%20PDF%20Extractor%20SDK%20Question)

or just send email to [support@bytescout.com](mailto:support@bytescout.com?subject=ByteScout%20PDF%20Extractor%20SDK%20Question)

## ON-PREMISE OFFLINE SDK

[Get Your 60 Day Free Trial](https://bytescout.com/download/web-installer?utm_source=github-readme)
[Explore SDK Docs](https://bytescout.com/documentation/index.html?utm_source=github-readme)
[Sign Up For Online Training](https://academy.bytescout.com/)

## ON-DEMAND REST WEB API

[Get your API key](https://pdf.co/documentation/api?utm_source=github-readme)
[Explore Web API Documentation](https://pdf.co/documentation/api?utm_source=github-readme)
[Explore Web API Samples](https://github.com/bytescout/ByteScout-SDK-SourceCode/tree/master/PDF.co%20Web%20API)

## VIDEO REVIEW

[https://www.youtube.com/watch?v=s28W3_KMraU](https://www.youtube.com/watch?v=s28W3_KMraU)

<!-- code block begin -->

##### ****Program.vb:**

```
Imports Bytescout.PDFExtractor

Class Program

    Friend Shared Sub Main(args As String())

        Dim inputFile As String = "encrypted (password is 'password').pdf"

        Using splitter As New DocumentSplitter("demo", "demo")

            ' Handle `PasswordRequired` event
            AddHandler splitter.PasswordRequired, New PasswordEventHandler(AddressOf splitter_PasswordRequired)

            ' Ignore document permissions
            splitter.CheckPermissions = False

            ' Split document
            splitter.Split(inputFile, "part1.pdf", "part2.pdf", 3)
        End Using

        Console.WriteLine()
        Console.WriteLine("Press any key...")
        Console.ReadKey()

    End Sub

    Private Shared Sub splitter_PasswordRequired(sender As Object, document As String, ByRef password As String)
        ' Ask user for password And put it to `Password` property.
        password = "password"
    End Sub

End Class

```

<!-- code block end -->

<!-- code block begin -->

##### ****SplittingExample.Converted.VS2005.vbproj:**

```
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
    <ProductVersion>8.0.50727</ProductVersion>
    <SchemaVersion>2.0</SchemaVersion>
    <ProjectGuid>{ED783E81-6D76-4015-9902-333096BD4B5C}</ProjectGuid>
    <OutputType>Exe</OutputType>
    <RootNamespace>SplittingExample</RootNamespace>
    <AssemblyName>SplittingExample</AssemblyName>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
    <DebugSymbols>true</DebugSymbols>
    <DebugType>full</DebugType>
    <Optimize>false</Optimize>
    <OutputPath>bin\Debug\</OutputPath>
    <DefineConstants>DEBUG,TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
    <DebugType>pdbonly</DebugType>
    <Optimize>true</Optimize>
    <OutputPath>bin\Release\</OutputPath>
    <DefineConstants>TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <Import Project="$(MSBuildBinPath)\Microsoft.VisualBasic.Targets" />
  <ItemGroup>
    <Import Include="Microsoft.VisualBasic" />
    <Import Include="System" />
    <Reference Include="Bytescout.PDFExtractor, Version=1.0.0.12, Culture=neutral, processorArchitecture=MSIL">
      <SpecificVersion>False</SpecificVersion>
    </Reference>
    <Reference Include="System" />
    <Compile Include="Program.vb" />
  </ItemGroup>
  <ItemGroup>
    <None Include="encrypted %28password is %27password%27%29.pdf">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </None>
  </ItemGroup>
</Project>
```

<!-- code block end -->

<!-- code block begin -->

##### ****SplittingExample.Converted.VS2008.vbproj:**

```
<Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
    <ProductVersion>8.0.50727</ProductVersion>
    <SchemaVersion>2.0</SchemaVersion>
    <ProjectGuid>{ED783E81-6D76-4015-9902-333096BD4B5C}</ProjectGuid>
    <OutputType>Exe</OutputType>
    <RootNamespace>SplittingExample</RootNamespace>
    <AssemblyName>SplittingExample</AssemblyName>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
    <DebugSymbols>true</DebugSymbols>
    <DebugType>full</DebugType>
    <Optimize>false</Optimize>
    <OutputPath>bin\Debug\</OutputPath>
    <DefineConstants>DEBUG,TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
    <DebugType>pdbonly</DebugType>
    <Optimize>true</Optimize>
    <OutputPath>bin\Release\</OutputPath>
    <DefineConstants>TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <Import Project="$(MSBuildBinPath)\Microsoft.VisualBasic.Targets" />
  <ItemGroup>
    <Import Include="Microsoft.VisualBasic" />
    <Import Include="System" />
    <Reference Include="Bytescout.PDFExtractor, Version=1.0.0.12, Culture=neutral, processorArchitecture=MSIL">
      <SpecificVersion>False</SpecificVersion>
    </Reference>
    <Reference Include="System" />
    <Compile Include="Program.vb" />
  </ItemGroup>
  <ItemGroup>
    <None Include="encrypted %28password is %27password%27%29.pdf">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </None>
  </ItemGroup>
</Project>
```

<!-- code block end -->

<!-- code block begin -->

##### ****SplittingExample.Converted.VS2010.vbproj:**

```
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0">
  <PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
    <ProductVersion>
    </ProductVersion>
    <SchemaVersion>2.0</SchemaVersion>
    <ProjectGuid>{ED783E81-6D76-4015-9902-333096BD4B5C}</ProjectGuid>
    <OutputType>Exe</OutputType>
    <RootNamespace>SplittingExample</RootNamespace>
    <AssemblyName>SplittingExample</AssemblyName>
    <OldToolsVersion>3.5</OldToolsVersion>
    <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
    <DebugSymbols>true</DebugSymbols>
    <DebugType>full</DebugType>
    <Optimize>false</Optimize>
    <OutputPath>bin\Debug\</OutputPath>
    <DefineConstants>DEBUG,TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
    <DebugType>pdbonly</DebugType>
    <Optimize>true</Optimize>
    <OutputPath>bin\Release\</OutputPath>
    <DefineConstants>TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <Import Project="$(MSBuildToolsPath)\Microsoft.VisualBasic.Targets" />
  <ItemGroup>
    <Import Include="Microsoft.VisualBasic" />
    <Import Include="System" />
    <Reference Include="Bytescout.PDFExtractor, Version=1.0.0.12, Culture=neutral, processorArchitecture=MSIL">
      <SpecificVersion>False</SpecificVersion>
    </Reference>
    <Reference Include="System" />
    <Compile Include="Program.vb" />
  </ItemGroup>
  <ItemGroup>
    <None Include="encrypted %28password is %27password%27%29.pdf">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </None>
  </ItemGroup>
</Project>
```

<!-- code block end -->


text:
using Newtonsoft.Json;
using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.IO;
using System.Web.UI;
using TropoCSharp.Tropo;
using TropoCSharp.Structs;

namespace TropoSamples
{
	/// <summary>
	/// A simple example showing how to say Hello World to a user.
	/// </summary>
    public partial class MessageTest : Page
	{
		public void Page_Load (object sender, EventArgs args)
		{

            using (StreamReader reader = new StreamReader(Request.InputStream))
            {

                // Create a new instance of the Tropo object.
                Tropo tropo = new Tropo();

                // Get the JSON submitted from Tropo.
                string sessionJSON = TropoUtilities.parseJSON(reader);

                try
                {
                    // Create a new Session object and pass in the JSON submitted from Tropo.
                    Session tropoSession = new Session(sessionJSON);

                    // Get parameters submitted with Session API call.
                    string numberToDial = tropoSession.Parameters.Get("numberToDial");
                    //numberToDial = "5093176303";
                    string sendFromNumber = tropoSession.Parameters.Get("sendFromNumber");
                    //sendFromNumber = "14082041999";
                    string channel = tropoSession.Parameters.Get("channel");
                    string network = tropoSession.Parameters.Get("network");
                    string textMessageBody = tropoSession.Parameters.Get("textMessageBody");

                    string[] week = new string[4];
                    week[0] = "http://artifacts.voxeolabs.net.s3.amazonaws.com/test/test.png";
                    week[1] = "this is MessageTest这是第二行";
                    week[2] = "https://www.travelchinaguide.com/images/photogallery/2012/beijing-tiananmen-tower.jpg";
                    week[3] = "Today is 13 Aug";
                    //week[3] = "https://me888dia.giphy.com/media/LHZyixOnHwDDy/giphy.gif";

                    List<String> to = new List<String>(1);
                    to.Add(numberToDial);
                    to.Add("14084654399");

                    string currenT = DateTime.Now.ToString("yyyy/MM/dd HH:MM tt");
                    Say say = new Say();
                    say.Value = "this is MMS test for webapi Csharp SDk sent @ " + currenT;
                    say.Media = week;

                    Message message = new Message();
                    message.To = to;
                    message.From = sendFromNumber;
                    message.Network = Network.MMS;
                    message.Say = say;
                    message.PromptLogSecurity = "suppress";
                    message.Voice = "en-us";

                    tropo.Message(message);

                }

                catch (JsonReaderException ex)
                {
                    EventLog log = new EventLog();
                    log.Source = "TROPOWEBAPI";
                    log.WriteEntry("Tropo WebAPI Exception " + ex.Message, EventLogEntryType.Error);
                    Response.StatusCode = 500;
                    tropo.Say("An error occured in the application. Bad JSON");

                }

                catch (Exception ex)
                {
                    EventLog log = new EventLog();
                    log.Source = "TROPOWEBAPI";
                    log.WriteEntry("Tropo WebAPI Exception " + ex.Message, EventLogEntryType.Error);
                    Response.StatusCode = 500;
                    tropo.Say("An error occured in the application.");
                }

                finally
                {
                    tropo.RenderJSON(Response);
                }
            }
		}
	}
}


text:
class AwsBackend
  class SnsSubscription
    attr_accessor :resp
    # format is:   "arn:aws:sns:region:account-id:topicname"
    # see http://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html#arn-syntax-glacier
    Topic_ARN = "arn:aws:sns:#{AwsBackend::Region}:#{::AWS_ACCOUNT_ID}:retrieve_archive"
    #Resource_ARN = ""

    def initialize
      client = Aws::SNS::Client.new(:region => AwsBackend::Region, :credentials => credentials)
      sns = Aws::SNS::Resource.new(region:AwsBackend::Region)

      topic = sns.create_topic(name: 'retrieve_archive')
      topic.set_attributes({
        attribute_name: "Policy",
        attribute_value: policy
      })

      @resp = client.subscribe({
        topic_arn: Topic_ARN,
        protocol: "https", # required
        endpoint: GetBack::Engine.routes.url_helpers.aws_subscription_notify_url
      })
    rescue Exception => e
      puts "AWS Error: #{e.message}"
      #puts e.backtrace.inspect
      # Rescue
    end

    private
    def credentials
      Aws::SharedCredentials.new(:profile_name => AwsBackend::ProfileName)
    end

    def policy
      # see http://docs.aws.amazon.com/sdk-for-ruby/v2/developer-guide/sns-example-enable-resource.html
      "{
        'Version':'2014-05-06',
        'Id':'__default_policy_ID',
        'Statement':[{
          'Sid':'__default_statement_ID',
          'Effect':'Allow',
          'Principal':{
            'AWS':'*'
          },
          'Action':['SNS:Publish'],
          'Resource':'#{Topic_ARN}',
          'Condition':{
            'ArnEquals':{
              'AWS:SourceArn': #{Resource_ARN}}
           }
        }]
      }"
    end
  end
end


text:
<?php

namespace Stash\Test\Driver;

use Stash\Test\Stubs\DriverUnavailableStub;

/**
 * @package Stash
 * @author  Robert Hafner <tedivm@tedivm.com>
 */
class UnavailableDriverTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @expectedException Stash\Exception\RuntimeException
     */
    public function testUnavailableDriver()
    {
        new DriverUnavailableStub();
    }
}


text:
class NotesSidebar < Sidebar
  description 'Displays the latest notes'
  setting :title, 'Notes'
  setting :count,      5,   :label => 'Number of notes'

  attr_accessor :notes

  def parse_request(contents, params)
    @notes = Note.published.page(params[:page]).per(count)
  end
end


text:
import React, { Component } from "react";
import { Field } from "redux-form";
import { Shake } from "reshake";

import { LoadingButton, SubmitButton, SuccessButton } from "../ui/buttons";
import renderTextField from "../ui/render_text_field";

/**
* A form component storing input states with API calling functionality.
* @extends Component
*/
class EmailForm extends Component {
    constructor(props) {
        super(props);
        this.handleSendClick = this.handleSendClick.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
        this.renderSendButton = this.renderSendButton.bind(this);
        this.renderTextField = renderTextField.bind(this);
        this.stopShaking = this.stopShaking.bind(this);
        this.state = {
            isShaking: false,
            makingRequest: false
        };
    }

    /** If the user comes back to the form, re-fill in the inputs. */
    componentDidMount() {
        if (this.props.contacted) {
            this.nameInput.value = this.props.name;
            this.emailInput.value = this.props.email;
            this.messageInput.value = this.props.message;
        }
    }

    /** After an update, stop the send button from shaking if it is. */
    componentDidUpdate() {
        if (this.state.isShaking) {
            this.shakeTimeout = setTimeout(this.stopShaking, 500);
        }
    }

    /** Clear timeout so component doesn't try to set state while unmounted. */
    componentWillUnmount() {
        this.shakeTimeout && clearTimeout(this.shakeTimeout);
    }

    /** Handle click events from the send button */
    handleSendClick() {
        if (!this.props.valid) {
            this.setState({ isShaking: true });
            this.nameInput.focus();
            this.emailInput.focus();
            this.messageInput.focus();
            this.messageInput.blur();
        }
    }

    /** If the form is appropriate, send an API POST request to send en email. */
    handleSubmit(data) {
        this.props.sendEmail(data.name, data.email, data.message);
        this.setState({makingRequest: true});
    }

    /** Stop the send button from shaking after a form error. */
    stopShaking() {
        this.setState({isShaking: false});
    }

    /** Render the shaking error button component. */
    renderShakingButton() {
        return (
            <Shake h={3} v={5} r={0} dur={42} max={100}
                fixed={true} fixedStop={false} freez={false}>

Send

            </Shake>
        );
    }

    /** Render the submit button component. */
    renderSendButton() {
        const loadingButton = <LoadingButton />;
        const sendButton = (
            <SubmitButton
                value="Send"
                onClick={this.handleSendClick} />
        );

        return this.state.makingRequest ? loadingButton : sendButton;
    }

    render() {
        // Form submission button components
        const sendButton = this.state.isShaking ?
            this.renderShakingButton() : this.renderSendButton();
        const sentButton = <SuccessButton value="Sent!" />;

        return (
            <fieldset disabled={this.props.contacted ? "disabled" : ""}>
                <form className="email-form"
                    onSubmit={this.props.handleSubmit(this.handleSubmit)}>

                        Send me an email

                            <Field
                                name="name"
                                title="Name"
                                element="input"
                                type="text"
                                component={this.renderTextField} />
                            <Field
                                name="email"
                                title="Email"
                                element="input"
                                type="text"
                                component={this.renderTextField} />

                            <Field
                                name="message"
                                title="Message"
                                element="textArea"
                                component={this.renderTextField} />

                    {this.props.contacted ? sentButton : sendButton}
                </form>
            </fieldset>
        );
    }
}

export default EmailForm;


text:
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Simple.Data.ElasticsearchTest
{
    public class Assume
    {
        public static void AssumeEqual(Object expected, Object actual, string valueName = "value")
        {
            if (!Object.Equals(expected, actual))
            {
                Assert.Inconclusive("Assumed \"" + valueName + "\"==\"" + expected + "\", but was \"" + actual + "\".");
            }
        }
    }
}


text:
import config
import time

my_config = config.get_config()
number_of_loops = my_config.getint("Global", "number_of_loops")

def intermediate_testing():
    for loop_count in range(number_of_loops):
        print ('Hi')
        print ('How')
        print ('Are')
        print ('You')

def intermediate_no_print_testing():
    for loop_count in range(number_of_loops):
        foo = 20
        foo += 20
        foo += 20
        foo += 20

start = time.time()
intermediate_no_print_testing()
end = time.time()
print(end - start)


text:
package userInterface.pharmacy;

import baseClasses.enterprise.Enterprise;
import baseClasses.enterprise.PharmacyEnterprise;
import baseClasses.network.Network;
import baseClasses.userAccount.UserAccount;
import java.awt.CardLayout;
import javax.swing.JPanel;

/**
 *
 * @author Abhishek
 */
public class PharmacyAdminWorkArea extends javax.swing.JPanel {

    /**
     * Creates new form GovernmentAdminWorkArea
     */
    Network internationalNetwork;
    UserAccount userAccount;
    private Enterprise inEnterprise;
    private PharmacyEnterprise pharmacyEnterprise;

    public PharmacyAdminWorkArea(Network internationalNetwork, UserAccount userAccount, Enterprise inEnterprise) {
        initComponents();
        this.internationalNetwork = internationalNetwork;
        this.userAccount = userAccount;
                 this.inEnterprise = inEnterprise;

                 if(inEnterprise.getClass() == PharmacyEnterprise.class)
                 {
                     pharmacyEnterprise = (PharmacyEnterprise) inEnterprise;
                 }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jSplitPane1 = new javax.swing.JSplitPane();
        jPanel1 = new javax.swing.JPanel();
        btnManagePharmacies = new javax.swing.JButton();
        btnPurchaseMedicineByManufacturer = new javax.swing.JButton();
        btnManageOrders = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();

        setLayout(new java.awt.BorderLayout());

        jSplitPane1.setDividerLocation(150);
        jSplitPane1.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);

        jPanel1.setBackground(new java.awt.Color(255, 255, 255));

        btnManagePharmacies.setBackground(new java.awt.Color(255, 255, 255));
        btnManagePharmacies.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
        btnManagePharmacies.setForeground(new java.awt.Color(0, 153, 0));
        btnManagePharmacies.setText("Manage Drug Inventory");
        btnManagePharmacies.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnManagePharmaciesActionPerformed(evt);
            }
        });

        btnPurchaseMedicineByManufacturer.setBackground(new java.awt.Color(255, 255, 255));
        btnPurchaseMedicineByManufacturer.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
        btnPurchaseMedicineByManufacturer.setForeground(new java.awt.Color(0, 153, 0));
        btnPurchaseMedicineByManufacturer.setText("Purchase Medicines By Manufacturer");
        btnPurchaseMedicineByManufacturer.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnPurchaseMedicineByManufacturerActionPerformed(evt);
            }
        });

        btnManageOrders.setBackground(new java.awt.Color(255, 255, 255));
        btnManageOrders.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
        btnManageOrders.setForeground(new java.awt.Color(0, 153, 0));
        btnManageOrders.setText("Manage Orders");
        btnManageOrders.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnManageOrdersActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(72, 72, 72)
                .addComponent(btnPurchaseMedicineByManufacturer, javax.swing.GroupLayout.PREFERRED_SIZE, 379, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 368, Short.MAX_VALUE)
                .addComponent(btnManagePharmacies, javax.swing.GroupLayout.PREFERRED_SIZE, 381, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(92, 92, 92))
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(424, 424, 424)
                .addComponent(btnManageOrders, javax.swing.GroupLayout.PREFERRED_SIZE, 381, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(33, 33, 33)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnManagePharmacies)
                    .addComponent(btnPurchaseMedicineByManufacturer))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 30, Short.MAX_VALUE)
                .addComponent(btnManageOrders)
                .addGap(24, 24, 24))
        );

        jSplitPane1.setLeftComponent(jPanel1);

        jPanel2.setBackground(new java.awt.Color(255, 255, 255));

        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/baseClasses/healtech logo.PNG"))); // NOI18N

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addGap(0, 1196, Short.MAX_VALUE)
                .addComponent(jLabel1))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addGap(0, 465, Short.MAX_VALUE)
                .addComponent(jLabel1))
        );

        jSplitPane1.setRightComponent(jPanel2);

        add(jSplitPane1, java.awt.BorderLayout.CENTER);
    }// </editor-fold>//GEN-END:initComponents

    private void btnManagePharmaciesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnManagePharmaciesActionPerformed
        // TODO add your handling code here:
        JPanel manageCitizenDetailsCard = new JPanel();
        manageCitizenDetailsCard.setLayout(new CardLayout());

        manageCitizenDetailsCard.add(new ManagePharmacyProfiles(internationalNetwork,manageCitizenDetailsCard));
        CardLayout layout = (CardLayout) manageCitizenDetailsCard.getLayout();
        layout.next(manageCitizenDetailsCard);

        jSplitPane1.setRightComponent(manageCitizenDetailsCard);
    }//GEN-LAST:event_btnManagePharmaciesActionPerformed

    private void btnPurchaseMedicineByManufacturerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPurchaseMedicineByManufacturerActionPerformed
        // TODO add your handling code here:
        jSplitPane1.setRightComponent(new PurchaseByManufacturer(internationalNetwork, userAccount, pharmacyEnterprise));

    }//GEN-LAST:event_btnPurchaseMedicineByManufacturerActionPerformed

    private void btnManageOrdersActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnManageOrdersActionPerformed
        // TODO add your handling code here:
        jSplitPane1.setBottomComponent(new MedicineOrderRequestDetailsPanel(pharmacyEnterprise, userAccount));
    }//GEN-LAST:event_btnManageOrdersActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnManageOrders;
    private javax.swing.JButton btnManagePharmacies;
    private javax.swing.JButton btnPurchaseMedicineByManufacturer;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JSplitPane jSplitPane1;
    // End of variables declaration//GEN-END:variables
}


text:
package com.vangent.hieos.DocViewer.client.view.patient;

import com.smartgwt.client.widgets.grid.HoverCustomizer;
import com.smartgwt.client.widgets.grid.ListGridRecord;

/**
 *
 * @author Vangent
 */
public class PatientListHoverCustomizer implements HoverCustomizer {

    /** Field description */
    private final String tooltip;

    /**
     * Constructs ...
     *
     *
     * @param str
     */
    public PatientListHoverCustomizer(String str) {

        super();
        this.tooltip = str;
    }

    /**
     * Method description
     *
     *
     * @param value
     * @param record
     * @param rowNum
     * @param colNum
     *
     * @return
     */
    @Override
    public String hoverHTML(Object value, ListGridRecord record, int rowNum,
                            int colNum) {
        return this.tooltip;
    }
}