text:
CREATE OR REPLACE VIEW `project_id.dataset_id.bigquery_audit_logs_v2` AS
WITH jobChangeEvent AS (
  SELECT
    protopayload_auditlog.authenticationInfo.principalEmail,
    resource.labels.project_id AS projectId,
    protopayload_auditlog.requestMetadata.callerIp AS callerIp,
    protopayload_auditlog.requestMetadata.callerSuppliedUserAgent AS callerSuppliedUserAgent,
    timestamp,
    protopayload_auditlog.serviceName,
    protopayload_auditlog.methodName,
    CONCAT(
      SPLIT(JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson, '$.jobChange.job.jobName'),"/")[SAFE_OFFSET(1)],
      ":",
      SPLIT(JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson, '$.jobChange.job.jobName'),"/")[SAFE_OFFSET(3)]
    ) AS jobId,
    CONCAT(
      SPLIT(JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson, '$.jobChange.job.jobStats.parentJobName'),
        "/")[SAFE_OFFSET(1)],
      ":",
      SPLIT(JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,'$.jobChange.job.jobStats.parentJobName'),
        "/")[SAFE_OFFSET(3)]
    ) AS parentJobId,
    JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson, '$.jobChange.job.jobName') AS jobChangeJobName,
    /*
     * JobStatus: Running state of a job
     * https://cloud.google.com/bigquery/docs/reference/auditlogs/rest/Shared.Types/BigQueryAuditMetadata#bigqueryauditmetadata.jobstatus
     */
    JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson, '$.jobChange.job.jobStatus.jobState') AS jobStatusJobState,
    JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.jobChange.job.jobStatus.errorResult.code') AS jobStatusErrorResultCode,
    JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.jobChange.job.jobStatus.errorResult.message') AS jobStatusErrorResultMessage,
    JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.jobChange.job.jobStatus.errorResult.details') AS jobStatusErrorResultDetails,
    JSON_EXTRACT_ARRAY(protopayload_auditlog.metadataJson,
      '$.jobChange.job.jobStatus.errors') AS jobStatusErrorsArray,
    /*
     * JobStats: Job statistics that may change after job starts.
     * https://cloud.google.com/bigquery/docs/reference/auditlogs/rest/Shared.Types/BigQueryAuditMetadata#bigqueryauditmetadata.jobstats
     */
    JSON_EXTRACT_SCALAR(
      protopayload_auditlog.metadataJson,'$.jobChange.job.jobStats.parentJobName') AS jobStatsParentJobName,
    TIMESTAMP(JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.jobChange.job.jobStats.createTime')) AS jobStatsCreateTime,
    TIMESTAMP(JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.jobChange.job.jobStats.startTime')) AS jobStatsStartTime,
    TIMESTAMP(JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.jobChange.job.jobStats.endTime')) AS jobStatsEndTime,
    CAST(JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.jobChange.job.jobStats.totalSlotMs') AS INT64) AS jobStatsTotalSlotMs,
    IF(
      ARRAY_LENGTH(JSON_EXTRACT_ARRAY(
        protopayload_auditlog.metadataJson, '$.jobChange.job.jobStats.reservationUsage')) = 1,
      JSON_EXTRACT_SCALAR(TRIM(TRIM(JSON_EXTRACT(
        protopayload_auditlog.metadataJson, '$.jobChange.job.jobStats.reservationUsage'), "["),"]"), '$.name'),
      JSON_EXTRACT(protopayload_auditlog.metadataJson, '$.jobChange.job.jobStats.reservationUsage')
    ) AS jobStatsReservationUsageName,
    IF(
      ARRAY_LENGTH(JSON_EXTRACT_ARRAY(
        protopayload_auditlog.metadataJson, '$.jobChange.job.jobStats.reservationUsage')) = 1,
      JSON_EXTRACT_SCALAR(TRIM(TRIM(JSON_EXTRACT(
        protopayload_auditlog.metadataJson, '$.jobChange.job.jobStats.reservationUsage'), "["),"]"), '$.slotMs'),
      JSON_EXTRACT(protopayload_auditlog.metadataJson, '$.jobChange.job.jobStats.reservationUsage')
    ) AS jobStatsReservationUsageSlotMs,
    /*
     * Query: Query job statistics
     * https://cloud.google.com/bigquery/docs/reference/auditlogs/rest/Shared.Types/BigQueryAuditMetadata#bigqueryauditmetadata.query_1
     */
    JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.jobChange.job.jobStats.queryStats.totalProcessedBytes') AS queryJobStatsTotalProcessedBytes,
    CAST(JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.jobChange.job.jobStats.queryStats.totalBilledBytes') AS INT64) AS queryJobStatsTotalBilledBytes,
    JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.jobChange.job.jobStats.queryStats.billingTier') AS queryJobStatsBillingTier,
    SPLIT(TRIM(TRIM(JSON_EXTRACT(protopayload_auditlog.metadataJson,
      '$.jobChange.job.jobStats.queryStats.referencedTables'),
      '["'), '"]'), '","') AS queryJobStatsReferencedTables,
    SPLIT(TRIM(TRIM(JSON_EXTRACT(protopayload_auditlog.metadataJson,
      '$.jobChange.job.jobStats.queryStats.referencedViews'),
      '["'), '"]'), '","') AS queryJobStatsReferencedViews,
    SPLIT(TRIM(TRIM(JSON_EXTRACT(protopayload_auditlog.metadataJson,
      '$.jobChange.job.jobStats.queryStats.referencedRoutines'),
      '["'), '"]'), '","') AS queryJobStatsReferencedRoutines,
    JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.jobChange.job.jobStats.queryStats.outputRowCount') AS queryJobStatsOutputRowCount,
    CAST(JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.jobChange.job.jobStats.queryStats.cacheHit') AS BOOL) AS queryJobStatsCacheHit,
    /*
     * Load: Load job statistics
     * https://cloud.google.com/bigquery/docs/reference/auditlogs/rest/Shared.Types/BigQueryAuditMetadata#bigqueryauditmetadata.load_1
     */
    CAST(JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.jobChange.job.jobStats.loadStats.totalOutputBytes') AS INT64 ) AS loadJobStatsTotalOutputBytes,
    /*
     * JobStats convenience custom fields
     */
    TIMESTAMP_DIFF(
      TIMESTAMP(JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
       '$.jobChange.job.jobStats.endTime')),
      TIMESTAMP(JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
       '$.jobChange.job.jobStats.startTime')),
      MILLISECOND) AS jobStatsRuntimeMs,
    TIMESTAMP_DIFF(
      TIMESTAMP(JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
        '$.jobChange.job.jobStats.endTime')),
      TIMESTAMP(JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
        '$.jobChange.job.jobStats.startTime')),
      SECOND) AS jobStatsRuntimeSecs,
    CAST(CEILING(SAFE_DIVIDE(TIMESTAMP_DIFF(
      TIMESTAMP(JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
        '$.jobChange.job.jobStats.endTime')),
      TIMESTAMP(JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
        '$.jobChange.job.jobStats.startTime')),
      SECOND), 60)) AS INT64) AS jobStatsExecutionMinuteBuckets,
    /*
     * Job configuration information.
     * https://cloud.google.com/bigquery/docs/reference/auditlogs/rest/Shared.Types/BigQueryAuditMetadata#bigqueryauditmetadata.jobconfig
     */
    JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson, '$.jobChange.job.jobConfig.type') AS jobConfigType,
    JSON_EXTRACT(protopayload_auditlog.metadataJson, '$.jobChange.job.jobConfig.labels') AS jobConfigLabels,
    /*
     * Describes a query job.
     * https://cloud.google.com/bigquery/docs/reference/auditlogs/rest/Shared.Types/BigQueryAuditMetadata#bigqueryauditmetadata.query
     */
    JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.jobChange.job.jobConfig.queryConfig.query') AS queryConfigQuery,
    CAST(JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.jobChange.job.jobConfig.queryConfig.queryTruncated') AS BOOL) AS queryConfigQueryTruncated,
    JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.jobChange.job.jobConfig.queryConfig.destinationTable') AS queryConfigDestinationTable,
    JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.jobChange.job.jobConfig.queryConfig.createDisposition') AS queryConfigCreateDisposition,
    JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.jobChange.job.jobConfig.queryConfig.writeDisposition') AS queryConfigWriteDisposition,
    JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.jobChange.job.jobConfig.queryConfig.defaultDataset') AS queryConfigDefaultDataset,
    REGEXP_EXTRACT_ALL(
      JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson, '$.jobChange.job.jobConfig.queryConfig.tableDefinitions'),
      r'"name":\"(.*?)\"}') AS tableDefinitionsName,
    REGEXP_EXTRACT_ALL(
      JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,'$.jobChange.job.jobConfig.queryConfig.tableDefinitions'),
      r'"sourceUris":\"(.*?)\"}') AS tableDefinitionsSourceUris,
    JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.jobChange.job.jobConfig.queryConfig.priority') AS queryConfigPriority,
    JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.jobChange.job.jobConfig.queryConfig.destinationTableEncryption.kmsKeyName') AS queryConfigDestinationTableEncryptionKmsKeyName,
    JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.jobChange.job.jobConfig.queryConfig.statementType') AS queryConfigStatementType,
    SPLIT(JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.jobChange.job.jobConfig.queryConfig.destinationTable'),
      "/")[SAFE_OFFSET(1)] AS queryConfigDestinationTableProjectId,
    SPLIT(JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.jobChange.job.jobConfig.queryConfig.destinationTable'),
      "/")[SAFE_OFFSET(3)] AS queryConfigDestinationTableDatasetId,
    SPLIT(JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.jobChange.job.jobConfig.queryConfig.destinationTable'),
      "/")[SAFE_OFFSET(5)] AS queryConfigDestinationTableId,
    /*
     * Describes a load job.
     * https://cloud.google.com/bigquery/docs/reference/auditlogs/rest/Shared.Types/BigQueryAuditMetadata#bigqueryauditmetadata.load
     */
    SPLIT(TRIM(TRIM(JSON_EXTRACT(protopayload_auditlog.metadataJson,
      '$.jobChange.job.jobConfig.loadConfig.sourceUris'),
      '["'), '"]'), '","') AS loadConfigSourceUris,
    CAST(JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.jobChange.job.jobConfig.loadConfig.sourceUrisTruncated') AS BOOL) AS loadConfigSourceUrisTruncated,
    JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.jobChange.job.jobConfig.loadConfig.schemaJson') AS loadConfigSchemaJson,
    CAST(JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.jobChange.job.jobConfig.loadConfig.schemaJsonUrisTruncated') AS BOOL) AS loadConfigSchemaJsonTruncated,
    JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.jobChange.job.jobConfig.loadConfig.destinationTable') AS loadConfigDestinationTable,
    JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.jobChange.job.jobConfig.loadConfig.createDisposition') AS loadConfigCreateDisposition,
    JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.jobChange.job.jobConfig.loadConfig.writeDisposition') AS loadConfigWriteDisposition,
    JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.jobChange.job.jobConfig.loadConfig.destinationTableEncryption.kmsKeyName'
    ) AS loadConfigDestinationTableEncryptionKmsKeyName,
    /*
     * Describes an extract job.
     * https://cloud.google.com/bigquery/docs/reference/auditlogs/rest/Shared.Types/BigQueryAuditMetadata#bigqueryauditmetadata.extract
     */
    SPLIT(TRIM(TRIM(JSON_EXTRACT(protopayload_auditlog.metadataJson,
      '$.jobChange.job.jobConfig.extractConfig.destinationUris'),
      '["'), '"]'), '","') AS extractConfigDestinationUris,
    CAST(JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.jobChange.job.jobConfig.extractConfig.destinationUrisTruncated')
      AS BOOL) AS extractConfigDestinationUrisTruncated,
    JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.jobChange.job.jobConfig.extractConfig.sourceTable') AS extractConfigSourceTable,
    SPLIT(JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.jobChange.job.jobConfig.extractConfig.sourceTable'),
      ",")[SAFE_OFFSET(1)] AS extractConfigSourceTableProjectId,
    SPLIT(JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.jobChange.job.jobConfig.extractConfig.sourceTable'),
      ",")[SAFE_OFFSET(3)] AS extractConfigSourceTableDatasetId,
    SPLIT(JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.jobChange.job.jobConfig.extractConfig.sourceTable'),
      ",")[SAFE_OFFSET(5)] AS extractConfigSourceTableId,
    /*
     * Describes a copy job, which copies an existing table to another table
     * https://cloud.google.com/bigquery/docs/reference/auditlogs/rest/Shared.Types/BigQueryAuditMetadata#bigqueryauditmetadata.tablecopy
     */
    SPLIT(TRIM(TRIM(JSON_EXTRACT(protopayload_auditlog.metadataJson,
      '$.jobChange.job.jobConfig.tableCopyConfig.sourceTables'),
      '["'),'"]') ,'","') AS tableCopySourceTables,
    CAST(JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.jobChange.job.jobConfig.tableCopyConfig.sourceTablesTruncated')
      AS BOOL) AS tableCopyConfigSourceTablesTruncated,
    JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.jobChange.job.jobConfig.tableCopyConfig.destinationTable') AS tableCopyConfigDestinationTable,
    JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.jobChange.job.jobConfig.createDisposition') AS tableCopyConfigCreateDisposition,
    JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.jobChange.job.jobConfig.writeDisposition') AS tableCopyConfigWriteDisposition,
    JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.jobChange.job.jobConfig.tableCopyConfig.destinationTableEncryption.kmsKeyName'
    ) AS tableCopyConfigDestinationTableEncryptionKmsKeyName,
    SPLIT(JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.jobChange.job.jobConfig.tableCopyConfig.destinationTable'),
      ".")[SAFE_OFFSET(1)] AS tableCopyConfigProjectId,
    SPLIT(JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.jobChange.job.jobConfig.tableCopyConfig.destinationTable'),
      ".")[SAFE_OFFSET(2)] AS tableCopyConfigDatasetId,
    SPLIT(JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.jobChange.job.jobConfig.tableCopyConfig.destinationTable'),
      ".")[SAFE_OFFSET(3)] AS tableCopyConfigTableId,
    JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson, '$.jobChange.before') AS jobChangeBefore,
    JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson, '$.jobChange.after') AS jobChangeAfter,
    REGEXP_EXTRACT(protopayload_auditlog.metadataJson, r'BigQueryAuditMetadata","(.*?)":') AS eventName,
  FROM `project_id.dataset_id.cloudaudit_googleapis_com_data_access`
),
/*
 * TableCreation: Table creation event.
 * https://cloud.google.com/bigquery/docs/reference/auditlogs/rest/Shared.Types/BigQueryAuditMetadata#bigqueryauditmetadata.tablecreation
 */
tableCreationEvent AS (
  SELECT
    CONCAT(
     SPLIT(JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson, '$.tableCreation.jobName'),"/")[SAFE_OFFSET(1)],
       ":",
     SPLIT(JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson, '$.tableCreation.jobName'),"/")[SAFE_OFFSET(3)]
    ) AS jobId,
    JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
    '$.tableCreation.jobName') AS tableCreationJobName,
    JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
     '$.tableCreation.table.tableName') AS tableCreationTableName,
    JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
     '$.tableCreation.table.tableInfo.friendlyName') AS tableCreationTableFriendlyName,
    JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
     '$.tableCreation.table.tableInfo.description') AS tableCreationTableDescription,
    JSON_EXTRACT(protopayload_auditlog.metadataJson,
     '$.tableCreation.table.tableInfo.labels') AS tableCreationTableLabels,
    JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
     '$.tableCreation.table.schemaJson') AS tableCreationTableSchemaJson,
    CAST(JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
     '$.tableCreation.table.schemaJsonTruncated') AS BOOL) AS tableCreationTableSchemaJsonTruncated,
    JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.tableCreation.table.view.query') AS tableCreationViewDefinitionQuery,
    CAST(JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.tableCreation.table.view.queryTruncated') AS BOOL) AS tableCreationViewDefinitionTruncated,
    JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.tableCreation.table.expireTime') AS tableCreationTableExpireTime,
    JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.tableCreation.table.createTime') AS tableCreationTableCreateTime,
    JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.tableCrhange.table.updateTime') AS tableCreationTableUpdateTime,
    JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.tableCreation.table.truncateTime') AS tableCreationTableTruncateTime,
    JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.tableCreation.table.encryption.kmsKeyName') AS tableCreationTableKmsKeyName,
    JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.tableCreation.reason')  AS tableCreationReason,
  FROM `project_id.dataset_id.cloudaudit_googleapis_com_activity`
),
/*
 * TableChange: Table metadata change event
 * https://cloud.google.com/bigquery/docs/reference/auditlogs/rest/Shared.Types/BigQueryAuditMetadata#bigqueryauditmetadata.tablechange
 */
tableChangeEvent AS (
  SELECT
    CONCAT(
     SPLIT(JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson, '$.tableChange.jobName'),"/")[SAFE_OFFSET(1)],
       ":",
     SPLIT(JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson, '$.tableChange.jobName'),"/")[SAFE_OFFSET(3)]
    ) AS jobId,
    JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
    '$.tableChange.jobName') AS tableChangeJobName,
    JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
     '$.tableChange.table.tableName') AS tableChangeTableName,
    JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
     '$.tableChange.table.tableInfo.friendlyName') AS tableChangeTableFriendlyName,
    JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
     '$.tableChange.table.tableInfo.description') AS tableChangeTableDescription,
    JSON_EXTRACT(protopayload_auditlog.metadataJson,
     '$.tableChange.table.tableInfo.labels') AS tableChangeTableLabels,
    JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
     '$.tableChange.table.schemaJson') AS tableChangeTableSchemaJson,
    CAST(JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
     '$.tableChange.table.schemaJsonTruncated') AS BOOL) AS tableChangeTableSchemaJsonTruncated,
    JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.tableChange.table.view.query') AS tableChangeViewDefinitionQuery,
    CAST(JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.tableChange.table.view.queryTruncated') AS BOOL) AS tableChangeViewDefinitionTruncated,
    JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.tableChange.table.expireTime') AS tableChangeTableExpireTime,
    JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.tableChange.table.createTime') AS tableChangeTableCreateTime,
    JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.tableChange.table.updateTime') AS tableChangeTableUpdateTime,
    JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.tableChange.table.truncateTime') AS tableChangeTableTruncateTime,
    JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.tableChange.table.encryption.kmsKeyName') AS tableChangeTableKmsKeyName,
    JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.tableChange.reason')  AS tableChangeReason,
    CAST(JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.tableChange.truncated') AS BOOL) AS tableChangeTruncated
  FROM `project_id.dataset_id.cloudaudit_googleapis_com_activity`
),
/*
 * TableDeletion: Table deletion event
 * https://cloud.google.com/bigquery/docs/reference/auditlogs/rest/Shared.Types/BigQueryAuditMetadata#bigqueryauditmetadata.tabledeletion
 */
tableDeletionEvent AS (
  SELECT
    CONCAT(
      SPLIT(
        JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson, '$.tableDeletion.jobName'),
        "/")[SAFE_OFFSET(1)],
      ":",
      SPLIT(
        JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson, '$.tableDeletion.jobName'),
        "/")[SAFE_OFFSET(3)]
      ) AS jobId,
    JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson, '$.tableDeletion.jobName') AS tableDeletionJobName,
    JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.tableDeletion.reason') AS tableDeletionReason,
  FROM `project_id.dataset_id.cloudaudit_googleapis_com_activity`
),
/*
 * TableDataRead: Data from tableDataRead audit logs
 * https://cloud.google.com/bigquery/docs/reference/auditlogs/rest/Shared.Types/BigQueryAuditMetadata#bigqueryauditmetadata.tabledataread
 */
tableDataReadEvent AS (
  SELECT
    CONCAT(
      SPLIT(
        JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
            '$.tableDataRead.jobName'),
            "/")[SAFE_OFFSET(1)],
      ":",
      SPLIT(
        JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
          '$.tableDataRead.jobName'),
            "/")[SAFE_OFFSET(3)]
    ) AS jobId,
    ARRAY_AGG(
      protopayload_auditlog.resourceName
      IGNORE NULLS ORDER BY protopayload_auditlog.resourceName) AS tableDataReadTableName,
    ARRAY_AGG(STRUCT(
      SPLIT(TRIM(TRIM(JSON_EXTRACT(protopayload_auditlog.metadataJson, '$.tableDataRead.fields'),
      '["'),'"]'),'","')
      AS fields) IGNORE NULLS ORDER BY protopayload_auditlog.resourceName) AS tableDataReadFields,
    ARRAY_AGG(
      CAST(JSON_EXTRACT(protopayload_auditlog.metadataJson, '$.tableDataRead.fieldsTruncated') AS BOOL)
      IGNORE NULLS ORDER BY protopayload_auditlog.resourceName) AS tableDataReadFieldsTruncated,
    ARRAY_AGG(STRUCT(
      SPLIT(TRIM(TRIM(JSON_EXTRACT(protopayload_auditlog.metadataJson,'$.tableDataRead.categories'),
      '["'),'"]'),'","')
      AS categories) IGNORE NULLS ORDER BY protopayload_auditlog.resourceName) AS tableDataReadCategories,
    ARRAY_AGG(
      CAST(JSON_EXTRACT(protopayload_auditlog.metadataJson, '$.tableDataRead.categoriesTruncated') AS BOOL)
      IGNORE NULLS ORDER BY protopayload_auditlog.resourceName) AS tableDataReadCategoriesTruncated,
    ARRAY_AGG(
      JSON_EXTRACT(protopayload_auditlog.metadataJson, '$.tableDataRead.reason')
      IGNORE NULLS ORDER BY protopayload_auditlog.resourceName) AS tableDataReadReason,
    ARRAY_AGG(
      JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson, '$.tableDataRead.jobName')
      IGNORE NULLS ORDER BY protopayload_auditlog.resourceName) AS tableDataReadJobName,
    ARRAY_AGG(
      JSON_EXTRACT(protopayload_auditlog.metadataJson, '$.tableDataRead.sessionName')
      IGNORE NULLS ORDER BY protopayload_auditlog.resourceName) AS tableDataReadSessionName,
  FROM `project_id.dataset_id.cloudaudit_googleapis_com_data_access`
  GROUP BY jobId
),
/*
 * TableDataChange: Table data change event.
 * https://cloud.google.com/bigquery/docs/reference/auditlogs/rest/Shared.Types/BigQueryAuditMetadata#bigqueryauditmetadata.tabledatachange
 */
tableDataChangeEvent AS (
  SELECT
    CONCAT(
      SPLIT(
        JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson, '$.tableDataChange.jobName'),
      "/")[SAFE_OFFSET(1)],
      ":",
      SPLIT(
        JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
          '$.tableDataChange.jobName'),
        "/")[SAFE_OFFSET(3)]
    ) AS jobId,
    JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.tableDataChange.deletedRowsCount') AS tableDataChangeDeletedRowsCount,
    JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.tableDataChange.insertedRowsCount') AS tableDataChangeInsertedRowsCount,
    CAST(JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.tableDataChange.truncated') AS BOOL) AS tableDataChangeTruncated,
    JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.tableDataChange.reason') AS tableDataChangeReason,
    JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.tableDataChange.jobName') AS tableDataChangeJobName,
  FROM `project_id.dataset_id.cloudaudit_googleapis_com_data_access`
),
/*
 * ModelDeletion: Model deletion event.
 * https://cloud.google.com/bigquery/docs/reference/auditlogs/rest/Shared.Types/BigQueryAuditMetadata#bigqueryauditmetadata.modeldeletion
 */
modelDeletionEvent AS (
  SELECT
    JSON_EXTRACT(protopayload_auditlog.metadataJson,
         '$.modelDeletion.reason') AS modelDeletionReason,
    JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
         '$.modelDeletion.jobName') AS modelDeletionJobName,
    CONCAT(
     SPLIT(
       JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
           '$.modelDeletion.jobName'),
           "/")[SAFE_OFFSET(1)],
     ":",
     SPLIT(
       JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
         '$.modelDeletion.jobName'),
           "/")[SAFE_OFFSET(3)]
   ) AS jobId,
  FROM `project_id.dataset_id.cloudaudit_googleapis_com_activity`
),
/*
 * ModelCreation: Model creation event.
 * https://cloud.google.com/bigquery/docs/reference/auditlogs/rest/Shared.Types/BigQueryAuditMetadata#bigqueryauditmetadata.modelcreation
 */
modelCreationEvent AS (
  SELECT
    JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.modelCreation.reason')  AS modelCreationReason,
    JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.modelCreation.jobName') AS modelCreationJobName,
    CONCAT(
      SPLIT(
        JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
          '$.modelCreation.jobName'),
           "/")[SAFE_OFFSET(1)],
      ":",
      SPLIT(
        JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
        '$.modelCreation.jobName'),
         "/")[SAFE_OFFSET(3)]
    ) AS jobId,
    JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.modelCreation.model.modelName')  AS modelCreationModelName,
    JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.modelCreation.model.modelInfo.entityInfo.friendlyName')  AS modelCreationEntityInfoFriendlyName,
    JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.modelCreation.model.modelInfo.entityInfo.description')  AS modelCreationEntityInfoDescription,
    JSON_EXTRACT(protopayload_auditlog.metadataJson,
      '$.modelCreation.model.modelInfo.entityInfo.labels')  AS modelCreationEntityInfoLabels,
    JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.modelCreation.model.expireTime')  AS modelCreationModelExpireTime,
    JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.modelCreation.model.createTime')  AS modelCreationModelCreateTime,
    JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.modelCreation.model.updateTime')  AS modelCreationModelUpdateTime,
    JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.modelCreation.model.encryption.kmsKeyName')  AS modelCreationEncryptionKmsKeyName,
  FROM `project_id.dataset_id.cloudaudit_googleapis_com_activity`
),
/*
 * ModelMetadataChange: Model metadata change event.
 * https://cloud.google.com/bigquery/docs/reference/auditlogs/rest/Shared.Types/BigQueryAuditMetadata#bigqueryauditmetadata.modelmetadatachange
 */
modelMetadataChangeEvent AS (
  SELECT
    JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.modelMetadataChange.reason') AS modelMetadataChangeReason,
    JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.modelMetadataChange.jobName') AS modelMetadataChangeJobName,
    CONCAT(
      SPLIT(
        JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
          '$.modelMetadataChange.jobName'),
           "/")[SAFE_OFFSET(1)],
      ":",
      SPLIT(
        JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
        '$.modelMetadataChange.jobName'),
         "/")[SAFE_OFFSET(3)]
    ) AS jobId,
    JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.modelMetadataChange.model.modelName') AS modelMetadataChangeModelName,
    JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.modelMetadataChange.model.modelInfo.entityInfo.friendlyName') AS modelMetadataChangeEntityInfoFriendlyName,
    JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.modelMetadataChange.model.modelInfo.entityInfo.description') AS modelMetadataChangeEntityInfoDescription,
    JSON_EXTRACT(protopayload_auditlog.metadataJson,
      '$.modelMetadataChange.model.modelInfo.entityInfo.labels') AS modelMetadataChangeEntityInfoLabels,
    JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.modelMetadataChange.model.expireTime') AS modelMetadataChangeModelExpireTime,
    JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.modelMetadataChange.model.createTime') AS modelMetadataChangeModelCreateTime,
    JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.modelMetadataChange.model.updateTime') AS modelMetadataChangeModelUpdateTime,
    JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.modelMetadataChange.model.encryption.kmsKeyName') AS modelMetadataChangeEncryptionKmsKeyName,
  FROM `project_id.dataset_id.cloudaudit_googleapis_com_activity`
),
/*
 * ModelDataChange: Model data change event.
 * https://cloud.google.com/bigquery/docs/reference/auditlogs/rest/Shared.Types/BigQueryAuditMetadata#bigqueryauditmetadata.modeldatachange
 */
modelDataChangeEvent AS (
  SELECT
    JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.modelDataChange.reason') AS modelDataChangeReason,
    JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.modelDataChange.jobName') AS modelDataChangeJobName,
    CONCAT(
      SPLIT(
        JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
            '$.modelDataChange.jobName'),
            "/")[SAFE_OFFSET(1)],
      ":",
      SPLIT(
        JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
          '$.modelDataChange.jobName'),
            "/")[SAFE_OFFSET(3)]
    ) AS jobId,
  FROM `project_id.dataset_id.cloudaudit_googleapis_com_data_access`
),
/*
 * RoutineCreation: Routine creation event.
 * https://cloud.google.com/bigquery/docs/reference/auditlogs/rest/Shared.Types/BigQueryAuditMetadata#bigqueryauditmetadata.routinecreation
 */
routineCreationEvent AS (
  SELECT
    JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.routineCreation.routine.routineName') AS routineCreationName,
    JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.routineCreation.routine.createTime') AS routineCreationCreateTime,
    JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.routineCreation.routine.updateTime') AS routineCreationUpdateTime,
    JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.routineCreation.reason') AS routineCreationReason,
    JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.routineCreation.jobName') AS routineCreationJobName,
    CONCAT(
      SPLIT(
        JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
            '$.routineCreation.jobName'),
            "/")[SAFE_OFFSET(1)],
      ":",
      SPLIT(
        JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
          '$.routineCreation.jobName'),
            "/")[SAFE_OFFSET(3)]
    ) AS jobId,
  FROM `project_id.dataset_id.cloudaudit_googleapis_com_activity`
),
/*
 * RoutineChange: Routine change event
 * https://cloud.google.com/bigquery/docs/reference/auditlogs/rest/Shared.Types/BigQueryAuditMetadata#bigqueryauditmetadata.routinechange
 */
routineChangeEvent AS (
  SELECT
    JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.routineChange.routine.routineName') AS routineChangeName,
    JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.routineChange.routine.createTime') AS routineChangeCreateTime,
    JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.routineChange.routine.updateTime') AS routineChangeUpdateTime,
    JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.routineChange.reason') AS routineChangeReason,
    JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.routineChange.jobName') AS routineChangeJobName,
    CONCAT(
      SPLIT(
        JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
            '$.routineChange.jobName'),
            "/")[SAFE_OFFSET(1)],
      ":",
      SPLIT(
        JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
          '$.routineChange.jobName'),
            "/")[SAFE_OFFSET(3)]
    ) AS jobId,
  FROM `project_id.dataset_id.cloudaudit_googleapis_com_activity`
),
/*
 * RoutineDeletion: Routine deletion event
 * https://cloud.google.com/bigquery/docs/reference/auditlogs/rest/Shared.Types/BigQueryAuditMetadata#bigqueryauditmetadata.routinedeletion
 */
routineDeletionEvent AS (
  SELECT
    JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.routineDeletion.routine.routineName') AS routineDeletionName,
    JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.routineDeletion.routine.createTime') AS routineDeletionCreateTime,
    JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.routineDeletion.routine.updateTime') AS routineDeletionUpdateTime,
    JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.routineDeletion.reason') AS routineDeletionReason,
    JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
      '$.routineDeletion.jobName') AS routineDeletionJobName,
    CONCAT(
      SPLIT(
        JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
            '$.routineDeletion.jobName'),
            "/")[SAFE_OFFSET(1)],
      ":",
      SPLIT(
        JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
          '$.routineDeletion.jobName'),
            "/")[SAFE_OFFSET(3)]
    ) AS jobId,
  FROM `project_id.dataset_id.cloudaudit_googleapis_com_activity`
) -- End of WITH clauses
SELECT
  principalEmail,
  callerIp,
  callerSuppliedUserAgent,
  timestamp AS eventTimestamp,
  serviceName,
  methodName,
  eventName,
  projectId,
  jobId,
  parentJobId,
  IF(jobChangeJobName IS NULL, False, True) AS hasJobChangeEvent,
  IF(tableChangeJobName IS NULL, False, True) AS hasTableChangeEvent,
  IF(tableCreationJobName IS NULL, False, True) AS hasTableCreationEvent,
  IF(tableDeletionJobName IS NULL, False, True) AS hasTableDeletionEvent,
  IF(tableDataReadJobName IS NULL, False, True) AS hasTableDataReadEvent,
  IF(tableDataChangeJobName IS NULL, False, True) AS hasTableDataChangeEvent,
  IF(modelDeletionJobName IS NULL, False, True) AS hasModelDeletionEvent,
  IF(modelCreationJobName IS NULL, False, True) AS hasModelCreationEvent,
  IF(modelMetadataChangeJobName IS NULL, False, True) AS hasModelMetadataChangeEvent,
  IF(routineCreationJobName IS NULL, False, True) AS hasRoutineCreationEvent,
  IF(routineChangeJobName IS NULL, False, True) AS hasRoutineChangeEvent,
  IF(routineDeletionJobName IS NULL, False, True) AS hasRoutineDeletionEvent,
  STRUCT(
    EXTRACT(MINUTE FROM jobStatsStartTime) AS minuteOfDay,
    EXTRACT(HOUR FROM jobStatsStartTime) AS hourOfDay,
    EXTRACT(DAYOFWEEK FROM jobStatsStartTime) - 1 AS dayOfWeek,
    EXTRACT(DAYOFYEAR FROM jobStatsStartTime) AS dayOfYear,
    EXTRACT(WEEK FROM jobStatsStartTime) AS week,
    EXTRACT(MONTH FROM jobStatsStartTime) AS month,
    EXTRACT(QUARTER FROM jobStatsStartTime) AS quarter,
    EXTRACT(YEAR FROM jobStatsStartTime) AS year
  ) AS jobStartDate,
  jobStatsRuntimeMs AS jobRuntimeMs,
  jobStatsRuntimeSecs AS jobRuntimeSec,
  REGEXP_CONTAINS(jobId, 'beam') AS isBeamJob,
  REGEXP_CONTAINS(queryConfigQuery, 'cloudaudit_googleapis_com_') AS isAuditDashboardQuery,
  SAFE_DIVIDE(jobStatsTotalSlotMs, jobStatsRuntimeMs) AS avgSlots,
  /*
   * The following statement breaks down the query into minute buckets
   * and provides the average slot usage within that minute. This is a
   * crude way of making it so you can retrieve the average slot utilization
   * for a particular minute across multiple queries.
   */
  ARRAY(
    SELECT
      STRUCT(
        TIMESTAMP_TRUNC(
          TIMESTAMP_ADD(jobStatsStartTime, INTERVAL bucket_num MINUTE), MINUTE
        ) AS time,
        SAFE_DIVIDE(jobStatsTotalSlotMs, jobStatsRuntimeMs) AS avgSlotUsage
      )
    FROM UNNEST(GENERATE_ARRAY(1, jobStatsExecutionMinuteBuckets)) AS bucket_num
  ) AS jobExecutionTimeline,
  ARRAY_LENGTH(queryJobStatsReferencedTables) AS totalTablesProcessed,
  ARRAY_LENGTH(queryJobStatsReferencedViews) AS totalViewsProcessed,
  (SAFE_DIVIDE(queryJobStatsTotalBilledBytes, pow(2,30))) AS totalBilledGigabytes,
  (SAFE_DIVIDE(queryJobStatsTotalBilledBytes, pow(2,40))) AS totalBilledTerabytes,
  (SAFE_DIVIDE(queryJobStatsTotalBilledBytes, pow(2,40))) * 5 AS estimatedCostUsd,
  CONCAT(
    queryConfigDestinationTableDatasetId, '.',
    queryConfigDestinationTableId) AS queryDestinationTableRelativePath,
  CONCAT(
    queryConfigDestinationTableProjectId, '.',
    queryConfigDestinationTableDatasetId, '.',
    queryConfigDestinationTableId) AS queryDestinationTableAbsolutePath,
  queryConfigDestinationTableProjectId AS queryDestinationTableProjectId,
  queryConfigDestinationTableDatasetId AS queryDestinationTableDatasetId,
  queryConfigDestinationTableId AS queryDestinationTableId,
  /*
   * jobChange STRUCT
   * https://cloud.google.com/bigquery/docs/reference/auditlogs/rest/Shared.Types/BigQueryAuditMetadata#bigqueryauditmetadata.jobchange
  */
  STRUCT(
    jobChangeJobName AS jobName,
    /*
     * jobConfig STRUCT
     * https://cloud.google.com/bigquery/docs/reference/auditlogs/rest/Shared.Types/BigQueryAuditMetadata#bigqueryauditmetadata.jobconfig
     */
    STRUCT(
      jobConfigType AS type,
      jobConfigLabels AS labels,
      /*
       * queryConfig STRUCT
       * https://cloud.google.com/bigquery/docs/reference/auditlogs/rest/Shared.Types/BigQueryAuditMetadata#bigqueryauditmetadata.query
       */
      STRUCT(
        queryConfigQuery AS query,
        queryConfigQueryTruncated AS queryTruncated,
        queryConfigDestinationTable AS destinationTable,
        queryConfigCreateDisposition AS createDisposition,
        queryConfigWriteDisposition AS writeDisposition,
        queryConfigDefaultDataset AS defaultDataset,
        STRUCT(
          tableDefinitionsName AS name,
          tableDefinitionsSourceUris AS sourceUris
        ) AS tableDefinitions,
        queryConfigPriority AS priority,
        STRUCT(
          queryConfigDestinationTableEncryptionKmsKeyName AS kmsKeyName
        ) AS destinationTableEncryption,
        queryConfigStatementType AS statementType
      ) AS queryConfig,
      /*
       * loadConfig STRUCT
       * https://cloud.google.com/bigquery/docs/reference/auditlogs/rest/Shared.Types/BigQueryAuditMetadata#bigqueryauditmetadata.load
       */
      STRUCT(
        loadConfigSourceUris AS sourceUris,
        loadConfigSourceUrisTruncated AS sourceUrisTruncated,
        loadConfigSchemaJson AS schemaJson,
        loadConfigSchemaJsonTruncated AS schemaJsonTruncated,
        loadConfigDestinationTable AS destinationTable,
        loadConfigCreateDisposition AS createDisposition,
        loadConfigWriteDisposition AS writeDisposition,
        STRUCT(
          loadConfigDestinationTableEncryptionKmsKeyName AS kmsKeyName
        ) AS destinationTableEncryption
      ) AS loadConfig,
      /*
       * extractConfig STRUCT
       * https://cloud.google.com/bigquery/docs/reference/auditlogs/rest/Shared.Types/BigQueryAuditMetadata#bigqueryauditmetadata.extract
       */
      STRUCT(
        extractConfigDestinationUris AS destinationUris,
        extractConfigDestinationUrisTruncated AS destinationUrisTruncated,
        extractConfigSourceTable AS sourceTable
      ) AS extractConfig,
      /*
       * tableCopyConfig STRUCT
       * https://cloud.google.com/bigquery/docs/reference/auditlogs/rest/Shared.Types/BigQueryAuditMetadata#bigqueryauditmetadata.tablecopy
       */
      STRUCT(
        tableCopySourceTables AS sourceTables,
        tableCopyConfigSourceTablesTruncated AS configSourceTablesTruncated,
        tableCopyConfigDestinationTable AS configDestinationTable,
        tableCopyConfigCreateDisposition AS configCreateDisposition,
        tableCopyConfigWriteDisposition AS configWriteDisposition,
        STRUCT(
          tableCopyConfigDestinationTableEncryptionKmsKeyName AS kmsKeyName
        ) AS destinationTableEncryption
      ) AS tableCopyConfig
    ) AS jobConfig,
    /*
     * jobStatus STRUCT
     * https://cloud.google.com/bigquery/docs/reference/auditlogs/rest/Shared.Types/BigQueryAuditMetadata#bigqueryauditmetadata.JobStatus
     */
    STRUCT(
      jobStatusJobState AS jobState,
      STRUCT(
        jobStatusErrorResultCode AS code,
        jobStatusErrorResultMessage AS message,
        jobStatusErrorResultDetails AS details
      ) AS errorResult,
      jobStatusErrorsArray AS errors
    ) AS jobStatus,
    /*
     * jobStats STRUCT
     * https://cloud.google.com/bigquery/docs/reference/auditlogs/rest/Shared.Types/BigQueryAuditMetadata#bigqueryauditmetadata.jobstats
     */
    STRUCT(
      jobStatsCreateTime AS createTime,
      jobStatsStartTime AS startTime,
      jobStatsEndTime AS endTime,
      jobStatsTotalSlotMs AS totalSlotMs,
      STRUCT(
        jobStatsReservationUsageName AS name,
        jobStatsReservationUsageSlotMs AS slotMs
      ) AS reservationUsage,
      jobStatsParentJobName AS parentJobName,
      STRUCT(
        queryJobStatsTotalProcessedBytes AS totalProcessedBytes,
        queryJobStatsTotalBilledBytes AS totalBilledBytes,
        queryJobStatsBillingTier AS billingTier,
        queryJobStatsReferencedTables AS referencedTables,
        queryJobStatsReferencedViews AS referencedViews,
        queryJobStatsReferencedRoutines AS referencedRoutines,
        queryJobStatsOutputRowCount AS outputRowCount,
        queryJobStatsCacheHit AS cacheHit
      ) AS queryStats,
      STRUCT(
        loadJobStatsTotalOutputBytes AS totalOutputBytes
      ) AS loadStats
    ) AS jobStats
  ) AS jobChange,
  /*
   * Load job statistics
   * https://cloud.google.com/bigquery/docs/reference/auditlogs/rest/Shared.Types/BigQueryAuditMetadata#bigqueryauditmetadata.load_1
  */
  loadJobStatsTotalOutputBytes AS totalLoadOutputBytes,
  (SAFE_DIVIDE(loadJobStatsTotalOutputBytes, pow(2,30))) AS totalLoadOutputGigabytes,
  (SAFE_DIVIDE(loadJobStatsTotalOutputBytes, pow(2,40))) AS totalLoadOutputTerabytes,
  /*
   * tableChange STRUCT
   * https://cloud.google.com/bigquery/docs/reference/auditlogs/rest/Shared.Types/BigQueryAuditMetadata#bigqueryauditmetadata.tablechange
   */
  STRUCT(
    STRUCT(
      tableChangeTableName,
      STRUCT(
        tableChangeTableFriendlyName AS friendlyName,
        tableChangeTableDescription AS description,
        tableChangeTableLabels AS labels
      ) AS tableInfo,
      tableChangeTableSchemaJson AS schemaJson,
      tableChangeTableSchemaJsonTruncated AS schemaJsonTruncated,
      STRUCT(
        tableChangeViewDefinitionQuery AS query,
        tableChangeViewDefinitionTruncated AS queryTruncated
      ) AS view,
      tableChangeTableExpireTime AS expireTime,
      tableChangeTableCreateTime AS createTime,
      tableChangeTableUpdateTime AS updateTime,
      tableChangeTableTruncateTime AS truncateTime,
      STRUCT(
        tableChangeTableKmsKeyName AS kmsKeyName
      ) AS encryption
    ) AS table,
    tableChangeReason AS reason,
    tableChangeJobName AS jobName
  ) AS tableChange,
  /*
   * tableCreation STRUCT
   * https://cloud.google.com/bigquery/docs/reference/auditlogs/rest/Shared.Types/BigQueryAuditMetadata#bigqueryauditmetadata.tablecreation
   */
  STRUCT(
    STRUCT(
      tableCreationTableName,
      STRUCT(
        tableCreationTableFriendlyName AS friendlyName,
        tableCreationTableDescription AS description,
        tableCreationTableLabels AS labels
      ) AS tableInfo,
      tableCreationTableSchemaJson AS schemaJson,
      tableCreationTableSchemaJsonTruncated AS schemaJsonTruncated,
      STRUCT(
        tableCreationViewDefinitionQuery AS query,
        tableCreationViewDefinitionTruncated AS queryTruncated
      ) AS view,
      tableCreationTableExpireTime AS expireTime,
      tableCreationTableCreateTime AS createTime,
      tableCreationTableUpdateTime AS updateTime,
      tableCreationTableTruncateTime AS truncateTime,
      STRUCT(
        tableCreationTableKmsKeyName AS kmsKeyName
      ) AS encryption
    ) AS table,
    tableCreationReason AS reason,
    tableCreationJobName AS jobName
  ) AS tableCreation,
  /*
   * tableDeletion STRUCT
   * https://cloud.google.com/bigquery/docs/reference/auditlogs/rest/Shared.Types/BigQueryAuditMetadata#bigqueryauditmetadata.tabledeletion
   */
  STRUCT(
    tableDeletionReason AS reason,
    tableDeletionJobName AS jobName
  ) AS tableDeletion,
  /*
   * tableDataRead STRUCT
   * https://cloud.google.com/bigquery/docs/reference/auditlogs/rest/Shared.Types/BigQueryAuditMetadata#bigqueryauditmetadata.tabledataread
   */
  STRUCT(
    tableDataReadTableName AS tableName,
    tableDataReadFields AS fields,
    tableDataReadFieldsTruncated AS fieldsTruncated,
    tableDataReadCategories AS categories,
    tableDataReadCategoriesTruncated AS categoriesTruncated,
    tableDataReadReason AS reason,
    tableDataReadJobName AS jobName,
    tableDataReadSessionName AS sessionName
  ) AS tableDataRead,
  /*
   * tableDataChange STRUCT
   * https://cloud.google.com/bigquery/docs/reference/auditlogs/rest/Shared.Types/BigQueryAuditMetadata#bigqueryauditmetadata.tabledatachange
   */
  STRUCT(
    tableDataChangeDeletedRowsCount AS deletedRowsCount,
    tableDataChangeInsertedRowsCount AS insertedRowsCount,
    tableDataChangeTruncated AS truncated,
    tableDataChangeReason AS reason,
    tableDataChangeJobName AS jobName
  ) AS tableDataChange,
   /*
   * modelDeletion STRUCT
   * https://cloud.google.com/bigquery/docs/reference/auditlogs/rest/Shared.Types/BigQueryAuditMetadata#bigqueryauditmetadata.modeldeletion
   */
  STRUCT(
    modelDeletionReason AS reason,
    modelDeletionJobName AS jobName
  ) AS modelDeletion,
  /*
   * modelCreation STRUCT
   * https://cloud.google.com/bigquery/docs/reference/auditlogs/rest/Shared.Types/BigQueryAuditMetadata#bigqueryauditmetadata.modelcreation
   */
  STRUCT(
    STRUCT(
      modelCreationModelName AS modelName,
      STRUCT(
        modelCreationEntityInfoFriendlyName AS friendlyName,
        modelCreationEntityInfoDescription AS description,
        modelCreationEntityInfoLabels AS labels
      ) AS entityInfo,
      modelCreationModelExpireTime AS expireTime,
      modelCreationModelCreateTime AS createTime,
      modelCreationModelUpdateTime AS updateTime,
      STRUCT(modelCreationEncryptionKmsKeyName AS kmsKeyName) AS encryptionInfo
    ) AS model,
    modelCreationReason AS reason,
    modelCreationJobName AS jobName
  ) AS modelCreation,
  /*
   * modelMetadataChange STRUCT
   * https://cloud.google.com/bigquery/docs/reference/auditlogs/rest/Shared.Types/BigQueryAuditMetadata#bigqueryauditmetadata.modelmetadatachange
   */
  STRUCT(
    STRUCT(
      modelMetadataChangeModelName AS modelName,
      STRUCT(
        modelMetadataChangeEntityInfoFriendlyName AS friendlyName,
        modelMetadataChangeEntityInfoDescription AS description,
        modelMetadataChangeEntityInfoLabels AS labels
      ) AS entityInfo,
      modelMetadataChangeModelExpireTime AS expireTime,
      modelMetadataChangeModelCreateTime AS createTime,
      modelMetadataChangeModelUpdateTime AS updateTime,
      STRUCT(modelMetadataChangeEncryptionKmsKeyName AS kmsKeyName) AS encryptionInfo
    ) AS model,
    modelMetadataChangeReason AS reason,
    modelMetadataChangeJobName AS jobName
  ) AS modelMetadataChange,
  /*
   * modelDataChange STRUCT
   * https://cloud.google.com/bigquery/docs/reference/auditlogs/rest/Shared.Types/BigQueryAuditMetadata#bigqueryauditmetadata.modeldeletion
   */
  STRUCT(
    modelDataChangeReason AS reason,
    modelDataChangeJobName AS jobName
  ) AS modelDataChange,
  /*
   * routineCreation STRUCT
   * https://cloud.google.com/bigquery/docs/reference/auditlogs/rest/Shared.Types/BigQueryAuditMetadata#bigqueryauditmetadata.routinecreation
   */
  STRUCT(
    STRUCT(
      routineCreationName AS name,
      routineCreationCreateTime AS createTime,
      routineCreationUpdateTime AS updateTime
    ) AS routine,
    routineCreationReason AS reason,
    routineCreationJobName AS jobName
  ) AS routineCreation,
  /*
   * routineChange STRUCT
   * https://cloud.google.com/bigquery/docs/reference/auditlogs/rest/Shared.Types/BigQueryAuditMetadata#bigqueryauditmetadata.routinechange
   */
  STRUCT(
    STRUCT(
      routineChangeName AS name,
      routineChangeCreateTime AS createTime,
      routineChangeUpdateTime AS updateTime
    ) AS routine,
    routineChangeReason AS reason,
    routineChangeJobName AS jobName
  ) AS routineChange,
  /*
   * routineDeletion STRUCT
   * https://cloud.google.com/bigquery/docs/reference/auditlogs/rest/Shared.Types/BigQueryAuditMetadata#bigqueryauditmetadata.routinedeletion
   */
  STRUCT(
    STRUCT(
      routineDeletionName AS name,
      routineDeletionCreateTime AS createTime,
      routineDeletionUpdateTime AS updateTime
    ) AS routine,
    routineDeletionReason AS reason,
    routineDeletionJobName AS jobName
  ) AS routineDeletion
FROM jobChangeEvent
LEFT JOIN tableDataChangeEvent USING(jobId)
LEFT JOIN tableDataReadEvent USING(jobId)
LEFT JOIN tableCreationEvent USING(jobId)
LEFT JOIN tableChangeEvent USING(jobId)
LEFT JOIN tableDeletionEvent USING(jobId)
LEFT JOIN modelDeletionEvent USING(jobId)
LEFT JOIN modelMetadataChangeEvent USING(jobId)
LEFT JOIN modelCreationEvent USING(jobId)
LEFT JOIN modelDataChangeEvent USING(jobId)
LEFT JOIN routineCreationEvent USING(jobId)
LEFT JOIN routineChangeEvent USING(jobId)
LEFT JOIN routineDeletionEvent USING(jobId)
WHERE jobChangeAfter = "DONE"


text:
layout: default
title: CAS - Installation Requirements
---

# Installation Requirements

Requirements at a glance:

1. [Java](http://www.java.com) >=1.7
2. [Servlet container](http://tomcat.apache.org/) supporting servlet specification >=3.0
3. [Apache Maven](http://maven.apache.org/) >=3.3
4. Familiarity with the [Spring Framework](http://www.springsource.org/)
5. Internet connectivity

Depending on choice of configuration components, there may be additional requirements such as LDAP directory,
database, and caching infrastructure. In most cases, however, requirements should be self evident to deployers who
choose components with clear hardware and software dependencies. In any case where additional requirements are
not obvious, the discussion of component configuration should mention system, software, hardware, and other
requirements.

## Servlet Containers
There is no officially supported servlet container for CAS, but [Apache Tomcat](http://tomcat.apache.org/) is the most
commonly used. Support for a particular servlet container depends on the expertise of community members, but the
following are known to work well and should receive first-class support on the
[Community Discussion Mailing List](../Mailing-Lists.html):

* [JBoss](http://www.jboss.org/)
* [Jetty](http://www.eclipse.org/jetty/)
* [GlassFish](http://glassfish.java.net/)
* [WebSphere](http://www.ibm.com/software/websphere/)

## Apache Maven
CAS uses Maven for building and creating a deployable package for installation into a Java servlet container. Maven is
also strongly recommended for configuration management required for the CAS installation process. CAS is fundamentally
a complex software product that becomes embedded and tighly integrated into the software environment of an institution.
For this reason it tends to require customization well beyond turnkey solutions, and the integration requirements tend
to change over time. A source-based installation process like
[Maven WAR overlay](../installation/Maven-Overlay-Installation.html) provides a straightforward and flexible solution
to complex and dynamic requirements. While it admittedly requires a high up-front cost in learning, it reaps numerous
benefits in the long run

## Spring Framework
CAS uses the many aspects of the Spring Framework; most notably,
[Spring MVC](http://static.springsource.org/spring/docs/3.2.x/spring-framework-reference/html/mvc.html) and
[Spring Webflow](http://www.springsource.org/spring-web-flow). Spring provides a complete and extensible framework for
the core CAS codebase as well as for deployers; it's straightforward to customize or extend CAS behavior by hooking
CAS and Spring API extension points. General knowledge of Spring is beneficial to understanding the interplay among
some framework compoents, but it's not strictly required. The XML-based configuration used to configure CAS and Spring
components, however, is a core concern for installation, customization, and extension. Competence with XML generally
and the
[Spring IOC Container](http://static.springsource.org/spring/docs/3.2.x/spring-framework-reference/html/beans.html)
in particular are prerequisites to CAS installation.

## Internet Connectivity
Internet connectivity is generally required for the build phase of any Maven-based project, including the recommended
Maven WAR overlays used to install CAS. Maven resolves dependencies by searching online repositories containing
artifacts (jar files in most cases) that are downloaded and installed locally. While it is possible to override this
behavior by alterning Maven configuration settings, it is considered advanced usage and not supported.

A common solution to overcoming lack of Internet connectivity on a CAS server is to build CAS on a dedicated build
host with internet connectivity. The `cas.war` file produced by the build is subsequently copied to the CAS server
for deployment.

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

  <title>Unauthorized (401)</title>

401 - You do not have the required permissions to access this page.


text:
package io.atomix.catalyst.util;

import static org.testng.Assert.*;

import org.testng.annotations.Test;

@Test
public class LRUCacheTest {

  public void testLRUBehavior() {
    LRUCache<String, String> cache = new LRUCache<>(2);
    cache.put("key1", "v1");
    cache.put("key2", "v2");

    // key3 should replace key1
    cache.put("key3", "v3");
    assertFalse(cache.containsKey("key1"));

    // this marks key2 as most recently used
    assertEquals("v2", cache.get("key2"));

    // key4 should replace key3
    cache.put("key4", "v4");
    assertFalse(cache.containsKey("key3"));
  }
}


text:
OPENSHIFT_VERSION=v3.9
while getopts c:f:i:oh opt; do
    case $opt in
        f)
            FLUSH_IPTABLES="true"
            ;;
        h)
            echo "Usage: oshinko-setup.sh [-f]"
            echo "Example: oshinko-setup.sh -i 192.168.1.10"
            echo "If -o is used, it will be the version of openshift used, default is v3.9"
            echo "If -i is used, the value will be the host used for your openshift cluster"
            echo "If -f is used, 'sudo iptables -F' will be issued before oc cluster up"
            echo "    It may help resolve a potential skydns issue"
            echo ""
            exit
            ;;
        i)
            HOST_IP_ADDRESS=$OPTARG
            ;;
        o)
            OPENSHIFT_VERSION=$OPTARG
            ;;
        \?)
            echo "Invalid option: -$OPTARG" >&2
            exit
            ;;
    esac
done

function setup_openshift() {
  sudo docker cp $(docker create docker.io/openshift/origin:$OPENSHIFT_VERSION):/bin/oc /usr/local/bin/oc
  oc cluster up --version=$OPENSHIFT_VERSION --public-hostname=$HOST_IP_ADDRESS
  docker pull docker.io/radanalyticsio/openshift-spark
  oc login -u system:admin
  export REGISTRY_URL=$(oc get svc -n default docker-registry -o jsonpath='{.spec.clusterIP}:{.spec.ports[0].port}')
  oc login -u developer -p developer
}

function install_extension() {
  export SOURCE_TREE="radanalyticsio/oshinko-console"
  oc login -u system:admin
  oc new-project oshinko-console
  oc new-app centos/httpd-24-centos7~https://github.com/${SOURCE_TREE} --context-dir=dist
  sleep 30s
  oc create route edge --service oshinko-console
  sleep 2s
  export CONSOLE_BASE_ROUTE=$(oc get route oshinko-console --template={{.spec.host}})
  # change the console config to reference our extension
  oc project openshift-web-console
  oc get configmap webconsole-config -o yaml > webconfig.yaml
  sed -i "s#scriptURLs\: \[\]#scriptURLs\:\n        - https://$CONSOLE_BASE_ROUTE/scripts/scripts.js\n        - https://$CONSOLE_BASE_ROUTE/scripts/templates.js#" webconfig.yaml
  sed -i "s#stylesheetURLs: \[\]#stylesheetURLs\:\n        - https://$CONSOLE_BASE_ROUTE/styles/oshinko.css\n#" webconfig.yaml
  oc replace -f webconfig.yaml
  echo "Here is the updated config for webconsole"
  oc get configmap webconsole-config -o yaml
  #restart web console
  oc project openshift-web-console
  export OLD_CONSOLE_POD=$(oc get pods -l webconsole=true --template="{{range .items}}{{.metadata.name}}{{end}}")
  oc delete pod $OLD_CONSOLE_POD
  sleep 20s
  export NEW_CONSOLE_POD=$(oc get pods -l webconsole=true --template="{{range .items}}{{.metadata.name}}{{end}}")
  oc logs $NEW_CONSOLE_POD
  echo "Listing of all pods"
  oc get pods --all-namespaces
}

function setup_docker_insecure_registry() {
  rpm -qa | grep -qw git || sudo dnf -y install git
  rpm -qa | grep -qw docker || sudo dnf -y install docker
  sudo systemctl start docker
  sudo sed -i -e "/^# INSECURE_REGISTRY/{ s/.*/INSECURE_REGISTRY='--insecure-registry 172.30.0.0\/16'/ }" /etc/sysconfig/docker
  sudo systemctl restart docker
}

if [ "$FLUSH_IPTABLES" == "true" ]
then
    echo "Flushing IP tables"
    sudo iptables -F
else
    echo "Not flushing IP tables"
fi

setup_docker_insecure_registry
setup_openshift
install_extension


text:
package com.brew.climbon.helpers;

import android.text.Editable;
import android.text.Html;
import android.text.Spanned;
import android.text.style.BulletSpan;
import android.text.style.LeadingMarginSpan;

import org.xml.sax.XMLReader;

import java.util.Stack;

public class TagHandler implements Html.TagHandler {
  /**
   * Keeps track of lists (ol, ul). On bottom of Stack is the outermost list
   * and on top of Stack is the most nested list
   */
  Stack<String> lists = new Stack<String>();
  /**
   * Tracks indexes of ordered lists so that after a nested list ends
   * we can continue with correct index of outer list
   */
  Stack<Integer> olNextIndex = new Stack<Integer>();
  /**
   * List indentation in pixels. Nested lists use multiple of this.
   */
  private static final int indent = 20;
  private static final int listItemIndent = indent * 2;
  private static final BulletSpan bullet = new BulletSpan(indent);

  @Override
  public void handleTag(boolean opening, String tag, Editable output, XMLReader xmlReader) {
    if (tag.equalsIgnoreCase("ul")) {
      if (opening) {
        lists.push(tag);
      } else {
        lists.pop();
      }
    }
    else if (tag.equalsIgnoreCase("ol")) {
      if (opening) {
        lists.push(tag);
        olNextIndex.push(Integer.valueOf(1)).toString();//TODO: add support for lists starting other index than 1
      } else {
        lists.pop();
        olNextIndex.pop().toString();
      }
    }
    else if (tag.equalsIgnoreCase("li")) {
      if (opening) {
        if (output.length() > 0 && output.charAt(output.length()-1) != '\n') {
          output.append("\n");
        }
        String parentList = lists.peek();
        if (parentList.equalsIgnoreCase("ol")) {
          start(output, new Ol());
          output.append(olNextIndex.peek().toString()+". ");
          olNextIndex.push(Integer.valueOf(olNextIndex.pop().intValue() + 1));
        }
        else if (parentList.equalsIgnoreCase("ul")) {
          start(output, new Ul());
        }
      }
      else {
        if (lists.peek().equalsIgnoreCase("ul")) {
          if ( output.charAt(output.length()-1) != '\n' ) {
            output.append("\n");
          }
          // Nested BulletSpans increases distance between bullet and text, so we must prevent it.
          int bulletMargin = indent;
          if (lists.size()>1) {
            bulletMargin = indent-bullet.getLeadingMargin(true);
            if (lists.size()>2) {
              // This get's more complicated when we add a LeadingMarginSpan into the same line:
              // we have also counter it's effect to BulletSpan
              bulletMargin -= (lists.size()-2) * listItemIndent;
            }
          }
          BulletSpan newBullet = new BulletSpan(bulletMargin);
          end(output,
              Ul.class,
              new LeadingMarginSpan.Standard(listItemIndent * (lists.size()-1)),
              newBullet);
        }
        else if (lists.peek().equalsIgnoreCase("ol")) {
          if ( output.charAt(output.length()-1) != '\n' ) {
            output.append("\n");
          }
          int numberMargin = listItemIndent * (lists.size()-1);
          if (lists.size()>2) {
            // Same as in ordered lists: counter the effect of nested Spans
            numberMargin -= (lists.size()-2) * listItemIndent;
          }
          end(output,
              Ol.class,
              new LeadingMarginSpan.Standard(numberMargin));
        }
      }
    } else {
    }
  }

  private static void start(Editable text, Object mark) {
    int len = text.length();
    text.setSpan(mark, len, len, Spanned.SPAN_MARK_MARK);
  }

  private static void end(Editable text, Class<?> kind, Object... replaces) {
    int len = text.length();
    Object obj = getLast(text, kind);
    int where = text.getSpanStart(obj);
    text.removeSpan(obj);
    if (where != len) {
      for (Object replace: replaces) {
        text.setSpan(replace, where, len, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
      }
    }
    return;
  }

  private static Object getLast(Spanned text, Class<?> kind) {
		/*
		 * This knows that the last returned object from getSpans()
		 * will be the most recently added.
		 */
    Object[] objs = text.getSpans(0, text.length(), kind);
    if (objs.length == 0) {
      return null;
    }
    return objs[objs.length - 1];
  }

  private static class Ul { }
  private static class Ol { }

}


text:
package com.helger.ubl20.codelist;

import com.helger.commons.annotation.CodingStyleguideUnaware;
import com.helger.commons.annotation.Nonempty;
import com.helger.commons.id.IHasID;
import com.helger.commons.lang.EnumHelper;
import com.helger.commons.name.IHasDisplayName;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;

/**
 * This file was automatically generated from Genericode file TransportationStatusCode-2.0.gc. Do NOT edit!
 * It contains a total of 329 entries!
 * @author com.helger.ubl20.main.MainCreateEnumsGenericode20
 */
@CodingStyleguideUnaware
public enum ETransportationStatusCode20
    implements IHasID<String> , IHasDisplayName
{
    _1("1", "Arrival, completed"),
    _2("2", "Loading, authorized"),
    _3("3", "Arrival, in defective condition"),
    _4("4", "Defective equipment returned to service"),
    _5("5", "Process, begun"),
    _6("6", "Booking, completed"),
    _7("7", "Booking, cancelled"),
    _8("8", "Cleared, import restrictions"),
    _9("9", "Cleared, export restrictions"),
    _10("10", "Cleared, by agriculture, food or fisheries authorities"),
    _11("11", "Cleared, by port authority"),
    _12("12", "Cleared, by customs"),
    _13("13", "Collection/pick-up, completed"),
    _14("14", "Process, completed"),
    _15("15", "Consolidated"),
    _16("16", "Crossed border"),
    _17("17", "Customs clearance, refused"),
    _18("18", "Damaged in the course of Transport"),
    _19("19", "Equipment, damage quoted for"),
    _20("20", "Delayed, in the course of Transport"),
    _21("21", "Delivery, completed"),
    _22("22", "Delivery, completed as per instruction"),
    _23("23", "Delivery, not completed"),
    _24("24", "Departure, completed"),
    _25("25", "Departure, delayed"),
    _26("26", "Deramped"),
    _27("27", "Despatch, completed"),
    _28("28", "Stripped"),
    _29("29", "Unloaded"),
    _30("30", "Empty on inspection"),
    _31("31", "En route"),
    _32("32", "Equipment, returned from repair"),
    _33("33", "Equipment, sent for repair"),
    _34("34", "Equipment, repaired"),
    _35("35", "Forwarded to destination"),
    _36("36", "Not found"),
    _37("37", "Found"),
    _38("38", "Freight paid"),
    _39("39", "Released from bond"),
    _40("40", "Arrival, at port"),
    _41("41", "Handed over under continued responsibility"),
    _44("44", "Misrouted consignment corrected"),
    _45("45", "Arrival, consignee informed"),
    _46("46", "Moved, into bond"),
    _47("47", "Moved, into packing depot"),
    _48("48", "Loading, completed onto a means of transport"),
    _49("49", "Lost"),
    _50("50", "Manifested"),
    _51("51", "Onloaded from a means of transport"),
    _53("53", "Collection/pick-up, not completed"),
    _54("54", "Unidentifiable"),
    _57("57", "Not loaded onto a means of transport"),
    _58("58", "Equipment, off hire"),
    _59("59", "Premature onloading"),
    _60("60", "Equipment, on hire"),
    _61("61", "Outstanding claims settled"),
    _62("62", "Overlanded"),
    _63("63", "Not available for collection/pick-up"),
    _64("64", "Collection/pick-up, awaited"),
    _65("65", "Equipment, plugged-in"),
    _66("66", "Plundered"),
    _67("67", "Positioned"),
    _68("68", "Pre-informed"),
    _69("69", "Disposed of"),
    _70("70", "Ramped equipment"),
    _71("71", "Ready for Transport"),
    _72("72", "Receipt of goods fully acknowledged"),
    _73("73", "Receipt of goods partially acknowledged"),
    _74("74", "Received"),
    _75("75", "Consignee changed"),
    _76("76", "Transport re-arranged"),
    _77("77", "Refused, action"),
    _78("78", "Released"),
    _79("79", "Reloaded onto a means of transport"),
    _80("80", "Returned as instructed"),
    _81("81", "Returned wrecked"),
    _82("82", "Returned"),
    _83("83", "Sealed equipment"),
    _84("84", "Service ordered"),
    _85("85", "Short landed"),
    _86("86", "Short shipped"),
    _87("87", "Despatched, completed via a wrong route"),
    _88("88", "Split consignment"),
    _89("89", "Steam cleaned"),
    _90("90", "Movement stopped"),
    _91("91", "Stored"),
    _92("92", "Stowed"),
    _93("93", "Stuffed"),
    _94("94", "Stuffed and sealed"),
    _95("95", "Sub-lease notice in"),
    _96("96", "Sub-lease notice out"),
    _97("97", "Damage surveyed"),
    _98("98", "Transferred in"),
    _99("99", "Transferred out"),
    _100("100", "Transshipment"),
    _101("101", "Delayed in transit"),
    _102("102", "Unknown"),
    _103("103", "Equipment, unplugged"),
    _104("104", "Delivery refused, to be re-arranged"),
    _105("105", "Delivery, postponed"),
    _106("106", "Delivery refused"),
    _107("107", "Anomaly on arrival"),
    _108("108", "Delivery claim"),
    _109("109", "Delivery, impossible, delivery notice left"),
    _110("110", "Delivery, impossible, no delivery notice left"),
    _111("111", "Transport terminated"),
    _112("112", "Held, at consignee's disposal"),
    _113("113", "Delivery, in progress"),
    _114("114", "Delivery, accepted subject to further inspection"),
    _115("115", "Discrepancy"),
    _116("116", "Export inhibited"),
    _117("117", "Missing"),
    _118("118", "Stowed on deck"),
    _119("119", "Unable to be located"),
    _120("120", "Unacceptable condition"),
    _121("121", "Stowed under deck"),
    _123("123", "Accompanying documents delivered"),
    _124("124", "For transfer"),
    _125("125", "No status"),
    _126("126", "Customs clearance, in progress"),
    _127("127", "Departed, completed on a means of transport"),
    _128("128", "Awaiting customs import release"),
    _129("129", "In-bond movement"),
    _130("130", "Consignment received from shipper"),
    _131("131", "For transfer, to another carrier"),
    _132("132", "Loading, in progress"),
    _133("133", "Special loading operations"),
    _134("134", "Embarking passengers"),
    _135("135", "Unloading, in progress"),
    _136("136", "Special unloading"),
    _137("137", "Disembarking passengers"),
    _138("138", "Relocation of a means of transport"),
    _139("139", "Manoeuvring operations, entering port"),
    _140("140", "Manoeuvring operations, leaving port"),
    _141("141", "Manoeuvring operations, within the port"),
    _142("142", "Means of transport, under preparation"),
    _143("143", "Ballast loading"),
    _144("144", "Ballast unloading"),
    _145("145", "Cargo space under preparation"),
    _146("146", "Provisioning"),
    _147("147", "Provisioning, fuel"),
    _148("148", "Provisioning, water"),
    _149("149", "Provisioning, oil"),
    _150("150", "Provisioning, food"),
    _151("151", "Sanitary operations"),
    _152("152", "Fumigation operations"),
    _153("153", "Desinfestation operations"),
    _154("154", "Deratization operations"),
    _155("155", "Degasation operations"),
    _156("156", "Crew recruitment operation"),
    _157("157", "Training operations"),
    _158("158", "Salvage operations"),
    _159("159", "Loading, alongside"),
    _161("161", "Loading, at anchor"),
    _162("162", "Unloading, at wharf"),
    _163("163", "Unloading on board"),
    _164("164", "Unloading, at anchor"),
    _165("165", "Loading and unloading, simultaneously"),
    _166("166", "Idle time operations"),
    _167("167", "Technical operations"),
    _168("168", "Compass calibration"),
    _169("169", "Document, clearance operation"),
    _170("170", "Customs formalities operation"),
    _171("171", "Medical control operations"),
    _172("172", "Loading, preparation for"),
    _174("174", "Unloading, preparation for"),
    _175("175", "Unloading, polluted ballast"),
    _176("176", "Obtaining documents from shipping register"),
    _177("177", "Obtaining wreckage documentation"),
    _178("178", "Waiting, to enter or leave"),
    _179("179", "Waiting, for a pilot"),
    _180("180", "Waiting, for a tug"),
    _181("181", "Waiting, for day light"),
    _182("182", "Waiting, due to meteorological circumstances"),
    _183("183", "Waiting, to form a convoy"),
    _184("184", "Waiting, for action by authorities"),
    _185("185", "Waiting, due to a ban"),
    _186("186", "Waiting, for entry permission"),
    _187("187", "Waiting, due to an action taken by authorities"),
    _188("188", "Waiting, due to the terms of charter"),
    _189("189", "Waiting, for a location"),
    _190("190", "Waiting, for cargo"),
    _191("191", "Waiting, for workers"),
    _192("192", "Waiting, for storage area"),
    _193("193", "Waiting, for equipment"),
    _194("194", "Waiting, for other means of transport"),
    _195("195", "Waiting, for handling equipment"),
    _196("196", "Waiting, for on board handling equipment"),
    _197("197", "Waiting, for cargo to be ready for loading"),
    _198("198", "Waiting, for means of transport to be ready"),
    _199("199", "Waiting, due to damaged cargo"),
    _200("200", "Waiting, for operational periods"),
    _201("201", "Waiting, for repair and/or maintenance of the means of transport"),
    _202("202", "Waiting, for repair and/or maintenance of handling equipment"),
    _203("203", "Embarking passengers from tender"),
    _204("204", "Waiting, for a counter convoy to pass"),
    _205("205", "Delivery address outside delivery area"),
    _206("206", "Arrival, after means of transport departed"),
    _207("207", "Delivery refused, agent"),
    _208("208", "Seals, replaced"),
    _209("209", "Delivery, scheduled"),
    _210("210", "Delivery, unsuccessful attempt"),
    _211("211", "Delivery not completed, business closed"),
    _212("212", "Delivery, changed schedule"),
    _213("213", "Delivery, further address needed"),
    _214("214", "Computer system not in operation"),
    _215("215", "Delivery, awaiting credit approval"),
    _216("216", "Delivery, awaiting customer arrangements"),
    _218("218", "Damaged"),
    _219("219", "Delivery pending, awaiting specified dates/times/periods"),
    _220("220", "Destination incorrect"),
    _222("222", "Derailment"),
    _224("224", "Delivery, industrial dispute"),
    _225("225", "Operation affected by customer action"),
    _227("227", "Delivery, equipment failure"),
    _228("228", "Inspection required by authority"),
    _229("229", "Export suspended"),
    _231("231", "Missing, goods item"),
    _232("232", "Import suspended"),
    _233("233", "Incorrect picklist"),
    _234("234", "Incorrect address"),
    _235("235", "Industrial dispute"),
    _236("236", "Waiting, for instructions"),
    _238("238", "Means of transport, damaged"),
    _239("239", "Mechanical breakdown"),
    _240("240", "Mechanical inspection required"),
    _241("241", "Missing, document"),
    _242("242", "New delivery arrangements advised"),
    _243("243", "No recipient contact information"),
    _247("247", "Collection/pick-up, package not available"),
    _248("248", "Tracking number unknown"),
    _250("250", "Transport payment not received"),
    _251("251", "Refused, non-payment by payer"),
    _253("253", "Refused, no reason given"),
    _254("254", "Delivery, scheduled past cut-off time"),
    _255("255", "Shunted to siding"),
    _256("256", "Signature not required"),
    _258("258", "Special service required"),
    _260("260", "Tracking information unavailable"),
    _265("265", "Reason unknown"),
    _266("266", "Delivery delayed, adverse weather conditions"),
    _267("267", "Free storage time expired"),
    _269("269", "Delivery, consignee absent"),
    _270("270", "Delayed operation, local circumstances"),
    _271("271", "Delayed operation, consignee's instructions"),
    _272("272", "Delayed operation, consignor's instructions"),
    _273("273", "Delayed operation"),
    _274("274", "Incomplete address"),
    _275("275", "Delivery refused, purchase order cancelled"),
    _276("276", "Delivery refused, return to the consignor"),
    _277("277", "Delivery refused, inconsistent with purchase order"),
    _278("278", "Delivery refused, incorrect delivery date"),
    _279("279", "Delivery refused, automatic return"),
    _280("280", "Delivery refused, duplicate delivery"),
    _281("281", "Delivery refused, instructions requested"),
    _282("282", "Delivery refused, consignee's condition"),
    _283("283", "Delivery refused, delivery incomplete"),
    _284("284", "Delivery refused, not ordered"),
    _285("285", "Delivery refused, remainder not accepted"),
    _286("286", "Delivery refused, spoilt state"),
    _287("287", "Missing, contents"),
    _288("288", "Not on package list"),
    _291("291", "Delivery refused, collect freight charges not paid"),
    _292("292", "Delivery refused, reimbursement not paid"),
    _295("295", "Delivery refused, opened"),
    _297("297", "Delivery refused, commercial dispute"),
    _298("298", "Delivery refused, error on product or packaging"),
    _299("299", "Delivery refused, delivery date/time changed"),
    _300("300", "Document, received without goods"),
    _301("301", "Goods, received without documentation"),
    _302("302", "Overcarried consignment"),
    _306("306", "Document, found"),
    _307("307", "Damaged but deliverable"),
    _308("308", "Spoilt"),
    _309("309", "Packaging/equipment opened"),
    _310("310", "Processed as contractually agreed"),
    _311("311", "Claim folder opened"),
    _312("312", "Moved, completed"),
    _313("313", "Returned by recipient"),
    _314("314", "Delayed, at origin"),
    _315("315", "Held, by logistic service provider"),
    _316("316", "Incident occurred but accepted by ordering party"),
    _317("317", "Delivery party' premises closed during normal hours"),
    _318("318", "Delivery incomplete, time shortage"),
    _319("319", "Despatch, preparation error"),
    _320("320", "Undefined incident attributed to logistic server provider"),
    _321("321", "Instruction to despatch, received"),
    _322("322", "Despatch, under preparation"),
    _323("323", "Return in progress"),
    _324("324", "Instruction to despatch, cancelled"),
    _325("325", "Delivery refused, by recipient"),
    _326("326", "Goods, held by third party on instruction from owner"),
    _327("327", "Weight or volume loss"),
    _328("328", "Moved, internally"),
    _329("329", "Consignment partially stolen"),
    _330("330", "Consignment partially lost or missing"),
    _331("331", "Destroyed"),
    _332("332", "Action by logistics service provider"),
    _333("333", "Action by logistics service provider on instruction by owner"),
    _334("334", "Document, refused"),
    _335("335", "Seals, damaged"),
    _336("336", "Seals, broken"),
    _337("337", "Seals, tampered"),
    _338("338", "Collection/pick-up, business closed"),
    _339("339", "Collection/pick-up, changed schedule"),
    _340("340", "Collection/pick-up, further address needed"),
    _341("341", "Collection/pick-up, industrial dispute"),
    _342("342", "Collection/pick-up, equipment failure"),
    _343("343", "Document, incorrect"),
    _344("344", "Collection/pick-up, scheduled past cut-off time"),
    _345("345", "Collection/pick-up, adverse weather conditions"),
    _346("346", "Unloading, completed from a means of transport"),
    _347("347", "Deliverable"),
    _348("348", "Not deliverable"),
    _349("349", "Handed over"),
    _350("350", "Signature required"),
    _351("351", "Defined incident attributed to logistic server provider"),
    _352("352", "Delivery not completed, business closed, inventory count"),
    _353("353", "Delivery not completed, business closed on Saturday"),
    _354("354", "Delivery not completed, business closed on national holiday"),
    _355("355", "En route, via local route"),
    _356("356", "En route, via national route"),
    _357("357", "En route, via international route"),
    _358("358", "Transport terminated, mail not received"),
    _359("+359", "Bill of Lading issued"),
    _360("+360", "Cleared, by logistics service provider"),
    _361("+361", "Delivery, expected"),
    _362("+362", "Measured"),
    _363("+363", "Loading, ready");
    public static final String AGENCY_ID = "6";
    public static final String AGENCY_LONG_NAME = "United Nations Economic Commission for Europe";
    public static final String LIST_ID = "UN/ECE rec 24";
    public static final String LIST_VERSION = "Third Revision";
    private final String m_sID;
    private final String m_sDisplayName;

    private ETransportationStatusCode20(@Nonnull @Nonempty final String sID, @Nonnull final String sDisplayName) {
        m_sID = sID;
        m_sDisplayName = sDisplayName;
    }

    @Nonnull
    @Nonempty
    public String getID() {
        return m_sID;
    }

    @Nonnull
    public String getDisplayName() {
        return m_sDisplayName;
    }

    @Nullable
    public static ETransportationStatusCode20 getFromIDOrNull(@Nullable final String sID) {
        return EnumHelper.getFromIDOrNull(ETransportationStatusCode20 .class, sID);
    }

    @Nullable
    public static String getDisplayNameFromIDOrNull(@Nullable final String sID) {
        final ETransportationStatusCode20 eValue = ETransportationStatusCode20 .getFromIDOrNull(sID);
        return ((eValue == null)?null:eValue.getDisplayName());
    }
}


text:
using System;
using NetOffice;
using NetOffice.Attributes;
namespace NetOffice.OWC10Api.Enums
{
	 /// <summary>
	 /// SupportByVersion OWC10 1
	 /// </summary>
	[SupportByVersion("OWC10", 1)]
	[EntityType(EntityType.IsEnum)]
	public enum DscObjectTypeEnum
	{
		 /// <summary>
		 /// SupportByVersion OWC10 1
		 /// </summary>
		 /// <remarks>-1</remarks>
		 [SupportByVersion("OWC10", 1)]
		 dscobjUnknown = -1,

		 /// <summary>
		 /// SupportByVersion OWC10 1
		 /// </summary>
		 /// <remarks>1</remarks>
		 [SupportByVersion("OWC10", 1)]
		 dscobjSchemaRowsource = 1,

		 /// <summary>
		 /// SupportByVersion OWC10 1
		 /// </summary>
		 /// <remarks>2</remarks>
		 [SupportByVersion("OWC10", 1)]
		 dscobjSchemaField = 2,

		 /// <summary>
		 /// SupportByVersion OWC10 1
		 /// </summary>
		 /// <remarks>4</remarks>
		 [SupportByVersion("OWC10", 1)]
		 dscobjSchemaRelationship = 4,

		 /// <summary>
		 /// SupportByVersion OWC10 1
		 /// </summary>
		 /// <remarks>8</remarks>
		 [SupportByVersion("OWC10", 1)]
		 dscobjRecordsetDef = 8,

		 /// <summary>
		 /// SupportByVersion OWC10 1
		 /// </summary>
		 /// <remarks>16</remarks>
		 [SupportByVersion("OWC10", 1)]
		 dscobjPageRowsource = 16,

		 /// <summary>
		 /// SupportByVersion OWC10 1
		 /// </summary>
		 /// <remarks>32</remarks>
		 [SupportByVersion("OWC10", 1)]
		 dscobjPageField = 32,

		 /// <summary>
		 /// SupportByVersion OWC10 1
		 /// </summary>
		 /// <remarks>64</remarks>
		 [SupportByVersion("OWC10", 1)]
		 dscobjSublistRelationship = 64,

		 /// <summary>
		 /// SupportByVersion OWC10 1
		 /// </summary>
		 /// <remarks>128</remarks>
		 [SupportByVersion("OWC10", 1)]
		 dscobjLookupRelationship = 128,

		 /// <summary>
		 /// SupportByVersion OWC10 1
		 /// </summary>
		 /// <remarks>256</remarks>
		 [SupportByVersion("OWC10", 1)]
		 dscobjGroupingDef = 256,

		 /// <summary>
		 /// SupportByVersion OWC10 1
		 /// </summary>
		 /// <remarks>512</remarks>
		 [SupportByVersion("OWC10", 1)]
		 dscobjDatamodel = 512,

		 /// <summary>
		 /// SupportByVersion OWC10 1
		 /// </summary>
		 /// <remarks>1024</remarks>
		 [SupportByVersion("OWC10", 1)]
		 dscobjPageRelatedField = 1024,

		 /// <summary>
		 /// SupportByVersion OWC10 1
		 /// </summary>
		 /// <remarks>2048</remarks>
		 [SupportByVersion("OWC10", 1)]
		 dscobjParameterValue = 2048,

		 /// <summary>
		 /// SupportByVersion OWC10 1
		 /// </summary>
		 /// <remarks>4096</remarks>
		 [SupportByVersion("OWC10", 1)]
		 dscobjSchemaRelatedField = 4096,

		 /// <summary>
		 /// SupportByVersion OWC10 1
		 /// </summary>
		 /// <remarks>8192</remarks>
		 [SupportByVersion("OWC10", 1)]
		 dscobjSchemaParameter = 8192,

		 /// <summary>
		 /// SupportByVersion OWC10 1
		 /// </summary>
		 /// <remarks>16384</remarks>
		 [SupportByVersion("OWC10", 1)]
		 dscobjSchemaProperty = 16384,

		 /// <summary>
		 /// SupportByVersion OWC10 1
		 /// </summary>
		 /// <remarks>32768</remarks>
		 [SupportByVersion("OWC10", 1)]
		 dscobjSchemaDiagram = 32768
	}
}


text:
<?php

namespace Web;

$viewDir = realpath(__DIR__ . '/../view/');

return [
    'layout/layout' => $viewDir . '/layout/layout.phtml',
    'layout/auth' => $viewDir . '/layout/auth.phtml',

    'error/404' => $viewDir . '/error/404.phtml',
    'error/index' => $viewDir . '/error/index.phtml',

    'web/index/index' => $viewDir . '/index/index.phtml',
    'web/auth/login' => $viewDir . '/auth/login.phtml',
    'web/auth/logout' => $viewDir . '/auth/logout.phtml',
    'web/auth/migrate' => $viewDir . '/auth/migrate.phtml',
    'web/registration/index' => $viewDir . '/registration/index.phtml',
    'web/registration/disabled' => $viewDir . '/registration/disabled.phtml',

    'partials/formElement' => $viewDir . '/partials/formElement.phtml',
];


text:
@protocol addOrDeleteNew_pinGuiBtnClickDelegate <NSObject>
- (void) addOrDeleteNew_pinGuiClick:(NSInteger)sender;
@end
@interface addOrDeleteNew_pingGuiTableViewCell : UITableViewCell
@property (weak, nonatomic) IBOutlet UIButton *addBtn;
@property (weak, nonatomic) IBOutlet UIButton *deleteBtn;
- (IBAction)addOrDeleteBtnClick:(UIButton *)sender;
@property(nonatomic, strong)id<addOrDeleteNew_pinGuiBtnClickDelegate>delegate;

@end


text:
package org.drools.core.ruleunit;

import java.math.BigDecimal;

import org.drools.core.definitions.rule.impl.RuleImpl;
import org.drools.core.spi.Activation;
import org.drools.core.test.model.MockActivation;
import org.junit.Before;
import org.junit.Test;
import org.kie.api.runtime.rule.RuleUnit;

import static org.assertj.core.api.Assertions.assertThat;

public class GuardTest {

    private RuleUnit guardedUnit;
    private RuleImpl guardingRule;
    private Guard guard;

    @Before
    public void prepareGuard() {
        guardedUnit = new TestRuleUnit(new Integer[]{}, BigDecimal.TEN);
        guardingRule = new RuleImpl();
        guard = new Guard(guardedUnit, guardingRule);
    }

    @Test
    public void testEquals() {
        assertThat(guard).isEqualTo(new Guard(guardedUnit, guardingRule));
    }

    @Test
    public void testAddActivation() {
        guard.addActivation(new MockActivation());
        assertThat(guard.getActivations()).isNotEmpty();
        assertThat(guard.getActivations()).hasSize(1);

        guard.addActivation(new MockActivation());
        guard.addActivation(new MockActivation());
        guard.addActivation(new MockActivation());

        assertThat(guard.getActivations()).hasSize(4);
    }

    @Test
    public void testRemoveActivation() {
        final Activation activation = new MockActivation();
        guard.addActivation(activation);
        assertThat(guard.getActivations()).isNotEmpty();
        guard.removeActivation(activation);
        assertThat(guard.getActivations()).isEmpty();
    }

    @Test
    public void testIsActive() {
        final Activation activation = new MockActivation();
        guard.addActivation(activation);
        assertThat(guard.isActive()).isTrue();
        guard.removeActivation(activation);
        assertThat(guard.isActive()).isFalse();
    }

    @Test
    public void testGetGuardedUnit() {
        assertThat(guardedUnit).isSameAs(guard.getGuardedUnit());
    }
}


text:
NAMESPACE_MICROSOFT_XBOX_SERVICES_MULTIPLAYER_CPP_BEGIN

multiplayer_role_type::multiplayer_role_type() :
    m_ownerManaged(false)
{
}

const std::unordered_map<string_t, multiplayer_role_info>&
multiplayer_role_type::roles() const
{
    return m_roles;
}

void
multiplayer_role_type::set_roles(
    _In_ const std::unordered_map<string_t, multiplayer_role_info>& roles
    )
{
    m_roles = roles;
}

bool
multiplayer_role_type::owner_managed() const
{
    return m_ownerManaged;
}

const std::vector<mutable_role_setting>&
multiplayer_role_type::mutable_role_settings() const
{
    return m_mutableRoleSettings;
}

std::vector<mutable_role_setting>
multiplayer_role_type::_Convert_string_vector_to_mutable_role_settings(
    std::vector<string_t> roleSettings
    )
{
    std::vector<mutable_role_setting> mutableRoleSettings;
    for (auto& setting : roleSettings)
    {
        if (utils::str_icmp(setting, _T("max")) == 0)
        {
            mutableRoleSettings.push_back(mutable_role_setting::max);
        }
        else if (utils::str_icmp(setting, _T("target")) == 0)
        {
            mutableRoleSettings.push_back(mutable_role_setting::target);
        }
    }

    return mutableRoleSettings;
}

xbox_live_result<multiplayer_role_type>
multiplayer_role_type::_Deserialize(
    _In_ const web::json::value& json
    )
{
    if (json.is_null()) return xbox_live_result<multiplayer_role_type>();

    multiplayer_role_type returnResult;
    std::error_code errc = xbox_live_error_code::no_error;

    returnResult.m_ownerManaged = utils::extract_json_bool(json, _T("ownerManaged"), errc, false);
    returnResult.m_mutableRoleSettings = _Convert_string_vector_to_mutable_role_settings(
        utils::extract_json_vector<string_t>(utils::json_string_extractor, json, _T("mutableRoleSettings"), errc, false)
        );

    auto rolesJson = utils::extract_json_field(json, _T("roles"), errc, false);
    if (!rolesJson.is_null() && rolesJson.is_object())
    {
        web::json::object rolesObj = rolesJson.as_object();
        for (const auto& role : rolesObj)
        {
            auto roleInfoResult = multiplayer_role_info::_Deserialize(role.second);
            if (roleInfoResult.err())
            {
                errc = roleInfoResult.err();
            }
            returnResult.m_roles[role.first] = roleInfoResult.payload();
        }
    }

    return xbox_live_result<multiplayer_role_type>(returnResult, errc);

}

NAMESPACE_MICROSOFT_XBOX_SERVICES_MULTIPLAYER_CPP_END


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace Tester
{
    public partial class fLogin : Form
    {
        public fLogin()
        {
            InitializeComponent();
        }

        private void btnSalir_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }
    }
}


text:
package conf

import (
	"errors"
	"flag"

	eleclient "go-common/app/service/main/vip/dao/ele-api-client"
	"go-common/library/cache/memcache"
	"go-common/library/cache/redis"
	"go-common/library/conf"
	"go-common/library/database/sql"
	ecode "go-common/library/ecode/tip"
	"go-common/library/log"
	bm "go-common/library/net/http/blademaster"
	"go-common/library/net/rpc"
	"go-common/library/net/rpc/warden"
	xtime "go-common/library/time"

	"github.com/BurntSushi/toml"
)

// Conf global variable.
var (
	Conf     = &Config{}
	client   *conf.Client
	confPath string
)

// Config struct of conf.
type Config struct {
	MsgURI string
	PayURI string
	VipURI string
	// log
	Log *log.Config
	// gorpc server
	RPCServer *rpc.ServerConfig
	// db
	Mysql *sql.Config
	// ecodes FIXME
	Ecode *ecode.Config
	//old db
	OldMysql *sql.Config
	// http client
	HTTPClient *bm.ClientConfig
	// mc
	Memcache *Memcache
	// pay conf
	PayConf *PayConf
	// rpc clients
	RPCClient2 *RPC
	// property
	Property *Property
	// http
	BM *bm.ServerConfig
	// redis
	Redis *Redis
	// associate conf
	AssociateConf *AssociateConf
	// ele conf
	ELEConf *eleclient.Config
	Host    *Host
	// grpc server
	WardenServer *warden.ServerConfig
	// grpc client
	CouponClient *warden.ClientConfig
}

// Host host.
type Host struct {
	Ele  string
	Mail string
}

// Redis redis
type Redis struct {
	*redis.Config
	Expire xtime.Duration
}

// Memcache memcache
type Memcache struct {
	*memcache.Config
	Expire xtime.Duration
}

//PayConf pay config
type PayConf struct {
	CustomerID     int64
	Token          string
	OrderNotifyURL string
	SignNotifyURL  string
	PlanID         int32
	ProductID      string
	Version        string
	ReturnURL      string
	OrderExpire    int
	SignType       string
}

// RPC clients config.
type RPC struct {
	Member *rpc.ClientConfig
	Point  *rpc.ClientConfig
	Coupon *rpc.ClientConfig
}

// Property config for biz logic.
type Property struct {
	NotifyURL                      string
	MsgURL                         string
	PayURL                         string
	PayCoURL                       string
	AccountURL                     string
	PassportURL                    string
	APIURL                         string
	APICoURL                       string
	VipURL                         string
	TokenBID                       string
	PGCURL                         string
	ActiveDate                     string
	ActiveTip                      string
	Expire                         string
	AnnualVipBcoinDay              int16
	AnnualVipBcoinCouponMoney      int
	AnnualVipBcoinCouponActivityID int
	GiveBpDay                      int8
	PointGetRule                   map[string]int
	PointActiveDate                map[string]string
	BubbleTicker                   xtime.Duration
	PayType                        map[string]string
	PayChannelMapping              map[string]string
	PointBalance                   int64
	ActiveStart                    string
	ActiveEnd                      string
	ConfigMap                      map[string]string
	PointExchangeTitle             map[string]string
	WillExpiredTitle               map[string]string
	ExpiredTitle                   map[string]string
	TipButtonName                  string
	TipButtonLink                  string
	AllowanceSwitch                int8
	CodeSwitch                     int8
	GiveSwitch                     int8
	PanelBgURL                     string
	CodeOpenedSearchSize           int
	WelfareBgHost                  string
}

// AssociateConf associate vip conf.
type AssociateConf struct {
	// user grant count limit
	GrantDurationMap         map[string]int64 //限制饿了么发放联合会员的次数
	BilibiliPrizeGrantKeyMap map[string]string
	MailCouponID1            string           //票务优惠券满99减5
	MailCouponID2            string           //电商优惠券满299减20
	BilibiliBuyDurationMap   map[string]int64 //限制bilibili购买联合会员的次数
}

func init() {
	flag.StringVar(&confPath, "conf", "", "default config path")
}

// Init create config instance.
func Init() (err error) {
	if confPath != "" {
		return local()
	}
	return remote()
}

func local() (err error) {
	_, err = toml.DecodeFile(confPath, &Conf)
	return
}

func remote() (err error) {
	if client, err = conf.New(); err != nil {
		return
	}
	if err = load(); err != nil {
		return
	}
	return
}

func load() (err error) {
	var (
		s       string
		ok      bool
		tmpConf *Config
	)
	if s, ok = client.Toml2(); !ok {
		return errors.New("load config center error")
	}
	if _, err = toml.Decode(s, &tmpConf); err != nil {
		return errors.New("could not decode config")
	}
	*Conf = *tmpConf
	return
}


text:
<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
    <title></title>
    <link rel="manifest" href="manifest.json">
    <!-- un-comment this code to enable service worker
    <script>
      if ('serviceWorker' in navigator) {
        navigator.serviceWorker.register('service-worker.js')
          .then(() => console.log('service worker installed'))
          .catch(err => console.log('Error', err));
      }
    </script>-->
    <script language="JavaScript" type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
    <!--     <link href="lib/ionic/css/ionic.css" rel="stylesheet"> -->
    <link href="css/style.css" rel="stylesheet">
    <link href="css/ionic.app.css" rel="stylesheet">
    <link href="lib/ion-md-input/css/ion-md-input.min.css" rel="stylesheet">
    <link href="lib/ionic-material/dist/ionic.material.min.css" rel="stylesheet">
    <link href="lib/ion-slide-tab/tabSlideBox.css" rel="stylesheet">
    <!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above
    <link href="css/ionic.app.css" rel="stylesheet">
    -->
    <!-- ionic/angularjs js -->
    <script src="lib/ionic/js/ionic.bundle.js"></script>
    <script src="lib/ion-slide-tab/tabSlideBox.js"></script>
    <script src="lib/ionic-toast/dist/ionic-toast.bundle.min.js"></script>
    <script type="text/javascript" src="lib/angular-storage/angular-storage.js"></script>
    <!-- cordova script (this will be a 404 during development) -->
    <script src="cordova.js"></script>
    <script src="lib/ngCordova/dist/ng-cordova.min.js"></script>
    <script src="js/socket.js"></script>
    <script src='https://cdn.rawgit.com/naptha/tesseract.js/1.0.10/dist/tesseract.js'></script>
    <script src="lib/chart/Chart.min.js"></script>
    <script src="lib/chart/angular-chart.min.js"></script>
    <script src="lib/ionic-material/dist/ionic.material.min.js"></script>
    <script src="lib/ion-md-input/js/ion-md-input.min.js"></script>
    <!-- your app's js -->
    <!-- <script src="http://maps.google.com/maps/api/js"></script> -->
    <script src="js/config.js"></script>
    <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAV04V_9WHrnZj9opDmLoyLlvrwXDIq33o"></script>
    <script src="lib/ngmap/ng-map.min.js"></script>
    <script src="lib/angular-messages/angular-messages.js"></script>
    <script src="js/app.js"></script>
    <script src="js/controllers.js"></script>
    <script src="js/trackTruck.js"></script>
    <script src="js/truck_details.js"></script>
    <script src="js/Truck_listCtrl.js"></script>
    <script src="js/take_photo.js"></script>
    <script src="js/owner.js"></script>
    <script src="js/profilecontroller.js"></script>
    <script src="js/Trucklist_managerCtrl.js"></script>
     <script src="js/createdjob.js"></script>
     <script src="js/createdjob_details.js"></script>
</head>

<body ng-app="starter">
    <ion-nav-view></ion-nav-view>
</body>

</html>


text:
using System;
using System.Runtime.Serialization;
using LibGit2Sharp.Core;

namespace LibGit2Sharp
{
    /// <summary>
    /// The exception that is thrown when the ref to merge with was as part of a pull operation not fetched.
    /// </summary>
    [Serializable]
    public class MergeFetchHeadNotFoundException : NotFoundException
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="MergeFetchHeadNotFoundException"/> class.
        /// </summary>
        public MergeFetchHeadNotFoundException()
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="MergeFetchHeadNotFoundException"/> class with a specified error message.
        /// </summary>
        /// <param name="message">A message that describes the error.</param>
        public MergeFetchHeadNotFoundException(string message)
            : base(message)
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="MergeFetchHeadNotFoundException"/> class with a specified error message and a reference to the inner exception that is the cause of this exception.
        /// </summary>
        /// <param name="message">The error message that explains the reason for the exception.</param>
        /// <param name="innerException">The exception that is the cause of the current exception. If the <paramref name="innerException"/> parameter is not a null reference, the current exception is raised in a catch block that handles the inner exception.</param>
        public MergeFetchHeadNotFoundException(string message, Exception innerException)
            : base(message, innerException)
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="MergeFetchHeadNotFoundException"/> class with a serialized data.
        /// </summary>
        /// <param name="info">The <see cref="SerializationInfo"/> that holds the serialized object data about the exception being thrown.</param>
        /// <param name="context">The <see cref="StreamingContext"/> that contains contextual information about the source or destination.</param>
        protected MergeFetchHeadNotFoundException(SerializationInfo info, StreamingContext context)
            : base(info, context)
        {
        }
    }
}
/* This is extra75 */