text:
body {
 margin: 0;
 padding: 0;
 font-family: Lucida Grande, Verdana, Geneva, Sans-serif;
 font-size: 11px;
 color: #4F5155;
 background: #fff url(<?php echo $image_url; ?>background.jpg) repeat-x left top;
}

a {
 color: #8B0D00;
 background-color: transparent;
 text-decoration: none;
 font-weight: bold;
}

a:visited {
 color: #8B0D00;
 background-color: transparent;
 text-decoration: none;
}

a:hover {
 color: #000;
 text-decoration: none;
 background-color: transparent;
}

#header {
 margin: 0;
 padding: 0;
}

#header_left {
 background-color: transparent;
 float: left;
 padding: 21px 0 0 32px;
 margin: 0
}

#header_right {
 background-color: transparent;
 float: right;
 text-align: right;
 padding: 35px 50px 20px 0;
 margin: 0
}

#footer {
 margin: 20px 0 15px 0;
 padding: 0;
}

#footer p {
 font-size: 10px;
 color: #999;
 text-align: center;
}

#outer {
 margin: 30px 40px 0 40px;
}

img {
 padding:0;
 border: 0;
 margin: 0;
}

.nopad {
 padding:0;
 border: 0;
 margin: 0;
}

table {
 background-color: #efefef;
}

th {
 background-color: #eee;
 font-weight: bold;
 padding: 6px;
 text-align: left;
}

td {
 background-color: #fff;
 padding: 6px;
}

form {
 margin: 0;
 padding: 0;
}

.input {
 font-family: Lucida Grande, Verdana, Geneva, Sans-serif;
 font-size: 11px;
 width: 600px;
 color: #333;
 border: 1px solid #B3B4BD;
 font-size: 11px;
 height: 2em;
 padding: 0;
 margin: 0;
}

.textarea {
 font-family: Lucida Grande, Verdana, Geneva, Sans-serif;
 font-size: 12px;
 width: 600px;
 color: #333;
 border: 1px solid #B3B4BD;
 padding: 0;
 margin: 0;
}

.select {
 background-color: #fff;
 font-size:  11px;
 font-weight: normal;
 color: #333;
 padding: 0;
 margin: 0 0 3px 0;
}

.checkbox {
 background-color: transparent;
 padding: 0;
 border: 0;
}

.submit {
 background-color: #8B0D00;
 color: transparent;
 font-weight: normal;
 border: 1px solid #000;
 margin: 6px 0 0 0;
 padding: 1px 5px 1px 5px;
}

redpajama_set_name: RedPajamaGithub


text:
"""
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License.  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

"""
import os
import status_params
import ambari_simplejson as json # simplejson is much faster comparing to Python 2.6 json module and has the same functions set.

from urlparse import urlparse

from functions import calc_xmn_from_xms, ensure_unit_for_memory

from ambari_commons.constants import AMBARI_SUDO_BINARY
from ambari_commons.os_check import OSCheck
from ambari_commons.str_utils import string_set_intersection

from resource_management.libraries.resources.hdfs_resource import HdfsResource
from resource_management.libraries.functions import conf_select
from resource_management.libraries.functions import stack_select
from resource_management.libraries.functions import format
from resource_management.libraries.functions import StackFeature
from resource_management.libraries.functions.stack_features import check_stack_feature
from resource_management.libraries.functions.stack_features import get_stack_feature_version
from resource_management.libraries.functions.default import default
from resource_management.libraries.functions import get_kinit_path
from resource_management.libraries.functions import is_empty
from resource_management.libraries.functions import get_unique_id_and_date
from resource_management.libraries.functions.get_not_managed_resources import get_not_managed_resources
from resource_management.libraries.script.script import Script
from resource_management.libraries.functions.expect import expect
from resource_management.libraries.functions.constants import Direction

# server configurations
config = Script.get_config()
exec_tmp_dir = Script.get_tmp_dir()
sudo = AMBARI_SUDO_BINARY

stack_name = status_params.stack_name
agent_stack_retry_on_unavailability = config['hostLevelParams']['agent_stack_retry_on_unavailability']
agent_stack_retry_count = expect("/hostLevelParams/agent_stack_retry_count", int)
version = default("/commandParams/version", None)
component_directory = status_params.component_directory
etc_prefix_dir = "/etc/hbase"

stack_version_unformatted = status_params.stack_version_unformatted
stack_version_formatted = status_params.stack_version_formatted
stack_root = status_params.stack_root

# get the correct version to use for checking stack features
version_for_stack_feature_checks = get_stack_feature_version(config)

stack_supports_ranger_kerberos = check_stack_feature(StackFeature.RANGER_KERBEROS_SUPPORT, version_for_stack_feature_checks)
stack_supports_ranger_audit_db = check_stack_feature(StackFeature.RANGER_AUDIT_DB_SUPPORT, version_for_stack_feature_checks)

# hadoop default parameters
hadoop_bin_dir = stack_select.get_hadoop_dir("bin")
hadoop_conf_dir = conf_select.get_hadoop_conf_dir()
daemon_script = "/usr/lib/hbase/bin/hbase-daemon.sh"
region_mover = "/usr/lib/hbase/bin/region_mover.rb"
region_drainer = "/usr/lib/hbase/bin/draining_servers.rb"
hbase_cmd = "/usr/lib/hbase/bin/hbase"
hbase_max_direct_memory_size = None

# hadoop parameters for stacks supporting rolling_upgrade
if stack_version_formatted and check_stack_feature(StackFeature.ROLLING_UPGRADE, stack_version_formatted):
  daemon_script = format('{stack_root}/current/hbase-client/bin/hbase-daemon.sh')
  region_mover = format('{stack_root}/current/hbase-client/bin/region_mover.rb')
  region_drainer = format('{stack_root}/current/hbase-client/bin/draining_servers.rb')
  hbase_cmd = format('{stack_root}/current/hbase-client/bin/hbase')

  hbase_max_direct_memory_size  = default('configurations/hbase-env/hbase_max_direct_memory_size', None)

  tmp_daemon_script = format("{stack_root}/current/{component_directory}/bin/hbase-daemon.sh")
  if os.path.exists(tmp_daemon_script):
    daemon_script = tmp_daemon_script

  region_mover = format("{stack_root}/current/{component_directory}/bin/region_mover.rb")
  region_drainer = format("{stack_root}/current/{component_directory}/bin/draining_servers.rb")
  hbase_cmd = format("{stack_root}/current/{component_directory}/bin/hbase")

hbase_conf_dir = status_params.hbase_conf_dir
limits_conf_dir = status_params.limits_conf_dir

hbase_user_nofile_limit = default("/configurations/hbase-env/hbase_user_nofile_limit", "32000")
hbase_user_nproc_limit = default("/configurations/hbase-env/hbase_user_nproc_limit", "16000")

# no symlink for phoenix-server at this point
phx_daemon_script = format('{stack_root}/current/phoenix-server/bin/queryserver.py')

hbase_excluded_hosts = config['commandParams']['excluded_hosts']
hbase_drain_only = default("/commandParams/mark_draining_only",False)
hbase_included_hosts = config['commandParams']['included_hosts']

hbase_user = status_params.hbase_user
hbase_principal_name = config['configurations']['hbase-env']['hbase_principal_name']
smokeuser = config['configurations']['cluster-env']['smokeuser']
_authentication = config['configurations']['core-site']['hadoop.security.authentication']
security_enabled = config['configurations']['cluster-env']['security_enabled']

# this is "hadoop-metrics.properties" for 1.x stacks
metric_prop_file_name = "hadoop-metrics2-hbase.properties"

# not supporting 32 bit jdk.
java64_home = config['hostLevelParams']['java_home']
java_version = expect("/hostLevelParams/java_version", int)

log_dir = config['configurations']['hbase-env']['hbase_log_dir']
java_io_tmpdir = default("/configurations/hbase-env/hbase_java_io_tmpdir", "/tmp")
master_heapsize = ensure_unit_for_memory(config['configurations']['hbase-env']['hbase_master_heapsize'])

regionserver_heapsize = ensure_unit_for_memory(config['configurations']['hbase-env']['hbase_regionserver_heapsize'])
regionserver_xmn_max = config['configurations']['hbase-env']['hbase_regionserver_xmn_max']
regionserver_xmn_percent = expect("/configurations/hbase-env/hbase_regionserver_xmn_ratio", float)
regionserver_xmn_size = calc_xmn_from_xms(regionserver_heapsize, regionserver_xmn_percent, regionserver_xmn_max)

hbase_regionserver_shutdown_timeout = expect('/configurations/hbase-env/hbase_regionserver_shutdown_timeout', int, 30)

phoenix_hosts = default('/clusterHostInfo/phoenix_query_server_hosts', [])
phoenix_enabled = default('/configurations/hbase-env/phoenix_sql_enabled', False)
has_phoenix = len(phoenix_hosts) > 0

underscored_version = stack_version_unformatted.replace('.', '_')
dashed_version = stack_version_unformatted.replace('.', '-')
if OSCheck.is_redhat_family() or OSCheck.is_suse_family():
  phoenix_package = format("phoenix_{underscored_version}_*")
elif OSCheck.is_ubuntu_family():
  phoenix_package = format("phoenix-{dashed_version}-.*")

pid_dir = status_params.pid_dir
tmp_dir = config['configurations']['hbase-site']['hbase.tmp.dir']
local_dir = config['configurations']['hbase-site']['hbase.local.dir']
ioengine_param = default('/configurations/hbase-site/hbase.bucketcache.ioengine', None)

client_jaas_config_file = format("{hbase_conf_dir}/hbase_client_jaas.conf")
master_jaas_config_file = format("{hbase_conf_dir}/hbase_master_jaas.conf")
regionserver_jaas_config_file = format("{hbase_conf_dir}/hbase_regionserver_jaas.conf")
rest_jaas_config_file = format("{hbase_conf_dir}/hbase_rest_jaas.conf")
queryserver_jaas_config_file = format("{hbase_conf_dir}/hbase_queryserver_jaas.conf")

ganglia_server_hosts = default('/clusterHostInfo/ganglia_server_host', []) # is not passed when ganglia is not present
has_ganglia_server = not len(ganglia_server_hosts) == 0
if has_ganglia_server:
  ganglia_server_host = ganglia_server_hosts[0]

ams_collector_hosts = default("/clusterHostInfo/metrics_collector_hosts", [])
has_metric_collector = not len(ams_collector_hosts) == 0
if has_metric_collector:
  if 'cluster-env' in config['configurations'] and \
      'metrics_collector_vip_host' in config['configurations']['cluster-env']:
    metric_collector_host = config['configurations']['cluster-env']['metrics_collector_vip_host']
  else:
    metric_collector_host = ams_collector_hosts[0]
  if 'cluster-env' in config['configurations'] and \
      'metrics_collector_vip_port' in config['configurations']['cluster-env']:
    metric_collector_port = config['configurations']['cluster-env']['metrics_collector_vip_port']
  else:
    metric_collector_web_address = default("/configurations/ams-site/timeline.metrics.service.webapp.address", "localhost:6188")
    if metric_collector_web_address.find(':') != -1:
      metric_collector_port = metric_collector_web_address.split(':')[1]
    else:
      metric_collector_port = '6188'
  if default("/configurations/ams-site/timeline.metrics.service.http.policy", "HTTP_ONLY") == "HTTPS_ONLY":
    metric_collector_protocol = 'https'
  else:
    metric_collector_protocol = 'http'
  metric_truststore_path= default("/configurations/ams-ssl-client/ssl.client.truststore.location", "")
  metric_truststore_type= default("/configurations/ams-ssl-client/ssl.client.truststore.type", "")
  metric_truststore_password= default("/configurations/ams-ssl-client/ssl.client.truststore.password", "")

  pass
metrics_report_interval = default("/configurations/ams-site/timeline.metrics.sink.report.interval", 60)
metrics_collection_period = default("/configurations/ams-site/timeline.metrics.sink.collection.period", 10)

# if hbase is selected the hbase_rs_hosts, should not be empty, but still default just in case
if 'slave_hosts' in config['clusterHostInfo']:
  rs_hosts = default('/clusterHostInfo/hbase_rs_hosts', '/clusterHostInfo/slave_hosts') #if hbase_rs_hosts not given it is assumed that region servers on same nodes as slaves
else:
  rs_hosts = default('/clusterHostInfo/hbase_rs_hosts', '/clusterHostInfo/all_hosts')

smoke_test_user = config['configurations']['cluster-env']['smokeuser']
smokeuser_principal =  config['configurations']['cluster-env']['smokeuser_principal_name']
smokeuser_permissions = "RWXCA"

titan_user = default('configurations/titan-env/titan_user', 'titan')
titan_user_permissions = "RWC"
titan_user_hbase_namespace = "@default"

service_check_data = get_unique_id_and_date()
user_group = config['configurations']['cluster-env']["user_group"]

if security_enabled:
  _hostname_lowercase = config['hostname'].lower()
  master_jaas_princ = config['configurations']['hbase-site']['hbase.master.kerberos.principal'].replace('_HOST',_hostname_lowercase)
  master_keytab_path = config['configurations']['hbase-site']['hbase.master.keytab.file']
  regionserver_jaas_princ = config['configurations']['hbase-site']['hbase.regionserver.kerberos.principal'].replace('_HOST',_hostname_lowercase)
  _rest_server_jaas_princ = config['configurations']['hbase-site']['hbase.rest.kerberos.principal']
  _rest_server_spnego_jaas_princ = config['configurations']['hbase-site']['hbase.rest.authentication.kerberos.principal']
  _queryserver_jaas_princ = config['configurations']['hbase-site']['phoenix.queryserver.kerberos.principal']
  if not is_empty(_queryserver_jaas_princ):
    queryserver_jaas_princ =_queryserver_jaas_princ.replace('_HOST',_hostname_lowercase)
  if not is_empty(_rest_server_jaas_princ):
    rest_server_jaas_princ = _rest_server_jaas_princ.replace('_HOST',_hostname_lowercase)
  if not is_empty(_rest_server_spnego_jaas_princ):
    rest_server_spnego_jaas_princ = _rest_server_spnego_jaas_princ.replace('_HOST',_hostname_lowercase)

regionserver_keytab_path = config['configurations']['hbase-site']['hbase.regionserver.keytab.file']
rest_server_keytab_path = config['configurations']['hbase-site']['hbase.rest.keytab.file']
rest_server_spnego_keytab_path = config['configurations']['hbase-site']['hbase.rest.authentication.kerberos.keytab']
queryserver_keytab_path = config['configurations']['hbase-site']['phoenix.queryserver.keytab.file']
smoke_user_keytab = config['configurations']['cluster-env']['smokeuser_keytab']
hbase_user_keytab = config['configurations']['hbase-env']['hbase_user_keytab']
kinit_path_local = get_kinit_path(default('/configurations/kerberos-env/executable_search_paths', None))
if security_enabled:
  kinit_cmd = format("{kinit_path_local} -kt {hbase_user_keytab} {hbase_principal_name};")
  kinit_cmd_master = format("{kinit_path_local} -kt {master_keytab_path} {master_jaas_princ};")
  master_security_config = format("-Djava.security.auth.login.config={hbase_conf_dir}/hbase_master_jaas.conf")
else:
  kinit_cmd = ""
  kinit_cmd_master = ""
  master_security_config = ""

#log4j.properties
if (('hbase-log4j' in config['configurations']) and ('content' in config['configurations']['hbase-log4j'])):
  log4j_props = config['configurations']['hbase-log4j']['content']
else:
  log4j_props = None

hbase_env_sh_template = config['configurations']['hbase-env']['content']

hbase_hdfs_root_dir = config['configurations']['hbase-site']['hbase.rootdir']
hbase_root_dir_scheme = urlparse(hbase_hdfs_root_dir).scheme

hbase_staging_dir = "/apps/hbase/staging"
#for create_hdfs_directory
hostname = config["hostname"]
hdfs_user_keytab = config['configurations']['hadoop-env']['hdfs_user_keytab']
hdfs_user = config['configurations']['hadoop-env']['hdfs_user']
hdfs_principal_name = config['configurations']['hadoop-env']['hdfs_principal_name']

hdfs_site = config['configurations']['hdfs-site']
default_fs = config['configurations']['core-site']['fs.defaultFS']

dfs_type = default("/commandParams/dfs_type", "")

import functools
#create partial functions with common arguments for every HdfsResource call
#to create/delete hdfs directory/file/copyfromlocal we need to call params.HdfsResource in code
HdfsResource = functools.partial(
  HdfsResource,
  user=hdfs_user,
  hdfs_resource_ignore_file = "/var/lib/ambari-agent/data/.hdfs_resource_ignore",
  security_enabled = security_enabled,
  keytab = hdfs_user_keytab,
  kinit_path_local = kinit_path_local,
  hadoop_bin_dir = hadoop_bin_dir,
  hadoop_conf_dir = hadoop_conf_dir,
  principal_name = hdfs_principal_name,
  hdfs_site = hdfs_site,
  default_fs = default_fs,
  immutable_paths = get_not_managed_resources(),
  dfs_type = dfs_type
)

# ranger host
ranger_admin_hosts = default("/clusterHostInfo/ranger_admin_hosts", [])
has_ranger_admin = not len(ranger_admin_hosts) == 0
xml_configurations_supported = config['configurations']['ranger-env']['xml_configurations_supported']
ambari_server_hostname = config['clusterHostInfo']['ambari_server_host'][0]

# ranger hbase properties
policymgr_mgr_url = config['configurations']['admin-properties']['policymgr_external_url']
if 'admin-properties' in config['configurations'] and 'policymgr_external_url' in config['configurations']['admin-properties'] and policymgr_mgr_url.endswith('/'):
  policymgr_mgr_url = policymgr_mgr_url.rstrip('/')
xa_audit_db_name = default('/configurations/admin-properties/audit_db_name', 'ranger_audits')
xa_audit_db_user = default('/configurations/admin-properties/audit_db_user', 'rangerlogger')
xa_db_host = config['configurations']['admin-properties']['db_host']
repo_name = str(config['clusterName']) + '_hbase'

common_name_for_certificate = config['configurations']['ranger-hbase-plugin-properties']['common.name.for.certificate']

zookeeper_znode_parent = config['configurations']['hbase-site']['zookeeper.znode.parent']
hbase_zookeeper_quorum = config['configurations']['hbase-site']['hbase.zookeeper.quorum']
hbase_zookeeper_property_clientPort = config['configurations']['hbase-site']['hbase.zookeeper.property.clientPort']
hbase_security_authentication = config['configurations']['hbase-site']['hbase.security.authentication']
hadoop_security_authentication = config['configurations']['core-site']['hadoop.security.authentication']

repo_config_username = config['configurations']['ranger-hbase-plugin-properties']['REPOSITORY_CONFIG_USERNAME']

ranger_env = config['configurations']['ranger-env']
ranger_plugin_properties = config['configurations']['ranger-hbase-plugin-properties']
policy_user = config['configurations']['ranger-hbase-plugin-properties']['policy_user']

#For curl command in ranger plugin to get db connector
jdk_location = config['hostLevelParams']['jdk_location']
java_share_dir = '/usr/share/java'
enable_ranger_hbase = False
if has_ranger_admin:
  enable_ranger_hbase = (config['configurations']['ranger-hbase-plugin-properties']['ranger-hbase-plugin-enabled'].lower() == 'yes')
  xa_audit_db_password = ''
  if not is_empty(config['configurations']['admin-properties']['audit_db_password']) and stack_supports_ranger_audit_db:
    xa_audit_db_password = unicode(config['configurations']['admin-properties']['audit_db_password'])
  repo_config_password = unicode(config['configurations']['ranger-hbase-plugin-properties']['REPOSITORY_CONFIG_PASSWORD'])
  xa_audit_db_flavor = (config['configurations']['admin-properties']['DB_FLAVOR']).lower()
  previous_jdbc_jar_name = None

  if stack_supports_ranger_audit_db:
    if xa_audit_db_flavor == 'mysql':
      jdbc_jar_name = default("/hostLevelParams/custom_mysql_jdbc_name", None)
      previous_jdbc_jar_name = default("/hostLevelParams/previous_custom_mysql_jdbc_name", None)
      audit_jdbc_url = format('jdbc:mysql://{xa_db_host}/{xa_audit_db_name}')
      jdbc_driver = "com.mysql.jdbc.Driver"
    elif xa_audit_db_flavor == 'oracle':
      jdbc_jar_name = default("/hostLevelParams/custom_oracle_jdbc_name", None)
      previous_jdbc_jar_name = default("/hostLevelParams/previous_custom_oracle_jdbc_name", None)
      colon_count = xa_db_host.count(':')
      if colon_count == 2 or colon_count == 0:
        audit_jdbc_url = format('jdbc:oracle:thin:@{xa_db_host}')
      else:
        audit_jdbc_url = format('jdbc:oracle:thin:@//{xa_db_host}')
      jdbc_driver = "oracle.jdbc.OracleDriver"
    elif xa_audit_db_flavor == 'postgres':
      jdbc_jar_name = default("/hostLevelParams/custom_postgres_jdbc_name", None)
      previous_jdbc_jar_name = default("/hostLevelParams/previous_custom_postgres_jdbc_name", None)
      audit_jdbc_url = format('jdbc:postgresql://{xa_db_host}/{xa_audit_db_name}')
      jdbc_driver = "org.postgresql.Driver"
    elif xa_audit_db_flavor == 'mssql':
      jdbc_jar_name = default("/hostLevelParams/custom_mssql_jdbc_name", None)
      previous_jdbc_jar_name = default("/hostLevelParams/previous_custom_mssql_jdbc_name", None)
      audit_jdbc_url = format('jdbc:sqlserver://{xa_db_host};databaseName={xa_audit_db_name}')
      jdbc_driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver"
    elif xa_audit_db_flavor == 'sqla':
      jdbc_jar_name = default("/hostLevelParams/custom_sqlanywhere_jdbc_name", None)
      previous_jdbc_jar_name = default("/hostLevelParams/previous_custom_sqlanywhere_jdbc_name", None)
      audit_jdbc_url = format('jdbc:sqlanywhere:database={xa_audit_db_name};host={xa_db_host}')
      jdbc_driver = "sap.jdbc4.sqlanywhere.IDriver"

  downloaded_custom_connector = format("{exec_tmp_dir}/{jdbc_jar_name}") if stack_supports_ranger_audit_db else None
  driver_curl_source = format("{jdk_location}/{jdbc_jar_name}") if stack_supports_ranger_audit_db else None
  driver_curl_target = format("{stack_root}/current/{component_directory}/lib/{jdbc_jar_name}") if stack_supports_ranger_audit_db else None
  previous_jdbc_jar = format("{stack_root}/current/{component_directory}/lib/{previous_jdbc_jar_name}") if stack_supports_ranger_audit_db else None
  sql_connector_jar = ''

  if security_enabled:
    master_principal = config['configurations']['hbase-site']['hbase.master.kerberos.principal']

  hbase_ranger_plugin_config = {
    'username': repo_config_username,
    'password': repo_config_password,
    'hadoop.security.authentication': hadoop_security_authentication,
    'hbase.security.authentication': hbase_security_authentication,
    'hbase.zookeeper.property.clientPort': hbase_zookeeper_property_clientPort,
    'hbase.zookeeper.quorum': hbase_zookeeper_quorum,
    'zookeeper.znode.parent': zookeeper_znode_parent,
    'commonNameForCertificate': common_name_for_certificate,
    'hbase.master.kerberos.principal': master_principal if security_enabled else ''
  }

  hbase_ranger_plugin_repo = {
    'isActive': 'true',
    'config': json.dumps(hbase_ranger_plugin_config),
    'description': 'hbase repo',
    'name': repo_name,
    'repositoryType': 'hbase',
    'assetType': '2'
  }

  if stack_supports_ranger_kerberos and security_enabled:
    hbase_ranger_plugin_config['policy.download.auth.users'] = hbase_user
    hbase_ranger_plugin_config['tag.download.auth.users'] = hbase_user
    hbase_ranger_plugin_config['policy.grantrevoke.auth.users'] = hbase_user

  if stack_supports_ranger_kerberos:
    hbase_ranger_plugin_config['ambari.service.check.user'] = policy_user

    hbase_ranger_plugin_repo = {
      'isEnabled': 'true',
      'configs': hbase_ranger_plugin_config,
      'description': 'hbase repo',
      'name': repo_name,
      'type': 'hbase'
    }

  ranger_hbase_principal = None
  ranger_hbase_keytab = None
  if stack_supports_ranger_kerberos and security_enabled and 'hbase-master' in component_directory.lower():
    ranger_hbase_principal = master_jaas_princ
    ranger_hbase_keytab = master_keytab_path
  elif  stack_supports_ranger_kerberos and security_enabled and 'hbase-regionserver' in component_directory.lower():
    ranger_hbase_principal = regionserver_jaas_princ
    ranger_hbase_keytab = regionserver_keytab_path

  xa_audit_db_is_enabled = False
  ranger_audit_solr_urls = config['configurations']['ranger-admin-site']['ranger.audit.solr.urls']
  if xml_configurations_supported and stack_supports_ranger_audit_db:
    xa_audit_db_is_enabled = config['configurations']['ranger-hbase-audit']['xasecure.audit.destination.db']
  xa_audit_hdfs_is_enabled = config['configurations']['ranger-hbase-audit']['xasecure.audit.destination.hdfs'] if xml_configurations_supported else None
  ssl_keystore_password = unicode(config['configurations']['ranger-hbase-policymgr-ssl']['xasecure.policymgr.clientssl.keystore.password']) if xml_configurations_supported else None
  ssl_truststore_password = unicode(config['configurations']['ranger-hbase-policymgr-ssl']['xasecure.policymgr.clientssl.truststore.password']) if xml_configurations_supported else None
  credential_file = format('/etc/ranger/{repo_name}/cred.jceks') if xml_configurations_supported else None

  #For SQLA explicitly disable audit to DB for Ranger
  if xa_audit_db_flavor == 'sqla':
    xa_audit_db_is_enabled = False

create_hbase_home_directory = check_stack_feature(StackFeature.HBASE_HOME_DIRECTORY, stack_version_formatted)
hbase_home_directory = format("/user/{hbase_user}")

atlas_hosts = default('/clusterHostInfo/atlas_server_hosts', [])
has_atlas = len(atlas_hosts) > 0

metadata_user = default('/configurations/atlas-env/metadata_user', None)
atlas_graph_storage_hostname = default('/configurations/application-properties/atlas.graph.storage.hostname', None)
atlas_graph_storage_hbase_table = default('/configurations/application-properties/atlas.graph.storage.hbase.table', None)
atlas_audit_hbase_tablename = default('/configurations/application-properties/atlas.audit.hbase.tablename', None)

if has_atlas:
  zk_hosts_matches = string_set_intersection(atlas_graph_storage_hostname, hbase_zookeeper_quorum)
  atlas_with_managed_hbase = len(zk_hosts_matches) > 0
else:
  atlas_with_managed_hbase = False

wal_directory = "/apps/hbase/data/MasterProcWALs"

backup_wal_dir = default('/configurations/hbase-env/backup_wal_dir', False)

#Need to make sure not to keep removing WAL logs once EU is finalized.
upgrade_direction = default("/commandParams/upgrade_direction", None)
to_backup_wal_dir = upgrade_direction is not None and upgrade_direction == Direction.UPGRADE and backup_wal_dir


text:
'use strict';

let React;
let Scheduler;
// let ReactCache;
let ReactDOM;
let ReactDOMClient;
// let Suspense;
let originalCreateElement;
// let TextResource;
// let textResourceShouldFail;
let originalHTMLImageElementSrcDescriptor;

let images = [];
let onLoadSpy = null;
let actualLoadSpy = null;

function PhaseMarkers({children}) {
  Scheduler.unstable_yieldValue('render start');
  React.useLayoutEffect(() => {
    Scheduler.unstable_yieldValue('last layout');
  });
  React.useEffect(() => {
    Scheduler.unstable_yieldValue('last passive');
  });
  return children;
}

function last(arr) {
  if (Array.isArray(arr)) {
    if (arr.length) {
      return arr[arr.length - 1];
    }
    return undefined;
  }
  throw new Error('last was passed something that was not an array');
}

function Text(props) {
  Scheduler.unstable_yieldValue(props.text);
  return props.text;
}

// function AsyncText(props) {
//   const text = props.text;
//   try {
//     TextResource.read([props.text, props.ms]);
//     Scheduler.unstable_yieldValue(text);
//     return text;
//   } catch (promise) {
//     if (typeof promise.then === 'function') {
//       Scheduler.unstable_yieldValue(`Suspend! [${text}]`);
//     } else {
//       Scheduler.unstable_yieldValue(`Error! [${text}]`);
//     }
//     throw promise;
//   }
// }

function Img({src: maybeSrc, onLoad, useImageLoader, ref}) {
  const src = maybeSrc || 'default';
  Scheduler.unstable_yieldValue('Img ' + src);
  return ;
}

function Yield() {
  Scheduler.unstable_yieldValue('Yield');
  Scheduler.unstable_requestPaint();
  return null;
}

function loadImage(element) {
  const event = new Event('load');
  element.__needsDispatch = false;
  element.dispatchEvent(event);
}

describe('ReactDOMImageLoad', () => {
  beforeEach(() => {
    jest.resetModules();
    React = require('react');
    Scheduler = require('scheduler');
    // ReactCache = require('react-cache');
    ReactDOM = require('react-dom');
    ReactDOMClient = require('react-dom/client');
    // Suspense = React.Suspense;

    onLoadSpy = jest.fn(reactEvent => {
      const src = reactEvent.target.getAttribute('src');
      Scheduler.unstable_yieldValue('onLoadSpy [' + src + ']');
    });

    actualLoadSpy = jest.fn(nativeEvent => {
      const src = nativeEvent.target.getAttribute('src');
      Scheduler.unstable_yieldValue('actualLoadSpy [' + src + ']');
      nativeEvent.__originalDispatch = false;
    });

    // TextResource = ReactCache.unstable_createResource(
    //   ([text, ms = 0]) => {
    //     let listeners = null;
    //     let status = 'pending';
    //     let value = null;
    //     return {
    //       then(resolve, reject) {
    //         switch (status) {
    //           case 'pending': {
    //             if (listeners === null) {
    //               listeners = [{resolve, reject}];
    //               setTimeout(() => {
    //                 if (textResourceShouldFail) {
    //                   Scheduler.unstable_yieldValue(
    //                     `Promise rejected [${text}]`,
    //                   );
    //                   status = 'rejected';
    //                   value = new Error('Failed to load: ' + text);
    //                   listeners.forEach(listener => listener.reject(value));
    //                 } else {
    //                   Scheduler.unstable_yieldValue(
    //                     `Promise resolved [${text}]`,
    //                   );
    //                   status = 'resolved';
    //                   value = text;
    //                   listeners.forEach(listener => listener.resolve(value));
    //                 }
    //               }, ms);
    //             } else {
    //               listeners.push({resolve, reject});
    //             }
    //             break;
    //           }
    //           case 'resolved': {
    //             resolve(value);
    //             break;
    //           }
    //           case 'rejected': {
    //             reject(value);
    //             break;
    //           }
    //         }
    //       },
    //     };
    //   },
    //   ([text, ms]) => text,
    // );
    // textResourceShouldFail = false;

    images = [];

    originalCreateElement = document.createElement;
    document.createElement = function createElement(tagName, options) {
      const element = originalCreateElement.call(document, tagName, options);
      if (tagName === 'img') {
        element.addEventListener('load', actualLoadSpy);
        images.push(element);
      }
      return element;
    };

    originalHTMLImageElementSrcDescriptor = Object.getOwnPropertyDescriptor(
      HTMLImageElement.prototype,
      'src',
    );

    Object.defineProperty(HTMLImageElement.prototype, 'src', {
      get() {
        return this.getAttribute('src');
      },
      set(value) {
        Scheduler.unstable_yieldValue('load triggered');
        this.__needsDispatch = true;
        this.setAttribute('src', value);
      },
    });
  });

  afterEach(() => {
    document.createElement = originalCreateElement;
    Object.defineProperty(
      HTMLImageElement.prototype,
      'src',
      originalHTMLImageElementSrcDescriptor,
    );
  });

  it('captures the load event if it happens before commit phase and replays it between layout and passive effects', async function() {
    const container = document.createElement('div');
    const root = ReactDOMClient.createRoot(container);

    React.startTransition(() =>
      root.render(
        <PhaseMarkers>

          <Yield />
          <Text text={'a'} />
        </PhaseMarkers>,
      ),
    );

    expect(Scheduler).toFlushAndYieldThrough([
      'render start',
      'Img default',
      'Yield',
    ]);
    const img = last(images);
    loadImage(img);
    expect(Scheduler).toHaveYielded([
      'actualLoadSpy [default]',
      // no onLoadSpy since we have not completed render
    ]);
    expect(Scheduler).toFlushAndYield([
      'a',
      'load triggered',
      'last layout',
      'last passive',
    ]);
    expect(img.__needsDispatch).toBe(true);
    loadImage(img);
    expect(Scheduler).toHaveYielded([
      'actualLoadSpy [default]', // the browser reloading of the image causes this to yield again
      'onLoadSpy [default]',
    ]);
    expect(onLoadSpy).toHaveBeenCalled();
  });

  it('captures the load event if it happens after commit phase and replays it', async function() {
    const container = document.createElement('div');
    const root = ReactDOMClient.createRoot(container);

    React.startTransition(() =>
      root.render(
        <PhaseMarkers>

        </PhaseMarkers>,
      ),
    );

    expect(Scheduler).toFlushAndYieldThrough([
      'render start',
      'Img default',
      'load triggered',
      'last layout',
    ]);
    Scheduler.unstable_requestPaint();
    const img = last(images);
    loadImage(img);
    expect(Scheduler).toHaveYielded([
      'actualLoadSpy [default]',
      'onLoadSpy [default]',
    ]);
    expect(Scheduler).toFlushAndYield(['last passive']);
    expect(img.__needsDispatch).toBe(false);
    expect(onLoadSpy).toHaveBeenCalledTimes(1);
  });

  it('it replays the last load event when more than one fire before the end of the layout phase completes', async function() {
    const container = document.createElement('div');
    const root = ReactDOMClient.createRoot(container);

    function Base() {
      const [src, setSrc] = React.useState('a');
      return (
        <PhaseMarkers>

          <Yield />
          <UpdateSrc setSrc={setSrc} />
        </PhaseMarkers>
      );
    }

    function UpdateSrc({setSrc}) {
      React.useLayoutEffect(() => {
        setSrc('b');
      }, [setSrc]);
      return null;
    }

    React.startTransition(() => root.render(<Base />));

    expect(Scheduler).toFlushAndYieldThrough([
      'render start',
      'Img a',
      'Yield',
    ]);
    const img = last(images);
    loadImage(img);
    expect(Scheduler).toHaveYielded(['actualLoadSpy [a]']);

    expect(Scheduler).toFlushAndYieldThrough([
      'load triggered',
      'last layout',
      // the update in layout causes a passive effects flush before a sync render
      'last passive',
      'render start',
      'Img b',
      'Yield',
      // yield is ignored becasue we are sync rendering
      'last layout',
      'last passive',
    ]);
    expect(images.length).toBe(1);
    loadImage(img);
    expect(Scheduler).toHaveYielded(['actualLoadSpy [b]', 'onLoadSpy [b]']);
    expect(onLoadSpy).toHaveBeenCalledTimes(1);
  });

  it('replays load events that happen in passive phase after the passive phase.', async function() {
    const container = document.createElement('div');
    const root = ReactDOMClient.createRoot(container);

    root.render(
      <PhaseMarkers>

      </PhaseMarkers>,
    );

    expect(Scheduler).toFlushAndYield([
      'render start',
      'Img default',
      'load triggered',
      'last layout',
      'last passive',
    ]);
    const img = last(images);
    loadImage(img);
    expect(Scheduler).toHaveYielded([
      'actualLoadSpy [default]',
      'onLoadSpy [default]',
    ]);
    expect(onLoadSpy).toHaveBeenCalledTimes(1);
  });

  it('captures and suppresses the load event if it happens before passive effects and a cascading update causes the img to be removed', async function() {
    const container = document.createElement('div');
    const root = ReactDOMClient.createRoot(container);

    function ChildSuppressing({children}) {
      const [showChildren, update] = React.useState(true);
      React.useLayoutEffect(() => {
        if (showChildren) {
          update(false);
        }
      }, [showChildren]);
      return showChildren ? children : null;
    }

    React.startTransition(() =>
      root.render(
        <PhaseMarkers>
          <ChildSuppressing>

            <Yield />
            <Text text={'a'} />
          </ChildSuppressing>
        </PhaseMarkers>,
      ),
    );

    expect(Scheduler).toFlushAndYieldThrough([
      'render start',
      'Img default',
      'Yield',
    ]);
    const img = last(images);
    loadImage(img);
    expect(Scheduler).toHaveYielded(['actualLoadSpy [default]']);
    expect(Scheduler).toFlushAndYield([
      'a',
      'load triggered',
      'last layout',
      'last passive',
    ]);
    expect(img.__needsDispatch).toBe(true);
    loadImage(img);
    // we expect the browser to load the image again but since we are no longer rendering
    // the img there will be no onLoad called
    expect(Scheduler).toHaveYielded(['actualLoadSpy [default]']);
    expect(Scheduler).toFlushWithoutYielding();
    expect(onLoadSpy).not.toHaveBeenCalled();
  });

  it('captures and suppresses the load event if it happens before passive effects and a cascading update causes the img to be removed, alternate', async function() {
    const container = document.createElement('div');
    const root = ReactDOMClient.createRoot(container);

    function Switch({children}) {
      const [shouldShow, updateShow] = React.useState(true);
      return children(shouldShow, updateShow);
    }

    function UpdateSwitchInLayout({updateShow}) {
      React.useLayoutEffect(() => {
        updateShow(false);
      }, []);
      return null;
    }

    React.startTransition(() =>
      root.render(
        <Switch>
          {(shouldShow, updateShow) => (
            <PhaseMarkers>
              <>
                {shouldShow === true ? (
                  <>

                    <Yield />
                    <Text text={'a'} />
                  </>
                ) : null}
                ,
                <UpdateSwitchInLayout updateShow={updateShow} />
              </>
            </PhaseMarkers>
          )}
        </Switch>,
      ),
    );

    expect(Scheduler).toFlushAndYieldThrough([
      // initial render
      'render start',
      'Img default',
      'Yield',
    ]);
    const img = last(images);
    loadImage(img);
    expect(Scheduler).toHaveYielded(['actualLoadSpy [default]']);
    expect(Scheduler).toFlushAndYield([
      'a',
      'load triggered',
      // img is present at first
      'last layout',
      'last passive',
      // sync re-render where the img is suppressed
      'render start',
      'last layout',
      'last passive',
    ]);
    expect(img.__needsDispatch).toBe(true);
    loadImage(img);
    // we expect the browser to load the image again but since we are no longer rendering
    // the img there will be no onLoad called
    expect(Scheduler).toHaveYielded(['actualLoadSpy [default]']);
    expect(Scheduler).toFlushWithoutYielding();
    expect(onLoadSpy).not.toHaveBeenCalled();
  });

  // it('captures the load event if it happens in a suspended subtree and replays it between layout and passive effects on resumption', async function() {
  //   function SuspendingWithImage() {
  //     Scheduler.unstable_yieldValue('SuspendingWithImage');
  //     return (
  //       <Suspense fallback={<Text text="Loading..." />}>
  //         <AsyncText text="A" ms={100} />
  //         <PhaseMarkers>
  //
  //         </PhaseMarkers>
  //       </Suspense>
  //     );
  //   }

  //   const container = document.createElement('div');
  //   const root = ReactDOMClient.createRoot(container);

  //   React.startTransition(() => root.render(<SuspendingWithImage />));

  //   expect(Scheduler).toFlushAndYield([
  //     'SuspendingWithImage',
  //     'Suspend! [A]',
  //     'render start',
  //     'Img default',
  //     'Loading...',
  //   ]);
  //   let img = last(images);
  //   loadImage(img);
  //   expect(Scheduler).toHaveYielded(['actualLoadSpy [default]']);
  //   expect(onLoadSpy).not.toHaveBeenCalled();

  //   // Flush some of the time
  //   jest.advanceTimersByTime(50);
  //   // Still nothing...
  //   expect(Scheduler).toFlushWithoutYielding();

  //   // Flush the promise completely
  //   jest.advanceTimersByTime(50);
  //   // Renders successfully
  //   expect(Scheduler).toHaveYielded(['Promise resolved [A]']);

  //   expect(Scheduler).toFlushAndYieldThrough([
  //     'A',
  //     // img was recreated on unsuspended tree causing new load event
  //     'render start',
  //     'Img default',
  //     'last layout',
  //   ]);

  //   expect(images.length).toBe(2);
  //   img = last(images);
  //   expect(img.__needsDispatch).toBe(true);
  //   loadImage(img);
  //   expect(Scheduler).toHaveYielded([
  //     'actualLoadSpy [default]',
  //     'onLoadSpy [default]',
  //   ]);

  //   expect(Scheduler).toFlushAndYield(['last passive']);

  //   expect(onLoadSpy).toHaveBeenCalledTimes(1);
  // });

  it('correctly replays the last img load even when a yield + update causes the host element to change', async function() {
    let externalSetSrc = null;
    let externalSetSrcAlt = null;

    function Base() {
      const [src, setSrc] = React.useState(null);
      const [srcAlt, setSrcAlt] = React.useState(null);
      externalSetSrc = setSrc;
      externalSetSrcAlt = setSrcAlt;
      return srcAlt || src ? <YieldingWithImage src={srcAlt || src} /> : null;
    }

    function YieldingWithImage({src}) {
      Scheduler.unstable_yieldValue('YieldingWithImage');
      React.useEffect(() => {
        Scheduler.unstable_yieldValue('Committed');
      });
      return (
        <>

          <Yield />
          <Text text={src} />
        </>
      );
    }

    const container = document.createElement('div');
    const root = ReactDOMClient.createRoot(container);

    root.render(<Base />);

    expect(Scheduler).toFlushWithoutYielding();

    React.startTransition(() => externalSetSrc('a'));

    expect(Scheduler).toFlushAndYieldThrough([
      'YieldingWithImage',
      'Img a',
      'Yield',
    ]);
    let img = last(images);
    loadImage(img);
    expect(Scheduler).toHaveYielded(['actualLoadSpy [a]']);

    ReactDOM.flushSync(() => externalSetSrcAlt('b'));

    expect(Scheduler).toHaveYielded([
      'YieldingWithImage',
      'Img b',
      'Yield',
      'b',
      'load triggered',
      'Committed',
    ]);
    expect(images.length).toBe(2);
    img = last(images);
    expect(img.__needsDispatch).toBe(true);
    loadImage(img);

    expect(Scheduler).toHaveYielded(['actualLoadSpy [b]', 'onLoadSpy [b]']);
    // why is there another update here?
    expect(Scheduler).toFlushAndYield([
      'YieldingWithImage',
      'Img b',
      'Yield',
      'b',
      'Committed',
    ]);
  });

  it('preserves the src property / attribute when triggering a potential new load event', () => {
    // this test covers a regression identified in https://github.com/mui/material-ui/pull/31263
    // where the resetting of the src property caused the property to change from relative to fully qualified

    // make sure we are not using the patched src setter
    Object.defineProperty(
      HTMLImageElement.prototype,
      'src',
      originalHTMLImageElementSrcDescriptor,
    );

    const container = document.createElement('div');
    const root = ReactDOMClient.createRoot(container);

    React.startTransition(() =>
      root.render(
        <PhaseMarkers>

          <Yield />
          <Text text={'a'} />
        </PhaseMarkers>,
      ),
    );

    // render to yield to capture state of img src attribute and property before commit
    expect(Scheduler).toFlushAndYieldThrough([
      'render start',
      'Img default',
      'Yield',
    ]);
    const img = last(images);
    const renderSrcProperty = img.src;
    const renderSrcAttr = img.getAttribute('src');

    // finish render and commit causing the src property to be rewritten
    expect(Scheduler).toFlushAndYield(['a', 'last layout', 'last passive']);
    const commitSrcProperty = img.src;
    const commitSrcAttr = img.getAttribute('src');

    // ensure attribute and properties agree
    expect(renderSrcProperty).toBe(commitSrcProperty);
    expect(renderSrcAttr).toBe(commitSrcAttr);
  });
});


text:
public class TestPassByValue {
  /** Main method */
  public static void main(String[] args) {
    // Declare and initialize variables
    int num1 = 1;
    int num2 = 2;

    System.out.println("Before invoking the swap method, num1 is " +
      num1 + " and num2 is " + num2);

    // Invoke the swap method to attempt to swap two variables
    swap(num1, num2);

    System.out.println("After invoking the swap method, num1 is " +
      num1 + " and num2 is " + num2);
  }

  /** Swap two variables */
  public static void swap(int n1, int n2) {
    System.out.println("\tInside the swap method");
    System.out.println("\t\tBefore swapping, n1 is " + n1
      + " and n2 is " + n2);

    // Swap n1 with n2
    int temp = n1;
    n1 = n2;
    n2 = temp;

    System.out.println("\t\tAfter swapping, n1 is " + n1
      + " and n2 is " + n2);
  }
}


text:
if [ -n "$FREESURFER_HOME" ]; then
	$FREESURFER_HOME/bin/clear_fs_env.csh
fi

# PLEASE CHANGE: Please specify location of CBIG repository
export CBIG_CODE_DIR=$HOME/storage/CBIG_private

# PLEASE CHANGE: define locations for these libraries
export FREESURFER_HOME=/apps/freesurfer/5.3.0
export CBIG_MATLAB_DIR=/apps/matlab/R2018b
export CBIG_SPM_DIR=/apps/spm/spm12
export CBIG_AFNI_DIR=/apps/afni/AFNI_2011_12_21_1014/linux_openmp_64
export CBIG_ANTS_DIR=/apps/ants/ants_v2.2.0/BUILD/bin/
export CBIG_WB_DIR=/apps/HCP/workbench-1.1.1/
export CBIG_FSLDIR=/apps/fsl/5.0.10

# DO NOT CHANGE: define locations for unit tests data and replication data
export CBIG_TESTDATA_DIR=/mnt/isilon/CSC1/Yeolab/CodeMaintenance/UnitTestData
export CBIG_REPDATA_DIR=/mnt/isilon/CSC1/Yeolab/CodeMaintenance/ReplicationData
export CBIG_IndCBM_REP_DIR=/mnt/isilon/CSC2/Yeolab/Data/Harvard_Cerebellum

# DO NOT CHANGE: define scheduler location
export CBIG_SCHEDULER_DIR=/opt/pbs/bin

# DO NOT CHANGE: set up your environment with the configurations above
SETUP_PATH=$CBIG_CODE_DIR/setup/CBIG_generic_setup.sh
source $SETUP_PATH

# DO NOT CHANGE: set up temporary directory for MRIread from FS6.0 for CBIG
# members using the HPC, Other users should comment this out
export TMPDIR=/tmp

# Do NOT CHANGE: set up MATLABPATH so that MATLAB can find startup.m in our repo
export MATLABPATH=$CBIG_CODE_DIR/setup

# specified the default Python environment.
# Please UNCOMMENT if you follow CBIG's set up for Python environments.
# We use Python version 3.5 as default.
# Please see $CBIG_CODE_DIR/setup/python_env_setup/README.md for more details.
# source activate CBIG_py3


text:
/***************************************************************************//**
* \file     PIRAmplifierStage2.c
* \version  1.0
*
* \brief
*  This file provides the source code to the API for the PGA_P4 Component
*
********************************************************************************
* \copyright
* Copyright 2016, Cypress Semiconductor Corporation.  All rights reserved.
* You may use this file only in accordance with the license, terms, conditions,
* disclaimers, and limitations in the end user license agreement accompanying
* the software package with which this file was provided.
*******************************************************************************/

#include "PIRAmplifierStage2_PVT.h"

uint8 PIRAmplifierStage2_initVar = 0u; /**< Describes the init state of the component */

uint32 PIRAmplifierStage2_internalGainPower = 0u; /**< Stores component Gain, Power and Enable values */

/***************************************************************************//**
* Compensation table
*
* There is a feedback compensation capacitor recomended setting (for certain
* gain and power setting) under the mask 0x0F000000u
* or (PIRAmplifierStage2_C_FB_MASK)
*
* Also there is an OpAmp compensation recomended setting (for certain
* gain and power setting) under the mask 0x00000003u
* or (PIRAmplifierStage2_GET_OA_COMP_TRIM)
*
* There is only 6 values for whole gain range because the recommended
* values are for each pair of adjacent gain values, e.g.:
* the first (index = 0) value is for gain = 1 and 1.4,
* the second (index = 1) value is for gain = 2 and 2.8,and so on,
* and the sixth (index = 5) value is for gain = 32 only.
*******************************************************************************/
const uint32 PIRAmplifierStage2_compTab[PIRAmplifierStage2_COMP_TAB_HEIGHT][PIRAmplifierStage2_COMP_TAB_WIDTH] =
{
#if (PIRAmplifierStage2_CHECK_OUTPUT_MODE) /* Class AB */
    {0x0F000002u, 0x0F000002u, 0x0F000002u},
    {0x07000002u, 0x09000002u, 0x09000002u},
    {0x04000002u, 0x04000002u, 0x04000002u},
    {0x03000001u, 0x02000002u, 0x03000002u},
    {0x01000001u, 0x00000002u, 0x00000002u},
    {0x01000001u, 0x01000001u, 0x02000001u}
#else /* Class A */
    {0x0F000002u, 0x0F000002u, 0x0F000002u},
    {0x08000002u, 0x09000002u, 0x09000002u},
    {0x03000001u, 0x05000002u, 0x04000002u},
    {0x00000001u, 0x02000002u, 0x03000002u},
    {0x00000001u, 0x00000002u, 0x01000002u},
    {0x00000001u, 0x00000001u, 0x00000001u}
#endif /* PIRAmplifierStage2_OUTPUT_MODE */
};

/*******************************************************************************
* Function Name: PIRAmplifierStage2_Init
****************************************************************************//**
*
*  Initializes component's parameters to the values set by user in the
*  customizer of the component placed onto schematic. Usually it is called in
*  PIRAmplifierStage2_Start().
*
*******************************************************************************/
void PIRAmplifierStage2_Init(void)
{
    /* Set default internal variable value */
    PIRAmplifierStage2_internalGainPower = PIRAmplifierStage2_DEFAULT_GAIN_POWER;

    /* Set default register values */
    PIRAmplifierStage2_CTB_CTRL_REG |= PIRAmplifierStage2_DEFAULT_CTB_CTRL;
    PIRAmplifierStage2_OA_RES_CTRL_REG &= (uint32) ~PIRAmplifierStage2_DEFAULT_OA_RES_CTRL_MASK;
    PIRAmplifierStage2_OA_RES_CTRL_REG |= PIRAmplifierStage2_DEFAULT_OA_RES_CTRL;

    #if (PIRAmplifierStage2_VREF_MODE == PIRAmplifierStage2_VREF_INTERNAL)
        /* Configure resistor matrix bottom to the internal Vss */
        PIRAmplifierStage2_OA_SW_REG |= PIRAmplifierStage2_RBOT_TO_VSSA;
    #endif /* Vref Internal */

    /* Check if component has been enabled */
    if((PIRAmplifierStage2_OA_RES_CTRL_REG & PIRAmplifierStage2_OA_PWR_MODE_MASK) != 0u)
    {
        /* Set the default power level */
        PIRAmplifierStage2_Enable();
    }

    /* Set default gain and correspondent Cfb and OA_trim values */
    PIRAmplifierStage2_SetGain(PIRAmplifierStage2_GAIN);
}

/*******************************************************************************
* Function Name: PIRAmplifierStage2_Enable
****************************************************************************//**
*
*  Powers up amplifier (to default power level or restored after
*  previous PIRAmplifierStage2_Stop() call).
*  Usually it is called in PIRAmplifierStage2_Start().
*
*******************************************************************************/
void PIRAmplifierStage2_Enable(void)
{
    PIRAmplifierStage2_OA_RES_CTRL_REG |= PIRAmplifierStage2_GET_POWER;
}

/*******************************************************************************
* Function Name: PIRAmplifierStage2_Start
****************************************************************************//**
*
*  Enables the amplifier operation (calls PIRAmplifierStage2_Enable).
*  Also on the first call (after the system reset) initializes all the component
*  related registers with default values (calls PIRAmplifierStage2_Init).
*
*  \globalvars
*   The PIRAmplifierStage2_initVar variable is used to indicate initial
*   configuration of this component. The variable is initialized to zero (0u)
*   and set to one (1u) at the first time PIRAmplifierStage2_Start() is called.
*   This allows to enable the component without re-initialization in all
*   subsequent calls of the PIRAmplifierStage2_Start() routine.
*
*******************************************************************************/
void PIRAmplifierStage2_Start(void)
{
    if(PIRAmplifierStage2_initVar == 0u)
    {
        PIRAmplifierStage2_Init();
        PIRAmplifierStage2_initVar = 1u;
    }

    PIRAmplifierStage2_Enable();
}

/*******************************************************************************
* Function Name: PIRAmplifierStage2_Stop
****************************************************************************//**
*
*  Powers down the amplifier.
*
*******************************************************************************/
void PIRAmplifierStage2_Stop(void)
{
    PIRAmplifierStage2_OA_RES_CTRL_REG &= (uint32)~PIRAmplifierStage2_OA_PWR_MODE_MASK;
}

/*******************************************************************************
* Function Name: PIRAmplifierStage2_SetPower
****************************************************************************//**
*
*  Sets the power level of amplifier.
*
* \param powerLevel
*  The power level setting of amplifier. Possible values:
*   * PIRAmplifierStage2_LOW - The lowest power consumption.
*   * PIRAmplifierStage2_MED - The middle setting.
*   * PIRAmplifierStage2_HIGH - The highest amplifier bandwidth.
*
*  \internal
*   The PIRAmplifierStage2_internalGainPower variable is used to store the
*   current gain and power level to set appropriate compensation settings.
*
*******************************************************************************/
void PIRAmplifierStage2_SetPower(uint32 powerLevel)
{
    uint32 locTmp;

    /* Save the powerLevel */
    PIRAmplifierStage2_internalGainPower &= (uint32) ~PIRAmplifierStage2_OA_PWR_MODE_MASK;
    PIRAmplifierStage2_internalGainPower |= powerLevel & PIRAmplifierStage2_OA_PWR_MODE_MASK;

    /* Save the rest of register bitfields */
    locTmp = PIRAmplifierStage2_OA_RES_CTRL_REG &
        (uint32)~(PIRAmplifierStage2_OA_PWR_MODE_MASK | PIRAmplifierStage2_C_FB_MASK);

    /* Set the power and the feedback capacitor values into the control register */
    PIRAmplifierStage2_OA_RES_CTRL_REG  = locTmp | PIRAmplifierStage2_GET_POWER | PIRAmplifierStage2_GET_C_FB;

    /* Set the OA compensation capacitor value */
    PIRAmplifierStage2_OA_COMP_TRIM_REG = PIRAmplifierStage2_GET_OA_COMP_TRIM;
}

/*******************************************************************************
* Function Name: PIRAmplifierStage2_SetGain
****************************************************************************//**
*
*  Sets values of the input and feedback resistors to set a
*  specific gain of the amplifier.
*
* \param gainLevel
*  The gain setting of amplifier. Possible values:
*   * PIRAmplifierStage2_GAIN_1    - gain 1.0.
*   * PIRAmplifierStage2_GAIN_1_4  - gain 1.4.
*   * PIRAmplifierStage2_GAIN_2    - gain 2.0.
*   * PIRAmplifierStage2_GAIN_2_8  - gain 2.8.
*   * PIRAmplifierStage2_GAIN_4    - gain 4.0.
*   * PIRAmplifierStage2_GAIN_5_8  - gain 5.8.
*   * PIRAmplifierStage2_GAIN_8    - gain 8.0.
*   * PIRAmplifierStage2_GAIN_10_7 - gain 10.7.
*   * PIRAmplifierStage2_GAIN_16   - gain 16.0
*   * PIRAmplifierStage2_GAIN_21_3 - gain 21.3.
*   * PIRAmplifierStage2_GAIN_32   - gain 32.0.
*
*  \internal
*   The PIRAmplifierStage2_internalGainPower variable is used to store the
*   current gain and power level to set appropriate compensation settings.
*
*******************************************************************************/
void PIRAmplifierStage2_SetGain(uint32 gainLevel)
{
    uint32 locTmp;

    /* Save the gainLevel */
    PIRAmplifierStage2_internalGainPower &= (uint32) ~PIRAmplifierStage2_RES_TAP_MASK;
    PIRAmplifierStage2_internalGainPower |= ((uint32)(gainLevel << PIRAmplifierStage2_RES_TAP_SHIFT)) &
                                                                 PIRAmplifierStage2_RES_TAP_MASK;
    /* Save the rest of register bitfields */
    locTmp = PIRAmplifierStage2_OA_RES_CTRL_REG &
        (uint32)~(PIRAmplifierStage2_RES_TAP_MASK | PIRAmplifierStage2_C_FB_MASK);

    /* Set the gain and the feedback capacitor values into the control register */
    PIRAmplifierStage2_OA_RES_CTRL_REG = locTmp | (PIRAmplifierStage2_internalGainPower &
        PIRAmplifierStage2_RES_TAP_MASK) | PIRAmplifierStage2_GET_C_FB;

    /* Set the OA compensation capacitor value */
    PIRAmplifierStage2_OA_COMP_TRIM_REG = PIRAmplifierStage2_GET_OA_COMP_TRIM;
}

/*******************************************************************************
* Function Name: PIRAmplifierStage2_PumpControl
****************************************************************************//**
*
*  Allows the user to turn the amplifier's boost pump on or off.
*  By Default the PIRAmplifierStage2_Init() function turns the pump on.
*
* \param onOff
*  The boost pump setting. Possible values:
*   * PIRAmplifierStage2_BOOST_OFF - Turn off the pump.
*   * PIRAmplifierStage2_BOOST_ON  - Turn on the pump.
*
**********************************************************************************/
void PIRAmplifierStage2_PumpControl(uint32 onOff)
{
    if(onOff == PIRAmplifierStage2_BOOST_ON)
    {
        PIRAmplifierStage2_OA_RES_CTRL_REG |= PIRAmplifierStage2_OA_PUMP_EN;
    }
    else
    {
        PIRAmplifierStage2_OA_RES_CTRL_REG &= (uint32)~PIRAmplifierStage2_OA_PUMP_EN;
    }
}

/* [] END OF FILE */


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

#include "chrome/browser/storage/durable_storage_permission_context.h"

#include <string>

#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/macros.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/browser/bookmarks/bookmark_model_factory.h"
#include "chrome/browser/content_settings/cookie_settings_factory.h"
#include "chrome/browser/content_settings/host_content_settings_map_factory.h"
#include "chrome/browser/engagement/important_sites_util.h"
#include "chrome/test/base/chrome_render_view_host_test_harness.h"
#include "chrome/test/base/testing_profile.h"
#include "components/bookmarks/test/bookmark_test_helpers.h"
#include "components/content_settings/core/browser/cookie_settings.h"
#include "components/content_settings/core/browser/host_content_settings_map.h"
#include "components/permissions/permission_request_id.h"
#include "content/public/browser/permission_controller_delegate.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/web_contents.h"
#include "testing/gtest/include/gtest/gtest.h"

using bookmarks::BookmarkModel;

namespace {

class TestDurablePermissionContext : public DurableStoragePermissionContext {
 public:
  explicit TestDurablePermissionContext(Profile* profile)
      : DurableStoragePermissionContext(profile),
        permission_set_count_(0),
        last_permission_set_persisted_(false),
        last_permission_set_setting_(CONTENT_SETTING_DEFAULT) {}

  int permission_set_count() const { return permission_set_count_; }
  bool last_permission_set_persisted() const {
    return last_permission_set_persisted_;
  }
  ContentSetting last_permission_set_setting() const {
    return last_permission_set_setting_;
  }

  ContentSetting GetContentSettingFromMap(const GURL& url_a,
                                          const GURL& url_b) {
    return HostContentSettingsMapFactory::GetForProfile(browser_context())
        ->GetContentSetting(url_a.GetOrigin(), url_b.GetOrigin(),
                            ContentSettingsType::DURABLE_STORAGE,
                            std::string());
  }

 private:
  // NotificationPermissionContext:
  void NotifyPermissionSet(const permissions::PermissionRequestID& id,
                           const GURL& requesting_origin,
                           const GURL& embedder_origin,
                           permissions::BrowserPermissionCallback callback,
                           bool persist,
                           ContentSetting content_setting) override {
    permission_set_count_++;
    last_permission_set_persisted_ = persist;
    last_permission_set_setting_ = content_setting;
    DurableStoragePermissionContext::NotifyPermissionSet(
        id, requesting_origin, embedder_origin, std::move(callback), persist,
        content_setting);
  }

  int permission_set_count_;
  bool last_permission_set_persisted_;
  ContentSetting last_permission_set_setting_;
};

}  // namespace

class DurableStoragePermissionContextTest
    : public ChromeRenderViewHostTestHarness {
 protected:
  void MakeOriginImportant(const GURL& origin) {
    ImportantSitesUtil::MarkOriginAsImportantForTesting(profile(), origin);
  }
};

TEST_F(DurableStoragePermissionContextTest, Bookmarked) {
  TestDurablePermissionContext permission_context(profile());
  GURL url("https://www.google.com");
  MakeOriginImportant(url);
  NavigateAndCommit(url);

  const permissions::PermissionRequestID id(
      web_contents()->GetMainFrame()->GetProcess()->GetID(),
      web_contents()->GetMainFrame()->GetRoutingID(), -1);

  ASSERT_EQ(0, permission_context.permission_set_count());
  ASSERT_FALSE(permission_context.last_permission_set_persisted());
  ASSERT_EQ(CONTENT_SETTING_DEFAULT,
            permission_context.last_permission_set_setting());

  permission_context.DecidePermission(
      web_contents(), id, url, url, true /* user_gesture */, base::DoNothing());
  // Success.
  EXPECT_EQ(1, permission_context.permission_set_count());
  EXPECT_TRUE(permission_context.last_permission_set_persisted());
  EXPECT_EQ(CONTENT_SETTING_ALLOW,
            permission_context.last_permission_set_setting());
}

TEST_F(DurableStoragePermissionContextTest, BookmarkAndIncognitoMode) {
  TestDurablePermissionContext permission_context(
      profile()->GetOffTheRecordProfile());
  GURL url("https://www.google.com");
  MakeOriginImportant(url);
  NavigateAndCommit(url);

  const permissions::PermissionRequestID id(
      web_contents()->GetMainFrame()->GetProcess()->GetID(),
      web_contents()->GetMainFrame()->GetRoutingID(), -1);

  ASSERT_EQ(0, permission_context.permission_set_count());
  ASSERT_FALSE(permission_context.last_permission_set_persisted());
  ASSERT_EQ(CONTENT_SETTING_DEFAULT,
            permission_context.last_permission_set_setting());

  permission_context.DecidePermission(
      web_contents(), id, url, url, true /* user_gesture */, base::DoNothing());
  // Success.
  EXPECT_EQ(1, permission_context.permission_set_count());
  EXPECT_TRUE(permission_context.last_permission_set_persisted());
  EXPECT_EQ(CONTENT_SETTING_ALLOW,
            permission_context.last_permission_set_setting());
}

TEST_F(DurableStoragePermissionContextTest, NoBookmark) {
  TestDurablePermissionContext permission_context(profile());
  GURL url("https://www.google.com");
  NavigateAndCommit(url);

  const permissions::PermissionRequestID id(
      web_contents()->GetMainFrame()->GetProcess()->GetID(),
      web_contents()->GetMainFrame()->GetRoutingID(), -1);

  ASSERT_EQ(0, permission_context.permission_set_count());
  ASSERT_FALSE(permission_context.last_permission_set_persisted());
  ASSERT_EQ(CONTENT_SETTING_DEFAULT,
            permission_context.last_permission_set_setting());

  permission_context.DecidePermission(
      web_contents(), id, url, url, true /* user_gesture */, base::DoNothing());

  // We shouldn't be granted.
  EXPECT_EQ(1, permission_context.permission_set_count());
  EXPECT_FALSE(permission_context.last_permission_set_persisted());
  EXPECT_EQ(CONTENT_SETTING_DEFAULT,
            permission_context.last_permission_set_setting());
}

TEST_F(DurableStoragePermissionContextTest, CookiesNotAllowed) {
  TestDurablePermissionContext permission_context(profile());
  GURL url("https://www.google.com");
  MakeOriginImportant(url);
  NavigateAndCommit(url);

  scoped_refptr<content_settings::CookieSettings> cookie_settings =
      CookieSettingsFactory::GetForProfile(profile());

  cookie_settings->SetCookieSetting(url, CONTENT_SETTING_BLOCK);

  const permissions::PermissionRequestID id(
      web_contents()->GetMainFrame()->GetProcess()->GetID(),
      web_contents()->GetMainFrame()->GetRoutingID(), -1);

  ASSERT_EQ(0, permission_context.permission_set_count());
  ASSERT_FALSE(permission_context.last_permission_set_persisted());
  ASSERT_EQ(CONTENT_SETTING_DEFAULT,
            permission_context.last_permission_set_setting());

  permission_context.DecidePermission(
      web_contents(), id, url, url, true /* user_gesture */, base::DoNothing());
  // We shouldn't be granted.
  EXPECT_EQ(1, permission_context.permission_set_count());
  EXPECT_FALSE(permission_context.last_permission_set_persisted());
  EXPECT_EQ(CONTENT_SETTING_DEFAULT,
            permission_context.last_permission_set_setting());
}

TEST_F(DurableStoragePermissionContextTest, EmbeddedFrame) {
  TestDurablePermissionContext permission_context(profile());
  GURL url("https://www.google.com");
  GURL requesting_url("https://www.youtube.com");
  MakeOriginImportant(url);
  NavigateAndCommit(url);

  const permissions::PermissionRequestID id(
      web_contents()->GetMainFrame()->GetProcess()->GetID(),
      web_contents()->GetMainFrame()->GetRoutingID(), -1);

  ASSERT_EQ(0, permission_context.permission_set_count());
  ASSERT_FALSE(permission_context.last_permission_set_persisted());
  ASSERT_EQ(CONTENT_SETTING_DEFAULT,
            permission_context.last_permission_set_setting());

  permission_context.DecidePermission(web_contents(), id, requesting_url, url,
                                      true /* user_gesture */,
                                      base::DoNothing());
  // We shouldn't be granted.
  EXPECT_EQ(1, permission_context.permission_set_count());
  EXPECT_FALSE(permission_context.last_permission_set_persisted());
  EXPECT_EQ(CONTENT_SETTING_DEFAULT,
            permission_context.last_permission_set_setting());
}

TEST_F(DurableStoragePermissionContextTest, NonsecureOrigin) {
  TestDurablePermissionContext permission_context(profile());
  GURL url("http://www.google.com");

  EXPECT_EQ(CONTENT_SETTING_BLOCK,
            permission_context
                .GetPermissionStatus(nullptr /* render_frame_host */, url, url)
                .content_setting);
}


text:
#pragma once

#include <string>

#include "common/singleton/const_singleton.h"

namespace Envoy {
namespace Config {

/**
 * Constant Type URLs.
 */
class TypeUrlValues {
public:
  const std::string Listener{"type.googleapis.com/envoy.api.v2.Listener"};
  const std::string Cluster{"type.googleapis.com/envoy.api.v2.Cluster"};
  const std::string ClusterLoadAssignment{"type.googleapis.com/envoy.api.v2.ClusterLoadAssignment"};
  const std::string Secret{"type.googleapis.com/envoy.api.v2.auth.Secret"};
  const std::string RouteConfiguration{"type.googleapis.com/envoy.api.v2.RouteConfiguration"};
  const std::string VirtualHost{"type.googleapis.com/envoy.api.v2.route.VirtualHost"};
  const std::string ScopedRouteConfiguration{
      "type.googleapis.com/envoy.api.v2.ScopedRouteConfiguration"};
  const std::string Runtime{"type.googleapis.com/envoy.service.discovery.v2.Runtime"};
};

using TypeUrl = ConstSingleton<TypeUrlValues>;

} // namespace Config
} // namespace Envoy


text:
package tap.nlp

import com.google.inject.AbstractModule
import play.api.Logger
import play.api.libs.concurrent.AkkaGuiceSupport
import tap.analysis.affectlexicon.AffectLexiconActor
import tap.nlp.factorie.LanguageToolActor

/**
  * Created by andrew@andrewresearch.net on 21/10/17.
  */

class NlpInitialiserModule extends AbstractModule with AkkaGuiceSupport {

  def configure():Unit = {
    Logger.info("Binding LanguageToolActor")
    bindActor[LanguageToolActor]("languagetool")
    bindActor[AffectLexiconActor]("affectlexicon")
  }

}


text:
from msrest.serialization import Model

class ClientCertificateCommonName(Model):
    """Client certificate details using common name.

    :param is_admin: Is this certificate used for admin access from the
     client, if false , it is used or query only access
    :type is_admin: bool
    :param certificate_common_name: Certificate common name to be granted
     access; be carefull using wild card common names
    :type certificate_common_name: str
    :param certificate_issuer_thumbprint: Certificate issuer thumbprint
    :type certificate_issuer_thumbprint: str
    """

    _validation = {
        'is_admin': {'required': True},
        'certificate_common_name': {'required': True},
        'certificate_issuer_thumbprint': {'required': True},
    }

    _attribute_map = {
        'is_admin': {'key': 'isAdmin', 'type': 'bool'},
        'certificate_common_name': {'key': 'certificateCommonName', 'type': 'str'},
        'certificate_issuer_thumbprint': {'key': 'certificateIssuerThumbprint', 'type': 'str'},
    }

    def __init__(self, is_admin, certificate_common_name, certificate_issuer_thumbprint):
        self.is_admin = is_admin
        self.certificate_common_name = certificate_common_name
        self.certificate_issuer_thumbprint = certificate_issuer_thumbprint


text:
package com.google.cloud.memcache.v1beta2.samples;

// [START memcache_v1beta2_generated_CloudMemcache_UpdateInstance_LRO_async]
import com.google.api.gax.longrunning.OperationFuture;
import com.google.cloud.memcache.v1beta2.CloudMemcacheClient;
import com.google.cloud.memcache.v1beta2.Instance;
import com.google.cloud.memcache.v1beta2.OperationMetadata;
import com.google.cloud.memcache.v1beta2.UpdateInstanceRequest;
import com.google.protobuf.FieldMask;

public class AsyncUpdateInstanceLRO {

  public static void main(String[] args) throws Exception {
    asyncUpdateInstanceLRO();
  }

  public static void asyncUpdateInstanceLRO() throws Exception {
    // This snippet has been automatically generated and should be regarded as a code template only.
    // It will require modifications to work:
    // - It may require correct/in-range values for request initialization.
    // - It may require specifying regional endpoints when creating the service client as shown in
    // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
    try (CloudMemcacheClient cloudMemcacheClient = CloudMemcacheClient.create()) {
      UpdateInstanceRequest request =
          UpdateInstanceRequest.newBuilder()
              .setUpdateMask(FieldMask.newBuilder().build())
              .setResource(Instance.newBuilder().build())
              .build();
      OperationFuture<Instance, OperationMetadata> future =
          cloudMemcacheClient.updateInstanceOperationCallable().futureCall(request);
      // Do something.
      Instance response = future.get();
    }
  }
}
// [END memcache_v1beta2_generated_CloudMemcache_UpdateInstance_LRO_async]


text:
require 'compass'
require 'sinatra'
require 'slim'
require 'mustacci/database'
require 'mustacci/build'
require 'mustacci/project'
require 'sinatra/base'
require 'faye'

module Mustacci
  class Frontend < Sinatra::Base

    def self.start
      set :mustacci, Mustacci.configuration
      set :port, Mustacci.configuration.frontend_port
      set :environment, :production
      enable :logging
      run!
    end

    Faye::WebSocket.load_adapter 'thin'
    use Faye::RackAdapter, mount: '/faye'

    set :root, File.expand_path('../../../frontend', __FILE__)

    configure do
      Compass.add_project_configuration(File.join(settings.root, 'compass.rb'))
    end

    helpers do

      def time(time)
        time = Time.parse(time) unless time.is_a?(Time)
        time.strftime('%d/%m/%Y %H:%M:%S')
      end

      def database
        @database ||= Mustacci::Dabatase.new
      end

      def build_status(build)
        slim :_build_status, layout: false, locals: { build: build }
      end

      def faye_channel(channel_id)
        slim :_faye_channel, layout: false, locals: { channel_id: channel_id }
      end

    end

    error do
      <<-HTML

HALP!

The shit hit the fan in such a way that I don't know what to do.

The error message: #{request.env['sinatra.error'].message}

      HTML
    end

    get '/' do
      @projects = Mustacci::Project.all
      slim :index
    end

    get '/projects/:id' do
      @project = Mustacci::Project.find(params[:id])
      slim :project
    end

    get '/projects/:project_id/builds/:id' do
      @project = Mustacci::Project.find(params[:project_id])
      @build = Mustacci::Build.find(params[:id])

      slim :build
    end

    get '/stylesheets/main.css' do
      sass :main, Compass.sass_engine_options
    end

  end
end


text:
"""Switch to the given Xcode version.

Usage:
  ./find_xcode.py -j /tmp/out.json -v 6.0.1

  Finds Xcode 6.0.1 and switches to it. Writes a summary to /tmp/out.json
  that includes the Xcode installations that were installed, the Xcode
  installations that matched the specified version, the Xcode version at
  the start of this script, and the Xcode version at the end of this script.

  e.g. {
    "installations": {
      "/Applications/Xcode5.app": "5.1.1 (5B1008)",
      "/Applications/Xcode6.app": "6.0 (6A313)",
      "/Applications/Xcode6.0.1.app": "6.0.1 (6A317)",
      "/Applications/Xcode6.1.app": "6.1 (6A1046a)",
    },
    "matches": {
      "/Applications/Xcode6.0.1.app": "6.0.1 (6A317)",
    },
    "previous version": {
      "path": "/Application/Xcode5.app",
      "version": "5.1.1",
      "build": "(5B1008)",
    },
    "current version": {
      "path": "/Applications/Xcode6.0.1.app",
      "version": "6.0.1",
      "build": "6A317",
    },
    "found": true,
  }
"""

import argparse
import json
import os
import sys

from slave.ios import utils

def get_xcodebuild_path(xcode_app):
  """Returns the path to xcodebuild under the given Xcode app.

  Args:
    xcode_app: The path to an installed Xcode.app. e.g. /Applications/Xcode.app.

  Returns:
    The absolute path to the xcodebuild binary under the given Xcode app.
  """
  return os.path.join(
    xcode_app,
    'Contents',
    'Developer',
    'usr',
    'bin',
    'xcodebuild',
  )

def get_xcode_version(xcodebuild):
  """Returns the Xcode version and build version.

  Args:
    xcodebuild: The absolute path to the xcodebuild binary.

  Returns:
    A tuple of (version string, build version string).
      e.g. ("6.0.1", "6A317")
  """
  # Sample output:
  # Xcode 6.0.1
  # Build version 6A317
  version_output = utils.call(xcodebuild, '-version').stdout

  return version_output[0].split(' ')[-1], version_output[1].split(' ')[-1]

def get_current_xcode_info():
  """Returns the current Xcode path, version, and build number.

  Returns:
    A dict with 'path', 'version', and 'build' keys.
      'path': The absolute path to the Xcode installation.
      'version': The Xcode version.
      'build': The Xcode build version.
  """
  version, build_version = get_xcode_version('xcodebuild')

  return {
    'path': utils.call('xcode-select', '--print-path').stdout[0],
    'version': version,
    'build': build_version,
  }

def find_xcode(target_version=None):
  """Finds all Xcode versions, switching to the given Xcode version.

  Args:
    target_version: The version of Xcode to switch to, or None if the
      Xcode version should not be switched.

  Returns:
    A summary dict as described in the usage section above.
  """
  xcode_info = {
    'installations': {
    },
    'current version': {
    },
  }

  if target_version:
    xcode_info['found'] = False
    xcode_info['matches'] = {}
    xcode_info['previous version'] = get_current_xcode_info()

    if xcode_info['previous version']['version'] == target_version:
      xcode_info['found'] = True

  for app in os.listdir(os.path.join('/', 'Applications')):
    if app.startswith('Xcode'):
      installation_path = os.path.join('/', 'Applications', app)
      xcodebuild = get_xcodebuild_path(installation_path)

      if os.path.exists(xcodebuild):
        version, build_version = get_xcode_version(xcodebuild)

        xcode_info['installations'][installation_path] = "%s (%s)" % (
          version,
          build_version,
        )

        if target_version and version == target_version:
          xcode_info['matches'][installation_path] = "%s (%s)" % (
            version,
            build_version,
          )

          # If this is the first match, switch to it.
          if not xcode_info['found']:
            utils.call(
              'sudo',
              'xcode-select',
              '-switch',
              os.path.join('/', 'Applications', app),
            )

            xcode_info['found'] = True

  xcode_info['current version'] = get_current_xcode_info()

  if target_version and not xcode_info['found']:
    # Flush buffers to ensure correct output ordering for buildbot.
    sys.stdout.flush()
    sys.stderr.write('Target Xcode version not found: %s\n' % target_version)
    sys.stderr.flush()

  return xcode_info

def main(args):
  xcode_info = find_xcode(args.version)

  with open(args.json_file, 'w') as json_file:
    json.dump(xcode_info, json_file)

  if args.version and not xcode_info['found']:
    return 1

  return 0

if __name__ == '__main__':
  parser = argparse.ArgumentParser()
  parser.add_argument(
    '-j',
    '--json-file',
    help='Location to write a JSON summary.',
    metavar='file',
    required=True,
    type=str,
  )
  parser.add_argument(
    '-v',
    '--version',
    help='Xcode version to find and switch to.',
    metavar='ver',
    type=str,
  )

  sys.exit(main(parser.parse_args()))


text:
import createHistory from 'history/createBrowserHistory';

export default createHistory();


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
Uses of Interface core.grammar.Derivation
</TITLE>

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Interface
core.grammar.Derivation

Packages that use Derivation

core.grammar

gggpIsokinetics

grammarGuidedGeneticProgramming

Uses of Derivation in core.grammar

Classes in core.grammar that implement Derivation

 class
DerivationImpl

Methods in core.grammar that return Derivation

 Derivation[]
DerivationImpl.crossoverGBX(Derivation d1,
             Derivation d2,
             int maxDepthGlobal)

 Derivation[]
Derivation.crossoverGBX(Derivation d1,
             Derivation d2,
             int maxDepthGlobal)

          The function implements a merge of two m-Trees, using the GBX algorithm described in "Crossover and Mutation Operators for
 Grammar-Guided Genetic Programming" as a guide.

 Derivation[]
DerivationImpl.crossoverGBXWithFunction(Derivation d1,
                         Derivation d2,
                         int maxDepthGlobal,
                         java.lang.String symbol)

 Derivation[]
Derivation.crossoverGBXWithFunction(Derivation d1,
                         Derivation d2,
                         int maxDepthGlobal,
                         java.lang.String s)

          The function has the same behavior that the function "crossoverGBX", and it has been added with the following
 additional feature: it updates the nodes that have an Element with a symbol "s" (those nodes have associated a
 function f and a value v).

 Derivation
DerivationImpl.duplicateDerivation(int level,
                    int absRank)

 Derivation
Derivation.duplicateDerivation(int level,
                    int absRank)

          As a Derivation is a m-Tree, the Tree has levels .

 Derivation
DerivationImpl.getMaxRandomDerivation(int maxDepthGlobal,
                       NonTerminal nt)

 Derivation
Derivation.getMaxRandomDerivation(int maxDepthGlobal,
                       NonTerminal nt)

          Returns a new Grammar's Derivation, using the symbol nt as the starting point, that is: the Productions
 that have nt as the left symbol are selected, and one of them is selected in a random way.

 Derivation
DerivationImpl.getMaxRandomDerivationWithFunction(int maxDepthGlobal,
                                   NonTerminal nt,
                                   java.util.Map<java.lang.String,java.lang.Double> features,
                                   Function f,
                                   java.lang.String symbol,
                                   int symbol2_pos)

 Derivation
Derivation.getMaxRandomDerivationWithFunction(int maxDepthGlobal,
                                   NonTerminal nt,
                                   java.util.Map<java.lang.String,java.lang.Double> features,
                                   Function F,
                                   java.lang.String s,
                                   int s2_pos)

          The function has the same behavior that the function "getMaxRandomDerivation", and it has been added with the
 following additional feature: given an Element (e) with the symbol "s" associated, the function adds to the
 Derivation's e node the following two items:

 1) A new function f, that is obtained through the parameter F ( F.createFunction ).

 Derivation
GrammarImpl.getRandomDerivation()

 Derivation
Grammar.getRandomDerivation()

          Returns a random Derivation of the Grammar starting from the Start symbol.

 Derivation
GrammarImpl.getRandomDerivation(NonTerminal nt)

 Derivation
Grammar.getRandomDerivation(NonTerminal nt)

          Returns a random Derivation of the Grammar starting from the NonTerminal nt.

 Derivation
GrammarImpl.getRandomDerivation(Production p)

 Derivation
Grammar.getRandomDerivation(Production p)

          Returns a random Derivation of the Grammar starting from the Production p.

 Derivation
GrammarImpl.getRandomDerivationMaxLenght(int l)

 Derivation
Grammar.getRandomDerivationMaxLenght(int l)

          Returns a random Derivation of the Grammar starting from the Start symbol and that satisfies
 the restriction that its length is at the most l.

 Derivation
GrammarImpl.getRandomDerivationMaxLenght(NonTerminal nt,
                             int l)

 Derivation
Grammar.getRandomDerivationMaxLenght(NonTerminal nt,
                             int l)

          Returns a random Derivation of the Grammar starting from the NonTerminal nt and that satisfies
 the restriction that its length is at the most l.

 Derivation
GrammarImpl.getRandomDerivationMaxLenght(Production p,
                             int l)

 Derivation
Grammar.getRandomDerivationMaxLenght(Production p,
                             int l)

          Returns a random Derivation of the Grammar starting from the Production p and that satisfies
 the restriction that its length is at the most l.

Methods in core.grammar with parameters of type Derivation

 int
DerivationComparator.compare(Derivation d1,
        Derivation d2)

 Derivation[]
DerivationImpl.crossoverGBX(Derivation d1,
             Derivation d2,
             int maxDepthGlobal)

 Derivation[]
Derivation.crossoverGBX(Derivation d1,
             Derivation d2,
             int maxDepthGlobal)

          The function implements a merge of two m-Trees, using the GBX algorithm described in "Crossover and Mutation Operators for
 Grammar-Guided Genetic Programming" as a guide.

 Derivation[]
DerivationImpl.crossoverGBXWithFunction(Derivation d1,
                         Derivation d2,
                         int maxDepthGlobal,
                         java.lang.String symbol)

 Derivation[]
Derivation.crossoverGBXWithFunction(Derivation d1,
                         Derivation d2,
                         int maxDepthGlobal,
                         java.lang.String s)

          The function has the same behavior that the function "crossoverGBX", and it has been added with the following
 additional feature: it updates the nodes that have an Element with a symbol "s" (those nodes have associated a
 function f and a value v).

Constructor parameters in core.grammar with type arguments of type Derivation

DerivationComparator(java.util.Map<Derivation,java.lang.Double> fitness)

Uses of Derivation in gggpIsokinetics

Methods in gggpIsokinetics that return types with arguments of type Derivation

 java.util.Map<Derivation,java.lang.Double>
Isokinetics.fitness(java.util.Collection<Derivation> individuals,
        cern.colt.matrix.DoubleMatrix2D features,
        java.util.List<java.lang.Object> parameters)

          The function calculates for each derivation (d) that belongs to "individuals", the entropy-based
 fitness function of the rule set associated to d, over the isokinetic curves sample set
 "features".

 java.util.Collection<Derivation>
Isokinetics.train(java.lang.String fileGrammar,
      java.lang.String fileFeaturesTotal,
      java.lang.String fileFeaturesTrain,
      int cols,
      int sizeP,
      int maxDepth,
      java.lang.String symbol,
      int symbol2,
      int K,
      int perBest,
      boolean elitism,
      int amountIter,
      double percentage,
      boolean applyEnt)

Methods in gggpIsokinetics with parameters of type Derivation

 java.util.Collection<Rules>
Isokinetics.parseRules(Derivation d,
           java.lang.String symbol)

 java.util.List<java.lang.Integer>
Isokinetics.test(Derivation individual,
     cern.colt.matrix.DoubleMatrix2D d)

Method parameters in gggpIsokinetics with type arguments of type Derivation

 java.util.Map<Derivation,java.lang.Double>
Isokinetics.fitness(java.util.Collection<Derivation> individuals,
        cern.colt.matrix.DoubleMatrix2D features,
        java.util.List<java.lang.Object> parameters)

          The function calculates for each derivation (d) that belongs to "individuals", the entropy-based
 fitness function of the rule set associated to d, over the isokinetic curves sample set
 "features".

Uses of Derivation in grammarGuidedGeneticProgramming

Methods in grammarGuidedGeneticProgramming that return types with arguments of type Derivation

 java.util.Collection<Derivation>
GggpImpl.crossover(java.util.Collection<Derivation> parents,
          int method,
          java.util.List<java.lang.Object> parameters)

          Method = 1: Defines the standard GBX operator.

 java.util.Map<Derivation,java.lang.Double>
GggpImpl.fitness(java.util.Collection<Derivation> individuals,
        cern.colt.matrix.DoubleMatrix2D features,
        java.util.List<java.lang.Object> parameters)

 java.util.Map<Derivation,java.lang.Double>
GggpImpl.getFitness()

 java.util.Collection<Derivation>
GggpImpl.getMatingPool()

 java.util.Collection<Derivation>
GggpImpl.getPopulation()

 java.util.Collection<Derivation>
GggpImpl.initPopulation(int method,
               java.util.List<java.lang.Object> parameters)

          Method = 1: Defines the standard GBIM initialization operator.

 java.util.Collection<Derivation>
GggpImpl.mutation(java.util.Collection<Derivation> individuals,
         int method,
         java.util.List<java.lang.Object> parameters)

 java.util.Collection<Derivation>
GggpImpl.nextGeneration(java.util.Collection<Derivation> matingPool,
               java.util.List<java.lang.Object> parameters)

 java.util.Collection<Derivation>
GggpImpl.parentSelection(java.util.Collection<Derivation> individuals,
                java.util.Map<Derivation,java.lang.Double> probabilities,
                java.util.Map<Derivation,java.lang.Double> fitness,
                int sizeMatingPool,
                int method,
                java.util.List<java.lang.Object> parameters)

          Method = 1: Defines the Tournament operator with replacement and selecting the fitest in a
             deterministic way

 java.util.Map<Derivation,java.lang.Double>
GggpImpl.parentSelectionProbabilities(java.util.Collection<Derivation> population,
                             java.util.Map<Derivation,java.lang.Double> fitness,
                             int method,
                             java.util.List<java.lang.Object> parameters)

 java.util.Collection<Derivation>
GggpImpl.survivalSelection(java.util.Collection<Derivation> oldIndividuals,
                  java.util.Collection<Derivation> newIndividuals,
                  int method,
                  java.util.List<java.lang.Object> parameters,
                  boolean elitism,
                  int perBest)

          Method = 1: Defines the Generation Model.

Method parameters in grammarGuidedGeneticProgramming with type arguments of type Derivation

 java.util.Collection<Derivation>
GggpImpl.crossover(java.util.Collection<Derivation> parents,
          int method,
          java.util.List<java.lang.Object> parameters)

          Method = 1: Defines the standard GBX operator.

 java.util.Map<Derivation,java.lang.Double>
GggpImpl.fitness(java.util.Collection<Derivation> individuals,
        cern.colt.matrix.DoubleMatrix2D features,
        java.util.List<java.lang.Object> parameters)

 java.util.Collection<Derivation>
GggpImpl.mutation(java.util.Collection<Derivation> individuals,
         int method,
         java.util.List<java.lang.Object> parameters)

 java.util.Collection<Derivation>
GggpImpl.nextGeneration(java.util.Collection<Derivation> matingPool,
               java.util.List<java.lang.Object> parameters)

 java.util.Collection<Derivation>
GggpImpl.parentSelection(java.util.Collection<Derivation> individuals,
                java.util.Map<Derivation,java.lang.Double> probabilities,
                java.util.Map<Derivation,java.lang.Double> fitness,
                int sizeMatingPool,
                int method,
                java.util.List<java.lang.Object> parameters)

          Method = 1: Defines the Tournament operator with replacement and selecting the fitest in a
             deterministic way

 java.util.Collection<Derivation>
GggpImpl.parentSelection(java.util.Collection<Derivation> individuals,
                java.util.Map<Derivation,java.lang.Double> probabilities,
                java.util.Map<Derivation,java.lang.Double> fitness,
                int sizeMatingPool,
                int method,
                java.util.List<java.lang.Object> parameters)

          Method = 1: Defines the Tournament operator with replacement and selecting the fitest in a
             deterministic way

 java.util.Collection<Derivation>
GggpImpl.parentSelection(java.util.Collection<Derivation> individuals,
                java.util.Map<Derivation,java.lang.Double> probabilities,
                java.util.Map<Derivation,java.lang.Double> fitness,
                int sizeMatingPool,
                int method,
                java.util.List<java.lang.Object> parameters)

          Method = 1: Defines the Tournament operator with replacement and selecting the fitest in a
             deterministic way

 java.util.Map<Derivation,java.lang.Double>
GggpImpl.parentSelectionProbabilities(java.util.Collection<Derivation> population,
                             java.util.Map<Derivation,java.lang.Double> fitness,
                             int method,
                             java.util.List<java.lang.Object> parameters)

 java.util.Map<Derivation,java.lang.Double>
GggpImpl.parentSelectionProbabilities(java.util.Collection<Derivation> population,
                             java.util.Map<Derivation,java.lang.Double> fitness,
                             int method,
                             java.util.List<java.lang.Object> parameters)

 double
GggpImpl.populationDiversity(java.util.Collection<Derivation> individuals,
                    int method,
                    java.util.List<java.lang.Object> parameters)

 void
GggpImpl.setFitness(java.util.Map<Derivation,java.lang.Double> f)

 void
GggpImpl.setMatingPool(java.util.Collection<Derivation> mp)

 void
GggpImpl.setPopulation(java.util.Collection<Derivation> p)

 java.util.Collection<Derivation>
GggpImpl.survivalSelection(java.util.Collection<Derivation> oldIndividuals,
                  java.util.Collection<Derivation> newIndividuals,
                  int method,
                  java.util.List<java.lang.Object> parameters,
                  boolean elitism,
                  int perBest)

          Method = 1: Defines the Generation Model.

 java.util.Collection<Derivation>
GggpImpl.survivalSelection(java.util.Collection<Derivation> oldIndividuals,
                  java.util.Collection<Derivation> newIndividuals,
                  int method,
                  java.util.List<java.lang.Object> parameters,
                  boolean elitism,
                  int perBest)

          Method = 1: Defines the Generation Model.

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes


text:
source ../testsupport.sh

run test.txt

exists test.txt.hello

true