text:
"""Classes for handling build and repackaging of clients.

This handles invocations for the build across the supported platforms including
handling Visual Studio, pyinstaller and other packaging mechanisms.
"""
import cStringIO
import logging
import os
import shutil
import struct
import subprocess
import zipfile

import yaml

# pylint: disable=g-import-not-at-top
# This is a workaround so we don't need to maintain the whole PyInstaller
# codebase as a full-fledged dependency.
try:
  from PyInstaller import __main__ as PyInstallerMain
except ImportError:
  # We ignore this failure since most people running the code don't build their
  # own clients and printing an error message causes confusion.  Those building
  # their own clients will need PyInstaller installed.
  pass

from grr.lib import config_lib
from grr.lib import rdfvalue
from grr.lib import registry
from grr.lib import utils
from grr.lib.rdfvalues import client as rdf_client

# pylint: enable=g-import-not-at-top

class PrivateConfigValidator(object):
  """Use this class to sanity check private config options at repack time."""
  __metaclass__ = registry.MetaclassRegistry
  __abstract = True  # pylint: disable=g-bad-name

  def ValidateEndConfig(self, config, context, errors_fatal=True):
    raise NotImplementedError()

class BuilderBase(object):
  """A base class for builder / repacker that provides utility functions."""

  def __init__(self, context=None):
    self.context = context or config_lib.CONFIG.context[:]
    self.context = ["ClientBuilder Context"] + self.context

  def GenerateDirectory(self,
                        input_dir=None,
                        output_dir=None,
                        replacements=None):
    input_dir = utils.NormalizePath(input_dir)
    output_dir = utils.NormalizePath(output_dir)
    replacements = replacements or []

    for (root, _, files) in os.walk(input_dir):
      for filename in files:
        in_file = utils.JoinPath(root, filename)
        out_file = in_file.replace(input_dir, output_dir)
        for (s, replacement) in replacements:
          out_file = out_file.replace(s, replacement)
        utils.EnsureDirExists(os.path.dirname(out_file))
        self.GenerateFile(in_file, out_file)

  def GenerateFile(self, input_filename=None, output_filename=None):
    """Generates a file from a template, interpolating config values."""
    if input_filename is None:
      input_filename = output_filename + ".in"
    if output_filename[-3:] == ".in":
      output_filename = output_filename[:-3]
    data = open(input_filename, "rb").read()
    logging.debug("Generating file %s from %s", output_filename, input_filename)

    with open(output_filename, "wb") as fd:
      fd.write(config_lib.CONFIG.InterpolateValue(data, context=self.context))

class ClientBuilder(BuilderBase):
  """A client builder is responsible for building the binary template.

  This is an abstract client builder class, used by the OS specific
  implementations. Note that client builders typically run on the target
  operating system.
  """
  REQUIRED_BUILD_YAML_KEYS = set([
      "Client.build_environment", "Client.build_time", "Template.build_type",
      "Template.build_context", "Template.version_major",
      "Template.version_minor", "Template.version_revision",
      "Template.version_release", "Template.arch"
  ])

  def MakeBuildDirectory(self):
    """Prepares the build directory."""
    # Create the build directory and let pyinstaller loose on it.
    self.build_dir = config_lib.CONFIG.Get("PyInstaller.build_dir",
                                           context=self.context)
    self.work_path = config_lib.CONFIG.Get("PyInstaller.workpath_dir",
                                           context=self.context)

    self.CleanDirectory(self.build_dir)
    self.CleanDirectory(self.work_path)

  def CleanDirectory(self, directory):
    logging.info("Clearing directory %s", directory)
    try:
      shutil.rmtree(directory)
    except OSError:
      pass

    utils.EnsureDirExists(directory)

  def BuildWithPyInstaller(self):
    """Use pyinstaller to build a client package."""
    self.CleanDirectory(
        config_lib.CONFIG.Get("PyInstaller.distpath", context=self.context))

    logging.info("Copying pyinstaller support files")
    self.spec_file = os.path.join(self.build_dir, "grr.spec")

    with open(self.spec_file, "wb") as fd:
      fd.write(config_lib.CONFIG.Get("PyInstaller.spec", context=self.context))

    with open(os.path.join(self.build_dir, "version.txt"), "wb") as fd:
      fd.write(
          config_lib.CONFIG.Get("PyInstaller.version", context=self.context))

    with open(os.path.join(self.build_dir, "grr.ico"), "wb") as fd:
      fd.write(config_lib.CONFIG.Get("PyInstaller.icon", context=self.context))

    # We expect the onedir output at this location.
    self.output_dir = os.path.join(
        config_lib.CONFIG.Get("PyInstaller.distpath", context=self.context),
        "grr-client")

    # Pyinstaller doesn't handle unicode strings.
    args = [
        "--distpath", str(
            config_lib.CONFIG.Get("PyInstaller.distpath",
                                  context=self.context)), "--workpath",
        str(
            config_lib.CONFIG.Get("PyInstaller.workpath_dir",
                                  context=self.context)), str(self.spec_file)
    ]
    logging.info("Running pyinstaller: %s", args)
    PyInstallerMain.run(pyi_args=[utils.SmartStr(x) for x in args])

    # Clear out some crud that pyinstaller includes.
    for path in ["tcl", "tk", "pytz"]:
      dir_path = os.path.join(self.output_dir, path)
      try:
        shutil.rmtree(dir_path)
        os.mkdir(dir_path)
        # Create an empty file so the directories get put in the installers.
        with open(os.path.join(dir_path, path), "wb"):
          pass
      except OSError:
        pass

    version_ini = config_lib.Resource().Filter("version.ini")
    if not os.path.exists(version_ini):
      raise RuntimeError("Couldn't find version_ini in virtual env root: %s" %
                         version_ini)
    shutil.copy(version_ini, os.path.join(self.output_dir, "version.ini"))

    with open(os.path.join(self.output_dir, "build.yaml"), "wb") as fd:
      self.WriteBuildYaml(fd)

  def WriteBuildYaml(self, fd, build_timestamp=True):
    """Write build spec to fd."""
    output = {
        "Client.build_environment":
            rdf_client.Uname.FromCurrentSystem().signature(),
        "Template.build_type":
            config_lib.CONFIG.Get("ClientBuilder.build_type",
                                  context=self.context),
        "Template.version_major":
            config_lib.CONFIG.Get("Source.version_major", context=self.context),
        "Template.version_minor":
            config_lib.CONFIG.Get("Source.version_minor", context=self.context),
        "Template.version_revision":
            config_lib.CONFIG.Get("Source.version_revision",
                                  context=self.context),
        "Template.version_release":
            config_lib.CONFIG.Get("Source.version_release",
                                  context=self.context),
        "Template.arch":
            config_lib.CONFIG.Get("Client.arch", context=self.context)
    }

    if build_timestamp:
      output["Client.build_time"] = rdfvalue.RDFDatetime.Now()
    else:
      self.REQUIRED_BUILD_YAML_KEYS.remove("Client.build_time")

    for key, value in output.iteritems():
      output[key] = str(value)

    output["Template.build_context"] = self.context

    if set(output.keys()) != self.REQUIRED_BUILD_YAML_KEYS:
      raise RuntimeError("Bad build.yaml: expected %s, got %s" %
                         (self.REQUIRED_BUILD_YAML_KEYS, output.keys()))
    fd.write(yaml.dump(output))

  def CopyMissingModules(self):
    """Copy any additional DLLs that cant be found."""

  def MakeExecutableTemplate(self, output_file=None):
    """Create the executable template.

    Args:
      output_file: string filename where we will write the template.

    The client is build in two phases. First an executable template is created
    with the client binaries contained inside a zip file. Then the installation
    package is created by appending the SFX extractor to this template and
    writing a config file into the zip file.

    This technique allows the client build to be carried out once on the
    supported platform (e.g. windows with MSVS), but the deployable installer
    can be build on any platform which supports python.

    Subclasses for each OS do the actual work, we just make sure the output
    directory is set up correctly here.
    """
    self.template_file = output_file or config_lib.CONFIG.Get(
        "ClientBuilder.template_path", context=self.context)
    utils.EnsureDirExists(os.path.dirname(self.template_file))

  def MakeZip(self, input_dir, output_file):
    """Creates a ZIP archive of the files in the input directory.

    Args:
      input_dir: the name of the input directory.
      output_file: the name of the output ZIP archive without extension.
    """
    logging.info("Generating zip template file at %s", output_file)
    basename, _ = os.path.splitext(output_file)
    shutil.make_archive(
        basename, "zip", base_dir=".", root_dir=input_dir, verbose=True)

class ClientRepacker(BuilderBase):
  """Takes the binary template and producing an installer.

  Note that this should be runnable on all operating systems.
  """

  CONFIG_SECTIONS = [
      "CA", "Client", "ClientRepacker", "Logging", "Config", "Nanny",
      "Installer", "Template"
  ]

  # Config options that should never make it to a deployable binary.
  SKIP_OPTION_LIST = ["Client.private_key"]

  def __init__(self, context=None, signer=None):
    super(ClientRepacker, self).__init__(context=context)
    self.signer = signer
    self.signed_template = False

  def GetClientConfig(self, context, validate=True, deploy_timestamp=True):
    """Generates the client config file for inclusion in deployable binaries."""
    with utils.TempDirectory() as tmp_dir:
      # Make sure we write the file in yaml format.
      filename = os.path.join(
          tmp_dir,
          config_lib.CONFIG.Get("ClientBuilder.config_filename",
                                context=context))

      new_config = config_lib.CONFIG.MakeNewConfig()
      new_config.Initialize(reset=True, data="")
      new_config.SetWriteBack(filename)

      # Only copy certain sections to the client. We enumerate all
      # defined options and then resolve those from the config in the
      # client's context. The result is the raw option as if the
      # client read our config file.
      for descriptor in sorted(
          config_lib.CONFIG.type_infos, key=lambda x: x.name):
        if descriptor.name in self.SKIP_OPTION_LIST:
          continue

        if descriptor.section in self.CONFIG_SECTIONS:
          value = config_lib.CONFIG.GetRaw(
              descriptor.name, context=context, default=None)

          if value is not None:
            logging.debug("Copying config option to client: %s",
                          descriptor.name)

            new_config.SetRaw(descriptor.name, value)

      if deploy_timestamp:
        new_config.Set("Client.deploy_time", str(rdfvalue.RDFDatetime.Now()))
      new_config.Write()

      if validate:
        self.ValidateEndConfig(new_config)

      private_validator = config_lib.CONFIG.Get(
          "ClientBuilder.private_config_validator_class", context=context)
      if private_validator:
        try:
          validator = PrivateConfigValidator.classes[private_validator]()
        except KeyError:
          logging.error("Couldn't find config validator class %s, "
                        "you probably need to copy it into lib/local",
                        private_validator)
          raise
        validator.ValidateEndConfig(new_config, self.context)

      return open(filename, "rb").read()

  def ValidateEndConfig(self, config, errors_fatal=True):
    """Given a generated client config, attempt to check for common errors."""
    errors = []

    location = config.Get("Client.server_urls", context=self.context)
    if not location:
      errors.append("Empty Client.server_urls")

    for url in location:
      if not url.startswith("http"):
        errors.append("Bad Client.server_urls specified %s" % url)

    key_data = config.GetRaw(
        "Client.executable_signing_public_key",
        default=None,
        context=self.context)
    if key_data is None:
      errors.append("Missing Client.executable_signing_public_key.")
    elif not key_data.startswith("-----BEGIN PUBLIC"):
      errors.append("Invalid Client.executable_signing_public_key: %s" %
                    key_data)

    certificate = config.GetRaw(
        "CA.certificate", default=None, context=self.context)
    if certificate is None or not certificate.startswith("-----BEGIN CERTIF"):
      errors.append("CA certificate missing from config.")

    for bad_opt in ["Client.private_key"]:
      if config.Get(bad_opt, context=self.context, default=""):
        errors.append("Client cert in conf, this should be empty at deployment"
                      " %s" % bad_opt)

    if errors_fatal and errors:
      for error in errors:
        logging.error("Build Config Error: %s", error)
      raise RuntimeError("Bad configuration generated. Terminating.")
    else:
      return errors

  def MakeDeployableBinary(self, template_path, output_path):
    """Use the template to create a customized installer."""

class WindowsClientRepacker(ClientRepacker):
  """Repackages windows installers."""

  def ValidateEndConfig(self, config, errors_fatal=True):
    """Windows specific config validations."""
    errors = super(WindowsClientRepacker, self).ValidateEndConfig(
        config, errors_fatal=errors_fatal)

    for path in config.GetRaw("Client.tempdir_roots"):
      if path.startswith("/"):
        errors.append(
            "Client.tempdir_root %s starts with /, probably has Unix path." %
            path)

    if config.GetRaw("Logging.path").startswith("/"):
      errors.append("Logging.path starts with /, probably has Unix path. %s" %
                    config["Logging.path"])

    if "Windows\\" in config.GetRaw("Logging.path"):
      errors.append("Windows in Logging.path, you probably want "
                    "%(WINDIR|env) instead")

    if not config["Client.binary_name"].endswith(".exe"):
      errors.append("Missing .exe extension on binary_name %s" %
                    config["Client.binary_name"])

    if not config["Nanny.binary"].endswith(".exe"):
      errors.append("Missing .exe extension on nanny_binary")

    if errors_fatal and errors:
      for error in errors:
        logging.error("Build Config Error: %s", error)
      raise RuntimeError("Bad configuration generated. Terminating.")
    else:
      return errors

  def InterpolateVariableInBinary(self, stream, parameter):
    """Replace magic strings in the binary with config parameters."""
    pattern = "<---------------- %s ------------------->" % parameter
    pattern = pattern.encode("utf_16_le")

    replacement = config_lib.CONFIG.Get(parameter, context=self.context)
    replacement = utils.SmartStr(replacement + "\x00").encode("utf_16_le")
    replacement = replacement[:len(pattern)]

    # Pad to the end of the string with nulls.
    replacement += "\x00" * (len(pattern) - len(replacement))

    start = 0
    while 1:
      offset = stream.getvalue().find(pattern, start)
      if offset < 0:
        return

      stream.seek(offset)
      stream.write(replacement)

  def Sign(self, inbuf):
    if self.signer:
      return self.signer.SignBuffer(inbuf)
    return inbuf

  def MakeDeployableBinary(self, template_path, output_path):
    """Repackage the template zip with the installer."""
    context = self.context + ["Client Context"]

    zip_data = cStringIO.StringIO()
    output_zip = zipfile.ZipFile(
        zip_data, mode="w", compression=zipfile.ZIP_DEFLATED)

    z_template = zipfile.ZipFile(open(template_path, "rb"))

    completed_files = []  # Track which files we've copied already.

    # Change the name of the main binary to the configured name.
    client_bin_name = config_lib.CONFIG.Get("Client.binary_name",
                                            context=context)

    extension = ""
    if "windows" == config_lib.CONFIG.Get("Client.platform", context=context):
      extension = ".exe"

    # The template always has the same binary name.
    bin_name = z_template.getinfo("grr-client" + extension)
    bin_dat = cStringIO.StringIO()
    bin_dat.write(z_template.read(bin_name))

    # Set output to console on binary if needed.
    SetPeSubsystem(
        bin_dat,
        console=config_lib.CONFIG.Get("ClientBuilder.console", context=context))

    # Interpolate resource strings.
    for parameter in [
        "Client.company_name", "Client.description", "Client.name",
        "Template.version_string", "ClientBuilder.package_name"
    ]:
      self.InterpolateVariableInBinary(bin_dat, parameter)

    output_zip.writestr(client_bin_name, self.Sign(bin_dat.getvalue()))

    CopyFileInZip(z_template, "%s.manifest" % bin_name.filename, output_zip,
                  "%s.manifest" % client_bin_name)
    completed_files.append(bin_name.filename)
    completed_files.append("%s.manifest" % bin_name.filename)

    # Change the name of the service binary to the configured name.
    service_template = z_template.getinfo("GRRservice.exe")

    service_bin_dat = cStringIO.StringIO()
    service_bin_dat.write(z_template.read(service_template))

    # Set output to console on service binary if needed.
    SetPeSubsystem(
        service_bin_dat,
        console=config_lib.CONFIG.Get("ClientBuilder.console", context=context))

    service_bin_name = config_lib.CONFIG.Get("Nanny.service_binary_name",
                                             context=context)
    output_zip.writestr(service_bin_name, self.Sign(service_bin_dat.getvalue()))
    completed_files.append(service_template.filename)

    if self.signed_template:
      # If the template libs were already signed we can skip signing
      CreateNewZipWithSignedLibs(
          z_template, output_zip, ignore_files=completed_files)
    else:
      CreateNewZipWithSignedLibs(
          z_template,
          output_zip,
          ignore_files=completed_files,
          signer=self.signer)
    output_zip.close()

    return self.MakeSelfExtractingZip(zip_data.getvalue(), output_path)

  def MakeSelfExtractingZip(self, payload_data, output_path):
    """Repack the installer into the payload.

    Args:
      payload_data: data payload for zip file
      output_path: filename for the zip output
    Raises:
      RuntimeError: if the ClientBuilder.unzipsfx_stub doesn't require admin.
    Returns:
      output_path: filename string of zip output file
    """
    context = self.context + ["Client Context"]

    src_zip = zipfile.ZipFile(cStringIO.StringIO(payload_data), mode="r")
    zip_data = cStringIO.StringIO()
    output_zip = zipfile.ZipFile(
        zip_data, mode="w", compression=zipfile.ZIP_DEFLATED)

    config_file_name = config_lib.CONFIG.Get("ClientBuilder.config_filename",
                                             context=context)
    # Copy the rest of the files from the package to the new zip.
    for template_file in src_zip.namelist():
      if template_file != config_file_name:
        # Avoid writing the config file twice if we're repacking a binary that
        # has already been run through deployment. We write it in the next step,
        # so no need to copy over from the original here.
        CopyFileInZip(src_zip, template_file, output_zip)

    client_config_content = self.GetClientConfig(context)

    output_zip.writestr(
        config_file_name,
        client_config_content,
        compress_type=zipfile.ZIP_STORED)

    # The zip file comment is used by the self extractor to run
    # the installation script
    output_zip.comment = "$AUTORUN$>%s" % config_lib.CONFIG.Get(
        "ClientBuilder.autorun_command_line", context=context)

    output_zip.close()

    utils.EnsureDirExists(os.path.dirname(output_path))
    with open(output_path, "wb") as fd:
      # First write the installer stub
      stub_data = cStringIO.StringIO()
      unzipsfx_stub = config_lib.CONFIG.Get("ClientBuilder.unzipsfx_stub",
                                            context=context)
      stub_raw = open(unzipsfx_stub, "rb").read()

      # Check stub has been compiled with the requireAdministrator manifest.
      if "level=\"requireAdministrator" not in stub_raw:
        raise RuntimeError("Bad unzip binary in use. Not compiled with the"
                           "requireAdministrator manifest option.")

      stub_data.write(stub_raw)

      # If in verbose mode, modify the unzip bins PE header to run in console
      # mode for easier debugging.
      SetPeSubsystem(
          stub_data,
          console=config_lib.CONFIG.Get("ClientBuilder.console",
                                        context=context))

      # Now patch up the .rsrc section to contain the payload.
      end_of_file = zip_data.tell() + stub_data.tell()

      # This is the IMAGE_SECTION_HEADER.Name which is also the start of
      # IMAGE_SECTION_HEADER.
      offset_to_rsrc = stub_data.getvalue().find(".rsrc")

      # IMAGE_SECTION_HEADER.PointerToRawData is a 32 bit int.
      stub_data.seek(offset_to_rsrc + 20)
      start_of_rsrc_section = struct.unpack("<I", stub_data.read(4))[0]

      # Adjust IMAGE_SECTION_HEADER.SizeOfRawData to span from the old start to
      # the end of file.
      stub_data.seek(offset_to_rsrc + 16)
      stub_data.write(struct.pack("<I", end_of_file - start_of_rsrc_section))

      # Concatenate stub and zip file.
      out_data = cStringIO.StringIO()
      out_data.write(stub_data.getvalue())
      out_data.write(zip_data.getvalue())

      # Then write the actual output file.
      fd.write(self.Sign(out_data.getvalue()))

    logging.info("Deployable binary generated at %s", output_path)

    return output_path

class DarwinClientRepacker(ClientRepacker):
  """Repackage OSX clients."""

  def MakeDeployableBinary(self, template_path, output_path):
    """This will add the config to the client template."""
    context = self.context + ["Client Context"]
    utils.EnsureDirExists(os.path.dirname(output_path))

    client_config_data = self.GetClientConfig(context)
    shutil.copyfile(template_path, output_path)
    zip_file = zipfile.ZipFile(output_path, mode="a")
    zip_info = zipfile.ZipInfo(filename="config.yaml")
    zip_file.writestr(zip_info, client_config_data)
    zip_file.close()
    return output_path

class LinuxClientRepacker(ClientRepacker):
  """Repackage Linux templates."""

  def GenerateDPKGFiles(self, template_path):
    """Generates the files needed by dpkg-buildpackage."""

    # Rename the generated binaries to the correct name.
    template_binary_dir = os.path.join(template_path, "dist/debian/grr-client")
    package_name = config_lib.CONFIG.Get("ClientBuilder.package_name",
                                         context=self.context)
    target_binary_dir = os.path.join(
        template_path,
        "dist/debian/%s%s" % (package_name,
                              config_lib.CONFIG.Get("ClientBuilder.target_dir",
                                                    context=self.context)))
    if package_name == "grr-client":
      # Need to rename the template path or the move will fail.
      shutil.move(template_binary_dir, "%s-template" % template_binary_dir)
      template_binary_dir = "%s-template" % template_binary_dir

    utils.EnsureDirExists(os.path.dirname(target_binary_dir))
    shutil.move(template_binary_dir, target_binary_dir)

    shutil.move(
        os.path.join(target_binary_dir, "grr-client"),
        os.path.join(
            target_binary_dir,
            config_lib.CONFIG.Get("Client.binary_name", context=self.context)))

    deb_in_dir = os.path.join(template_path, "dist/debian/debian.in/")

    self.GenerateDirectory(deb_in_dir,
                           os.path.join(template_path, "dist/debian"),
                           [("grr-client", package_name)])

    # Generate directories for the /usr/sbin link.
    utils.EnsureDirExists(
        os.path.join(template_path, "dist/debian/%s/usr/sbin" % package_name))

    # Generate the nanny template. This only exists from client version 3.1.2.5
    # onwards.
    if config_lib.CONFIG["Template.version_numeric"] >= 3125:
      self.GenerateFile(
          os.path.join(target_binary_dir, "nanny.sh.in"),
          os.path.join(target_binary_dir, "nanny.sh"))

    # Generate the upstart template.
    self.GenerateFile(
        os.path.join(template_path, "dist/debian/upstart.in/grr-client.conf"),
        os.path.join(template_path, "dist/debian/%s.upstart" % package_name))

    # Generate the initd template. The init will not run if it detects upstart
    # is present.
    self.GenerateFile(
        os.path.join(template_path, "dist/debian/initd.in/grr-client"),
        os.path.join(template_path, "dist/debian/%s.init" % package_name))

    # Generate the systemd unit file.
    self.GenerateFile(
        os.path.join(template_path,
                     "dist/debian/systemd.in/grr-client.service"),
        os.path.join(template_path, "dist/debian/%s.service" % package_name))

    # Clean up the template dirs.
    shutil.rmtree(deb_in_dir)
    shutil.rmtree(os.path.join(template_path, "dist/debian/upstart.in"))
    shutil.rmtree(os.path.join(template_path, "dist/debian/initd.in"))
    shutil.rmtree(os.path.join(template_path, "dist/debian/systemd.in"))

  def MakeDeployableBinary(self, template_path, output_path):
    """This will add the config to the client template and create a .deb."""
    buildpackage_binary = "/usr/bin/dpkg-buildpackage"
    if not os.path.exists(buildpackage_binary):
      logging.error("dpkg-buildpackage not found, unable to repack client.")
      return

    with utils.TempDirectory() as tmp_dir:
      template_dir = os.path.join(tmp_dir, "dist")
      utils.EnsureDirExists(template_dir)

      zf = zipfile.ZipFile(template_path)
      for name in zf.namelist():
        dirname = os.path.dirname(name)
        utils.EnsureDirExists(os.path.join(template_dir, dirname))
        with open(os.path.join(template_dir, name), "wb") as fd:
          fd.write(zf.read(name))

      # Generate the dpkg files.
      self.GenerateDPKGFiles(tmp_dir)

      # Create a client config.
      client_context = ["Client Context"] + self.context
      client_config_content = self.GetClientConfig(client_context)

      # We need to strip leading /'s or .join will ignore everything that comes
      # before it.
      target_dir = config_lib.CONFIG.Get("ClientBuilder.target_dir",
                                         context=self.context).lstrip("/")
      agent_dir = os.path.join(
          template_dir,
          "debian",
          config_lib.CONFIG.Get("ClientBuilder.package_name",
                                context=self.context),
          target_dir)

      with open(
          os.path.join(
              agent_dir,
              config_lib.CONFIG.Get("ClientBuilder.config_filename",
                                    context=self.context)),
          "wb") as fd:
        fd.write(client_config_content)

      # Set the daemon to executable.
      os.chmod(
          os.path.join(
              agent_dir,
              config_lib.CONFIG.Get("Client.binary_name",
                                    context=self.context)),
          0755)

      arch = config_lib.CONFIG.Get("Template.arch", context=self.context)

      try:
        old_working_dir = os.getcwd()
      except OSError:
        old_working_dir = os.environ.get("HOME", "/tmp")

      try:
        os.chdir(template_dir)
        command = [buildpackage_binary, "-uc", "-d", "-b", "-a%s" % arch]

        try:
          subprocess.check_output(command, stderr=subprocess.STDOUT)
        except subprocess.CalledProcessError as e:
          if "Failed to sign" not in e.output:
            logging.error("Error calling %s.", command)
            logging.error(e.output)
            raise

        filename_base = config_lib.CONFIG.Get(
            "ClientBuilder.debian_package_base", context=self.context)
        output_base = config_lib.CONFIG.Get("ClientRepacker.output_basename",
                                            context=self.context)
      finally:
        try:
          os.chdir(old_working_dir)
        except OSError:
          pass

      utils.EnsureDirExists(os.path.dirname(output_path))

      for extension in [
          ".changes", config_lib.CONFIG.Get("ClientBuilder.output_extension",
                                            context=self.context)
      ]:
        input_name = "%s%s" % (filename_base, extension)
        output_name = "%s%s" % (output_base, extension)

        shutil.move(
            os.path.join(tmp_dir, input_name),
            os.path.join(os.path.dirname(output_path), output_name))

      logging.info("Created package %s", output_path)
      return output_path

class CentosClientRepacker(LinuxClientRepacker):
  """Repackages Linux RPM templates."""

  def Sign(self, rpm_filename):
    if self.signer:
      return self.signer.AddSignatureToRPM(rpm_filename)

  def MakeDeployableBinary(self, template_path, output_path):
    """This will add the config to the client template and create a .rpm."""

    rpmbuild_binary = "/usr/bin/rpmbuild"
    if not os.path.exists(rpmbuild_binary):
      logging.error("rpmbuild not found, unable to repack client.")
      return

    with utils.TempDirectory() as tmp_dir:
      template_dir = os.path.join(tmp_dir, "dist")
      utils.EnsureDirExists(template_dir)

      zf = zipfile.ZipFile(template_path)
      for name in zf.namelist():
        dirname = os.path.dirname(name)
        utils.EnsureDirExists(os.path.join(template_dir, dirname))
        with open(os.path.join(template_dir, name), "wb") as fd:
          fd.write(zf.read(name))

      # Set up a RPM building environment.

      rpm_root_dir = os.path.join(tmp_dir, "rpmbuild")

      rpm_build_dir = os.path.join(rpm_root_dir, "BUILD")
      utils.EnsureDirExists(rpm_build_dir)

      rpm_buildroot_dir = os.path.join(rpm_root_dir, "BUILDROOT")
      utils.EnsureDirExists(rpm_buildroot_dir)

      rpm_rpms_dir = os.path.join(rpm_root_dir, "RPMS")
      utils.EnsureDirExists(rpm_rpms_dir)

      rpm_specs_dir = os.path.join(rpm_root_dir, "SPECS")
      utils.EnsureDirExists(rpm_specs_dir)

      template_binary_dir = os.path.join(tmp_dir, "dist/rpmbuild/grr-client")

      target_binary_dir = "%s%s" % (rpm_build_dir, config_lib.CONFIG.Get(
          "ClientBuilder.target_dir", context=self.context))

      utils.EnsureDirExists(os.path.dirname(target_binary_dir))
      try:
        shutil.rmtree(target_binary_dir)
      except OSError:
        pass
      shutil.move(template_binary_dir, target_binary_dir)
      client_name = config_lib.CONFIG.Get("Client.name", context=self.context)
      client_binary_name = config_lib.CONFIG.Get("Client.binary_name",
                                                 context=self.context)
      if client_binary_name != "grr-client":
        shutil.move(
            os.path.join(target_binary_dir, "grr-client"),
            os.path.join(target_binary_dir, client_binary_name))

      # Generate spec
      spec_filename = os.path.join(rpm_specs_dir, "%s.spec" % client_name)
      self.GenerateFile(
          os.path.join(tmp_dir, "dist/rpmbuild/grr.spec.in"), spec_filename)

      initd_target_filename = os.path.join(rpm_build_dir, "etc/init.d",
                                           client_name)

      # Generate init.d
      utils.EnsureDirExists(os.path.dirname(initd_target_filename))
      self.GenerateFile(
          os.path.join(tmp_dir, "dist/rpmbuild/grr-client.initd.in"),
          initd_target_filename)

      # Generate systemd unit
      if config_lib.CONFIG["Template.version_numeric"] >= 3125:
        systemd_target_filename = os.path.join(rpm_build_dir,
                                               "usr/lib/systemd/system/",
                                               "%s.service" % client_name)

        utils.EnsureDirExists(os.path.dirname(systemd_target_filename))
        self.GenerateFile(
            os.path.join(tmp_dir, "dist/rpmbuild/grr-client.service.in"),
            systemd_target_filename)

        # Generate prelinking blacklist file
        prelink_target_filename = os.path.join(rpm_build_dir,
                                               "etc/prelink.conf.d",
                                               "%s.conf" % client_name)

        utils.EnsureDirExists(os.path.dirname(prelink_target_filename))
        self.GenerateFile(
            os.path.join(tmp_dir, "dist/rpmbuild/prelink_blacklist.conf.in"),
            prelink_target_filename)

      # Create a client config.
      client_context = ["Client Context"] + self.context
      client_config_content = self.GetClientConfig(client_context)

      with open(
          os.path.join(
              target_binary_dir,
              config_lib.CONFIG.Get("ClientBuilder.config_filename",
                                    context=self.context)),
          "wb") as fd:
        fd.write(client_config_content)

      # Undo all prelinking for libs or the rpm might have checksum mismatches.
      logging.info("Undoing prelinking.")
      prelink = "/usr/sbin/prelink"
      if os.access(prelink, os.X_OK):
        libs = os.path.join(target_binary_dir, "lib*")
        # This returns non-zero if there are no prelinked binaries so we can't
        # check_call.
        subprocess.call("%s -u %s 2>/dev/null" % (prelink, libs), shell=True)
      else:
        raise RuntimeError("Can't execute %s, skipping." % prelink)

      # Set the daemon to executable.
      os.chmod(os.path.join(target_binary_dir, client_binary_name), 0755)

      client_arch = config_lib.CONFIG.Get("Template.arch", context=self.context)
      if client_arch == "amd64":
        client_arch = "x86_64"

      command = [
          rpmbuild_binary, "--define", "_topdir " + rpm_root_dir, "--target",
          client_arch, "--buildroot", rpm_buildroot_dir, "-bb", spec_filename
      ]
      try:
        subprocess.check_output(command, stderr=subprocess.STDOUT)
      except subprocess.CalledProcessError as e:
        logging.error("Error calling %s.", command)
        logging.error(e.output)
        raise

      client_version = config_lib.CONFIG.Get("Template.version_string",
                                             context=self.context)
      rpm_filename = os.path.join(rpm_rpms_dir, client_arch, "%s-%s-1.%s.rpm" %
                                  (client_name, client_version, client_arch))

      utils.EnsureDirExists(os.path.dirname(output_path))
      shutil.move(rpm_filename, output_path)

      logging.info("Created package %s", output_path)
      self.Sign(output_path)
      return output_path

def CopyFileInZip(from_zip, from_name, to_zip, to_name=None, signer=None):
  """Read a file from a ZipFile and write it to a new ZipFile."""
  data = from_zip.read(from_name)
  if to_name is None:
    to_name = from_name
  if signer:
    logging.debug("Signing %s", from_name)
    data = signer.SignBuffer(data)
  to_zip.writestr(to_name, data)

def CreateNewZipWithSignedLibs(z_in,
                               z_out,
                               ignore_files=None,
                               signer=None,
                               skip_signing_files=None):
  ignore_files = ignore_files or []
  skip_signing_files = skip_signing_files or []
  extensions_to_sign = [".sys", ".exe", ".dll", ".pyd"]
  for template_file in z_in.namelist():
    if template_file not in ignore_files:
      extension = os.path.splitext(template_file)[1].lower()
      if (signer and template_file not in skip_signing_files and
          extension in extensions_to_sign):
        CopyFileInZip(z_in, template_file, z_out, signer=signer)
      else:
        CopyFileInZip(z_in, template_file, z_out)

def SetPeSubsystem(fd, console=True):
  """Takes file like obj and returns (offset, value) for the PE subsystem."""
  current_pos = fd.tell()
  fd.seek(0x3c)  # _IMAGE_DOS_HEADER.e_lfanew
  header_offset = struct.unpack("<I", fd.read(4))[0]
  # _IMAGE_NT_HEADERS.OptionalHeader.Subsystem ( 0x18 + 0x44)
  subsystem_offset = header_offset + 0x5c
  fd.seek(subsystem_offset)
  if console:
    fd.write("\x03")
  else:
    fd.write("\x02")
  fd.seek(current_pos)


text:
IDENTIFIER=$( defaults read /Library/Preferences/ManagedInstalls ClientIdentifier );
HOSTNAMETEMP=$( scutil --get ComputerName );
# Subs in underscores for spaces in the HOSTNAME
HOSTNAME=${HOSTNAMETEMP// /_}

if [ ! -z "$IDENTIFIER" ]; then

	# Change this URL to the location of your Munki Enroll install
	SUBMITURL="http://localhost:8888/munki/munki-enroll/enroll.php"

	# Test the connection to the server
	SHORTURL=$(echo "$SUBMITURL" | awk -F/ '{print $3}' | awk -F: '{print $1}')
	PINGTEST=$(ping -o "$SHORTURL" | grep "64 bytes")

	if [ ! -z "$PINGTEST" ]; then

	    # Application paths
	    CURL="/usr/bin/curl"

	    $CURL --max-time 5 --silent --get \
	        -d hostname="$HOSTNAME" \
	        -d identifier="$IDENTIFIER" \
	        "$SUBMITURL"

	    # This is a fix for clients based on a manifest in the root /manifests directory
	    # See GitHub issue No. 5
	    if [ $( echo "$IDENTIFIER" | grep "/" ) ]
	    then
	    IDENTIFIER_PATH=$( echo "$IDENTIFIER" | sed 's/\/[^/]*$//' );
	    defaults write /Library/Preferences/ManagedInstalls ClientIdentifier "$IDENTIFIER_PATH/clients/$HOSTNAME"
	    else
	     defaults write /Library/Preferences/ManagedInstalls ClientIdentifier "clients/$HOSTNAME"
	    fi

	    exit 0

	else

	    # No good connection to the server
	    exit 1

	fi

else

	echo "A ClientIdentifier must be set before running this script!"
	exit 1

fi

redpajama_set_name: RedPajamaGithub


text:
module Riddle
  class Client
    # Used to interrogate responses from the Sphinx daemon. Keep in mind none
    # of the methods here check whether the data they're grabbing are what the
    # user expects - it just assumes the user knows what the data stream is
    # made up of.
    class Response
      # Create with the data to interpret
      def initialize(str)
        @str = str
        @marker = 0
      end

      # Return the next string value in the stream
      def next
        len = next_int
        result = @str[@marker, len]
        @marker += len

        return result
      end

      # Return the next integer value from the stream
      def next_int
        int = @str[@marker, 4].unpack('N*').first
        @marker += 4

        return int
      end

      def next_64bit_int
        high, low = @str[@marker, 8].unpack('N*N*')[0..1]
        @marker += 8

        return (high << 32) + low
      end

      # Return the next float value from the stream
      def next_float
        float = @str[@marker, 4].unpack('N*').pack('L').unpack('f*').first
        @marker += 4

        return float
      end

      # Returns an array of string items
      def next_array
        count = next_int
        items = []
        for i in 0...count
          items << self.next
        end

        return items
      end

      # Returns an array of int items
      def next_int_array
        count = next_int
        items = []
        for i in 0...count
          items << self.next_int
        end

        return items
      end

      def next_float_array
        count = next_int
        items = []
        for i in 0...count
          items << self.next_float
        end

        return items
      end

      def next_64bit_int_array
        count = next_int
        items = []
        for i in 0...count
          items << self.next_64bit_int
        end

        return items
      end

      # Returns the length of the streamed data
      def length
        @str.length
      end
    end
  end
end


text:
name: Missing or incorrect documentation
about: Help us improve the Nixpkgs and NixOS reference manuals
title: ''
labels: '9.needs: documentation'
assignees: ''

---

## Problem

<!-- describe your problem -->

## Checklist

<!-- make sure this issue is not redundant or obsolete -->

- [ ] checked [latest Nixpkgs manual] \([source][nixpkgs-source]) and [latest NixOS manual] \([source][nixos-source])
- [ ] checked [open documentation issues] for possible duplicates
- [ ] checked [open documentation pull requests] for possible solutions

[latest Nixpkgs manual]: https://nixos.org/manual/nixpkgs/unstable/
[latest NixOS manual]: https://nixos.org/manual/nixos/unstable/
[nixpkgs-source]: https://github.com/NixOS/nixpkgs/tree/master/doc
[nixos-source]: https://github.com/NixOS/nixpkgs/tree/master/nixos/doc/manual
[open documentation issues]: https://github.com/NixOS/nixpkgs/issues?q=is%3Aissue+is%3Aopen+label%3A%229.needs%3A+documentation%22
[open documentation pull requests]: https://github.com/NixOS/nixpkgs/pulls?q=is%3Aopen+is%3Apr+label%3A%228.has%3A+documentation%22%2C%226.topic%3A+documentation%22

## Proposal

<!-- propose a solution -->


text:
"""

"""
__author__ = 'donal'
__project__ = 'Skeleton_Flask_v11'
from flask.ext.wtf import Form  # Seems odd (this line not next) but correct: wtf Form is slightly different
from wtforms import FileField, StringField, IntegerField

class DataUploadForm(Form):
    attach = FileField('Your data.')
    subdir = StringField("Subdirectory")
    bucket = StringField("Bucket")

class BucketMap(Form):
    """
    """
    member_id = IntegerField()
    bucket = StringField("Bucket")
    user_name = StringField("S3 Username")

    def get_existing_data(self, iam):
        # user-entry data
        self.member_id.default = iam.member_id
        self.bucket.default = iam.bucket
        self.user_name.default = iam.user_name
        # process those changes
        self.process()


text:
"""Add Work and change existing one's definition by using lambda

Revision ID: f0492b40e6
Revises: 223f67eabc3
Create Date: 2014-10-01 02:01:47.389283

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = 'f0492b40e6'
down_revision = '223f67eabc3'

def upgrade():
    op.create_table(
        'wikipedia_works',
        sa.Column('work', sa.String(), nullable=False),
        sa.Column('author', sa.String(), nullable=True),
        sa.PrimaryKeyConstraint('work')
    )

def downgrade():
    op.drop_table('wikipedia_works')


text:
VALUE cNumeric;

void
Init_numeric()
{
	cNumeric = define_class(intern("Numeric"), cObject);
}


text:
#ifndef BOOST_MPL_PUSH_BACK_HPP_INCLUDED
#define BOOST_MPL_PUSH_BACK_HPP_INCLUDED

// Copyright Aleksey Gurtovoy 2000-2004
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/mpl for documentation.

// $Id$
// $Date$
// $Revision$

#include <boost/mpl/push_back_fwd.hpp>
#include <boost/mpl/aux_/push_back_impl.hpp>
#include <boost/mpl/sequence_tag.hpp>
#include <boost/mpl/aux_/na_spec.hpp>
#include <boost/mpl/aux_/lambda_support.hpp>

namespace mars_boost {} namespace boost = mars_boost; namespace mars_boost { namespace mpl {

template<
      typename BOOST_MPL_AUX_NA_PARAM(Sequence)
    , typename BOOST_MPL_AUX_NA_PARAM(T)
    >
struct push_back
    : push_back_impl< typename sequence_tag<Sequence>::type >
        ::template apply< Sequence,T >
{
    BOOST_MPL_AUX_LAMBDA_SUPPORT(2,push_back,(Sequence,T))
};

template<
      typename BOOST_MPL_AUX_NA_PARAM(Sequence)
    >
struct has_push_back
    : has_push_back_impl< typename sequence_tag<Sequence>::type >
        ::template apply< Sequence >
{
    BOOST_MPL_AUX_LAMBDA_SUPPORT(1,has_push_back,(Sequence))
};

BOOST_MPL_AUX_NA_SPEC(2, push_back)
BOOST_MPL_AUX_NA_SPEC(1, has_push_back)

}}

#endif // BOOST_MPL_PUSH_BACK_HPP_INCLUDED


text:
'use strict';

import * as assert from 'assert';
import { IFilter, or, matchesPrefix, matchesStrictPrefix, matchesCamelCase, matchesSubString, matchesContiguousSubString, matchesWords } from 'vs/base/common/filters';

function filterOk(filter: IFilter, word: string, wordToMatchAgainst: string, highlights?: { start: number; end: number; }[]) {
	var r = filter(word, wordToMatchAgainst);
	assert(r);
	if (highlights) {
		assert.deepEqual(r, highlights);
	}
}

function filterNotOk(filter, word, suggestion) {
	assert(!filter(word, suggestion));
}

suite('Filters', () => {
	test('or', function () {
		var filter, counters;
		var newFilter = function (i, r) {
			return function () { counters[i]++; return r; };
		};

		counters = [0, 0];
		filter = or(newFilter(0, false), newFilter(1, false));
		filterNotOk(filter, 'anything', 'anything');
		assert.deepEqual(counters, [1, 1]);

		counters = [0, 0];
		filter = or(newFilter(0, true), newFilter(1, false));
		filterOk(filter, 'anything', 'anything');
		assert.deepEqual(counters, [1, 0]);

		counters = [0, 0];
		filter = or(newFilter(0, true), newFilter(1, true));
		filterOk(filter, 'anything', 'anything');
		assert.deepEqual(counters, [1, 0]);

		counters = [0, 0];
		filter = or(newFilter(0, false), newFilter(1, true));
		filterOk(filter, 'anything', 'anything');
		assert.deepEqual(counters, [1, 1]);
	});

	test('PrefixFilter - case sensitive', function () {
		filterNotOk(matchesStrictPrefix, '', '');
		filterOk(matchesStrictPrefix, '', 'anything', []);
		filterOk(matchesStrictPrefix, 'alpha', 'alpha', [{ start: 0, end: 5 }]);
		filterOk(matchesStrictPrefix, 'alpha', 'alphasomething', [{ start: 0, end: 5 }]);
		filterNotOk(matchesStrictPrefix, 'alpha', 'alp');
		filterOk(matchesStrictPrefix, 'a', 'alpha', [{ start: 0, end: 1 }]);
		filterNotOk(matchesStrictPrefix, 'x', 'alpha');
		filterNotOk(matchesStrictPrefix, 'A', 'alpha');
		filterNotOk(matchesStrictPrefix, 'AlPh', 'alPHA');
	});

	test('PrefixFilter - ignore case', function () {
		filterOk(matchesPrefix, 'alpha', 'alpha', [{ start: 0, end: 5 }]);
		filterOk(matchesPrefix, 'alpha', 'alphasomething', [{ start: 0, end: 5 }]);
		filterNotOk(matchesPrefix, 'alpha', 'alp');
		filterOk(matchesPrefix, 'a', 'alpha', [{ start: 0, end: 1 }]);
		filterNotOk(matchesPrefix, 'x', 'alpha');
		filterOk(matchesPrefix, 'A', 'alpha', [{ start: 0, end: 1 }]);
		filterOk(matchesPrefix, 'AlPh', 'alPHA', [{ start: 0, end: 4 }]);
	});

	test('CamelCaseFilter', function () {
		filterNotOk(matchesCamelCase, '', '');
		filterOk(matchesCamelCase, '', 'anything', []);
		filterOk(matchesCamelCase, 'alpha', 'alpha', [{ start: 0, end: 5 }]);
		filterOk(matchesCamelCase, 'AlPhA', 'alpha', [{ start: 0, end: 5 }]);
		filterOk(matchesCamelCase, 'alpha', 'alphasomething', [{ start: 0, end: 5 }]);
		filterNotOk(matchesCamelCase, 'alpha', 'alp');

		filterOk(matchesCamelCase, 'c', 'CamelCaseRocks', [
			{ start: 0, end: 1 }
		]);
		filterOk(matchesCamelCase, 'cc', 'CamelCaseRocks', [
			{ start: 0, end: 1 },
			{ start: 5, end: 6 }
		]);
		filterOk(matchesCamelCase, 'ccr', 'CamelCaseRocks', [
			{ start: 0, end: 1 },
			{ start: 5, end: 6 },
			{ start: 9, end: 10 }
		]);
		filterOk(matchesCamelCase, 'cacr', 'CamelCaseRocks', [
			{ start: 0, end: 2 },
			{ start: 5, end: 6 },
			{ start: 9, end: 10 }
		]);
		filterOk(matchesCamelCase, 'cacar', 'CamelCaseRocks', [
			{ start: 0, end: 2 },
			{ start: 5, end: 7 },
			{ start: 9, end: 10 }
		]);
		filterOk(matchesCamelCase, 'ccarocks', 'CamelCaseRocks', [
			{ start: 0, end: 1 },
			{ start: 5, end: 7 },
			{ start: 9, end: 14 }
		]);
		filterOk(matchesCamelCase, 'cr', 'CamelCaseRocks', [
			{ start: 0, end: 1 },
			{ start: 9, end: 10 }
		]);
		filterOk(matchesCamelCase, 'fba', 'FooBarAbe', [
			{ start: 0, end: 1 },
			{ start: 3, end: 5 }
		]);
		filterOk(matchesCamelCase, 'fbar', 'FooBarAbe', [
			{ start: 0, end: 1 },
			{ start: 3, end: 6 }
		]);
		filterOk(matchesCamelCase, 'fbara', 'FooBarAbe', [
			{ start: 0, end: 1 },
			{ start: 3, end: 7 }
		]);
		filterOk(matchesCamelCase, 'fbaa', 'FooBarAbe', [
			{ start: 0, end: 1 },
			{ start: 3, end: 5 },
			{ start: 6, end: 7 }
		]);
		filterOk(matchesCamelCase, 'fbaab', 'FooBarAbe', [
			{ start: 0, end: 1 },
			{ start: 3, end: 5 },
			{ start: 6, end: 8 }
		]);
		filterOk(matchesCamelCase, 'c2d', 'canvasCreation2D', [
			{ start: 0, end: 1 },
			{ start: 14, end: 16 }
		]);
		filterOk(matchesCamelCase, 'cce', '_canvasCreationEvent', [
			{ start: 1, end: 2 },
			{ start: 7, end: 8 },
			{ start: 15, end: 16 }
		]);
	});

	test('CamelCaseFilter - #19256', function () {
		assert(matchesCamelCase('Debug Console', 'Open: Debug Console'));
		assert(matchesCamelCase('Debug console', 'Open: Debug Console'));
		assert(matchesCamelCase('debug console', 'Open: Debug Console'));
	});

	test('matchesContiguousSubString', function () {
		filterOk(matchesContiguousSubString, 'cela', 'cancelAnimationFrame()', [
			{ start: 3, end: 7 }
		]);
	});

	test('matchesSubString', function () {
		filterOk(matchesSubString, 'cmm', 'cancelAnimationFrame()', [
			{ start: 0, end: 1 },
			{ start: 9, end: 10 },
			{ start: 18, end: 19 }
		]);
	});

	test('WordFilter', function () {
		filterOk(matchesWords, 'alpha', 'alpha', [{ start: 0, end: 5 }]);
		filterOk(matchesWords, 'alpha', 'alphasomething', [{ start: 0, end: 5 }]);
		filterNotOk(matchesWords, 'alpha', 'alp');
		filterOk(matchesWords, 'a', 'alpha', [{ start: 0, end: 1 }]);
		filterNotOk(matchesWords, 'x', 'alpha');
		filterOk(matchesWords, 'A', 'alpha', [{ start: 0, end: 1 }]);
		filterOk(matchesWords, 'AlPh', 'alPHA', [{ start: 0, end: 4 }]);
		assert(matchesWords('Debug Console', 'Open: Debug Console'));

		filterOk(matchesWords, 'gp', 'Git: Pull', [{ start: 0, end: 1 }, { start: 5, end: 6 }]);
		filterOk(matchesWords, 'g p', 'Git: Pull', [{ start: 0, end: 1 }, { start: 4, end: 6 }]);
		filterOk(matchesWords, 'gipu', 'Git: Pull', [{ start: 0, end: 2 }, { start: 5, end: 7 }]);

		filterOk(matchesWords, 'gp', 'Category: Git: Pull', [{ start: 10, end: 11 }, { start: 15, end: 16 }]);
		filterOk(matchesWords, 'g p', 'Category: Git: Pull', [{ start: 10, end: 11 }, { start: 14, end: 16 }]);
		filterOk(matchesWords, 'gipu', 'Category: Git: Pull', [{ start: 10, end: 12 }, { start: 15, end: 17 }]);

		filterNotOk(matchesWords, 'it', 'Git: Pull');
		filterNotOk(matchesWords, 'll', 'Git: Pull');

		filterOk(matchesWords, 'git: プル', 'git: プル', [{ start: 0, end: 7 }]);
		filterOk(matchesWords, 'git プル', 'git: プル', [{ start: 0, end: 3 }, { start: 4, end: 7 }]);

		filterOk(matchesWords, 'öäk', 'Öhm: Älles Klar', [{ start: 0, end: 1 }, { start: 5, end: 6 }, { start: 11, end: 12 }]);
	});
});


text:
package assignment_4b;

public abstract class Animal {
	private String latinName;
	private String friendlyName;

	public Animal(String latinName){
		this.latinName = latinName;
	}

	public abstract String getInfo();

	public String getLatinName(){
		return latinName;
	}

	public String getFriendlyName() {
		return friendlyName;
	}

	public void setFriendlyName(String friendlyName) {
		this.friendlyName = friendlyName;
	}
}


text:
const BitField = require('bitfield').default
const debug = require('debug')('webtorrent:webconn')
const get = require('simple-get')
const ltDontHave = require('lt_donthave')
const sha1 = require('simple-sha1')
const Wire = require('bittorrent-protocol')

const VERSION = require('../package.json').version

const SOCKET_TIMEOUT = 60000
const RETRY_DELAY = 10000

/**
 * Converts requests for torrent blocks into http range requests.
 * @param {string} url web seed url
 * @param {Object} torrent
 */
class WebConn extends Wire {
  constructor (url, torrent) {
    super()

    this.url = url
    this.connId = url // Unique id to deduplicate web seeds
    this.webPeerId = sha1.sync(url) // Used as the peerId for this fake remote peer
    this._torrent = torrent

    this._init()
  }

  _init () {
    this.setKeepAlive(true)

    this.use(ltDontHave())

    this.once('handshake', (infoHash, peerId) => {
      if (this.destroyed) return
      this.handshake(infoHash, this.webPeerId)
      const numPieces = this._torrent.pieces.length
      const bitfield = new BitField(numPieces)
      for (let i = 0; i <= numPieces; i++) {
        bitfield.set(i, true)
      }
      this.bitfield(bitfield)
    })

    this.once('interested', () => {
      debug('interested')
      this.unchoke()
    })

    this.on('uninterested', () => { debug('uninterested') })
    this.on('choke', () => { debug('choke') })
    this.on('unchoke', () => { debug('unchoke') })
    this.on('bitfield', () => { debug('bitfield') })
    this.lt_donthave.on('donthave', () => { debug('donthave') })

    this.on('request', (pieceIndex, offset, length, callback) => {
      debug('request pieceIndex=%d offset=%d length=%d', pieceIndex, offset, length)
      this.httpRequest(pieceIndex, offset, length, (err, data) => {
        if (err) {
          // Cancel all in progress requests for this piece
          this.lt_donthave.donthave(pieceIndex)

          // Wait a little while before saying the webseed has the failed piece again
          const retryTimeout = setTimeout(() => {
            if (this.destroyed) return

            this.have(pieceIndex)
          }, RETRY_DELAY)
          if (retryTimeout.unref) retryTimeout.unref()
        }

        callback(err, data)
      })
    })
  }

  httpRequest (pieceIndex, offset, length, cb) {
    const pieceOffset = pieceIndex * this._torrent.pieceLength
    const rangeStart = pieceOffset + offset /* offset within whole torrent */
    const rangeEnd = rangeStart + length - 1

    // Web seed URL format:
    // For single-file torrents, make HTTP range requests directly to the web seed URL
    // For multi-file torrents, add the torrent folder and file name to the URL
    const files = this._torrent.files
    let requests
    if (files.length <= 1) {
      requests = [{
        url: this.url,
        start: rangeStart,
        end: rangeEnd
      }]
    } else {
      const requestedFiles = files.filter(file => {
        return file.offset <= rangeEnd && (file.offset + file.length) > rangeStart
      })
      if (requestedFiles.length < 1) {
        return cb(new Error('Could not find file corresponding to web seed range request'))
      }

      requests = requestedFiles.map(requestedFile => {
        const fileEnd = requestedFile.offset + requestedFile.length - 1
        const url = this.url +
          (this.url[this.url.length - 1] === '/' ? '' : '/') +
          requestedFile.path
        return {
          url,
          fileOffsetInRange: Math.max(requestedFile.offset - rangeStart, 0),
          start: Math.max(rangeStart - requestedFile.offset, 0),
          end: Math.min(fileEnd, rangeEnd - requestedFile.offset)
        }
      })
    }

    // Now make all the HTTP requests we need in order to load this piece
    // Usually that's one requests, but sometimes it will be multiple
    // Send requests in parallel and wait for them all to come back
    let numRequestsSucceeded = 0
    let hasError = false

    let ret
    if (requests.length > 1) {
      ret = Buffer.alloc(length)
    }

    requests.forEach(request => {
      const url = request.url
      const start = request.start
      const end = request.end
      debug(
        'Requesting url=%s pieceIndex=%d offset=%d length=%d start=%d end=%d',
        url, pieceIndex, offset, length, start, end
      )
      const opts = {
        url,
        method: 'GET',
        headers: {
          'user-agent': `WebTorrent/${VERSION} (https://webtorrent.io)`,
          range: `bytes=${start}-${end}`
        },
        timeout: SOCKET_TIMEOUT
      }
      function onResponse (res, data) {
        if (res.statusCode < 200 || res.statusCode >= 300) {
          if (hasError) return
          hasError = true
          return cb(new Error(`Unexpected HTTP status code ${res.statusCode}`))
        }
        debug('Got data of length %d', data.length)

        if (requests.length === 1) {
          // Common case: fetch piece in a single HTTP request, return directly
          cb(null, data)
        } else {
          // Rare case: reconstruct multiple HTTP requests across 2+ files into one
          // piece buffer
          data.copy(ret, request.fileOffsetInRange)
          if (++numRequestsSucceeded === requests.length) {
            cb(null, ret)
          }
        }
      }
      get.concat(opts, (err, res, data) => {
        if (hasError) return
        if (err) {
          // Browsers allow HTTP redirects for simple cross-origin
          // requests but not for requests that require preflight.
          // Use a simple request to unravel any redirects and get the
          // final URL.  Retry the original request with the new URL if
          // it's different.
          //
          // This test is imperfect but it's simple and good for common
          // cases.  It catches all cross-origin cases but matches a few
          // same-origin cases too.
          if (typeof window === 'undefined' || url.startsWith(`${window.location.origin}/`)) {
            hasError = true
            return cb(err)
          }

          return get.head(url, (errHead, res) => {
            if (hasError) return
            if (errHead) {
              hasError = true
              return cb(errHead)
            }
            if (res.statusCode < 200 || res.statusCode >= 300) {
              hasError = true
              return cb(new Error(`Unexpected HTTP status code ${res.statusCode}`))
            }
            if (res.url === url) {
              hasError = true
              return cb(err)
            }

            opts.url = res.url
            get.concat(opts, (err, res, data) => {
              if (hasError) return
              if (err) {
                hasError = true
                return cb(err)
              }
              onResponse(res, data)
            })
          })
        }
        onResponse(res, data)
      })
    })
  }

  destroy () {
    super.destroy()
    this._torrent = null
  }
}

module.exports = WebConn


text:
/**
 * @author Petru Cojocar <petru.cojocar@gmail.com>.
 */

try { angular.module('Web.Components') } catch(err) { angular.module('Web.Components', []) }

angular.module('Web.Components')
    .directive('comMessenger', ['Web.Components.MessengerService',
        function (MessengerService) {
            var appMessenger = {
                restrict: 'E',
                template: '
' +
                            '
' +
                            '
' +
                          '
',
                replace: true,
                scope: {
                    channel: '@',
                    settings: '='
                },
                link: function (scope, element, attrs)
                {
                    if (typeof(scope.channel) === 'undefined') {
                        throw ('appMessenger requires a channel! Please add one using the attribute [channel]');
                    }

                    scope.messages = [];
                    scope.options = {};

                    // register the channel
                    MessengerService.registerChannel(scope);
                }
            };

            return appMessenger;
        }
    ])
    .factory('Web.Components.MessengerService', [
        function ()
        {
            var $private = {
                /**
                 * Accepted message types
                 */
                types: {
                    info:   'info',
                    warn:   'warning',
                    ok:     'success',
                    err:    'error'
                },
                /**
                 * Accepted layout placements
                 */
                layouts: {
                    'top-center': {
                        animate: {
                            in: 'fadeInDown animated',
                            out: 'fadeOutDown animated'
                        }
                    },
                    'top-full-width': {
                        animate: {
                            in: 'fadeInDown animated',
                            out: 'fadeOutDown animated'
                        }
                    },
                    'top-left': {
                        animate: {
                            in: 'fadeInDown animated',
                            out: 'fadeOutLeft animated'
                        }
                    },
                    'top-right': {
                        animate: {
                            in: 'fadeInDown animated',
                            out: 'fadeOutRight animated'
                        }
                    },
                    'host-top': {
                        animate: {
                            in: 'fadeInDown animated',
                            out: 'fadeOutDown animated'
                        }
                    },
                    'bottom-center': {
                        animate: {
                            in: 'fadeInUp animated',
                            out: 'fadeOutUp animated'
                        }
                    },
                    'bottom-full-width': {
                        animate: {
                            in: 'fadeInUp animated',
                            out: 'fadeOutUp animated'
                        }
                    },
                    'bottom-left': {
                        animate: {
                            in: 'fadeInUp animated',
                            out: 'fadeOutLeft animated'
                        }
                    },
                    'bottom-right': {
                        animate: {
                            in: 'fadeInUp animated',
                            out: 'fadeOutRight animated'
                        }
                    }
                }
            };

            var MessengerService = {
                channels: {}
            };

            /**
             * Register a channel
             * @param scope
             */
            MessengerService.registerChannel = function (scope)
            {
                if (typeof(this.channels[scope.channel]) === 'undefined') {

                    /**
                     * Default Options(Settings)
                     * @type {{layout: string, animate: {in: string, out: string}}}
                     */
                    var defaultOptions = {
                        layout: 'top-full-width',
                        animate: {
                            in: 'fadeInDown animated',
                            out: 'fadeOutDown animated'
                        },
                        msgCss: '',     // extra class to add for the message container
                        dt: 5           // default message display time 5 seconds
                    };

                    // create default settings for channel
                    if (typeof(scope.settings) === 'undefined') {
                        scope.options = defaultOptions;
                    } else {
                        scope.options = _.deepExtend(scope.settings, scope.options);
                        scope.options = _.deepExtend(defaultOptions, scope.options);
                    }

                    this.channels[scope.channel] = {
                        scope: scope
                    };

                } else {
                    throw 'Messenger Channel [' + channel + '] is already registered';
                }
            };

            /**
             * Send a message to a channel
             * @param channelName
             * @param msg
             * @param msgType
             * @param displayTime
             */
            MessengerService.send = function (channelName, msg, msgType, displayTime)
            {
                if (typeof(this.channels[channelName]) !== 'undefined') {

                    var $scope = this.channels[channelName].scope;

                    if (typeof(msgType) !== 'undefined') {
                        if (typeof($private.types[msgType]) !== 'undefined') {
                            msgType = $private.types[msgType];
                        } else {
                            throw 'Unrecognized message type: ['+msgType+']';
                        }
                    } else {
                        msgType = 'default';
                    }

                    var _cssClass = 'com-message-' + msgType;
                    var isSticky = false;

                    if (typeof(displayTime) !== 'undefined') {
                        if (_.isBoolean(displayTime)) {
                            if (displayTime) {
                                isSticky = true;
                            }
                        } else {
                            displayTime = displayTime * 1000;
                        }
                    } else {
                        displayTime = $scope.options.dt * 1000;
                    }

                    var message = {
                        content: msg,
                        class: _cssClass,
                        state: true
                    };

                    // hider
                    if (!isSticky) {
                        setTimeout(function () {
                            message.state = false;
                            $scope.$apply();
                        }, displayTime);
                    }

                    // push message
                    $scope.messages.push(message);

                    setTimeout(function () {
                        $scope.$apply();
                    }, 100);

                } else {
                    throw 'Messenger Channel [' + channelName + '] is not registered';
                }
            };

            /**
             * Clear all messages from a channel
             * @param channelName
             */
            MessengerService.clear = function (channelName)
            {
                if (typeof(this.channels[channelName]) !== 'undefined') {
                    var $scope = this.channels[channelName].scope;

                    $scope.messages = [];

                    setTimeout(function () {
                        $scope.$apply();
                    }, 100);

                } else {
                    throw 'Messenger Channel [' + channelName + '] is not registered';
                }
            };

            return MessengerService;
        }
    ]);


text:
/**
 * @file ColorPalette.hpp
 * @author Joshua Behrens <code@joshua-behrens.de>
 * Helper-class for indexing colors
 */
#ifndef _PIETVM_PERSISTENCY_COLORPALETTE_HPP
#define _PIETVM_PERSISTENCY_COLORPALETTE_HPP

#include <map>
#include <list>

#include "Color.hpp"

namespace PietVM
{
	namespace Persistency
	{
		/**
		 * Helper class for indexing colors
		 */
		class ColorPalette
		{
		private:
			/**
			 * Map with all colors
			 */
			std::map<U32, Color> colorIndex;

			/**
			 * Index counter
			 */
			U32 nextIndex;
		public:
			/**
			 * Iterator type is always const to prohibit changes
			 */
			typedef std::map<U32, Color>::const_iterator iterator;

			/**
			 * Iterator access to the start of the index list
			 * @return iterator Iterator to the start
			 */
			iterator begin() const;

			/**
			 * Iterator access to the end of the index list
			 * @return iterator Iterator to the end
			 */
			iterator end() const;

			/**
             * Returns the amount of indexed elements
             * @return std::size_t Amount of indexed elements
			 */
			std::size_t size() const;

			/**
			 * Clears the list of indexed elements and resets the index counter
			 */
			void clear();

			/**
			 * List type for the color only functions
			 */
			typedef std::list<Color> ColorList;

			/**
			 * Returns all indexed colors without their indices
			 * @return ColorList All indexed colors
			 */
			ColorList GetColors() const;

			/**
			 * Tries to add the color and assigns the given index to param2. If color is already indexed the given indexed is of the already existing element
			 * @param const Color& color         The color to add
			 * @param PietVM::U32& assignedIndex The index that was assigned to the color
			 * @return True if the color was not indexed before, otherwise false
			 */
			bool TryAdd(const Color& color, U32& assignedIndex);

			/**
			 * Adds a color to the index and returns the given index
			 * Throws exception if color already exists
			 * @param const Color& color The color to add
			 * @return PietVM::U32 The new assigned index
			 * TODO throw error if entry already exists
			 */
			U32 Add(const Color& color);

			/**
			 * Checks whether a given color is already indexed
			 * @param const Color& color The color to check
			 * @return bool True if the given color is already indexed, otherwise false
			 */
			bool Contains(const Color& color) const;

			/**
			 * Returns the given index of the color in question.
			 * Throws error if color is not indexed
			 * @param const Color& color The color to check
			 * @return PietVM::U32 The given index of the color
			 * TODO throw error if no index if assigned to the color
			 */
			U32 IndexOf(const Color& color) const;
		}; // ColorPalette
	} // Persistency
} // PietVM

#endif // _PIETVM_PERSISTENCY_COLORPALETTE_HPP


text:
package main

// snippet-start:[ssm.go.get_parameter.imports]
import (
	"flag"
	"fmt"

	"github.com/aws/aws-sdk-go/aws/session"
	"github.com/aws/aws-sdk-go/service/ssm"
	"github.com/aws/aws-sdk-go/service/ssm/ssmiface"
)

// snippet-end:[ssm.go.get_parameter.imports]

// GetParameter fetches details of a parameter in SSM
// Inputs:
//     svc is an Amazon SSM service client
//     name is the name of the parameter
// Output:
//     If success, information about the parameter and nil
//     Otherwise, nil and an error from the call to GetParameter
func GetParameter(svc ssmiface.SSMAPI, name *string) (*ssm.GetParameterOutput, error) {
	// snippet-start:[ssm.go.get_parameter.call]
	results, err := svc.GetParameter(&ssm.GetParameterInput{
		Name:  name,
	})
	// snippet-end:[ssm.go.get_parameter.call]

	return results, err
}

func main() {
	// snippet-start:[ssm.go.get_parameter.args]
	parameterName := flag.String("n", "", "The name of the parameter")
	flag.Parse()

	if *parameterName == "" {
		fmt.Println("You must supply the name of the parameter")
		fmt.Println("-n NAME")
		return
	}

	// snippet-end:[ssm.go.get_parameter.args]

	// snippet-start:[ssm.go.get_parameter.session]
	sess := session.Must(session.NewSessionWithOptions(session.Options{
		SharedConfigState: session.SharedConfigEnable,
	}))

	svc := ssm.New(sess)
	// snippet-end:[ssm.go.get_parameter.session]

	results, err := GetParameter(svc, parameterName)
	if err != nil {
		fmt.Println(err.Error())
		return
	}

	// snippet-start:[ssm.go.get_parameter.display]
	fmt.Println(*results.Parameter.Value)
	// snippet-end:[ssm.go.get_parameter.display]
}

// snippet-end:[ssm.go.get_parameter]


text:
function showRetryButton() {
  $.ajax({ url: "/cities", method: 'get', dataType: 'json' }).
     done(function(data){
       $('#cityselector').html(data.html);
       $('#pleasewait').slideUp().
           fadeOut({complete: function(){ $('#retrybutton').fadeIn(); } });
     });
}

function showPleaseWait() {
  $('#retrybutton').slideUp().
    fadeOut({complete: function(){$('#pleasewait').fadeIn();}});
}


text:
<!doctype html>

	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<title>MonitorOptions | mongodb</title>
	<meta name="description" content="Documentation for mongodb">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<link rel="stylesheet" href="../assets/css/main.css">

						Search
						<input id="tsd-search-field" type="text" />

Preparing search index...

The search index is not available

					mongodb

						Options

								All

Public

Public/Protected

All

							<input type="checkbox" id="tsd-filter-inherited" checked />
							Inherited
							<input type="checkbox" id="tsd-filter-externals" checked />
							Externals

					Menu

					mongodb

					MonitorOptions

Interface MonitorOptions

Hierarchy

						Omit<ConnectionOptions, "id" | "generation" | "hostAddress">

								MonitorOptions

Index

Properties

ALPNProtocols

auto<wbr>Encrypter

ca

cancellation<wbr>Token

cert

check<wbr>Server<wbr>Identity

ciphers

compressors

connect<wbr>TimeoutMS

connection<wbr>Type

credentials

crl

ecdh<wbr>Curve

family

heartbeat<wbr>FrequencyMS

hints

keep<wbr>Alive

keep<wbr>Alive<wbr>Initial<wbr>Delay

key

local<wbr>Address

local<wbr>Port

lookup

metadata

minDHSize

min<wbr>Heartbeat<wbr>FrequencyMS

monitor<wbr>Commands

no<wbr>Delay

passphrase

pfx

reject<wbr>Unauthorized

secure<wbr>Context

secure<wbr>Protocol

server<wbr>Api

servername

session

socket<wbr>TimeoutMS

tls

Properties

Optional ALPNProtocols

ALPNProtocols: Uint8Array | string[] | Uint8Array[]

Inherited from Omit.ALPNProtocols

Defined in node_modules/@types/node/tls.d.ts:376

An array of strings or a Buffer naming possible ALPN protocols.
							(Protocols should be ordered by their priority.)

Optional auto<wbr>Encrypter

auto<wbr>Encrypter: AutoEncrypter

Inherited from Omit.autoEncrypter

Defined in src/cmap/connection.ts:124

Optional ca

ca: string | Buffer | (string | Buffer)[]

Inherited from Omit.ca

Defined in node_modules/@types/node/tls.d.ts:583

Optionally override the trusted CA certificates. Default is to trust
								the well-known CAs curated by Mozilla. Mozilla's CAs are completely
							replaced when CAs are explicitly specified using this option.

Optional cancellation<wbr>Token

cancellation<wbr>Token: CancellationToken

Inherited from Omit.cancellationToken

Defined in src/cmap/connection.ts:136

Optional cert

cert: string | Buffer | (string | Buffer)[]

Inherited from Omit.cert

Defined in node_modules/@types/node/tls.d.ts:595

 Cert chains in PEM format. One cert chain should be provided per
								private key. Each cert chain should consist of the PEM formatted
								certificate for a provided private key, followed by the PEM
								formatted intermediate certificates (if any), in order, and not
								including the root CA (the root CA must be pre-known to the peer,
								see ca). When providing multiple cert chains, they do not have to
								be in the same order as their private keys in key. If the
								intermediate certificates are not provided, the peer will not be
							able to validate the certificate, and the handshake will fail.

Optional check<wbr>Server<wbr>Identity

check<wbr>Server<wbr>Identity: (host: string, cert: PeerCertificate) => Error | undefined

Inherited from Omit.checkServerIdentity

Defined in node_modules/@types/node/tls.d.ts:455

Type declaration

(host: string, cert: PeerCertificate): Error | undefined

Parameters

host: string

cert: PeerCertificate

Returns Error | undefined

Optional ciphers

ciphers: string

Inherited from Omit.ciphers

Defined in node_modules/@types/node/tls.d.ts:609

Cipher suite specification, replacing the default. For more
								information, see modifying the default cipher suite. Permitted
								ciphers can be obtained via tls.getCiphers(). Cipher names must be
							uppercased in order for OpenSSL to accept them.

Optional compressors

compressors: ("none" | "snappy" | "zlib")[]

Inherited from Omit.compressors

Defined in src/cmap/stream_description.ts:17

connect<wbr>TimeoutMS

connect<wbr>TimeoutMS: number

Overrides Omit.connectTimeoutMS

Defined in src/sdam/monitor.ts:60

Optional connection<wbr>Type

connection<wbr>Type: typeof Connection

Inherited from Omit.connectionType

Defined in src/cmap/connection.ts:128

internal

Optional credentials

credentials: MongoCredentials

Inherited from Omit.credentials

Defined in src/cmap/connection.ts:129

Optional crl

crl: string | Buffer | (string | Buffer)[]

Inherited from Omit.crl

Defined in node_modules/@types/node/tls.d.ts:617

PEM formatted CRLs (Certificate Revocation Lists).

Optional ecdh<wbr>Curve

ecdh<wbr>Curve: string

Inherited from Omit.ecdhCurve

Defined in node_modules/@types/node/tls.d.ts:636

A string describing a named curve or a colon separated list of curve
								NIDs or names, for example P-521:P-384:P-256, to use for ECDH key
								agreement. Set to auto to select the curve automatically. Use
								crypto.getCurves() to obtain a list of available curve names. On
								recent releases, openssl ecparam -list_curves will also display the
								name and description of each available elliptic curve. Default:
							tls.DEFAULT_ECDH_CURVE.

Optional family

family: number

Inherited from Omit.family

Defined in node_modules/@types/node/net.d.ts:50

heartbeat<wbr>FrequencyMS

heartbeat<wbr>FrequencyMS: number

Defined in src/sdam/monitor.ts:61

Optional hints

hints: number

Inherited from Omit.hints

Defined in node_modules/@types/node/net.d.ts:49

Optional keep<wbr>Alive

keep<wbr>Alive: boolean

Inherited from Omit.keepAlive

Defined in src/cmap/connection.ts:132

Optional keep<wbr>Alive<wbr>Initial<wbr>Delay

keep<wbr>Alive<wbr>Initial<wbr>Delay: number

Inherited from Omit.keepAliveInitialDelay

Defined in src/cmap/connection.ts:133

Optional key

key: string | Buffer | (Buffer | KeyObject)[]

Inherited from Omit.key

Defined in node_modules/@types/node/tls.d.ts:653

Private keys in PEM format. PEM allows the option of private keys
								being encrypted. Encrypted keys will be decrypted with
								options.passphrase. Multiple keys using different algorithms can be
								provided either as an array of unencrypted key strings or buffers,
								or an array of objects in the form {pem: <string|buffer>[,
								passphrase: <string>]}. The object form can only occur in an array.
									object.passphrase is optional. Encrypted keys will be decrypted with
							object.passphrase if provided, or options.passphrase if it is not.

Optional local<wbr>Address

local<wbr>Address: string

Inherited from Omit.localAddress

Defined in node_modules/@types/node/net.d.ts:47

Optional local<wbr>Port

local<wbr>Port: number

Inherited from Omit.localPort

Defined in node_modules/@types/node/net.d.ts:48

Optional lookup

lookup: LookupFunction

Inherited from Omit.lookup

Defined in node_modules/@types/node/net.d.ts:51

metadata

metadata: ClientMetadata

Inherited from Omit.metadata

Defined in src/cmap/connection.ts:138

Optional minDHSize

minDHSize: number

Inherited from Omit.minDHSize

Defined in node_modules/@types/node/tls.d.ts:458

min<wbr>Heartbeat<wbr>FrequencyMS

min<wbr>Heartbeat<wbr>FrequencyMS: number

Defined in src/sdam/monitor.ts:62

monitor<wbr>Commands

monitor<wbr>Commands: boolean

Inherited from Omit.monitorCommands

Defined in src/cmap/connection.ts:126

Optional no<wbr>Delay

no<wbr>Delay: boolean

Inherited from Omit.noDelay

Defined in src/cmap/connection.ts:134

Optional passphrase

passphrase: string

Inherited from Omit.passphrase

Defined in node_modules/@types/node/tls.d.ts:688

Shared passphrase used for a single private key and/or a PFX.

Optional pfx

pfx: string | Buffer | (string | Buffer | PxfObject)[]

Inherited from Omit.pfx

Defined in node_modules/@types/node/tls.d.ts:699

PFX or PKCS12 encoded private key and certificate chain. pfx is an
								alternative to providing key and cert individually. PFX is usually
								encrypted, if it is, passphrase will be used to decrypt it. Multiple
								PFX can be provided either as an array of unencrypted PFX buffers,
								or an array of objects in the form {buf: <string|buffer>[,
								passphrase: <string>]}. The object form can only occur in an array.
									object.passphrase is optional. Encrypted PFX will be decrypted with
							object.passphrase if provided, or options.passphrase if it is not.

Optional reject<wbr>Unauthorized

reject<wbr>Unauthorized: boolean

Inherited from Omit.rejectUnauthorized

Defined in node_modules/@types/node/tls.d.ts:393

If true the server will reject any connection which is not
								authorized with the list of supplied CAs. This option only has an
							effect if requestCert is true.

default

true

Optional secure<wbr>Context

secure<wbr>Context: SecureContext

Inherited from Omit.secureContext

Defined in node_modules/@types/node/tls.d.ts:358

An optional TLS context object from tls.createSecureContext()

Optional secure<wbr>Protocol

secure<wbr>Protocol: string

Inherited from Omit.secureProtocol

Defined in node_modules/@types/node/tls.d.ts:717

Legacy mechanism to select the TLS protocol version to use, it does
								not support independent control of the minimum and maximum version,
								and does not support limiting the protocol to TLSv1.3. Use
								minVersion and maxVersion instead. The possible values are listed as
								SSL_METHODS, use the function names as strings. For example, use
								'TLSv1_1_method' to force TLS version 1.1, or 'TLS_method' to allow
								any TLS protocol version up to TLSv1.3. It is not recommended to use
								TLS versions less than 1.2, but it may be required for
							interoperability. Default: none, see minVersion.

Optional server<wbr>Api

server<wbr>Api: ServerApi

Inherited from Omit.serverApi

Defined in src/cmap/connection.ts:125

Optional servername

servername: string

Inherited from Omit.servername

Defined in node_modules/@types/node/tls.d.ts:456

Optional session

session: Buffer

Inherited from Omit.session

Defined in node_modules/@types/node/tls.d.ts:457

Optional socket<wbr>TimeoutMS

socket<wbr>TimeoutMS: number

Inherited from Omit.socketTimeoutMS

Defined in src/cmap/connection.ts:135

tls

tls: boolean

Inherited from Omit.tls

Defined in src/cmap/connection.ts:131

						Exports

						Monitor<wbr>Options

								ALPNProtocols

								auto<wbr>Encrypter

								ca

								cancellation<wbr>Token

								cert

								check<wbr>Server<wbr>Identity

								ciphers

								compressors

								connect<wbr>TimeoutMS

								connection<wbr>Type

								credentials

								crl

								ecdh<wbr>Curve

								family

								heartbeat<wbr>FrequencyMS

								hints

								keep<wbr>Alive

								keep<wbr>Alive<wbr>Initial<wbr>Delay

								key

								local<wbr>Address

								local<wbr>Port

								lookup

								metadata

								minDHSize

								min<wbr>Heartbeat<wbr>FrequencyMS

								monitor<wbr>Commands

								no<wbr>Delay

								passphrase

								pfx

								reject<wbr>Unauthorized

								secure<wbr>Context

								secure<wbr>Protocol

								server<wbr>Api

								servername

								session

								socket<wbr>TimeoutMS

								tls

Legend

Constructor

Property

Method

Accessor

Inherited constructor

Inherited property

Inherited method

Inherited accessor

Constructor

Property

Method

Private property

Private method

Static property

Static method

Generated using TypeDoc


text:
FROM jenkinsci/blueocean

USER root