text:
package org.apache.hadoop.hbase.client;

import java.io.IOException;
import java.util.UUID;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.HBaseClassTestRule;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.master.snapshot.SnapshotManager;
import org.apache.hadoop.hbase.regionserver.ConstantSizeRegionSplitPolicy;
import org.apache.hadoop.hbase.snapshot.SnapshotDescriptionUtils;
import org.apache.hadoop.hbase.testclassification.LargeTests;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.experimental.categories.Category;

/**
 * This class tests that the use of a temporary snapshot directory supports snapshot functionality
 * while the temporary directory is on the same file system as the root directory
 * <p>
 * This is an end-to-end test for the snapshot utility
 */
@Category(LargeTests.class)
public class TestSnapshotDFSTemporaryDirectory extends TestSnapshotTemporaryDirectory {

  @ClassRule
  public static final HBaseClassTestRule CLASS_RULE =
    HBaseClassTestRule.forClass(TestSnapshotDFSTemporaryDirectory.class);

  /**
   * Setup the config for the cluster
   * @throws Exception on failure
   */
  @BeforeClass
  public static void setupCluster() throws Exception {
    setupConf(UTIL.getConfiguration());
    UTIL.startMiniCluster(NUM_RS);
    admin = UTIL.getHBaseAdmin();
  }

  private static void setupConf(Configuration conf) throws IOException {
    // disable the ui
    conf.setInt("hbase.regionsever.info.port", -1);
    // change the flush size to a small amount, regulating number of store files
    conf.setInt("hbase.hregion.memstore.flush.size", 25000);
    // so make sure we get a compaction when doing a load, but keep around some
    // files in the store
    conf.setInt("hbase.hstore.compaction.min", 10);
    conf.setInt("hbase.hstore.compactionThreshold", 10);
    // block writes if we get to 12 store files
    conf.setInt("hbase.hstore.blockingStoreFiles", 12);
    // Enable snapshot
    conf.setBoolean(SnapshotManager.HBASE_SNAPSHOT_ENABLED, true);
    conf.set(HConstants.HBASE_REGION_SPLIT_POLICY_KEY,
      ConstantSizeRegionSplitPolicy.class.getName());

    String snapshotPath = UTIL.getDefaultRootDirPath().toString() + Path.SEPARATOR
      + UUID.randomUUID().toString() + Path.SEPARATOR + ".tmpdir" + Path.SEPARATOR;
    conf.set(SnapshotDescriptionUtils.SNAPSHOT_WORKING_DIR,
      "file://" + new Path(snapshotPath).toUri());
  }
}


text:
import { ControlMessagesComponent } from './control-message.component';
import { ValidationService } from './validation.service';
import { FormsModule } from '@angular/forms';
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { MaterialModule } from './material.module';

@NgModule({
  imports: [
    CommonModule,
    FormsModule
  ],
  declarations: [
    ControlMessagesComponent
  ],
  providers: [
    // {provide: JQUERY_TOKEN, useValue: jQuery}
    ValidationService
  ],
  exports: [
    MaterialModule,
    CommonModule,
    ControlMessagesComponent
  ]
})
export class SharedModule { }

redpajama_set_name: RedPajamaGithub


text:
#include <aws/s3control/model/S3ManifestOutputLocation.h>
#include <aws/core/utils/xml/XmlSerializer.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/memory/stl/AWSStringStream.h>

#include <utility>

using namespace Aws::Utils::Xml;
using namespace Aws::Utils;

namespace Aws
{
namespace S3Control
{
namespace Model
{

S3ManifestOutputLocation::S3ManifestOutputLocation() :
    m_expectedManifestBucketOwnerHasBeenSet(false),
    m_bucketHasBeenSet(false),
    m_manifestPrefixHasBeenSet(false),
    m_manifestEncryptionHasBeenSet(false),
    m_manifestFormat(GeneratedManifestFormat::NOT_SET),
    m_manifestFormatHasBeenSet(false)
{
}

S3ManifestOutputLocation::S3ManifestOutputLocation(const XmlNode& xmlNode) :
    m_expectedManifestBucketOwnerHasBeenSet(false),
    m_bucketHasBeenSet(false),
    m_manifestPrefixHasBeenSet(false),
    m_manifestEncryptionHasBeenSet(false),
    m_manifestFormat(GeneratedManifestFormat::NOT_SET),
    m_manifestFormatHasBeenSet(false)
{
  *this = xmlNode;
}

S3ManifestOutputLocation& S3ManifestOutputLocation::operator =(const XmlNode& xmlNode)
{
  XmlNode resultNode = xmlNode;

  if(!resultNode.IsNull())
  {
    XmlNode expectedManifestBucketOwnerNode = resultNode.FirstChild("ExpectedManifestBucketOwner");
    if(!expectedManifestBucketOwnerNode.IsNull())
    {
      m_expectedManifestBucketOwner = Aws::Utils::Xml::DecodeEscapedXmlText(expectedManifestBucketOwnerNode.GetText());
      m_expectedManifestBucketOwnerHasBeenSet = true;
    }
    XmlNode bucketNode = resultNode.FirstChild("Bucket");
    if(!bucketNode.IsNull())
    {
      m_bucket = Aws::Utils::Xml::DecodeEscapedXmlText(bucketNode.GetText());
      m_bucketHasBeenSet = true;
    }
    XmlNode manifestPrefixNode = resultNode.FirstChild("ManifestPrefix");
    if(!manifestPrefixNode.IsNull())
    {
      m_manifestPrefix = Aws::Utils::Xml::DecodeEscapedXmlText(manifestPrefixNode.GetText());
      m_manifestPrefixHasBeenSet = true;
    }
    XmlNode manifestEncryptionNode = resultNode.FirstChild("ManifestEncryption");
    if(!manifestEncryptionNode.IsNull())
    {
      m_manifestEncryption = manifestEncryptionNode;
      m_manifestEncryptionHasBeenSet = true;
    }
    XmlNode manifestFormatNode = resultNode.FirstChild("ManifestFormat");
    if(!manifestFormatNode.IsNull())
    {
      m_manifestFormat = GeneratedManifestFormatMapper::GetGeneratedManifestFormatForName(StringUtils::Trim(Aws::Utils::Xml::DecodeEscapedXmlText(manifestFormatNode.GetText()).c_str()).c_str());
      m_manifestFormatHasBeenSet = true;
    }
  }

  return *this;
}

void S3ManifestOutputLocation::AddToNode(XmlNode& parentNode) const
{
  Aws::StringStream ss;
  if(m_expectedManifestBucketOwnerHasBeenSet)
  {
   XmlNode expectedManifestBucketOwnerNode = parentNode.CreateChildElement("ExpectedManifestBucketOwner");
   expectedManifestBucketOwnerNode.SetText(m_expectedManifestBucketOwner);
  }

  if(m_bucketHasBeenSet)
  {
   XmlNode bucketNode = parentNode.CreateChildElement("Bucket");
   bucketNode.SetText(m_bucket);
  }

  if(m_manifestPrefixHasBeenSet)
  {
   XmlNode manifestPrefixNode = parentNode.CreateChildElement("ManifestPrefix");
   manifestPrefixNode.SetText(m_manifestPrefix);
  }

  if(m_manifestEncryptionHasBeenSet)
  {
   XmlNode manifestEncryptionNode = parentNode.CreateChildElement("ManifestEncryption");
   m_manifestEncryption.AddToNode(manifestEncryptionNode);
  }

  if(m_manifestFormatHasBeenSet)
  {
   XmlNode manifestFormatNode = parentNode.CreateChildElement("ManifestFormat");
   manifestFormatNode.SetText(GeneratedManifestFormatMapper::GetNameForGeneratedManifestFormat(m_manifestFormat));
  }

}

} // namespace Model
} // namespace S3Control
} // namespace Aws


text:
package libcore.io;

@com.francetelecom.rd.stubs.annotation.ClassDone(0)
public final class IoUtils
{
  // Constructors

  private IoUtils(){
  }
  // Methods

  public static void close(java.io.FileDescriptor arg1) throws java.io.IOException{
  }
  public static void setBlocking(java.io.FileDescriptor arg1, boolean arg2) throws java.io.IOException{
  }
  public static void closeQuietly(java.lang.AutoCloseable arg1){
  }
  public static void closeQuietly(java.io.FileDescriptor arg1){
  }
  public static void closeQuietly(java.net.Socket arg1){
  }
  public static byte [] readFileAsByteArray(java.lang.String arg1) throws java.io.IOException{
    return (byte []) null;
  }
  public static java.lang.String readFileAsString(java.lang.String arg1) throws java.io.IOException{
    return (java.lang.String) null;
  }
  public static void deleteContents(java.io.File arg1) throws java.io.IOException{
  }
}


text:
;

require "optparse"

##
# # Ruby implementation of rcloadenv
#
# See https://github.com/GoogleCloudPlatform/rcloadenv for more information
# on this tool.
#
module RCLoadEnv
end

require "rcloadenv/cli"
require "rcloadenv/credentials"
require "rcloadenv/loader"
require "rcloadenv/version"


text:
import requests
import logging
from packaging.version import Version
from functools import wraps
from xml.etree.ElementTree import ParseError
from typing import Any, Callable, Dict, Optional, TYPE_CHECKING

from .exceptions import (
    ServerResponseError,
    InternalServerError,
    NonXMLResponseError,
    EndpointUnavailableError,
)
from ..query import QuerySet
from ... import helpers, get_versions

if TYPE_CHECKING:
    from ..server import Server
    from requests import Response

logger = logging.getLogger("tableau.endpoint")

Success_codes = [200, 201, 202, 204]

XML_CONTENT_TYPE = "text/xml"
JSON_CONTENT_TYPE = "application/json"

CONTENT_TYPE_HEADER = "content-type"
TABLEAU_AUTH_HEADER = "x-tableau-auth"
USER_AGENT_HEADER = "User-Agent"

class Endpoint(object):
    def __init__(self, parent_srv: "Server"):
        self.parent_srv = parent_srv

    @staticmethod
    def _make_common_headers(auth_token, content_type):
        _client_version: Optional[str] = get_versions()["version"]
        headers = {}
        if auth_token is not None:
            headers[TABLEAU_AUTH_HEADER] = auth_token
        if content_type is not None:
            headers[CONTENT_TYPE_HEADER] = content_type
        headers[USER_AGENT_HEADER] = "Tableau Server Client/{}".format(_client_version)
        return headers

    def _make_request(
        self,
        method: Callable[..., "Response"],
        url: str,
        content: Optional[bytes] = None,
        auth_token: Optional[str] = None,
        content_type: Optional[str] = None,
        parameters: Optional[Dict[str, Any]] = None,
    ) -> "Response":
        parameters = parameters or {}
        if "headers" not in parameters:
            parameters["headers"] = {}
        parameters.update(self.parent_srv.http_options)
        parameters["headers"].update(Endpoint._make_common_headers(auth_token, content_type))

        if content is not None:
            parameters["data"] = content

        logger.debug("request {}, url: {}".format(method.__name__, url))
        if content:
            logger.debug("request content: {}".format(helpers.strings.redact_xml(content[:1000])))

        server_response = method(url, **parameters)
        self._check_status(server_response, url)

        loggable_response = self.log_response_safely(server_response)
        logger.debug("Server response from {0}:\n\t{1}".format(url, loggable_response))

        if content_type == "application/xml":
            self.parent_srv._namespace.detect(server_response.content)

        return server_response

    def _check_status(self, server_response, url: str = None):
        if server_response.status_code >= 500:
            raise InternalServerError(server_response, url)
        elif server_response.status_code not in Success_codes:
            try:
                raise ServerResponseError.from_response(server_response.content, self.parent_srv.namespace, url)
            except ParseError:
                # This will happen if we get a non-success HTTP code that doesn't return an xml error object
                # e.g metadata endpoints, 503 pages, totally different servers
                # we convert this to a better exception and pass through the raw response body
                raise NonXMLResponseError(server_response.content)
            except Exception:
                # anything else re-raise here
                raise

    def log_response_safely(self, server_response: requests.Response) -> str:
        # Checking the content type header prevents eager evaluation of streaming requests.
        content_type = server_response.headers.get("Content-Type")

        # Response.content is a property. Calling it will load the entire response into memory. Checking if the
        # content-type is an octet-stream accomplishes the same goal without eagerly loading content.
        # This check is to determine if the response is a text response (xml or otherwise)
        # so that we do not attempt to log bytes and other binary data.
        loggable_response = "Content type {}".format(content_type)
        if content_type == "application/octet-stream":
            loggable_response = "A stream of type {} [Truncated File Contents]".format(content_type)
        elif server_response.encoding and len(server_response.content) > 0:
            loggable_response = helpers.strings.redact_xml(server_response.content.decode(server_response.encoding))
        return loggable_response

    def get_unauthenticated_request(self, url):
        return self._make_request(self.parent_srv.session.get, url)

    def get_request(self, url, request_object=None, parameters=None):
        if request_object is not None:
            try:
                # Query param delimiters don't need to be encoded for versions before 3.7 (2020.1)
                self.parent_srv.assert_at_least_version("3.7", "Query param encoding")
                parameters = parameters or {}
                parameters["params"] = request_object.get_query_params()
            except EndpointUnavailableError:
                url = request_object.apply_query_params(url)

        return self._make_request(
            self.parent_srv.session.get,
            url,
            auth_token=self.parent_srv.auth_token,
            parameters=parameters,
        )

    def delete_request(self, url):
        # We don't return anything for a delete request
        self._make_request(self.parent_srv.session.delete, url, auth_token=self.parent_srv.auth_token)

    def put_request(self, url, xml_request=None, content_type=XML_CONTENT_TYPE, parameters=None):
        return self._make_request(
            self.parent_srv.session.put,
            url,
            content=xml_request,
            auth_token=self.parent_srv.auth_token,
            content_type=content_type,
            parameters=parameters,
        )

    def post_request(self, url, xml_request, content_type=XML_CONTENT_TYPE, parameters=None):
        return self._make_request(
            self.parent_srv.session.post,
            url,
            content=xml_request,
            auth_token=self.parent_srv.auth_token,
            content_type=content_type,
            parameters=parameters,
        )

    def patch_request(self, url, xml_request, content_type=XML_CONTENT_TYPE, parameters=None):
        return self._make_request(
            self.parent_srv.session.patch,
            url,
            content=xml_request,
            auth_token=self.parent_srv.auth_token,
            content_type=content_type,
            parameters=parameters,
        )

def api(version):
    """Annotate the minimum supported version for an endpoint.

    Checks the version on the server object and compares normalized versions.
    It will raise an exception if the server version is > the version specified.

    Args:
        `version` minimum version that supports the endpoint. String.
    Raises:
        EndpointUnavailableError
    Returns:
        None

    Example:
    >>> @api(version="2.3")
    >>> def get(self, req_options=None):
    >>>     ...
    """

    def _decorator(func):
        @wraps(func)
        def wrapper(self, *args, **kwargs):
            self.parent_srv.assert_at_least_version(version, self.__class__.__name__)
            return func(self, *args, **kwargs)

        return wrapper

    return _decorator

def parameter_added_in(**params):
    """Annotate minimum versions for new parameters or request options on an endpoint.

    The api decorator documents when an endpoint was added, this decorator annotates
    keyword arguments on endpoints that may control functionality added after an endpoint was introduced.

    The REST API will ignore invalid parameters in most cases, so this raises a warning instead of throwing
    an exception.

    Args:
        Key/value pairs of the form `parameter`=`version`. Kwargs.
    Raises:
        UserWarning
    Returns:
        None

    Example:
    >>> @api(version="2.0")
    >>> @parameter_added_in(no_extract='2.5')
    >>> def download(self, workbook_id, filepath=None, extract_only=False):
    >>>     ...
    """

    def _decorator(func):
        @wraps(func)
        def wrapper(self, *args, **kwargs):
            import warnings

            server_ver = Version(self.parent_srv.version or "0.0")
            params_to_check = set(params) & set(kwargs)
            for p in params_to_check:
                min_ver = Version(str(params[p]))
                if server_ver < min_ver:
                    error = "{!r} not available in {}, it will be ignored. Added in {}".format(p, server_ver, min_ver)
                    warnings.warn(error)
            return func(self, *args, **kwargs)

        return wrapper

    return _decorator

class QuerysetEndpoint(Endpoint):
    @api(version="2.0")
    def all(self, *args, **kwargs):
        queryset = QuerySet(self)
        return queryset

    @api(version="2.0")
    def filter(self, *_, **kwargs):
        if _:
            raise RuntimeError("Only keyword arguments accepted.")
        queryset = QuerySet(self).filter(**kwargs)
        return queryset

    @api(version="2.0")
    def order_by(self, *args, **kwargs):
        queryset = QuerySet(self).order_by(*args)
        return queryset

    @api(version="2.0")
    def paginate(self, **kwargs):
        queryset = QuerySet(self).paginate(**kwargs)
        return queryset


text:
package org.apache.spark.sql.catalyst.optimizer

import org.apache.spark.api.python.PythonEvalType
import org.apache.spark.sql.catalyst.dsl.expressions._
import org.apache.spark.sql.catalyst.dsl.plans._
import org.apache.spark.sql.catalyst.expressions.{Expression, PythonUDF}
import org.apache.spark.sql.catalyst.plans.PlanTest
import org.apache.spark.sql.catalyst.plans.logical.{LocalRelation, LogicalPlan}
import org.apache.spark.sql.catalyst.rules.RuleExecutor
import org.apache.spark.sql.types.IntegerType

class RemoveRedundantAggregatesSuite extends PlanTest {

  object Optimize extends RuleExecutor[LogicalPlan] {
    val batches = Batch("RemoveRedundantAggregates", FixedPoint(10),
      RemoveRedundantAggregates) :: Nil
  }

  private def aggregates(e: Expression): Seq[Expression] = {
    Seq(
      count(e),
      PythonUDF("pyUDF", null, IntegerType, Seq(e),
        PythonEvalType.SQL_GROUPED_AGG_PANDAS_UDF, udfDeterministic = true)
    )
  }

  test("Remove redundant aggregate") {
    val relation = LocalRelation('a.int, 'b.int)
    for (agg <- aggregates('b)) {
      val query = relation
        .groupBy('a)('a, agg)
        .groupBy('a)('a)
        .analyze
      val expected = relation
        .groupBy('a)('a)
        .analyze
      val optimized = Optimize.execute(query)
      comparePlans(optimized, expected)
    }
  }

  test("Remove 2 redundant aggregates") {
    val relation = LocalRelation('a.int, 'b.int)
    for (agg <- aggregates('b)) {
      val query = relation
        .groupBy('a)('a, agg)
        .groupBy('a)('a)
        .groupBy('a)('a)
        .analyze
      val expected = relation
        .groupBy('a)('a)
        .analyze
      val optimized = Optimize.execute(query)
      comparePlans(optimized, expected)
    }
  }

  test("Remove redundant aggregate with different grouping") {
    val relation = LocalRelation('a.int, 'b.int)
    val query = relation
      .groupBy('a, 'b)('a)
      .groupBy('a)('a)
      .analyze
    val expected = relation
      .groupBy('a)('a)
      .analyze
    val optimized = Optimize.execute(query)
    comparePlans(optimized, expected)
  }

  test("Remove redundant aggregate with aliases") {
    val relation = LocalRelation('a.int, 'b.int)
    for (agg <- aggregates('b)) {
      val query = relation
        .groupBy('a + 'b)(('a + 'b) as 'c, agg)
        .groupBy('c)('c)
        .analyze
      val expected = relation
        .groupBy('a + 'b)(('a + 'b) as 'c)
        .analyze
      val optimized = Optimize.execute(query)
      comparePlans(optimized, EnforceGroupingReferencesInAggregates(expected))
    }
  }

  test("Remove redundant aggregate with non-deterministic upper") {
    val relation = LocalRelation('a.int, 'b.int)
    val query = relation
      .groupBy('a)('a)
      .groupBy('a)('a, rand(0) as 'c)
      .analyze
    val expected = relation
      .groupBy('a)('a, rand(0) as 'c)
      .analyze
    val optimized = Optimize.execute(query)
    comparePlans(optimized, expected)
  }

  test("Remove redundant aggregate with non-deterministic lower") {
    val relation = LocalRelation('a.int, 'b.int)
    val query = relation
      .groupBy('a, 'c)('a, rand(0) as 'c)
      .groupBy('a, 'c)('a, 'c)
      .analyze
    val expected = relation
      .groupBy('a, 'c)('a, rand(0) as 'c)
      .analyze
    val optimized = Optimize.execute(query)
    comparePlans(optimized, expected)
  }

  test("Keep non-redundant aggregate - upper has agg expression") {
    val relation = LocalRelation('a.int, 'b.int)
    for (agg <- aggregates('b)) {
      val query = relation
        .groupBy('a, 'b)('a, 'b)
        // The count would change if we remove the first aggregate
        .groupBy('a)('a, agg)
        .analyze
      val optimized = Optimize.execute(query)
      comparePlans(optimized, query)
    }
  }

  test("Keep non-redundant aggregate - upper references agg expression") {
    val relation = LocalRelation('a.int, 'b.int)
    for (agg <- aggregates('b)) {
      val query = relation
        .groupBy('a)('a, agg as 'c)
        .groupBy('c)('c)
        .analyze
      val optimized = Optimize.execute(query)
      comparePlans(optimized, query)
    }
  }

  test("Keep non-redundant aggregate - upper references non-deterministic non-grouping") {
    val relation = LocalRelation('a.int, 'b.int)
    val query = relation
      .groupBy('a)('a, ('a + rand(0)) as 'c)
      .groupBy('a, 'c)('a, 'c)
      .analyze
    val optimized = Optimize.execute(query)
    comparePlans(optimized, query)
  }
}


text:
if [ ! -f /etc/haproxy/haproxy.cfg ]; then
	#Install haproxy
	/usr/bin/sudo apt-get -y install haproxy
	#Configure haproxy
	#This enables haproxy to start upon init
	cat > /etc/default/haproxy <<EOD
# Set ENABLED to 1 if you want the init script to start haproxy.
ENABLED=1
# Add extra flags here.
#EXTRAOPTS="-de -m 16"
EOD
	#This configures the loadbalancer in the .cfg file
	cat > /etc/haproxy/haproxy.cfg <<EOD
global
	daemon
	maxconn 256

defaults
	mode http
	timeout connect 5000ms
	timeout client 50000ms
	timeout server 50000ms

#Here we will want to add as many load balancers as there are teams/projects (7)
frontend http
	bind *:80
	default_backend webservers

backend webservers
	balance roundrobin
	option httpchk
	option forwardfor
	option http-server-close
	#insert a cookie if not found, else, redirect user to webserver
	cookie SERVERID insert indirect nocache
	server webserver1 172.16.0.2:80 maxconn 32 check cookie webserver1
	server webserver2 172.16.0.3:80 maxconn 32 check cookie webserver2

#Here you implement HAProxy Admin
listen admin
	bind *:8080
	stats enable
EOD
	#Copy file for record keeping
	cp /etc/haproxy/haproxy.cfg /etc/haproxy/haproxy.cfg.orig
	/usr/sbin/service haproxy restart
fi


text:
package org.spongepowered.despector.transform.matcher.instruction;

import org.spongepowered.despector.ast.insn.Instruction;
import org.spongepowered.despector.ast.insn.var.ArrayAccess;
import org.spongepowered.despector.transform.matcher.InstructionMatcher;
import org.spongepowered.despector.transform.matcher.MatchContext;

/**
 * A matcher for {@link ArrayAccess} instructions.
 */
public class ArrayAccessMatcher implements InstructionMatcher<ArrayAccess> {

    private InstructionMatcher<?> array;
    private InstructionMatcher<?> index;

    ArrayAccessMatcher(InstructionMatcher<?> array, InstructionMatcher<?> index) {
        this.array = array == null ? InstructionMatcher.ANY : array;
        this.index = index == null ? InstructionMatcher.ANY : index;
    }

    @Override
    public ArrayAccess match(MatchContext ctx, Instruction insn) {
        if (!(insn instanceof ArrayAccess)) {
            return null;
        }
        ArrayAccess invoke = (ArrayAccess) insn;
        if (!this.array.matches(ctx, invoke.getArrayVar())) {
            return null;
        }
        if (!this.index.matches(ctx, invoke.getIndex())) {
            return null;
        }
        return invoke;
    }

    /**
     * A matcher builder.
     */
    public static class Builder {

        private InstructionMatcher<?> array;
        private InstructionMatcher<?> index;

        public Builder() {
            reset();
        }

        /**
         * Sets the matcher for the array value.
         */
        public Builder array(InstructionMatcher<?> val) {
            this.array = val;
            return this;
        }

        /**
         * Sets the matcher for the array index.
         */
        public Builder index(InstructionMatcher<?> index) {
            this.index = index;
            return this;
        }

        /**
         * Resets the builder.
         */
        public Builder reset() {
            this.array = null;
            this.index = null;
            return this;
        }

        /**
         * Creates a new matcher.
         */
        public ArrayAccessMatcher build() {
            return new ArrayAccessMatcher(this.array, this.index);
        }

    }

}


text:
#wpwrap {
    background: #F0F1F2 url(../images/texture.png) repeat
}

#adminmenuback {
    z-index: 0
}

#domainmapping-content * {
    font-family: "Lato", Helvetica Neue, Helvetica, sans-serif;
    -webkit-font-smoothing: antialiased !important
}

.domainmapping-clear {
    clear: both
}

.domainmapping-tab-switch {
    border-bottom: 1px solid #ccc
}

.domainmapping-tab-switch ul {
    margin: 20px 0;
    padding: 0 0 0 10px;
    list-style: none;
    clear: both
}

.domainmapping-tab-switch li {
    float: left;
    margin: 0;
    padding: 0;
    list-style: none
}

.domainmapping-tab-switch a {
    display: block;
    background-color: #f1f2f3;
    margin: 0 6px -1px 0;
    padding: 14px 30px 15px;
    font-size: 16px;
    line-height: 16px;
    color: #aaa;
    text-decoration: none;
    outline: none;
    border: 1px solid #ccc
}

.domainmapping-tab-switch a:hover {
    color: #01b1f3;
    text-decoration: none;
    outline: none
}

.domainmapping-tab-switch a.active {
    color: #464646;
    border-bottom: 1px solid #f9f9fa;
    background-color: rgba(0, 0, 0, 0)
}

.domainmapping-tab {
    margin-top: 10px;
    font-size: 14px;
    line-height: 21px;
    max-width: 1400px
}

.domainmapping-info {
	border: 1px solid #c0f0f0;
    border-left: 3px solid #01b1f3;
    border-left-color: rgba(1, 177, 243, 0.7);
    background-color: #cff;
    background-color: rgba(204, 255, 255, 0.4);
    color: #444;
    padding: 1em 1.5em;
    margin: 1em 0;
	-moz-box-shadow: 0 0 3px #ddd;
    -webkit-box-shadow: 0 0 3px #ddd;
    box-shadow: 0 0 3px #ddd;
}

.domainmapping-info-error {
	border-color: #f0b0b0;
    border-left-color: #f33;
    background-color: #fbb
}

.domainmapping-info-success {
	border-color: #c0f0c0;
    border-left-color: #093;
    background-color: #cfc
}

.domainmapping-info-warning {
	border-color: #f0f0c0;
    border-left-color: #cc0;
    background-color: #ffc
}

.domainmapping-info code {
	font-family: monospace !important;
	font-size: 12px;
	padding: 2px 5px;
}

.domainmapping-info > * {
	margin-top: 0;
}

.domainmapping-info > *:last-child {
	margin-bottom: 0;
}

#reseller-options-tab .domainmapping-info > ul {
	list-style: circle;
	padding-left: 20px;
}

#reseller-options-tab .domainmapping-info > ul li {
	list-style: disc;
}

#domainmapping-content .updated {
    padding: 10px 15px;
    margin: 1em 0;
    font-size: 14px
}

.domainmapping-box {
    border: 3px solid #00487f;
    border-top-width: 0;
    background-color: white;
    margin-bottom: 20px
}

.domainmapping-box h3 {
    padding: 5px 10px 7px;
    margin: 0;
    background-color: #00487f;
    color: white
}

.domainmapping-origin {
    color: #01b1f3;
    font-weight: bold
}

.domainmapping-box-content {
    padding: 10px 20px
}

.domainmapping-box-content p {
    margin-top: 0
}

.domainmapping-box .domainmapping-domains-list {
    margin: 0;
    padding: 0;
    list-style: none
}

.domainmapping-domains-list li {
    list-style: none;
    text-align: center;
    padding: 8px 0 10px;
    margin: 0;
    border-bottom: 1px dashed #dfdfdf;
    position: relative
}

.domainmapping-mapped,
.domainmapping-map-primary,
.domainmapping-map-remove {
    position: absolute;
    top: 12px
}

.domainmapping-mapped {
    left: 0
}

.domainmapping-map-state, .domainmapping-map-state:hover {
    color: black
}

.domainmapping-map-primary {
	right: 26px;
}

.domainmapping-map-remove {
    right: 0;
    color: red
}

.domainmapping-mapped,
.domainmapping-map-state,
.domainmapping-map-primary,
.domainmapping-map-remove {
    text-decoration: none
}

.domainmapping-box .domainmapping-domains-list li > span {
    color: #464646;
    font-weight: bold
}

.domainmapping-box .domainmapping-form {
    text-align: left;
    border-bottom-width: 0;
    margin-top: 10px
}

.domainmapping-form input[type="text"],
.domainmapping-form input[type="email"] {
    padding: 5px 10px;
    width: 200px;
    float: left;
    margin: 0
}

.domainmapping-form input.domainmapping-input-domain {
    border: 0;
    -moz-border-radius: 0;
    -webkit-border-radius: 0;
    border-radius: 0
}

.domainmapping-form input.domainmapping-input-sufix,
.domainmapping-form input.domainmapping-input-prefix {
	border: 1px solid #dfdfdf;
}

.domainmapping-form input.domainmapping-input-domain:active,
.domainmapping-form input.domainmapping-input-domain:focus {
    border-color: #dfdfdf;
    -moz-box-shadow: none;
    -webkit-box-shadow: none;
    box-shadow: none
}

.domainmapping-form input.domainmapping-input-sufix {
    width: 30px;
    margin-right: 10px;
    border-left-width: 0;
    -webkit-border-top-left-radius: 0;
    -moz-border-radius-topleft: 0;
    border-top-left-radius: 0;
    -moz-border-radius-topleft: 0;
    -webkit-border-bottom-left-radius: 0;
    -moz-border-radius-bottomleft: 0;
    border-bottom-left-radius: 0;
    -moz-border-radius-bottomleft: 0
}

.domainmapping-form input.domainmapping-input-sufix.domainmapping-input-empty {
    padding: 5px 0;
    width: 2px;
}

.domainmapping-form input.domainmapping-input-prefix {
    width: 60px;
    border-right-width: 0;
    padding-right: 0;
    margin-right: 0;
    -webkit-border-top-right-radius: 0;
    -moz-border-radius-topright: 0;
    border-top-right-radius: 0;
    -moz-border-radius-topright: 0;
    -webkit-border-bottom-right-radius: 0;
    -moz-border-radius-bottomright: 0;
    border-bottom-right-radius: 0;
    -moz-border-radius-bottomright: 0
}

.domainmapping-form input.domainmapping-input-sufix,
.domainmapping-form input.domainmapping-input-prefix {
    background-color: #f1f1f1
}

.domainmapping-form select.domainmapping-select-domain {
    float: left;
    background-color: white;
    -moz-border-radius: 0;
    -webkit-border-radius: 0;
    border-radius: 0;
    height: 27px;
    padding: 4px 0;
    margin: 0;
    -moz-box-shadow: none;
    -webkit-box-shadow: none;
    box-shadow: none;
    border: 0;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
}

.domainmapping-controls-wrapper {
    border-top: 1px solid #dfdfdf;
    border-bottom: 1px solid #dfdfdf;
    float: left
}

.domainmapping-form-submit {
    padding: 5px 20px;
    margin: 0;
    font-size: 14px;
    text-transform: uppercase;
    outline: none;
    -moz-border-radius: 3px;
    -webkit-border-radius: 3px;
    border-radius: 3px;
    -webkit-background-clip: padding;
    background-clip: padding;
    -webkit-background-clip: padding-box;
    background-clip: padding-box;
    -moz-box-shadow: 0 1px 0 #001c33, inset 0 1px 0 #004f8c;
    -webkit-box-shadow: 0 1px 0 #001c33, inset 0 1px 0 #004f8c;
    box-shadow: 0 1px 0 #001c33, inset 0 1px 0 #004f8c;
    background-image: -moz-linear-gradient(bottom, #003866 0%, #00487f 100%);
    background-image: -o-linear-gradient(bottom, #003866 0%, #00487f 100%);
    background-image: -webkit-linear-gradient(bottom, #003866 0%, #00487f 100%);
    background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0, #003866 0%), color-stop(1, #00487f 100%));
    filter: "progid:DXImageTransform.Microsoft.gradient(startColorStr=#003866 0%, EndColorStr=#00487f 100%)";
    background-image: linear-gradient(bottom, #003866 0%, #00487f 100%);
    color: #e2ecf4;
    text-shadow: 0 -1px 0 #002a4c;
    border: none;
    cursor: pointer
}

.domainmapping-form-submit:active {
    background-image: -moz-linear-gradient(bottom, #00487f 0%, #003866 100%);
    background-image: -o-linear-gradient(bottom, #00487f 0%, #003866 100%);
    background-image: -webkit-linear-gradient(bottom, #00487f 0%, #003866 100%);
    background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0, #00487f 0%), color-stop(1, #003866 100%));
    filter: "progid:DXImageTransform.Microsoft.gradient(startColorStr=#00487f 0%, EndColorStr=#003866 100%)";
    background-image: linear-gradient(bottom, #00487f 0%, #003866 100%);
}

.wp-core-ui .domainmapping-button i,
.domainmapping-form-submit i {
    margin-right: 3px;
	margin-top: 2px;
}

.domainmapping-invalid-domain,
.domainmapping-need-revalidate {
    color: red
}

.domainmapping-valid-domain {
    color: green
}

.domainmapping-wait-status-refresh {
    background-image: url(../images/ajax-loader-small.gif);
    background-position: center center;
    background-repeat: no-repeat;
    height: 21px
}

.domainmapping-domains-wrapper {
    position: relative
}

.domainmapping-locker {
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    top: 0;
    z-index: 9999;
    background-color: rgba(255, 255, 255, 0.85);
    background-image: url(../images/ajax-loader-big.gif);
    background-position: center center;
    background-repeat: no-repeat;
    display: none
}

.domainmapping-domains-wrapper-locked .domainmapping-locker {
    display: block
}

.domainmapping-form-hidden .domainmapping-form {
    display: none
}

.domainmapping-form-hidden li:nth-last-child(2) {
    border-bottom-width: 0
}

.domainmapping-label {
    width: 200px;
    display: inline-block;
	margin-top: -4px;
}

.domainmapping-descr {
	display: block;
	margin-left: 205px;
	width: 600px;
	font-size: 85%;
	font-style: italic;
	color: gray;
}

.domainmapping-resellers-switch {
    margin: 0;
    padding: 0;
    list-style: none
}

#reseller-options-tab ul li {
    margin: 0;
    padding: 0;
    list-style: none
}

input.domainmapping-radio {
    margin-top: 3px;
    margin-right: 5px
}

.domainmapping-reseller-settings {
    display: none;
    margin-top: 40px;
}

.domainmapping-reseller-settings.active {
    display: block
}

.domainmapping-reseller-settings .domainmapping-label {
	width: 100px;
}

#domainmapping-enom-header {
    background-color: #113D83;
    background-image: linear-gradient(left, #113D83 0, #305AA3 50%, #113D83 100%);
    background-image: -o-linear-gradient(left, #113D83 0, #305AA3 50%, #113D83 100%);
    background-image: -moz-linear-gradient(left, #113D83 0, #305AA3 50%, #113D83 100%);
    background-image: -webkit-linear-gradient(left, #113D83 0, #305AA3 50%, #113D83 100%);
    background-image: -ms-linear-gradient(left, #113D83 0, #305AA3 50%, #113D83 100%);
    background-image: -webkit-gradient(linear, left bottom, right bottom, color-stop(0, #113D83), color-stop(0.5, #305AA3), color-stop(1, #113D83))
}

#domainmapping-enom-logo {
    height: 60px;
    background-image: url(../images/enom.png);
    background-repeat: no-repeat;
    background-position: 15px 15px
}

#domainmapping-check-domain-form,
#domainmapping-iframe-form {
    margin-bottom: 10px;
}

#domainmapping-iframe-form h4 {
    margin-top: 40px;
    padding-bottom: 5px;
    border-bottom: 1px dashed #ccc;
    font-size: 16px;
}

#domainmapping-iframe-form h4:first-child {
    margin-top: 0;
}

#domainmapping-iframe-form h4 i {
    margin-right: 5px;
	margin-top: 3px;
}

#domainmapping-iframe-form input[type="text"],
#domainmapping-iframe-form input[type="password"],
#domainmapping-iframe-form input[type="email"],
#domainmapping-iframe-form select {
    float: none;
    width: 500px;
}

.domainmapping-field-required {
    color: red;
    font-weight: bold;
}

#domainmapping-ppp-overlay {
    display: none;
    position: fixed;
    z-index: 9998;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: black;
    -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=40)";
    filter: alpha(opacity=40);
    opacity: 0.4;
    -webkit-touch-callout: none;
    -moz-user-select: none;
    -webkit-user-select: none;
    user-select: none;
    -khtml-user-select: none;
    -moz-user-select: -moz-none;
    -webkit-user-select: -moz-none;
    user-select: -moz-none
}

#domainmapping-ppp {
    display: none;
    position: fixed;
    left: 50%;
    top: 45%;
    z-index: 9999;
    background-color: white;
    -moz-border-radius: 4px;
    -webkit-border-radius: 4px;
    border-radius: 4px;
    border: 5px solid black;
    -moz-box-shadow: 0 0 10px black;
    -webkit-box-shadow: 0 0 10px black;
    box-shadow: 0 0 10px black;
    font-size: 14px;
    line-height: 21px;
    text-align: center;
    font-family: "Lato", Helvetica Neue, Helvetica, sans-serif;
    -webkit-font-smoothing: antialiased !important;
    -webkit-touch-callout: none;
    -moz-user-select: none;
    -webkit-user-select: none;
    user-select: none;
    -khtml-user-select: none;
    -moz-user-select: -moz-none;
    -webkit-user-select: -moz-none;
    user-select: -moz-none
}

#domainmapping-ppp.domainmapping-ppp-error {
    border-color: #f55
}

#domainmapping-ppp.domainmapping-ppp-success {
    border-color: #6c6
}

#domainmapping-ppp-body {
    padding: 30px 20px;
    min-width: 400px;
    max-width: 700px;
    font-size: 16px;
    line-height: 24px
}

#domainmapping-ppp-body small {
    font-size: 13px;
    line-height: 19px;
    color: #222;
}

#domainmapping-ppp-footer {
    padding: 10px 20px
}

.domainmapping-ppp-success #domainmapping-ppp-footer {
    background-color: #dfd
}

.domainmapping-ppp-error #domainmapping-ppp-footer {
    background-color: #fdd
}

.wp-core-ui #domainmapping-content .button {
    padding-top: 1px;
    padding-bottom: 2px;
    height: auto;
    font-size: 14px;
}

.domainmapping-request-valid,
.domainmapping-request-invalid {
    color: white;
    padding: 1px 6px 2px;
    -moz-border-radius: 4px;
    -webkit-border-radius: 4px;
    border-radius: 4px;
    font-weight: bold
}

.domainmapping-request-invalid {
    background-color: #DB4A4A
}

.domainmapping-request-valid {
    background-color: #56A356
}

#domainmapping-content .widefat td {
    font-size: 13px;
    line-height: 20px
}

#domainmapping-content .widefat thead tr th,
#domainmapping-content .widefat tfoot tr th {
    font-weight: bold
}

#domainmapping-content .tablenav .displaying-num {
    font-size: 13px
}

#domainmapping-content .tablenav .tablenav-pages {
    font-size: 13px
}

#domainmapping-reseller-log-table .tablenav.top {
    margin-bottom: 10px
}

#domainmapping-reseller-log-table .column-requested_at span {
    color: #aaa;
    display: block
}

#domainmapping-reseller-log-table .column-valid,
#domainmapping-reseller-log-table .column-action,
#domainmapping-reseller-log-table .column-requested_at {
    width: 200px
}

#domainmapping-content .subsubsub {
    font-size: 14px;
    line-height: 21px
}

.domainmapping-log-item-invalid {
    background-color: #fee;
}

.domainmapping-log-item-valid {
    background-color: #efe;
}

.domainmapping-purchase-paypal-link {
    margin-top: 5px;
    height: 26px;
    display: block;
    float: left;
}

.domainmapping-compressed-list {
    margin: 0;
}

.domainmapping-compressed-list > li {
    margin: 0;
    padding: 0;
}

.domainmapping-block-header {
    border-bottom: 1px dashed #ddd;
    margin: 40px 0 10px;
    padding-bottom: 10px;
}

.domainmapping-transparent-button {
    background-color: transparent;
    border: none;
    margin: 0;
    padding: 0;
    cursor: pointer;
}

.domainmapping-paypal-form {
    margin-top: 5px;
}

.domainmapping-iframe {
    width: 60%;
    margin: 0 auto;
    padding: 30px 0;
}

#domainmapping-iframe-content {
    -moz-box-shadow: 0 0 7px #999;
    -webkit-box-shadow: 0 0 7px #999;
    box-shadow: 0 0 7px #999;
}

.domainmapping-push-right {
    float: right;
}

.domainmapping-push-left {
    float: left;
}

.domainmapping-form-buttons {
    margin-top: 50px;
}

#domainmapping-front-mapping {
	float: right;
}

#domainmapping-front-mapping > span {
	float: left;
	display: block;
	padding-top: 4px;
	margin-right: 5px;
}

/* 162552-1396019580 */


text:
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO

RAISERROR('Create procedure: [dbo].[usp_hcCollectDatabaseDetails]', 10, 1) WITH NOWAIT
GO
IF  EXISTS (
	    SELECT *
	      FROM sys.objects
	     WHERE object_id = OBJECT_ID(N'[dbo].[usp_hcCollectDatabaseDetails]')
	       AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[usp_hcCollectDatabaseDetails]
GO

CREATE PROCEDURE [dbo].[usp_hcCollectDatabaseDetails]
		@projectCode			[varchar](32)=NULL,
		@sqlServerNameFilter	[sysname]='%',
		@databaseNameFilter		[sysname]='%',
		@debugMode				[bit]=0
/* WITH ENCRYPTION */
AS

-- ============================================================================
-- Copyright (c) 2004-2015 Dan Andrei STEFAN (danandrei.stefan@gmail.com)
-- ============================================================================
-- Author			 : Dan Andrei STEFAN
-- Create date		 : 30.12.2014
-- Module			 : Database Analysis & Performance Monitoring
-- ============================================================================

SET NOCOUNT ON

------------------------------------------------------------------------------------------------------------------------------------------
DECLARE @projectID				[smallint],
		@sqlServerName			[sysname],
		@instanceID				[smallint],
		@catalogDatabaseID		[int],
		@databaseID				[int],
		@databaseName			[sysname],
		@queryToRun				[nvarchar](4000),
		@strMessage				[nvarchar](4000)

DECLARE @serverVersionNum		[numeric](9,6),
		@sqlServerVersion		[sysname],
		@dbccLastKnownGood		[datetime],
		@isAzureSQLDatabase		[bit]

/*-------------------------------------------------------------------------------------------------------------------------------*/
IF object_id('#databaseSpaceInfo') IS NOT NULL DROP TABLE #databaseSpaceInfo
CREATE TABLE #databaseSpaceInfo
(
	[volume_mount_point]	[nvarchar](512)		NULL,
	[is_log_file]			[bit]				NULL,
	[size_mb]				[numeric](20,3)		NULL,
	[space_used_mb]			[numeric](20,3)		NULL,
	[is_growth_limited]		[bit]				NULL
)

/*-------------------------------------------------------------------------------------------------------------------------------*/
IF object_id('#dbccDBINFO') IS NOT NULL DROP TABLE #dbccDBINFO
CREATE TABLE #dbccDBINFO
	(
		[id]				[int] IDENTITY(1,1),
		[ParentObject]		[varchar](255),
		[Object]			[varchar](255),
		[Field]				[varchar](255),
		[Value]				[varchar](255)
	)

/*-------------------------------------------------------------------------------------------------------------------------------*/
IF object_id('#dbccLastKnownGood') IS NOT NULL DROP TABLE #dbccLastKnownGood
CREATE TABLE #dbccLastKnownGood
(
	[Value]					[sysname]			NULL
)

/*-------------------------------------------------------------------------------------------------------------------------------*/
IF object_id('#statsDatabaseDetails') IS NOT NULL DROP TABLE #statsDatabaseDetails
CREATE TABLE #statsDatabaseDetails
(
	[database_id]				[int]			NOT NULL,
	[query_type]				[tinyint]		NOT NULL,
	[data_size_mb]				[numeric](20,3)	NULL,
	[data_space_used_percent]	[numeric](6,2)	NULL,
	[log_size_mb]				[numeric](20,3)	NULL,
	[log_space_used_percent]	[numeric](6,2)	NULL,
	[is_auto_close]				[bit]			NULL,
	[is_auto_shrink]			[bit]			NULL,
	[volume_mount_point]		[nvarchar](512)	NULL,
	[last_backup_time]			[datetime]		NULL,
	[last_dbcc checkdb_time]	[datetime]		NULL,
	[recovery_model]			[tinyint]		NULL,
	[page_verify_option]		[tinyint]		NULL,
	[compatibility_level]		[tinyint]		NULL,
	[is_growth_limited]			[bit]			NULL,
	[is_snapshot]				[bit]			NULL
)

/*-------------------------------------------------------------------------------------------------------------------------------*/
IF object_id('#statsDatabaseAlwaysOnDetails') IS NOT NULL DROP TABLE #statsDatabaseAlwaysOnDetails
CREATE TABLE #statsDatabaseAlwaysOnDetails
(
	[cluster_name]					[sysname]		NOT NULL,
	[ag_name]						[sysname]		NOT NULL,
	[host_name]						[sysname]		NOT NULL,
	[instance_name]					[sysname]		NOT NULL,
	[database_name]					[sysname]		NOT NULL,
	[role_desc]						[nvarchar](60)	NULL,
	[replica_join_state_desc]		[nvarchar](60)	NULL,
	[replica_connected_state_desc]	[nvarchar](60)	NULL,
	[failover_mode_desc]			[nvarchar](60)	NULL,
	[availability_mode_desc]		[nvarchar](60)	NULL,
	[synchronization_health_desc]	[nvarchar](60)	NULL,
	[synchronization_state_desc]	[nvarchar](60)	NULL,
	[suspend_reason_desc]			[nvarchar](60)	NULL,
	[readable_secondary_replica]	[nvarchar](60)	NULL
)

/*-------------------------------------------------------------------------------------------------------------------------------*/
IF object_id('#msdbBackupHistory') IS NOT NULL DROP TABLE #msdbBackupHistory
CREATE TABLE #msdbBackupHistory
(
	[database_name]			[sysname]		NOT NULL,
	[backup_type]			[nvarchar](60)	NULL,
	[backup_start_date]		[datetime]		NULL,
	[duration_sec]			[int]			NULL,
	[size_bytes]			[bigint]		NULL,
	[file_name]				[nvarchar](256)	NULL
)

------------------------------------------------------------------------------------------------------------------------------------------
--get default projectCode
IF @projectCode IS NULL
	SET @projectCode = [dbo].[ufn_getProjectCode](NULL, NULL)

SELECT @projectID = [id]
FROM [dbo].[catalogProjects]
WHERE [code] = @projectCode

IF @projectID IS NULL
	begin
		SET @strMessage=N'The value specifief for Project Code is not valid.'
		EXEC [dbo].[usp_logPrintMessage] @customMessage = @strMessage, @raiseErrorAsPrint = 1, @messagRootLevel = 0, @messageTreelevel = 1, @stopExecution=1
	end

-----------------------------------------------------------------------------------------------------
DECLARE @reportOptionGetBackupSizeLastDays [int]
BEGIN TRY
	SELECT	@reportOptionGetBackupSizeLastDays = [value]
	FROM	[report].[htmlOptions]
	WHERE	[name] = N'Analyze backup size (GB) in the last days'
			AND [module] = 'health-check'
END TRY
BEGIN CATCH
	SET @reportOptionGetBackupSizeLastDays = 7
END CATCH
SET @reportOptionGetBackupSizeLastDays = ISNULL(@reportOptionGetBackupSizeLastDays, 7)

DECLARE   @startEvent		[datetime]

SET @startEvent = DATEADD(day, -@reportOptionGetBackupSizeLastDays, GETUTCDATE())
SET @startEvent = CONVERT([datetime], CONVERT([varchar](10), @startEvent, 120), 120);

------------------------------------------------------------------------------------------------------------------------------------------
--A. get databases informations
-------------------------------------------------------------------------------------------------------------------------
SET @strMessage = 'Step 1: Delete existing information....'
EXEC [dbo].[usp_logPrintMessage] @customMessage = @strMessage, @raiseErrorAsPrint = 1, @messagRootLevel = 0, @messageTreelevel = 1, @stopExecution=0

INSERT	INTO [health-check].[statsDatabaseUsageHistory]([catalog_database_id], [instance_id],
									  				 [data_size_mb], [data_space_used_percent], [log_size_mb], [log_space_used_percent],
													 [volume_mount_point], [event_date_utc])
		SELECT	shcdd.[catalog_database_id], shcdd.[instance_id],
				shcdd.[data_size_mb], shcdd.[data_space_used_percent], shcdd.[log_size_mb], shcdd.[log_space_used_percent],
				shcdd.[volume_mount_point], shcdd.[event_date_utc]
		FROM [health-check].[statsDatabaseDetails]		shcdd
		INNER JOIN [dbo].[catalogDatabaseNames]			cdb ON cdb.[id] = shcdd.[catalog_database_id] AND cdb.[instance_id] = shcdd.[instance_id]
		INNER JOIN [dbo].[catalogInstanceNames]			cin ON cin.[id] = cdb.[instance_id] AND cin.[project_id] = cdb.[project_id]
		WHERE cin.[project_id] = @projectID
				AND cin.[name] LIKE @sqlServerNameFilter
				AND cdb.[name] LIKE @databaseNameFilter

DELETE shcdd
FROM [health-check].[statsDatabaseDetails]		shcdd
INNER JOIN [dbo].[catalogDatabaseNames]			cdb ON cdb.[id] = shcdd.[catalog_database_id] AND cdb.[instance_id] = shcdd.[instance_id]
INNER JOIN [dbo].[catalogInstanceNames]			cin ON cin.[id] = cdb.[instance_id] AND cin.[project_id] = cdb.[project_id]
WHERE cin.[project_id] = @projectID
		AND cin.[name] LIKE @sqlServerNameFilter
		AND cdb.[name] LIKE @databaseNameFilter

DELETE lsam
FROM [dbo].[logAnalysisMessages]	lsam
INNER JOIN [dbo].[catalogInstanceNames] cin ON cin.[id] = lsam.[instance_id] AND cin.[project_id] = lsam.[project_id]
WHERE cin.[project_id] = @projectID
		AND cin.[name] LIKE @sqlServerNameFilter
		AND lsam.[descriptor]='dbo.usp_hcCollectDatabaseDetails'

DELETE sdaodM
FROM [health-check].[statsDatabaseAlwaysOnDetails] sdaodM
INNER JOIN
	(
		SELECT sdaod.[cluster_name], sdaod.[ag_name]
		FROM [health-check].[statsDatabaseAlwaysOnDetails] sdaod
		INNER JOIN [dbo].[catalogDatabaseNames]			cdb ON cdb.[id] = sdaod.[catalog_database_id] AND cdb.[instance_id] = sdaod.[instance_id]
		INNER JOIN [dbo].[catalogInstanceNames]			cin ON cin.[id] = cdb.[instance_id] AND cin.[project_id] = cdb.[project_id]
		WHERE	cin.[project_id] = @projectID
				AND cin.[name] LIKE @sqlServerNameFilter
				AND cdb.[name] LIKE @databaseNameFilter
				AND sdaod.[role_desc] = 'PRIMARY'
	)X ON sdaodM.[cluster_name] = X.[cluster_name] AND sdaodM.[ag_name] = X.[ag_name]

-------------------------------------------------------------------------------------------------------------------------
SET @strMessage='Step 2: Get Database Details Information....'
EXEC [dbo].[usp_logPrintMessage] @customMessage = @strMessage, @raiseErrorAsPrint = 1, @messagRootLevel = 0, @messageTreelevel = 1, @stopExecution=0

DECLARE crsActiveInstances CURSOR LOCAL FAST_FORWARD FOR 	SELECT	cin.[instance_id], cin.[instance_name], cin.[version],
																	CASE WHEN cin.[engine] IN (5, 6) THEN 1 ELSE 0 END AS [isAzureSQLDatabase]
															FROM	[dbo].[vw_catalogInstanceNames] cin
															WHERE 	cin.[project_id] = @projectID
																	AND cin.[instance_active]=1
																	AND cin.[instance_name] LIKE @sqlServerNameFilter
															ORDER BY cin.[instance_name]
OPEN crsActiveInstances
FETCH NEXT FROM crsActiveInstances INTO @instanceID, @sqlServerName, @sqlServerVersion, @isAzureSQLDatabase
WHILE @@FETCH_STATUS=0
	begin
		SET @strMessage='Analyzing server: ' + @sqlServerName
		EXEC [dbo].[usp_logPrintMessage] @customMessage = @strMessage, @raiseErrorAsPrint = 1, @messagRootLevel = 1, @messageTreelevel = 1, @stopExecution=0

		DELETE FROM #statsDatabaseDetails

		BEGIN TRY
			SET @serverVersionNum=SUBSTRING(@sqlServerVersion, 1, CHARINDEX('.', @sqlServerVersion)-1) + '.' + REPLACE(SUBSTRING(@sqlServerVersion, CHARINDEX('.', @sqlServerVersion)+1, LEN(@sqlServerVersion)), '.', '')
		END TRY
		BEGIN CATCH
			SET @serverVersionNum = 9.0
		END CATCH

		DECLARE crsActiveDatabases CURSOR LOCAL FAST_FORWARD FOR 	SELECT [catalog_database_id], [database_id], [database_name], [linked_server_name]
																	FROM (
																			SELECT	cdn.[catalog_database_id], cdn.[database_id], cdn.[database_name],
																					CASE WHEN @isAzureSQLDatabase = 0
																						 THEN @sqlServerName
																						 ELSE CASE WHEN ss.[name] IS NOT NULL THEN ss.[name] ELSE NULL END
																					END [linked_server_name]
																			FROM	[dbo].[vw_catalogDatabaseNames] cdn
																			LEFT JOIN [sys].[servers] ss ON ss.[catalog] = cdn.[database_name] COLLATE SQL_Latin1_General_CP1_CI_AS
																			WHERE 	cdn.[project_id] = @projectID
																					AND cdn.[instance_id] = @instanceID
																					AND cdn.[active]=1
																					AND cdn.[database_name] LIKE @databaseNameFilter
																					AND CHARINDEX(cdn.[state_desc], 'ONLINE, READ ONLY')<>0
																		)x
																	WHERE [linked_server_name] IS NOT NULL
																	ORDER BY [database_name]
		OPEN crsActiveDatabases
		FETCH NEXT FROM crsActiveDatabases INTO @catalogDatabaseID, @databaseID, @databaseName, @sqlServerName
		WHILE @@FETCH_STATUS=0
			begin
				SET @strMessage='database: ' + [dbo].[ufn_getObjectQuoteName](@databaseName, 'quoted')
				EXEC [dbo].[usp_logPrintMessage] @customMessage = @strMessage, @raiseErrorAsPrint = 1, @messagRootLevel = 1, @messageTreelevel = 2, @stopExecution=0

				/* get space allocated / used details */
				IF (SELECT COUNT(*) FROM [health-check].[statsDiskSpaceInfo]
					WHERE	[instance_id] = @instanceID
							AND DATEDIFF(day, [event_date_utc], GETUTCDATE()) <= 1
					) = 0 OR @isAzureSQLDatabase = 1
				begin
					IF @sqlServerName <> @@SERVERNAME
						SET @queryToRun = N'SELECT *
											FROM OPENQUERY([' + @sqlServerName + N'], ''EXEC (''''USE ' + [dbo].[ufn_getObjectQuoteName](@databaseName, 'quoted') + N';
													SELECT    [volume_mount_point]
															, CAST([is_logfile]		AS [bit]) AS [is_logfile]
															, SUM([size_mb])		AS [size_mb]
															, SUM([space_used_mb])	AS [space_used_mb]
															, MAX(CAST([is_growth_limited] AS [tinyint])) AS [is_growth_limited]
													FROM (
															SELECT    [name]
																	, CAST([size] AS [numeric](20,3)) * 8 / 1024. AS [size_mb]
																	, CAST(FILEPROPERTY([name], ''''''''SpaceUsed'''''''') AS [numeric](20,3)) * 8 / 1024. AS [space_used_mb]
																	, CAST(FILEPROPERTY([name], ''''''''IsLogFile'''''''') AS [bit])		AS [is_logfile] ' +
																	CASE WHEN @isAzureSQLDatabase = 0
																		 THEN	CASE WHEN @serverVersionNum >= 10.5
																					 THEN N', CASE WHEN LEN([volume_mount_point])=3 THEN UPPER([volume_mount_point]) ELSE [volume_mount_point] END [volume_mount_point] '
																					 ELSE N', REPLACE(LEFT([physical_name], 2), '''''''':'''''''', '''''''''''''''') AS [volume_mount_point] '
																				END
																		 ELSE N', ( SELECT ISNULL([elastic_pool_name], sd.[name])
																					FROM sys.database_service_objectives dso
																					INNER JOIN sys.databases sd ON dso.[database_id] = sd.[database_id]
																					WHERE sd.[name]=''''''''' + @databaseName + '''''''''
  																				  ) AS [volume_mount_point] '
																	END + N'
																	, CASE WHEN ([max_size]=-1 AND [type]=0) OR ([max_size]=-1 AND [type]=1) OR ([max_size]=268435456 AND [type]=1) THEN 0 ELSE 1 END AS [is_growth_limited]
															FROM sys.database_files' +
															CASE WHEN @serverVersionNum >= 10.5 AND @isAzureSQLDatabase = 0
																 THEN N' CROSS APPLY sys.dm_os_volume_stats(DB_ID(), [file_id])'
																 ELSE N''
															END +
															N'
														)sf
													GROUP BY [volume_mount_point], [is_logfile]
											'''')'')x'
					ELSE
						SET @queryToRun = N'USE ' + [dbo].[ufn_getObjectQuoteName](@databaseName, 'quoted') + N';
											SELECT    [volume_mount_point]
													, CAST([is_logfile]		AS [bit]) AS [is_logfile]
													, SUM([size_mb])		AS [size_mb]
													, SUM([space_used_mb])	AS [space_used_mb]
													, MAX(CAST([is_growth_limited] AS [tinyint])) AS [is_growth_limited]
											FROM (
													SELECT    [name]
															, CAST([size] AS [numeric](20,3)) * 8 / 1024. AS [size_mb]
															, CAST(FILEPROPERTY([name], ''SpaceUsed'') AS [numeric](20,3)) * 8 / 1024. AS [space_used_mb]
															, CAST(FILEPROPERTY([name], ''IsLogFile'') AS [bit])		AS [is_logfile] ' +
															CASE WHEN @serverVersionNum >= 10.5
																	THEN N', CASE WHEN LEN([volume_mount_point])=3 THEN UPPER([volume_mount_point]) ELSE [volume_mount_point] END [volume_mount_point] '
																	ELSE N', REPLACE(LEFT([physical_name], 2), '''''''':'''''''', '''''''''''''''') AS [volume_mount_point] '
																END + N'
															, CASE WHEN ([max_size]=-1 AND [type]=0) OR ([max_size]=-1 AND [type]=1) OR ([max_size]=268435456 AND [type]=1) THEN 0 ELSE 1 END AS [is_growth_limited]
													FROM sys.database_files' +
													CASE WHEN @serverVersionNum >= 10.5
															THEN N' CROSS APPLY sys.dm_os_volume_stats(DB_ID(), [file_id])'
															ELSE N''
													END + N'
												)sf
											GROUP BY [volume_mount_point], [is_logfile]'
				end
				ELSE
					begin
						IF @sqlServerName <> @@SERVERNAME
								SET @queryToRun = N'OPENQUERY([' + @sqlServerName + N'], ''EXEC (''''USE ' + [dbo].[ufn_getObjectQuoteName](@databaseName, 'quoted') + N';
																									SELECT    [name]
																											, [physical_name]
																											, CAST([size] AS [numeric](20,3)) * 8 / 1024. AS [size_mb]
																											, CAST(FILEPROPERTY([name], ''''''''SpaceUsed'''''''') AS [numeric](20,3)) * 8 / 1024. AS [space_used_mb]
																											, CAST(FILEPROPERTY([name], ''''''''IsLogFile'''''''') AS [bit])		AS [is_logfile]
																											, CASE WHEN ([max_size]=-1 AND [type]=0) OR ([max_size]=-1 AND [type]=1) OR ([max_size]=268435456 AND [type]=1) THEN 0 ELSE 1 END AS [is_growth_limited]
																									FROM sys.database_files
																								'''')'')'
						ELSE
							SET @queryToRun = N'(SELECT   [name]
														, [physical_name]
														, CAST([size] AS [numeric](20,3)) * 8 / 1024. AS [size_mb]
														, CAST(FILEPROPERTY([name], ''SpaceUsed'') AS [numeric](20,3)) * 8 / 1024. AS [space_used_mb]
														, CAST(FILEPROPERTY([name], ''IsLogFile'') AS [bit])		AS [is_logfile]
														, CASE WHEN ([max_size]=-1 AND [type]=0) OR ([max_size]=-1 AND [type]=1) OR ([max_size]=268435456 AND [type]=1) THEN 0 ELSE 1 END AS [is_growth_limited]
												FROM sys.database_files
												)'

						SET @queryToRun = CASE WHEN  @sqlServerName = @@SERVERNAME
											   THEN N'USE ' + [dbo].[ufn_getObjectQuoteName](@databaseName, 'quoted') + N';'
											   ELSE N''
										  END + N'
												SELECT    CASE WHEN [volume_mount_point] = '''' THEN NULL ELSE [volume_mount_point] END [volume_mount_point]
														, CAST([is_logfile]		AS [bit]) AS [is_logfile]
														, SUM([size_mb])		AS [size_mb]
														, SUM([space_used_mb])	AS [space_used_mb]
														, MAX(CAST([is_growth_limited] AS [tinyint])) AS [is_growth_limited]
												FROM (
														SELECT    [name]
																, [is_logfile]
																, MAX(ISNULL([size_mb], 0))					AS [size_mb]
																, MAX(ISNULL([space_used_mb], 0))			AS [space_used_mb]
																, MAX(ISNULL(dsi.[volume_mount_point], ''''))	AS [volume_mount_point]
																, MAX([is_growth_limited])		AS [is_growth_limited]
														FROM ' + @queryToRun + N' df
														LEFT JOIN [' + DB_NAME() + N'].[health-check].[vw_statsDiskSpaceInfo] dsi ON CHARINDEX(dsi.[volume_mount_point] COLLATE SQL_Latin1_General_CP1_CI_AS, df.[physical_name] COLLATE SQL_Latin1_General_CP1_CI_AS) > 0
																															AND dsi.[instance_name] = ''' + @sqlServerName + N'''
														GROUP BY [name], [is_logfile]
													)sf
												GROUP BY [volume_mount_point], [is_logfile]'
						end

				IF @debugMode = 1 EXEC [dbo].[usp_logPrintMessage] @customMessage = @queryToRun, @raiseErrorAsPrint = 0, @messagRootLevel = 0, @messageTreelevel = 1, @stopExecution=0
				DELETE FROM #databaseSpaceInfo
				BEGIN TRY
						INSERT	INTO #databaseSpaceInfo([volume_mount_point], [is_log_file], [size_mb], [space_used_mb], [is_growth_limited])
							EXEC sp_executesql @queryToRun
				END TRY
				BEGIN CATCH
					SET @strMessage = ERROR_MESSAGE()
					EXEC [dbo].[usp_logPrintMessage] @customMessage = @strMessage, @raiseErrorAsPrint = 0, @messagRootLevel = 0, @messageTreelevel = 1, @stopExecution=0

					INSERT	INTO [dbo].[logAnalysisMessages]([instance_id], [project_id], [event_date_utc], [descriptor], [message])
							SELECT  @instanceID
								  , @projectID
								  , GETUTCDATE()
								  , 'dbo.usp_hcCollectDatabaseDetails'
								  , [dbo].[ufn_getObjectQuoteName](@databaseName, 'quoted') + ':' + @strMessage
				END CATCH

				/* get last date for dbcc checkdb, only for 2k5+ */
				IF @isAzureSQLDatabase = 0
					begin
						IF @sqlServerName <> @@SERVERNAME
							begin
								IF @serverVersionNum < 11
									SET @queryToRun = N'SELECT MAX([VALUE]) AS [Value]
														FROM OPENQUERY([' + @sqlServerName + N'], ''SET FMTONLY OFF; EXEC (''''DBCC DBINFO (' + [dbo].[ufn_getObjectQuoteName](@databaseName, 'quoted') + N') WITH TABLERESULTS, NO_INFOMSGS'''')'')x
														WHERE [Field]=''dbi_dbccLastKnownGood'''
								ELSE
									SET @queryToRun = N'SELECT MAX([Value]) AS [Value]
														FROM OPENQUERY([' + @sqlServerName + N'], ''SET FMTONLY OFF; EXEC (''''DBCC DBINFO (' + [dbo].[ufn_getObjectQuoteName](@databaseName, 'quoted') + N') WITH TABLERESULTS, NO_INFOMSGS'''') WITH RESULT SETS(([ParentObject] [nvarchar](max), [Object] [nvarchar](max), [Field] [nvarchar](max), [Value] [nvarchar](max))) '')x
														WHERE [Field]=''dbi_dbccLastKnownGood'''
							end
						ELSE
							begin
								BEGIN TRY
									SET @queryToRun = N'DBCC DBINFO (''' + [dbo].[ufn_getObjectQuoteName](@databaseName, 'sql') + N''') WITH TABLERESULTS, NO_INFOMSGS'
									INSERT INTO #dbccDBINFO
											EXEC sp_executesql @queryToRun
								END TRY
								BEGIN CATCH
									SET @strMessage = ERROR_MESSAGE()
									EXEC [dbo].[usp_logPrintMessage] @customMessage = @strMessage, @raiseErrorAsPrint = 0, @messagRootLevel = 0, @messageTreelevel = 1, @stopExecution=0

									INSERT	INTO [dbo].[logAnalysisMessages]([instance_id], [project_id], [event_date_utc], [descriptor], [message])
											SELECT  @instanceID
													, @projectID
													, GETUTCDATE()
													, 'dbo.usp_hcCollectDatabaseDetails'
													, [dbo].[ufn_getObjectQuoteName](@databaseName, 'quoted') + ':' + @strMessage
								END CATCH

								SET @queryToRun = N'SELECT MAX([Value]) AS [Value] FROM #dbccDBINFO WHERE [Field]=''dbi_dbccLastKnownGood'''
							end

						IF @debugMode = 1 EXEC [dbo].[usp_logPrintMessage] @customMessage = @queryToRun, @raiseErrorAsPrint = 0, @messagRootLevel = 0, @messageTreelevel = 1, @stopExecution=0

						DELETE FROM #dbccLastKnownGood
						BEGIN TRY
							INSERT	INTO #dbccLastKnownGood([Value])
									EXEC sp_executesql @queryToRun
						END TRY
						BEGIN CATCH
							SET @strMessage = ERROR_MESSAGE()
							EXEC [dbo].[usp_logPrintMessage] @customMessage = @strMessage, @raiseErrorAsPrint = 0, @messagRootLevel = 0, @messageTreelevel = 1, @stopExecution=0

							INSERT	INTO [dbo].[logAnalysisMessages]([instance_id], [project_id], [event_date_utc], [descriptor], [message])
									SELECT  @instanceID
											, @projectID
											, GETUTCDATE()
											, 'dbo.usp_hcCollectDatabaseDetails'
											, [dbo].[ufn_getObjectQuoteName](@databaseName, 'quoted') + ':' + @strMessage
						END CATCH

						BEGIN TRY
							SELECT @dbccLastKnownGood = CASE WHEN [Value] = '1900-01-01 00:00:00.000' THEN NULL ELSE [Value] END
							FROM #dbccLastKnownGood
						END TRY
						BEGIN CATCH
							SET @dbccLastKnownGood=NULL
						END CATCH
					end

				/* compute database statistics */
				INSERT	INTO #statsDatabaseDetails([query_type], [database_id], [data_size_mb], [data_space_used_percent], [log_size_mb], [log_space_used_percent], [volume_mount_point], [last_dbcc checkdb_time], [is_growth_limited])
						SELECT    1, @databaseID
								, CAST([data_size_mb] AS [numeric](20,3)) AS [data_size_mb]
								, CAST(CASE WHEN [data_size_mb] <>0 THEN [data_space_used_mb] * 100. / [data_size_mb] ELSE 0 END AS [numeric](6,2)) AS [data_used_percent]
								, CAST([log_size_mb] AS [numeric](20,3)) AS [log_size_mb]
								, CAST(CASE WHEN [log_size_mb] <>0 THEN [log_space_used_mb] * 100. / [log_size_mb] ELSE 0 END AS [numeric](6,2)) AS [log_used_percent]
								, LTRIM(RTRIM([volume_mount_point])) AS [volume_mount_point]
								, @dbccLastKnownGood
								, [is_growth_limited]
						FROM (
								SELECT    SUM(CASE WHEN [is_log_file] = 0 THEN dsi.[size_mb] ELSE 0 END)		AS [data_size_mb]
										, SUM(CASE WHEN [is_log_file] = 0 THEN dsi.[space_used_mb] ELSE 0 END) 	AS [data_space_used_mb]
										, SUM(CASE WHEN [is_log_file] = 1 THEN dsi.[size_mb] ELSE 0 END) 		AS [log_size_mb]
										, SUM(CASE WHEN [is_log_file] = 1 THEN dsi.[space_used_mb] ELSE 0 END) 	AS [log_space_used_mb]
										, MAX(ISNULL(x.[volume_mount_points], '')) [volume_mount_point]
										, MAX(CAST([is_growth_limited] AS [tinyint])) [is_growth_limited]
								FROM #databaseSpaceInfo dsi
								CROSS APPLY(
											SELECT STUFF(
															(	SELECT ', ' + [volume_mount_point]
																FROM (
																		SELECT DISTINCT [volume_mount_point]
																		FROM #databaseSpaceInfo
																	) AS x
																ORDER BY [volume_mount_point]
																FOR XML PATH('')
															),1,1,''
														) AS [volume_mount_points]
											)x
							)db

				IF @isAzureSQLDatabase = 1
					begin
						/* get last date for backup and other database flags / options */
						SET @queryToRun = N'SELECT	  2 AS [query_type]
													, bkp.[database_id]
													, NULL AS [last_backup_time]
													, CAST(DATABASEPROPERTY(bkp.[database_name], ''IsAutoClose'')  AS [bit])	AS [is_auto_close]
													, CAST(DATABASEPROPERTY(bkp.[database_name], ''IsAutoShrink'')  AS [bit])	AS [is_auto_shrink]
													, bkp.[recovery_model]
													, bkp.[page_verify_option]
													, bkp.[compatibility_level]
													, bkp.[is_snapshot]
											FROM (
													SELECT	  sdb.[name]	AS [database_name]
															, sdb.[database_id]
															, sdb.[recovery_model]
															, sdb.[page_verify_option]
															, sdb.[compatibility_level]
															, CASE WHEN sdb.[source_database_id] IS NULL THEN 0 ELSE 1 END AS [is_snapshot]
													FROM sys.databases sdb
													WHERE sdb.[name]=''' + @databaseName + N'''
													GROUP BY sdb.[name], sdb.[database_id], sdb.[recovery_model], sdb.[page_verify_option], sdb.[compatibility_level], sdb.[source_database_id]
												)bkp'
						SET @queryToRun = [dbo].[ufn_formatSQLQueryForLinkedServer](@sqlServerName, @queryToRun)
						IF @debugMode = 1 EXEC [dbo].[usp_logPrintMessage] @customMessage = @queryToRun, @raiseErrorAsPrint = 0, @messagRootLevel = 0, @messageTreelevel = 1, @stopExecution=0

						BEGIN TRY
							INSERT	INTO #statsDatabaseDetails([query_type], [database_id], [last_backup_time], [is_auto_close], [is_auto_shrink], [recovery_model], [page_verify_option], [compatibility_level], [is_snapshot])
									EXEC sp_executesql @queryToRun
						END TRY
						BEGIN CATCH
							SET @strMessage = ERROR_MESSAGE()
							EXEC [dbo].[usp_logPrintMessage] @customMessage = @strMessage, @raiseErrorAsPrint = 0, @messagRootLevel = 0, @messageTreelevel = 1, @stopExecution=0

							INSERT	INTO [dbo].[logAnalysisMessages]([instance_id], [project_id], [event_date_utc], [descriptor], [message])
									SELECT  @instanceID
											, @projectID
											, GETUTCDATE()
											, 'dbo.usp_hcCollectDatabaseDetails'
											, @strMessage
						END CATCH
					end

				FETCH NEXT FROM crsActiveDatabases INTO @catalogDatabaseID, @databaseID, @databaseName, @sqlServerName
			end
		CLOSE crsActiveDatabases
		DEALLOCATE crsActiveDatabases

		/* get last date for backup and other database flags / options */
		IF @isAzureSQLDatabase = 0
			begin
				SET @queryToRun = N'SELECT	  2 AS [query_type]
											, bkp.[database_id]
											, CASE WHEN bkp.[last_backup_time] = CONVERT([datetime], ''1900-01-01'', 120) THEN NULL ELSE bkp.[last_backup_time] END AS [last_backup_time]
											, CAST(DATABASEPROPERTY(bkp.[database_name], ''IsAutoClose'')  AS [bit])	AS [is_auto_close]
											, CAST(DATABASEPROPERTY(bkp.[database_name], ''IsAutoShrink'')  AS [bit])	AS [is_auto_shrink]
											, bkp.[recovery_model]
											, bkp.[page_verify_option]
											, bkp.[compatibility_level]
											, bkp.[is_snapshot]
									FROM (
											SELECT	  sdb.[name]	AS [database_name]
													, sdb.[database_id]
													, sdb.[recovery_model]
													, sdb.[page_verify_option]
													, sdb.[compatibility_level] ' +
													CASE WHEN @isAzureSQLDatabase = 0
														 THEN N', MAX(ISNULL(bs.[backup_finish_date], CONVERT([datetime], ''1900-01-01'', 120)))'
														 ELSE N', NULL'
													END + N' AS [last_backup_time]
													, CASE WHEN sdb.[source_database_id] IS NULL THEN 0 ELSE 1 END AS [is_snapshot]
											FROM sys.databases sdb ' +
											CASE WHEN @isAzureSQLDatabase = 0
												 THEN N'LEFT OUTER JOIN msdb.dbo.backupset bs ON bs.[database_name] = sdb.[name] AND bs.type IN (''D'', ''I'')'
												 ELSE N''
											END + N'
											WHERE sdb.[name] LIKE ''' + @databaseNameFilter + N'''
											GROUP BY sdb.[name], sdb.[database_id], sdb.[recovery_model], sdb.[page_verify_option], sdb.[compatibility_level], sdb.[source_database_id]
										)bkp'
				SET @queryToRun = [dbo].[ufn_formatSQLQueryForLinkedServer](@sqlServerName, @queryToRun)
				IF @debugMode = 1 EXEC [dbo].[usp_logPrintMessage] @customMessage = @queryToRun, @raiseErrorAsPrint = 0, @messagRootLevel = 0, @messageTreelevel = 1, @stopExecution=0

				BEGIN TRY
					INSERT	INTO #statsDatabaseDetails([query_type], [database_id], [last_backup_time], [is_auto_close], [is_auto_shrink], [recovery_model], [page_verify_option], [compatibility_level], [is_snapshot])
							EXEC sp_executesql @queryToRun
				END TRY
				BEGIN CATCH
					SET @strMessage = ERROR_MESSAGE()
					EXEC [dbo].[usp_logPrintMessage] @customMessage = @strMessage, @raiseErrorAsPrint = 0, @messagRootLevel = 0, @messageTreelevel = 1, @stopExecution=0

					INSERT	INTO [dbo].[logAnalysisMessages]([instance_id], [project_id], [event_date_utc], [descriptor], [message])
							SELECT  @instanceID
									, @projectID
									, GETUTCDATE()
									, 'dbo.usp_hcCollectDatabaseDetails'
									, @strMessage
				END CATCH

				/* get msdb backup files history */
				TRUNCATE TABLE #msdbBackupHistory;
				SET @queryToRun = N'SELECT	  bs.[database_name]
											, CASE bs.[type] WHEN ''D'' THEN ''full'' WHEN ''I'' THEN ''diff'' WHEN ''L'' THEN ''log'' END AS [backup_type]
											, bs.[backup_start_date]
											, DATEDIFF(ss, bs.[backup_start_date], bs.[backup_finish_date]) AS [duration_sec]
											, ' + CASE WHEN @serverVersionNum > 10
														THEN N'bs.[compressed_backup_size]'
														ELSE N'bs.[backup_size]'
												  END + N' AS [size_bytes]
											, REPLACE(bmf.[physical_device_name], REVERSE(SUBSTRING(REVERSE(bmf.[physical_device_name]), CHARINDEX(''\'', REVERSE(bmf.[physical_device_name])), LEN(REVERSE(bmf.[physical_device_name])))), '''') AS [file_name]
									FROM msdb.dbo.backupset bs
									INNER JOIN msdb.dbo.backupmediafamily bmf on bs.[media_set_id] = bmf.[media_set_id]
									WHERE	bs.[backup_start_date] >= DATEADD(hour, DATEDIFF(hour, GETUTCDATE(), GETDATE()), CONVERT([datetime], CONVERT([varchar](10), DATEADD(day, -' + CAST(@reportOptionGetBackupSizeLastDays AS [nvarchar]) + N', GETUTCDATE()), 120), 120))'
				SET @queryToRun = [dbo].[ufn_formatSQLQueryForLinkedServer](@sqlServerName, @queryToRun)
				IF @debugMode = 1 EXEC [dbo].[usp_logPrintMessage] @customMessage = @queryToRun, @raiseErrorAsPrint = 0, @messagRootLevel = 0, @messageTreelevel = 1, @stopExecution=0

				BEGIN TRY
					INSERT	INTO #msdbBackupHistory([database_name], [backup_type], [backup_start_date], [duration_sec], [size_bytes], [file_name])
							EXEC sp_executesql @queryToRun
				END TRY
				BEGIN CATCH
					SET @strMessage = ERROR_MESSAGE()
					EXEC [dbo].[usp_logPrintMessage] @customMessage = @strMessage, @raiseErrorAsPrint = 0, @messagRootLevel = 0, @messageTreelevel = 1, @stopExecution=0

					INSERT	INTO [dbo].[logAnalysisMessages]([instance_id], [project_id], [event_date_utc], [descriptor], [message])
							SELECT  @instanceID
									, @projectID
									, GETUTCDATE()
									, 'dbo.usp_hcCollectDatabaseDetails'
									, @strMessage
				END CATCH
			end

		/* check for AlwaysOn Availability Groups configuration */
		IF @serverVersionNum >= 12 AND @isAzureSQLDatabase = 0
			begin
				SET @queryToRun = N'SELECT    hc.[cluster_name]
											, ag.[name] AS [ag_name]
											, hinm.[node_name] as [host_name]
											, arcn.[replica_server_name] AS [instance_name]
											, adc.[database_name]
											, ars.[role_desc]
											, rcs.[join_state_desc] AS [replica_join_state_desc]
											, ars.[connected_state_desc] AS [replica_connected_state_desc]
											, ar.[failover_mode_desc]
											, ar.[availability_mode_desc]
											, hdrs.[suspend_reason_desc]
											, ars.[synchronization_health_desc]
											, hdrs.[synchronization_state_desc]
											, ar.[secondary_role_allow_connections_desc]
									FROM sys.availability_replicas ar
									INNER JOIN sys.dm_hadr_availability_replica_states ars ON ars.[replica_id]=ar.[replica_id] AND ars.[group_id]=ar.[group_id]
									INNER JOIN sys.availability_groups ag ON ag.[group_id]=ar.[group_id]
									INNER JOIN sys.dm_hadr_availability_replica_cluster_nodes arcn ON arcn.[group_name]=ag.[name] AND arcn.[replica_server_name]=ar.[replica_server_name]
									INNER JOIN sys.dm_hadr_database_replica_states hdrs ON ar.[replica_id]=hdrs.[replica_id]
									INNER JOIN sys.availability_databases_cluster adc ON adc.[group_id]=hdrs.[group_id] AND adc.[group_database_id]=hdrs.[group_database_id]
									INNER JOIN sys.dm_hadr_instance_node_map hinm ON hinm.[ag_resource_id] = ag.[resource_id] AND hinm.[instance_name] = arcn.[replica_server_name]
									INNER JOIN sys.dm_hadr_cluster hc ON 1=1
									INNER JOIN sys.dm_hadr_availability_replica_cluster_states rcs on rcs.replica_id=ar.replica_id and rcs.group_id=hdrs.group_id'

				SET @queryToRun = [dbo].[ufn_formatSQLQueryForLinkedServer](@sqlServerName, @queryToRun)
				IF @debugMode = 1 EXEC [dbo].[usp_logPrintMessage] @customMessage = @queryToRun, @raiseErrorAsPrint = 0, @messagRootLevel = 0, @messageTreelevel = 1, @stopExecution=0

				BEGIN TRY
					INSERT	INTO #statsDatabaseAlwaysOnDetails(	[cluster_name], [ag_name], [host_name], [instance_name], [database_name], [role_desc],
																[replica_join_state_desc], [replica_connected_state_desc], [failover_mode_desc], [availability_mode_desc], [suspend_reason_desc],
																[synchronization_health_desc], [synchronization_state_desc], [readable_secondary_replica])
							EXEC sp_executesql @queryToRun
				END TRY
				BEGIN CATCH
					SET @strMessage = ERROR_MESSAGE()
					EXEC [dbo].[usp_logPrintMessage] @customMessage = @strMessage, @raiseErrorAsPrint = 0, @messagRootLevel = 0, @messageTreelevel = 1, @stopExecution=0

					INSERT	INTO [dbo].[logAnalysisMessages]([instance_id], [project_id], [event_date_utc], [descriptor], [message])
							SELECT  @instanceID
									, @projectID
									, GETUTCDATE()
									, 'dbo.usp_hcCollectDatabaseDetails'
									, @strMessage
				END CATCH
			end

		/* save results to stats table */
		INSERT	INTO [health-check].[statsDatabaseDetails]([catalog_database_id], [instance_id],
				 											 [data_size_mb], [data_space_used_percent], [log_size_mb], [log_space_used_percent],
															 [is_auto_close], [is_auto_shrink], [volume_mount_point],
															 [last_backup_time], [last_dbcc checkdb_time],  [recovery_model], [page_verify_option], [compatibility_level], [is_growth_limited], [is_snapshot], [event_date_utc])
				SELECT cdn.[id], @instanceID,
				 		qt.[data_size_mb], qt.[data_space_used_percent], qt.[log_size_mb], qt.[log_space_used_percent],
						qt.[is_auto_close], qt.[is_auto_shrink], qt.[volume_mount_point],
						qt.[last_backup_time], qt.[last_dbcc checkdb_time],  qt.[recovery_model], qt.[page_verify_option], qt.[compatibility_level], qt.[is_growth_limited], qt.[is_snapshot], GETUTCDATE()
				FROM (
						SELECT    ISNULL(qt1.[database_id], qt2.[database_id]) [database_id]
								, qt2.[recovery_model]
								, qt2.[page_verify_option]
								, qt2.[compatibility_level]
								, qt1.[data_size_mb]
								, qt1.[data_space_used_percent]
								, qt1.[log_size_mb]
								, qt1.[log_space_used_percent]
								, qt1.[volume_mount_point]
								, qt2.[is_auto_close]
								, qt2.[is_auto_shrink]
								, qt2.[last_backup_time]
								, qt1.[last_dbcc checkdb_time]
								, qt1.[is_growth_limited]
								, ISNULL(qt2.[is_snapshot], 0) AS [is_snapshot]
						FROM (
								SELECT    [database_id]
										, [data_size_mb]
										, [data_space_used_percent]
										, [log_size_mb]
										, [log_space_used_percent]
										, [volume_mount_point]
										, [last_dbcc checkdb_time]
										, [is_growth_limited]
								FROM #statsDatabaseDetails
								WHERE [query_type]=1
							) qt1
						FULL OUTER JOIN
							(
								SELECT    [database_id]
										, [is_auto_close]
										, [is_auto_shrink]
										, [last_backup_time]
										, [recovery_model]
										, [page_verify_option]
										, [compatibility_level]
										, [is_snapshot]
								FROM #statsDatabaseDetails
								WHERE [query_type]=2
							) qt2 ON qt1.[database_id] = qt2.[database_id]
					)qt
				INNER JOIN [dbo].[catalogDatabaseNames] cdn ON	cdn.[database_id] = qt.[database_id]
															AND cdn.[instance_id] = @instanceID
															AND cdn.[project_id] = @projectID

		INSERT	INTO [health-check].[statsDatabaseAlwaysOnDetails](	[catalog_database_id], [instance_id], [cluster_name], [ag_name], [role_desc],
																	[replica_join_state_desc], [replica_connected_state_desc], [failover_mode_desc], [availability_mode_desc], [suspend_reason_desc],
																	[synchronization_health_desc], [synchronization_state_desc], [readable_secondary_replica], [event_date_utc])
				SELECT  DISTINCT
						  cdn.[id] AS [catalog_database_id]
						, cin.[id] AS [instance_id]
						, X.[cluster_name]
						, X.[ag_name]
						, X.[role_desc]
						, X.[replica_join_state_desc]
						, X.[replica_connected_state_desc]
						, X.[failover_mode_desc]
						, X.[availability_mode_desc]
						, X.[suspend_reason_desc]
						, X.[synchronization_health_desc]
						, X.[synchronization_state_desc]
						, X.[readable_secondary_replica]
						, GETUTCDATE()
				FROM #statsDatabaseAlwaysOnDetails X
				INNER JOIN dbo.catalogMachineNames cmn  ON	cmn.[name] = X.[host_name] COLLATE DATABASE_DEFAULT
				INNER JOIN dbo.catalogInstanceNames cin ON	cin.[name] = X.[instance_name] COLLATE DATABASE_DEFAULT
															AND cin.[project_id] = cmn.[project_id]
															AND cin.[machine_id] = cmn.[id]
				INNER JOIN dbo.catalogDatabaseNames cdn ON	cdn.[name] = X.[database_name] COLLATE DATABASE_DEFAULT
															AND cdn.[project_id] = cmn.[project_id]
															AND cdn.[instance_id] = cin.[id]
				LEFT JOIN [health-check].[statsDatabaseAlwaysOnDetails] sdaod ON sdaod.[catalog_database_id] = cdn.[id]
																				AND sdaod.[instance_id] = cin.[id]
																				AND sdaod.[cluster_name] = X.[cluster_name] COLLATE DATABASE_DEFAULT
																				AND sdaod.[ag_name] = X.[ag_name] COLLATE DATABASE_DEFAULT
				WHERE cin.[project_id] = @projectID
						AND sdaod.[id] IS NULL

		/* extract backupset information - include backup details not made using this utility */
		;WITH tdpBackups AS
		(
			SELECT	  lem.[project_id], lem.[instance_id], lem.[instance_name], lem.[database_name]
					, info.value ('size_bytes[1]', 'bigint') as [size_bytes]
					, info.value ('file_name[1]', 'sysname') as [file_name]
					, info.value ('type[1]', 'nvarchar(16)') as [backup_type]
					, lem.[event_date_utc]
					, lem.[message_xml]
			FROM (
					SELECT l.[project_id], l.[instance_id], l.[instance_name], l.[database_name], l.[message_xml], l.[event_date_utc]
					FROM [dbo].[vw_logEventMessages] l
					INNER JOIN [dbo].[vw_catalogProjects] p ON l.[project_id] = p.[project_id]
					WHERE l.[module]='dbo.usp_mpDatabaseBackup'
						AND l.[event_name]='database backup'
						AND l.[event_type]=0
						AND l.[message] LIKE '<backupset>%'
						AND l.[event_date_utc] >= @startEvent
						AND p.[project_code] LIKE @projectCode
						AND l.[instance_name] LIKE @sqlServerNameFilter
				) lem
			CROSS APPLY [message_xml].nodes('//backupset/detail') M(info)
		)
		INSERT	INTO [dbo].[logEventMessages]([project_id], [instance_id], [event_date_utc], [module], [event_name], [database_name], [message], [event_type])
		SELECT	@projectID, @instanceID, GETUTCDATE()
				, 'dbo.usp_mpDatabaseBackup' AS [module]
				, 'database backup' AS [event_name]
				, bs.[database_name]
				, '<backupset><detail>' +
						'<database_name>' + [dbo].[ufn_getObjectQuoteName](bs.[database_name], 'xml') + '</database_name>' +
						'<type>' + bs.[backup_type] + '</type>' +
						'<start_date>' + CONVERT([varchar](24), ISNULL([backup_start_date], GETDATE()), 121) + '</start_date>' +
						'<duration>' + REPLICATE('0', 2-LEN(CAST([duration_sec] / 3600 AS [varchar]))) + CAST([duration_sec] / 3600 AS [varchar]) + 'h'
											+ ' ' + REPLICATE('0', 2-LEN(CAST(([duration_sec] / 60) % 60 AS [varchar]))) + CAST(([duration_sec] / 60) % 60 AS [varchar]) + 'm'
											+ ' ' + REPLICATE('0', 2-LEN(CAST([duration_sec] % 60 AS [varchar]))) + CAST([duration_sec] % 60 AS [varchar]) + 's' + '</duration>' +
						'<size>' + CONVERT([varchar](32), CAST(bs.[size_bytes]/(1024*1024*1.0) AS [money]), 1) + ' mb</size>' +
						'<size_bytes>' + CAST(bs.[size_bytes] AS [varchar](32)) + '</size_bytes>' +
						'<verified>N/A</verified>' +
						'<file_name>' + [dbo].[ufn_getObjectQuoteName](bs.[file_name], 'xml') + '</file_name>' +
						'<error_code>0</error_code>' +
					'</detail></backupset>'
				, 0 AS [event_type]
		FROM #msdbBackupHistory bs
		LEFT JOIN tdpBackups tdp ON		tdp.[instance_name] = @sqlServerName
									AND	tdp.[database_name] = bs.[database_name]
									AND tdp.[backup_type] = bs.[backup_type]
									AND tdp.[file_name] = bs.[file_name]
		WHERE tdp.[instance_name] IS NULL

		FETCH NEXT FROM crsActiveInstances INTO @instanceID, @sqlServerName, @sqlServerVersion, @isAzureSQLDatabase
	end
CLOSE crsActiveInstances
DEALLOCATE crsActiveInstances
GO


text:
package org.scalatest.finders

import org.scalatest.funsuite.AnyFunSuite
import org.scalatest.propspec.AnyPropSpec

class FunctionFinderSuite extends FinderSuite {
  test("FunctionFinder should find test name for tests written in test suite that extends org.scalatest.FunSuite") {
    class TestingFunSuite extends AnyFunSuite {
      test("test 1") {

      }
      test("test 2") {
        test("nested") {

        }
      }
      test("test 3") {

      }
    }

    val suiteClass = classOf[TestingFunSuite]
    val suiteClassDef = new ClassDefinition(suiteClass.getName, null, Array.empty, "TestingFunSuite")
    val suiteConstructor = new ConstructorBlock(suiteClass.getName, suiteClassDef, Array.empty)
    val test1 = new MethodInvocation(suiteClass.getName, null, suiteConstructor, Array.empty, "test", new StringLiteral(suiteClass.getName, null, "test 1"))
    val test2 = new MethodInvocation(suiteClass.getName, null, suiteConstructor, Array.empty, "test", new StringLiteral(suiteClass.getName, null, "test 2"))
    val nested = new MethodInvocation(suiteClass.getName, null, test2, Array.empty, "test", new StringLiteral(suiteClass.getName, null, "nested"))
    val test3 = new MethodInvocation(suiteClass.getName, null, suiteConstructor, Array.empty, "test", new StringLiteral(suiteClass.getName, null, "test 3"))

    val finders = LocationUtils.getFinders(suiteClass)
    assert(finders.size == 1, "org.scalatest.FunSpec should have 1 finder, but we got: " + finders.size)
    val finder = finders.get(0)
    assert(finder.getClass == classOf[FunSuiteFinder], "Suite that uses org.scalatest.FunSuite should use FunSuiteFinder.")
    val test1Selection = finder.find(test1)
    expectSelection(test1Selection, suiteClass.getName, suiteClass.getName + ": \"test 1\"", Array("test 1"))
    val test2Selection = finder.find(test2)
    expectSelection(test2Selection, suiteClass.getName, suiteClass.getName + ": \"test 2\"", Array("test 2"))
    val nestedSelection = finder.find(nested)
    expectSelection(nestedSelection, suiteClass.getName, suiteClass.getName + ": \"test 2\"", Array("test 2"))
    val test3Selection = finder.find(test3)
    expectSelection(test3Selection, suiteClass.getName, suiteClass.getName + ": \"test 3\"", Array("test 3"))
  }

  test("FunctionFinder should find test name for tests written in test suite that extends org.scalatest.PropSpec") {
    class TestingPropSpec extends AnyPropSpec {
      property("Fraction constructor normalizes numerator and denominator.") {

      }

      property("Fraction constructor throws IAE on bad data.") {
        println("nested")
      }
    }

    val suiteClass = classOf[TestingPropSpec]
    val suiteClassDef = new ClassDefinition(suiteClass.getName, null, Array.empty, "TestingPropSpec")
    val suiteConstructor = new ConstructorBlock(suiteClass.getName, suiteClassDef, Array.empty)
    val prop1 = new MethodInvocation(suiteClass.getName, null, suiteConstructor, Array.empty, "property", new StringLiteral(suiteClass.getName, null, "Fraction constructor normalizes numerator and denominator."))
    val prop2 = new MethodInvocation(suiteClass.getName, null, suiteConstructor, Array.empty, "property", new StringLiteral(suiteClass.getName, null, "Fraction constructor throws IAE on bad data."))
    val nested = new MethodInvocation(suiteClass.getName, null, prop2, Array.empty, "println", new StringLiteral(suiteClass.getName, null, "nested"))

    val finders = LocationUtils.getFinders(suiteClass)
    assert(finders.size == 1, "org.scalatest.PropSpec should have 1 finder, but we got: " + finders.size)
    val finder = finders.get(0)
    assert(finder.getClass == classOf[PropSpecFinder], "Suite that uses org.scalatest.PropSpec should use PropSpecFinder.")
    val prop1Selection = finder.find(prop1)
    expectSelection(prop1Selection, suiteClass.getName, suiteClass.getName + ": \"Fraction constructor normalizes numerator and denominator.\"", Array("Fraction constructor normalizes numerator and denominator."))
    val prop2Selection = finder.find(prop2)
    expectSelection(prop2Selection, suiteClass.getName, suiteClass.getName + ": \"Fraction constructor throws IAE on bad data.\"", Array("Fraction constructor throws IAE on bad data."))
    val nestedSelection = finder.find(nested)
    expectSelection(nestedSelection, suiteClass.getName, suiteClass.getName + ": \"Fraction constructor throws IAE on bad data.\"", Array("Fraction constructor throws IAE on bad data."))
  }
}


text:
from django.conf import settings
from django.urls import reverse  # noqa
from django.core import mail  # noqa
from django.test import TestCase
from rest_framework.test import APIClient  # noqa
from rest_framework_json_api.utils import (
    get_resource_type_from_serializer, format_field_names)
from api_v3.misc.queue import queue  # noqa

class ApiTestCase(TestCase):

    JSON_API_CONTENT_TYPE = 'application/vnd.api+json'

    def as_jsonapi_payload(self, serializer_class, obj, update={}):
        data = serializer_class(obj).data
        data.update(update)
        return dict(
            data=dict(
                id=obj.id,
                attributes=format_field_names(
                    data, settings.JSON_API_FORMAT_FIELD_NAMES
                ),
                type=get_resource_type_from_serializer(serializer_class)
            )
        )


text:
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('ingest', '0011_auto_20170302_2130'),
    ]

    operations = [
        migrations.AddField(
            model_name='scan',
            name='file_count',
            field=models.BigIntegerField(null=True, blank=True),
            preserve_default=True,
        ),
    ]