text:
#!/bin/bash
#
# An entrypoint script for Artifactory to allow custom setup before server starts
#

: ${ART_PRIMARY_BASE_URL:=http://artifactory-node1:8081/artifactory}
: ${ARTIFACTORY_USER_NAME:=artifactory}
: ${ARTIFACTORY_USER_ID:=1030}
: ${ARTIFACTORY_HOME:=/opt/jfrog/artifactory}
: ${ARTIFACTORY_DATA:=/var/opt/jfrog/artifactory}
: ${REPLICATOR_DATA:=${ARTIFACTORY_DATA}/replicator}
: ${ACCESS_ETC_FOLDER:=${ARTIFACTORY_DATA}/access/etc}
ART_ETC=$ARTIFACTORY_DATA/etc
ARTIFACTORY_MASTER_KEY_FILE=${ART_ETC}/security/master.key

: ${ARTIFACTORY_EXTRA_CONF:=/artifactory_extra_conf}
: ${ACCESS_EXTRA_CONF:=/access_extra_conf}

: ${RECOMMENDED_MAX_OPEN_FILES:=32000}
: ${MIN_MAX_OPEN_FILES:=10000}

: ${RECOMMENDED_MAX_OPEN_PROCESSES:=1024}

export ARTIFACTORY_PID=${ARTIFACTORY_HOME}/run/artifactory.pid

logger() {
    DATE_TIME=$(date +"%Y-%m-%d %H:%M:%S")
    if [ -z "$CONTEXT" ]
    then
        CONTEXT=$(caller)
    fi
    MESSAGE=$1
    CONTEXT_LINE=$(echo "$CONTEXT" | awk '{print $1}')
    CONTEXT_FILE=$(echo "$CONTEXT" | awk -F"/" '{print $NF}')
    printf "%s %05s %s %s\n" "$DATE_TIME" "[$CONTEXT_LINE" "$CONTEXT_FILE]" "$MESSAGE"
    CONTEXT=
}

errorExit () {
    logger "ERROR: $1"; echo
    exit 1
}

warn () {
    logger "WARNING: $1"
}

# Print on container startup information about Dockerfile location
printDockerFileLocation() {
    logger "Dockerfile for this image can found inside the container."
    logger "To view the Dockerfile: 'cat /docker/artifactory-pro/Dockerfile.artifactory'."
}

# Check the max open files and open processes set on the system
checkULimits () {
    logger "Checking open files and processes limits"

    CURRENT_MAX_OPEN_FILES=$(ulimit -n)
    logger "Current max open files is $CURRENT_MAX_OPEN_FILES"

    if [ ${CURRENT_MAX_OPEN_FILES} != "unlimited" ] && [ "$CURRENT_MAX_OPEN_FILES" -lt "$RECOMMENDED_MAX_OPEN_FILES" ]; then
        if [ "$CURRENT_MAX_OPEN_FILES" -lt "$MIN_MAX_OPEN_FILES" ]; then
            errorExit "Max number of open files $CURRENT_MAX_OPEN_FILES, is too low. Cannot run Artifactory!"
        fi

        warn "Max number of open files $CURRENT_MAX_OPEN_FILES is low!"
        warn "You should add the parameter '--ulimit nofile=${RECOMMENDED_MAX_OPEN_FILES}:${RECOMMENDED_MAX_OPEN_FILES}' to your the 'docker run' command."
    fi

    CURRENT_MAX_OPEN_PROCESSES=$(ulimit -u)
    logger "Current max open processes is $CURRENT_MAX_OPEN_PROCESSES"

    if [ "$CURRENT_MAX_OPEN_PROCESSES" != "unlimited" ] && [ "$CURRENT_MAX_OPEN_PROCESSES" -lt "$RECOMMENDED_MAX_OPEN_PROCESSES" ]; then
        warn "Max number of processes $CURRENT_MAX_OPEN_PROCESSES is too low!"
        warn "You should add the parameter '--ulimit noproc=${RECOMMENDED_MAX_OPEN_PROCESSES}:${RECOMMENDED_MAX_OPEN_PROCESSES}' to your the 'docker run' command."
    fi
}

# Check that data dir is mounted and warn if not
checkMounts () {
    logger "Checking if $ARTIFACTORY_DATA is mounted"
    mount | grep ${ARTIFACTORY_DATA} > /dev/null
    if [ $? -ne 0 ]; then
        warn "Artifactory data directory ($ARTIFACTORY_DATA) is not mounted from the host. This means that all data and configurations will be lost once container is removed!"
    else
        logger "$ARTIFACTORY_DATA is mounted"
    fi
}

# Add additional conf files that were mounted to ARTIFACTORY_EXTRA_CONF
addExtraConfFiles () {
    logger "Adding extra configuration files to ${ARTIFACTORY_HOME}/etc if any exist"

    # If directory not empty
    if [ -d "${ARTIFACTORY_EXTRA_CONF}" ] && [ "$(ls -A ${ARTIFACTORY_EXTRA_CONF})" ]; then
        logger "Adding files from ${ARTIFACTORY_EXTRA_CONF} to ${ARTIFACTORY_HOME}/etc"
        cp -rfv ${ARTIFACTORY_EXTRA_CONF}/* ${ARTIFACTORY_HOME}/etc || errorExit "Copy files from ${ARTIFACTORY_EXTRA_CONF} to ${ARTIFACTORY_HOME}/etc failed"
    fi
}

# Add additional conf files that were mounted to ACCESS_EXTRA_CONF
addExtraAccessConfFiles () {
    logger "Adding extra configuration files to ${ACCESS_ETC_FOLDER} if any exist"

    # If directory not empty
    if [ -d "${ACCESS_EXTRA_CONF}" ] && [ "$(ls -A ${ACCESS_EXTRA_CONF})" ]; then
        logger "Adding files from ${ACCESS_EXTRA_CONF} to ${ACCESS_ETC_FOLDER}"
        cp -rfv ${ACCESS_EXTRA_CONF}/* ${ACCESS_ETC_FOLDER} || errorExit "Copy files from ${ACCESS_EXTRA_CONF} to ${ACCESS_ETC_FOLDER} failed"
    fi
}

# In case data dirs are missing or not mounted, need to create them
setupDataDirs () {
    logger "Setting up data directories if missing"
    if [ ! -d ${ARTIFACTORY_DATA}/etc ]; then
        mkdir -p ${ARTIFACTORY_DATA}/etc errorExit "Failed creating $ARTIFACTORY_DATA/etc"

        # Add extra conf files to a newly created etc/ only!
        addExtraConfFiles
    fi
    [ -d ${ARTIFACTORY_DATA}/data ]        || mkdir -p ${ARTIFACTORY_DATA}/data        || errorExit "Creating ${ARTIFACTORY_DATA}/data failed"
    [ -d ${ARTIFACTORY_DATA}/logs ]        || mkdir -p ${ARTIFACTORY_DATA}/logs        || errorExit "Creating ${ARTIFACTORY_DATA}/logs failed"
    [ -d ${ARTIFACTORY_DATA}/backup ]      || mkdir -p ${ARTIFACTORY_DATA}/backup      || errorExit "Creating ${ARTIFACTORY_DATA}/backup failed"
    [ -d ${ARTIFACTORY_DATA}/access ]      || mkdir -p ${ARTIFACTORY_DATA}/access      || errorExit "Creating ${ARTIFACTORY_DATA}/access failed"
    [ -d ${ARTIFACTORY_HOME}/run ]         || mkdir -p ${ARTIFACTORY_HOME}/run         || errorExit "Creating ${ARTIFACTORY_HOME}/run failed"
    [ -d ${ARTIFACTORY_HOME}/etc/plugins ] || mkdir -p ${ARTIFACTORY_HOME}/etc/plugins || errorExit "Creating ${ARTIFACTORY_HOME}/etc/plugins failed"
    [ -d ${REPLICATOR_DATA} ]              || mkdir -p ${REPLICATOR_DATA}              || errorExit "Creating ${REPLICATOR_DATA} failed"

}

# In case data dirs are missing or not mounted, need to create them
setupAccessDataDirs () {
    logger "Setting up data directories if missing"
    if [ ! -d ${ACCESS_ETC_FOLDER} ]; then
        mkdir -p ${ACCESS_ETC_FOLDER} || errorExit "Failed creating $ACCESS_ETC_FOLDER"
    fi

    # Add extra conf files to a newly created Access etc/ only!
    addExtraAccessConfFiles
}

# Generate an artifactory.config.import.yml if parameters passed
# Only if artifactory.config.import.yml does not already exist!
prepareArtConfigYaml () {
    local artifactory_config_import_yml=${ARTIFACTORY_DATA}/etc/artifactory.config.import.yml
    if [ ! -f ${artifactory_config_import_yml} ]; then
        if [ -n "$AUTO_GEN_REPOS" ] || [ -n "$ART_BASE_URL" ] || [ -n "$ART_LICENSE" ]; then

            # Make sure license is provided (must be passed in Pro)
            if [ -z "$ART_LICENSE" ]; then
                errorExit "To use the feature of auto configuration, you must pass a valid Artifactory license as an ART_LICENSE environment variable!"
            fi

            logger "Generating ${artifactory_config_import_yml}"
            [ -n "$ART_LICENSE" ] && LIC_STR="licenseKey: $ART_LICENSE"
            [ -n "$ART_BASE_URL" ] && BASE_URL_STR="baseUrl: $ART_BASE_URL"
            [ -n "$AUTO_GEN_REPOS" ] && GEN_REPOS_STR="repoTypes:"

            cat <<EY1 > "$artifactory_config_import_yml"
version: 1
GeneralConfiguration:
  ${LIC_STR}
  ${BASE_URL_STR}
EY1

            if [ -n "$GEN_REPOS_STR" ]; then
                cat <<EY2 >> "$artifactory_config_import_yml"
OnboardingConfiguration:
  ${GEN_REPOS_STR}
EY2
                for repo in $(echo ${AUTO_GEN_REPOS} | tr ',' ' '); do
                    cat <<EY3 >> "$artifactory_config_import_yml"
   - ${repo}
EY3
                done
            fi
        fi
    fi
}

# Create the Artifactory user (support passing name and id as parameters)
setupArtUser () {
    logger "Create $ARTIFACTORY_USER_NAME user if missing"
    id -u ${ARTIFACTORY_USER_NAME} > /dev/null 2>&1
    if [ $? -ne 0 ]; then
        logger "User does not exist. Creating it..."
        useradd -M -s /usr/sbin/nologin --uid ${ARTIFACTORY_USER_ID} --user-group ${ARTIFACTORY_USER_NAME} || errorExit "Creating user $ARTIFACTORY_USER_NAME failed"
    else
        logger "User $ARTIFACTORY_USER_NAME already exists"
    fi
}

# Do the actual permission check and chown
checkAndSetOwnerOnDir () {
    local DIR_TO_CHECK=$1
    local USER_TO_CHECK=$2
    local GROUP_TO_CHECK=$3

    logger "Checking permissions on $DIR_TO_CHECK"
    local STAT=( $(stat -Lc "%U %G" ${DIR_TO_CHECK}) )
    local USER=${STAT[0]}
    local GROUP=${STAT[1]}

    if [[ ${USER} != "$USER_TO_CHECK" ]] || [[ ${GROUP} != "$GROUP_TO_CHECK"  ]] ; then
        logger "$DIR_TO_CHECK is owned by $USER:$GROUP. Setting to $USER_TO_CHECK:$GROUP_TO_CHECK."
        chown -R ${USER_TO_CHECK}:${GROUP_TO_CHECK} ${DIR_TO_CHECK} || errorExit "Setting ownership on $DIR_TO_CHECK failed"
    else
        logger "$DIR_TO_CHECK is already owned by $USER_TO_CHECK:$GROUP_TO_CHECK."
    fi
}

setAccessCreds() {
    ACCESS_SOURCE_IP_ALLOWED=${ACCESS_SOURCE_IP_ALLOWED:-127.0.0.1}
    ACCESS_CREDS_FILE=${ART_ETC}/security/access/keys/access.creds
    BOOTSTRAP_CREDS_FILE=${ACCESS_ETC_FOLDER}/bootstrap.creds
    if [ ! -z "${ACCESS_USER}" ] && [ ! -z "${ACCESS_PASSWORD}" ] && [ ! -f ${ACCESS_CREDS_FILE} ] ; then
        logger "Creating bootstrap.creds using ACCESS_USER and ACCESS_PASSWORD env variables"
        mkdir -p ${ACCESS_ETC_FOLDER} || errorExit "Couldn't create ${ACCESS_ETC_FOLDER}"
        echo "${ACCESS_USER}@${ACCESS_SOURCE_IP_ALLOWED}=${ACCESS_PASSWORD}" > ${BOOTSTRAP_CREDS_FILE}
        chmod 600 ${BOOTSTRAP_CREDS_FILE} || errorExit "Setting permission on ${BOOTSTRAP_CREDS_FILE} failed"
        chown ${ARTIFACTORY_USER_NAME}:${ARTIFACTORY_USER_NAME} ${BOOTSTRAP_CREDS_FILE} || errorExit "Setting ownership on ${BOOTSTRAP_CREDS_FILE} failed"
    fi
}

setMasterKey() {
    ARTIFACTORY_SECURITY_FOLDER=${ART_ETC}/security
    if [ ! -z "${ARTIFACTORY_MASTER_KEY}" ] && [ ! -f "${ARTIFACTORY_MASTER_KEY_FILE}" ] ; then
        logger "Creating master.key using ARTIFACTORY_MASTER_KEY environment variable"
        mkdir -p ${ARTIFACTORY_SECURITY_FOLDER} || errorExit "Creating folder ${ARTIFACTORY_SECURITY_FOLDER} failed"
        echo "${ARTIFACTORY_MASTER_KEY}" > "${ARTIFACTORY_MASTER_KEY_FILE}"
    fi

    if [ -f "${ARTIFACTORY_MASTER_KEY_FILE}" ] ; then
        chmod 600 ${ARTIFACTORY_MASTER_KEY_FILE} || errorExit "Setting permission on ${ARTIFACTORY_MASTER_KEY_FILE} failed"
        chown ${ARTIFACTORY_USER_NAME}:${ARTIFACTORY_USER_NAME} ${ARTIFACTORY_MASTER_KEY_FILE} || errorExit "Setting ownership on ${ARTIFACTORY_MASTER_KEY_FILE} failed"
    fi
}

# Check and set permissions on ARTIFACTORY_HOME and ARTIFACTORY_DATA
setupPermissions () {
    # ARTIFACTORY_HOME
    checkAndSetOwnerOnDir $ARTIFACTORY_HOME $ARTIFACTORY_USER_NAME $ARTIFACTORY_USER_NAME

    # ARTIFACTORY_DATA
    checkAndSetOwnerOnDir $ARTIFACTORY_DATA $ARTIFACTORY_USER_NAME $ARTIFACTORY_USER_NAME

    # HA_DATA_DIR (If running in HA mode)
    if [ -d "$HA_DATA_DIR" ]; then
        checkAndSetOwnerOnDir $HA_DATA_DIR $ARTIFACTORY_USER_NAME $ARTIFACTORY_USER_NAME
    fi

    # HA_BACKUP_DIR (If running in HA mode)
    if [ -d "$HA_BACKUP_DIR" ]; then
        checkAndSetOwnerOnDir $HA_BACKUP_DIR $ARTIFACTORY_USER_NAME $ARTIFACTORY_USER_NAME
    fi
}

# Wait for primary node if needed
waitForPrimaryNode () {
    logger "Waiting for primary node to be up"

    local CMD="curl -s --max-time 5 -o /dev/null -w %{http_code} --fail $ART_PRIMARY_BASE_URL/webapp/#/login"
    logger "Running $CMD"
    while [[ ! "$($CMD)" =~ ^(2|4)[0-9]{2} ]]; do
        logger "."
        sleep 4
    done

    logger "Primary node ($ART_PRIMARY_BASE_URL) is up!"
}

# Wait for existence of etc/security/master.key
waitForMasterKey () {
    logger "Waiting for $ARTIFACTORY_MASTER_KEY_FILE"

    while [ ! -f ${ARTIFACTORY_MASTER_KEY_FILE} ]; do
        logger "."
        sleep 4
    done
    logger "$ARTIFACTORY_MASTER_KEY_FILE exists! Setting ${ARTIFACTORY_USER_NAME} as owner"

    # Make sure file is owned by artifactory
    chmod 600 ${ARTIFACTORY_MASTER_KEY_FILE} || errorExit "Setting owner of ${ARTIFACTORY_MASTER_KEY_FILE} to ${ARTIFACTORY_USER_NAME} failed"
    chown ${ARTIFACTORY_USER_NAME}:${ARTIFACTORY_USER_NAME} ${ARTIFACTORY_MASTER_KEY_FILE} || errorExit "Setting owner of ${ARTIFACTORY_MASTER_KEY_FILE} to ${ARTIFACTORY_USER_NAME} failed"
}

# Wait for DB port to be accessible
waitForDB () {
    local PROPS_FILE=$1
    local DB_TYPE=$2

    [ -f "$PROPS_FILE" ] || errorExit "$PROPS_FILE does not exist"

    local DB_HOST_PORT=
    local TIMEOUT=30
    local COUNTER=0

    # Extract DB host and port
    case "$DB_TYPE" in
        postgresql|mysql)
            DB_HOST_PORT=$(grep -e '^url=' "$PROPS_FILE" | sed -e 's,^.*:\/\/\(.*\)\/.*,\1,g' | tr ':' '/')
        ;;
        oracle)
            DB_HOST_PORT=$(grep -e '^url=' "$PROPS_FILE" | sed -e 's,.*@\(.*\):.*,\1,g' | tr ':' '/')
        ;;
        mssql)
            DB_HOST_PORT=$(grep -e '^url=' "$PROPS_FILE" | sed -e 's,^.*:\/\/\(.*\);databaseName.*,\1,g' | tr ':' '/')
        ;;
        *)
            errorExit "DB_TYPE $DB_TYPE not supported"
        ;;
    esac

    logger "Waiting for DB $DB_TYPE to be ready on $DB_HOST_PORT within $TIMEOUT seconds"

    while [ $COUNTER -lt $TIMEOUT ]; do
        (</dev/tcp/$DB_HOST_PORT) 2>/dev/null
        if [ $? -eq 0 ]; then
            logger "DB $DB_TYPE up in $COUNTER seconds"
            return 1
        else
            logger "."
            sleep 1
        fi
        let COUNTER=$COUNTER+1
    done

    return 0
}

# Set and configure DB type
checkHA () {
    # Check if HA (if one HA_XXX is set)
    if [ -n "$HA_NODE_ID" ] || [ -n "$HA_IS_PRIMARY" ]; then
        logger "Detected an Artifactory HA setup"
        if [ -z "$HA_NODE_ID" ]; then
            logger "HA_NODE_ID not set. Generating"
            HA_NODE_ID="node-$(hostname)"
            logger "HA_NODE_ID set to $HA_NODE_ID"
        fi
        if [ -z "$HA_IS_PRIMARY" ]; then
            errorExit "To setup Artifactory HA, you must set the HA_IS_PRIMARY environment variable"
        fi
        if [ -z "$HA_DATA_DIR" ]; then
            warn "HA_DATA_DIR is not set, Artifactory will use local data folder"
            HA_DATA_DIR="$ARTIFACTORY_DATA/data"
        fi
        if [ -z "$HA_BACKUP_DIR" ]; then
            warn "HA_BACKUP_DIR is not set, Artifactory will use local backup folder"
            HA_BACKUP_DIR="$ARTIFACTORY_DATA/backup"
        fi
        if [ -z "$HA_MEMBERSHIP_PORT" ]; then
            HA_MEMBERSHIP_PORT=10002
        fi

        # Get the container's internal IP to be used for ha-node.properties
        HA_HOST_IP=$(hostname -i)
        logger "HA_HOST_IP is set to $HA_HOST_IP"

        if [ -z "$HA_CONTEXT_URL" ]; then
            warn "HA_CONTEXT_URL is missing, using HA_HOST_IP as context url"
            HA_CONTEXT_URL=http://$HA_HOST_IP:8081/artifactory
        fi

        # If this is not the primary node, make sure the primary node's URL is passed and wait for it before proceeding
        if [[ $HA_IS_PRIMARY =~ false ]]; then
            logger "This is not the primary node. Must wait for primary node before starting"
            waitForPrimaryNode
        fi

        # Wait for etc/security/master.key (only on non-primary nodes)
        if [[ $HA_IS_PRIMARY =~ false ]] && [ "$HA_WAIT_FOR_MASTER_KEY" == "true" ]; then
            logger "HA_WAIT_FOR_MASTER_KEY set. Waiting for ${ARTIFACTORY_MASTER_KEY_FILE} existence"
            waitForMasterKey
        fi

        # Install license file if exists in /tmp
        if ls /tmp/art*.lic 1> /dev/null 2>&1; then
            logger "Found /tmp/art*.lic. Using it..."
            cp -v /tmp/art*.lic $ART_ETC/artifactory.lic
            chown -R ${ARTIFACTORY_USER_NAME}: $ART_ETC/artifactory.lic || errorExit "Change owner of $ART_ETC/artifactory.lic to ${ARTIFACTORY_USER_NAME} failed"
        fi

        # Start preparing the HA setup if not already exists
        if [ ! -f "$ART_ETC/ha-node.properties" ]; then
            logger "Preparing $ART_ETC/ha-node.properties"
            cat <<EOF > "$ART_ETC/ha-node.properties"
node.id=$HA_NODE_ID
context.url=$HA_CONTEXT_URL
membership.port=$HA_MEMBERSHIP_PORT
primary=$HA_IS_PRIMARY
hazelcast.interface=$HA_HOST_IP
EOF
            if [ -n "$HA_DATA_DIR" ] && [ -n "$HA_BACKUP_DIR" ] ; then
                echo "artifactory.ha.data.dir=$HA_DATA_DIR" >> "$ART_ETC/ha-node.properties"
                echo "artifactory.ha.backup.dir=$HA_BACKUP_DIR" >> "$ART_ETC/ha-node.properties"
            fi

            chown ${ARTIFACTORY_USER_NAME}: $ART_ETC/ha-node.properties || errorExit "Change owner of $ART_ETC/ha-node.properties to ${ARTIFACTORY_USER_NAME} failed"
        else
            # Update existing for the case the IP changed
            logger "$ART_ETC/ha-node.properties already exists. Making sure properties with IP are updated correctly"
            sed -i "s,^context.url=.*,context.url=$HA_CONTEXT_URL,g" $ART_ETC/ha-node.properties || errorExit "Updating $ART_ETC/ha-node.properties with context.url failed"
            sed -i "s,^hazelcast.interface=.*,hazelcast.interface=$HA_HOST_IP,g" $ART_ETC/ha-node.properties || errorExit "Updating $ART_ETC/ha-node.properties with hazelcast.interface failed"
        fi
        logger "Content of $ART_ETC/ha-node.properties:"
        cat $ART_ETC/ha-node.properties; echo
    fi
}

# Check DB type configurations before starting Artifactory
setDBConf () {
    # Set default DB_HOST
    if [ -z "$DB_HOST" ]; then
        DB_HOST=$DB_TYPE
    fi

    logger "Checking if need to copy $DB_TYPE configuration"
    # If already exists, just make sure it's configured for postgres
    if [ -f ${DB_PROPS} ]; then
        logger "${DB_PROPS} already exists. Making sure it's set to $DB_TYPE... "
        grep type=$DB_TYPE ${DB_PROPS} > /dev/null
        if [ $? -eq 0 ]; then
            logger "${DB_PROPS} already set to $DB_TYPE"
        else
            errorExit "${DB_PROPS} already exists and is set to a DB different than $DB_TYPE"
        fi
    else
        NEED_COPY=true
    fi

    # On a new install and startup, need to make the initial copy before Artifactory starts
    if [ "$NEED_COPY" == "true" ]; then
        logger "Copying $DB_TYPE configuration... "
        cp ${ARTIFACTORY_HOME}/misc/db/$DB_TYPE.properties ${DB_PROPS} || errorExit "Copying $ARTIFACTORY_HOME/misc/db/$DB_TYPE.properties to ${DB_PROPS} failed"
        chown ${ARTIFACTORY_USER_NAME}: ${DB_PROPS} || errorExit "Change owner of ${DB_PROPS} to ${ARTIFACTORY_USER_NAME} failed"

        sed -i "s/localhost/$DB_HOST/g" ${DB_PROPS}

        # Set custom DB parameters if specified
        if [ ! -z "$DB_USER" ]; then
            logger "Setting DB_USER to $DB_USER"
            sed -i "s/username=.*/username=$DB_USER/g" ${DB_PROPS}
        fi
        if [ ! -z "$DB_PASSWORD" ]; then
            logger "Setting DB_PASSWORD to **********"
            sed -i "s/password=.*/password=$DB_PASSWORD/g" ${DB_PROPS}
        fi

        # Set the URL depending on what parameters are passed
        if [ ! -z "$DB_URL" ]; then
            logger "Setting DB_URL to $DB_URL (ignoring DB_HOST and DB_PORT if set)"
            # Escape any & signs (so sed will not get messed up)
            DB_URL=$(echo -n ${DB_URL} | sed "s|&|\\\\&|g")
            sed -i "s|url=.*|url=$DB_URL|g" ${DB_PROPS}
        else
            if [ ! -z "$DB_PORT" ]; then
                logger "Setting DB_PORT to $DB_PORT"
                case "$DB_TYPE" in
                    mysql|postgresql)
                        oldPort=$(grep -E "(url).*" ${DB_PROPS}  | awk -F":" '{print $4}' | awk -F"/" '{print $1}')
                    ;;
                    oracle)
                        oldPort=$(grep -E "(url).*" ${DB_PROPS} | awk -F":" '{print $5}')
                    ;;
                    mssql)
                        oldPort=$(grep -E "(url).*" ${DB_PROPS}  | awk -F":" '{print $4}' | awk -F";" '{print $1}')
                    ;;
                esac

                sed -i "s/$oldPort/$DB_PORT/g" ${DB_PROPS}
            fi
            if [ ! -z "$DB_HOST" ]; then
                logger "Setting DB_HOST to $DB_HOST"
                case "$DB_TYPE" in
                    mysql|postgresql|mssql)
                        oldHost=$(grep -E "(url).*" ${DB_PROPS} | awk -F"//" '{print $2}' | awk -F":" '{print $1}')
                    ;;
                    oracle)
                        oldHost=$(grep -E "(url).*" ${DB_PROPS} | awk -F"@" '{print $2}' | awk -F":" '{print $1}')
                    ;;
                esac

                sed -i "s/$oldHost/$DB_HOST/g" ${DB_PROPS}
            fi
        fi
    fi
}

# Set and configure DB type
setDBType () {
    logger "Checking DB_TYPE"

    if [ ! -z "$DB_TYPE" ]; then
        logger "DB_TYPE is set to $DB_TYPE"
        NEED_COPY=false
        DB_PROPS=${ART_ETC}/db.properties

        case "$DB_TYPE" in
            postgresql)
                if ! ls $ARTIFACTORY_HOME/tomcat/lib/postgresql-*.jar 1> /dev/null 2>&1; then
                    errorExit "No postgresql connector found"
                fi
                setDBConf
            ;;
            mysql)
                if ! ls $ARTIFACTORY_HOME/tomcat/lib/mysql-connector-java*.jar 1> /dev/null 2>&1; then
                    errorExit "No mysql connector found"
                fi
                setDBConf
            ;;
            oracle)
                if ! ls $ARTIFACTORY_HOME/tomcat/lib/ojdb*.jar 1> /dev/null 2>&1; then
                    errorExit "No oracle ojdbc driver found"
                fi
                setDBConf
            ;;
            mssql)
                if ! ls $ARTIFACTORY_HOME/tomcat/lib/sqljdbc*.jar 1> /dev/null 2>&1; then
                    errorExit "No mssql connector found"
                fi
                setDBConf
            ;;
            *)
                errorExit "DB_TYPE $DB_TYPE not supported"
            ;;
        esac

        # Wait for DB
        # On slow systems, when working with docker-compose, the DB container might be up,
        # but not ready to accept connections when Artifactory is already trying to access it.
        if [[ ! "$HA_IS_PRIMARY" =~ false ]]; then
            waitForDB "$DB_PROPS" "$DB_TYPE"
            [ $? -eq 1 ] || errorExit "DB $DB_TYPE failed to start in the given time"
        fi
    else
        logger "DB_TYPE not set. Artifactory will use built in Derby DB"
    fi
}

addExtraJavaArgs () {
    logger "Adding EXTRA_JAVA_OPTIONS if exist"
    if [ ! -z "$EXTRA_JAVA_OPTIONS" ] && [ ! -f ${ARTIFACTORY_HOME}/bin/artifactory.default.origin ]; then
        logger "Adding EXTRA_JAVA_OPTIONS $EXTRA_JAVA_OPTIONS"
        cp -v ${ARTIFACTORY_HOME}/bin/artifactory.default ${ARTIFACTORY_HOME}/bin/artifactory.default.origin
        echo "export JAVA_OPTIONS=\"\$JAVA_OPTIONS $EXTRA_JAVA_OPTIONS\"" >> ${ARTIFACTORY_HOME}/bin/artifactory.default
    fi
}

addPlugins () {
    logger "Adding plugins if exist"
    mv -fv /tmp/plugins/* ${ARTIFACTORY_HOME}/etc/plugins/
    chown -R ${ARTIFACTORY_USER_NAME}:${ARTIFACTORY_USER_NAME} ${ARTIFACTORY_HOME}/etc/plugins || errorExit "Setting ownership on ${ARTIFACTORY_HOME}/etc/plugins failed"
}

terminate () {
    echo -e "\nTerminating Artifactory"
    ${ARTIFACTORY_HOME}/bin/artifactory.sh stop
}

# Catch Ctrl+C and other termination signals to try graceful shutdown
trap terminate SIGINT SIGTERM SIGHUP

######### Main #########

echo; echo "Preparing to run Artifactory in Docker"
echo "====================================="

printDockerFileLocation
checkULimits
checkMounts
setupDataDirs
setupAccessDataDirs
prepareArtConfigYaml
setupArtUser
addPlugins
setAccessCreds
setMasterKey
setupPermissions
checkHA
setDBType
addExtraJavaArgs

echo; echo "====================================="; echo

# Run Artifactory as ARTIFACTORY_USER_NAME user
exec gosu ${ARTIFACTORY_USER_NAME} ${ARTIFACTORY_HOME}/bin/artifactory.sh &
art_pid=$!

echo ${art_pid} > ${ARTIFACTORY_PID}

wait ${art_pid}


text:
// Didn't really want to do this one
// Copied from github.com/leebyron

function isFinalState(state) {
    for (let i = 0; i < state.items.length; i++) {
        if (state.items[i] !== 3) {
            return false
        }
    }
    return true
}

// A state is invalid if any Microchip (items[e + 1]) is not near it's Generator
// (items[e]) but on the same floor of another Generator.
function isValidState(state) {
    const items = state.items
    for (let i = 0; i < items.length; i += 2) {
        if (items[i] !== items[i + 1]) {
            for (let j = 0; j < items.length; j += 2) {
                if (items[j] === items[i + 1]) {
                    return false
                }
            }
        }
    }
    return true
}

// If we think of all the possible states as a graph, with edges between
// possible moves, we don't want to get caught in a cycle, so we remember which
// edges we've explored and don't explore them again.
function nextValidUnexploredStates(exploredStates, state) {
    const possibleStates = nextPossibleStates(state)
    return possibleStates.filter(state => {
        const hash = stateHash(state)
        if (exploredStates[hash]) {
            return false
        }
        exploredStates[hash] = true
        return isValidState(state)
    })
}

// Note: a configuration with different elements in the same microchip + generator
// position would eventually reach the same outcome, so this hash intentionally
// looses that information via sorting pairs lexically.
function stateHash(state) {
    const elementPairs = [];
    for (let i = 0; i < state.items.length; i += 2) {
        elementPairs.push(String(state.items[i]) + String(state.items[i + 1]))
    }
    return state.elevator + elementPairs.sort().join('')
}

// From any position, the elevator can move one up or one down and take with it
// 1 or 2 items. Bias towards keeping more items higher on the elevator.
// Note: The elevator only works if it has an item in it.
function nextPossibleStates(state) {
    const canMove = []
    for (let i = 0; i < state.items.length; i++) {
        if (state.items[i] === state.elevator) {
            canMove.push(i)
        }
    }

    const states = []
    if (state.elevator !== 3) {
        for (let i = 0; i < canMove.length; i++) {
            for (let j = i + 1; j < canMove.length; j++) {
                states.push(movedState(states, state, 1, canMove[i], canMove[j]))
            }
            states.push(movedState(states, state, 1, canMove[i]))
        }
    }
    if (state.elevator !== 0) {
        for (let i = 0; i < canMove.length; i++) {
            states.push(movedState(states, state, -1, canMove[i]))
            for (let j = i + 1; j < canMove.length; j++) {
                states.push(movedState(states, state, -1, canMove[i], canMove[j]))
            }
        }
    }
    return states
}

// Compute a state which is one move away from the previous state
function movedState(states, state, direction, itemA, itemB) {
    const nextState = {}
    for (let item in state) {
        nextState[item] = state[item]
    }
    nextState.elevator += direction
    nextState.items = nextState.items.slice()
    nextState.items[itemA] += direction
    if (itemB !== undefined) {
        nextState.items[itemB] += direction
    }
    return nextState
}

// Add to a stack, used for keeping track of the path of moves towards a
// final state.
function conj(prev, state) {
    return { prev, state }
}

// Use a LL queue instead of an array for max perf.
function makeQueue() {
    return { head: null, tail: null, length: 0 }
}

function push(queue, value) {
    const node = { next: null, value }
    if (queue.head) {
        queue.head.next = node
    }
    queue.head = node
    if (!queue.tail) {
        queue.tail = node
    }
    queue.length++
}

function pop(queue) {
    const node = queue.tail
    if (node) {
        queue.tail = node.next
        if (!queue.tail) {
            queue.head = null
        }
        node.next = null
        queue.length--
        return node.value
    }
}

// This will do a breadth-first-search over the possible states of the world.
// Essentially, djikstra's graph search algorithm.
function searchForSolution(initialState) {
    const exploredStates = {}

    const queue = makeQueue()
    push(queue, conj(null, initialState))

    let node
    while (node = pop(queue)) {
        const { state } = node

        // Return final state as a solution path.
        if (isFinalState(state)) {
            const steps = []
            while (node) {
                steps.push(node.state)
                node = node.prev
            }
            return steps.reverse()
        }

        // Otherwise continue the BFS
        const nextStates = nextValidUnexploredStates(exploredStates, state)
        for (let i = 0; i < nextStates.length; i++) {
            push(queue, conj(node, nextStates[i]))
        }
    }

    throw new Error('No solution found')
}

/*
The first floor contains a strontium generator, a strontium-compatible microchip, a plutonium generator, and a plutonium-compatible microchip.
The second floor contains a thulium generator, a ruthenium generator, a ruthenium-compatible microchip, a curium generator, and a curium-compatible microchip.
The third floor contains a thulium-compatible microchip.
The fourth floor contains nothing relevant.

Upon entering the isolated containment area, however, you notice some extra parts on the first floor that weren't listed on the record outside:
An elerium generator.
An elerium-compatible microchip.
A dilithium generator.
A dilithium-compatible microchip.
 */
const initialState = {
    elevator: 0,
    items: [
        0, 0, // Strontium
        0, 0, // Plutonium
        1, 2, // Thulium
        1, 1, // Ruthenium
        1, 1, // Curium
        0, 0, // Elerium
        0, 0, // Dilithium
    ]
}

const solution = searchForSolution(initialState)
console.log('Found solution! Only ' + (solution.length - 1) + ' steps.')

redpajama_set_name: RedPajamaGithub


text:
@interface MOBProjectionEPSG27215 : MOBProjection

@end


text:
package com.crivano.swaggerservlet;

import junit.framework.TestCase;
import junit.framework.TestSuite;

/**
 * Unit test for simple App.
 */
public class ParameterTest extends TestCase {
	private SwaggerServlet ss = null;
	private Swagger sv = null;

	@SuppressWarnings("serial")
	@Override
	protected void setUp() throws Exception {
		super.setUp();
		ss = new SwaggerServlet();
		ss.setAPI(ISwaggerPetstore.class);
		ss.setActionPackage("com.crivano.swaggerservlet");
	}

	@Override
	protected void tearDown() throws Exception {
		super.tearDown();
		ss.destroy();
	}

	public ParameterTest(String testName) {
		super(testName);
	}

	public static junit.framework.Test suite() {
		return new TestSuite(ParameterTest.class);
	}

	public void testGetParameter_Default_Success() throws Exception {
		ss.addPublicProperty("foo", "bar");
		assertEquals("bar", ss.getProperty("foo"));
	}

	public void testGetParameter_Default_WithContext_Success() throws Exception {
		ss.servletContext = "context";
		ss.addPublicProperty("foo", "bar");
		assertEquals("bar", ss.getProperty("foo"));
	}

	public void testGetParameter_Default_ChangeContext_Fail() throws Exception {
		ss.servletContext = "context";
		ss.addPublicProperty("foo", "bar");
		ss.servletContext = "context2";
		try {
			ss.getProperty("foo");
			throw new Exception();
		} catch (RuntimeException ex) {
			assertEquals("Can't access property 'context2.foo' because it was not declared in servlet's initialization",
					ex.getMessage());
		}
	}

	public void testGetGlobalParameter_Default_ChangeContext_Fail() throws Exception {
		ss.servletContext = "context";
		ss.addPublicProperty("/foo", "bar");
		ss.servletContext = "context2";
		assertEquals("bar", ss.getProperty("/foo"));
	}

}


text:
using Microsoft.Extensions.Options;
using OrchardCore.Environment.Extensions;

namespace OrchardCore.Tests.Stubs
{
    public class StubManifestOptions : IOptions<ManifestOptions>
    {
        private ManifestOption[] _options;
        public StubManifestOptions(params ManifestOption[] options)
        {
            _options = options;
        }

        public ManifestOptions Value
        {
            get
            {
                var options = new ManifestOptions();

                foreach (var option in _options)
                {
                    options.ManifestConfigurations.Add(option);
                }

                return options;
            }
        }
    }
}


text:
@import ATPathSpec;

@interface ATPathSpecMatchInfoTests : XCTestCase
@end

@implementation ATPathSpecMatchInfoTests

- (void)testStaticNameMatch {
    ATPathSpec *spec = [ATPathSpec pathSpecWithString:@"README.txt" syntaxOptions:ATPathSpecSyntaxFlavorExtended];
    NSDictionary *info = [spec matchInfoForPath:@"docs/README.txt" type:ATPathSpecEntryTypeFile];
    XCTAssertNotNil(info);
    XCTAssertEqualObjects(info[ATPathSpecMatchInfoMatchedStaticName], @"README.txt");
    XCTAssertNil(info[ATPathSpecMatchInfoMatchedSuffix]);
}

- (void)testStaticNameInSubdirMatch {
    ATPathSpec *spec = [ATPathSpec pathSpecWithString:@"docs/README.txt" syntaxOptions:ATPathSpecSyntaxFlavorExtended];
    NSDictionary *info = [spec matchInfoForPath:@"docs/README.txt" type:ATPathSpecEntryTypeFile];
    XCTAssertNotNil(info);
    XCTAssertEqualObjects(info[ATPathSpecMatchInfoMatchedStaticName], @"README.txt");
    XCTAssertNil(info[ATPathSpecMatchInfoMatchedSuffix]);
}

- (void)testSuffixMaskMatch {
    ATPathSpec *spec = [ATPathSpec pathSpecWithString:@"*.txt" syntaxOptions:ATPathSpecSyntaxFlavorExtended];
    NSDictionary *info = [spec matchInfoForPath:@"docs/README.txt" type:ATPathSpecEntryTypeFile];
    XCTAssertNotNil(info);
    XCTAssertNil(info[ATPathSpecMatchInfoMatchedStaticName]);
    XCTAssertEqualObjects(info[ATPathSpecMatchInfoMatchedSuffix], @".txt");
}

- (void)testDoubleExtensionSuffixMaskMatch {
    ATPathSpec *spec = [ATPathSpec pathSpecWithString:@"*.coffee.md" syntaxOptions:ATPathSpecSyntaxFlavorExtended];
    NSDictionary *info = [spec matchInfoForPath:@"docs/something.coffee.md" type:ATPathSpecEntryTypeFile];
    XCTAssertNotNil(info);
    XCTAssertNil(info[ATPathSpecMatchInfoMatchedStaticName]);
    XCTAssertEqualObjects(info[ATPathSpecMatchInfoMatchedSuffix], @".coffee.md");
}

- (void)testPatternMatch {
    ATPathSpec *spec = [ATPathSpec pathSpecWithString:@"*o*/READ*.txt" syntaxOptions:ATPathSpecSyntaxFlavorExtended];
    NSDictionary *info = [spec matchInfoForPath:@"docs/README.txt" type:ATPathSpecEntryTypeFile];
    XCTAssertNotNil(info);
    XCTAssertNil(info[ATPathSpecMatchInfoMatchedStaticName]);
    XCTAssertEqualObjects(info[ATPathSpecMatchInfoMatchedSuffix], @".txt");
}

- (void)testMaskMatchInPath {
    ATPathSpec *spec = [ATPathSpec pathSpecWithString:@"*.txt" syntaxOptions:ATPathSpecSyntaxFlavorGitignore];
    NSDictionary *info = [spec matchInfoForPath:@"docs.txt/README.md" type:ATPathSpecEntryTypeFile];
    XCTAssertNotNil(info);
    XCTAssertNil(info[ATPathSpecMatchInfoMatchedStaticName]);
    XCTAssertNil(info[ATPathSpecMatchInfoMatchedSuffix]);
}

- (void)testPatternMatchWithNegation {
    ATPathSpec *spec = [ATPathSpec pathSpecWithString:@"*.txt !~*" syntaxOptions:ATPathSpecSyntaxFlavorExtended];
    NSDictionary *info = [spec matchInfoForPath:@"docs/README.txt" type:ATPathSpecEntryTypeFile];
    XCTAssertNotNil(info);
    XCTAssertNil(info[ATPathSpecMatchInfoMatchedStaticName]);
    XCTAssertEqualObjects(info[ATPathSpecMatchInfoMatchedSuffix], @".txt");
}

- (void)testWildMatchWithNegation {
    ATPathSpec *spec = [ATPathSpec pathSpecWithString:@"READ* !~*.txt" syntaxOptions:ATPathSpecSyntaxFlavorExtended];
    NSDictionary *info = [spec matchInfoForPath:@"docs/README.txt" type:ATPathSpecEntryTypeFile];
    XCTAssertNotNil(info);
    XCTAssertNil(info[ATPathSpecMatchInfoMatchedStaticName]);
    XCTAssertNil(info[ATPathSpecMatchInfoMatchedSuffix]);
}

- (void)testStaticAndPatternIntersectionMatch {
    ATPathSpec *spec = [ATPathSpec pathSpecWithString:@"README.txt & *.txt" syntaxOptions:ATPathSpecSyntaxFlavorExtended];
    NSDictionary *info = [spec matchInfoForPath:@"docs/README.txt" type:ATPathSpecEntryTypeFile];
    XCTAssertNotNil(info);
    XCTAssertEqualObjects(info[ATPathSpecMatchInfoMatchedStaticName], @"README.txt");
    XCTAssertEqualObjects(info[ATPathSpecMatchInfoMatchedSuffix], @".txt");
}

@end


text:
package com.vedantatree.redmineconnector.test;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;

import java.util.Iterator;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.vedantatree.redmineconnector.RCException;
import com.vedantatree.redmineconnector.RedmineConnector;
import com.vedantatree.redmineconnector.RedmineDataPaginator;
import com.vedantatree.redmineconnector.bdo.RedmineBDO;
import com.vedantatree.redmineconnector.bdo.User;

/**
 * Test case for RedmineConnector User API
 *
 *
 * @author Mohit Gupta [mohit.gupta@vedantatree.com]
 * @since 1.1.0
 */
public class TestRedmineUser
{

	private static Log			LOGGER	= LogFactory.getLog( TestRedmineProjects.class );

	private RedmineConnector	redmineConnector;

	@Before
	public void setUp() throws Exception
	{
		// TODO clean all redmine data
		redmineConnector = RedmineConnector.getSharedInstance();
	}

	@After
	public void tearDown() throws Exception
	{
		// TODO clean all redmine data
		redmineConnector = null;

		// write a class for data cleaning, like all projects, users, issues etc
	}

	@Test
	public void testUserCRUD() throws Exception
	{
		User newUser = TestUtils.newUserInstance();
		User createdUser = null;
		try
		{
			createdUser = redmineConnector.createUser( newUser );
			TestUtils.checkUserData( newUser, createdUser );

			createdUser = redmineConnector.getUserById( createdUser.getId(), null );
			TestUtils.checkUserData( newUser, createdUser );

			createdUser.setFirstName( createdUser.getFirstName() + "-U-" );
			redmineConnector.updateUser( createdUser );
			User updatedUser = redmineConnector.getUserById( createdUser.getId(), null );
			TestUtils.checkUserData( createdUser, updatedUser );

		}
		finally
		{
			if( createdUser != null )
			{
				LOGGER.debug( "deleting user >>>>>>>>>>>>>>>>>>>>>>>>>" + createdUser.getId() + "----"
						+ createdUser.getLogin() );
				boolean deleted = redmineConnector.deleteUser( createdUser.getId() );
				assertEquals( "Requested to delete the User, result should be true but received false", true, deleted );
			}
		}

		try
		{
			createdUser = redmineConnector.getUserById( createdUser.getId(), null );
		}
		catch( RCException rce )
		{
			if( rce.getErrorCode() != RCException.OBJECT_NOT_FOUND )
			{
				fail( "User has already been deleted. However we get the User object from Redmine. rceErrorCode["
						+ rce.getErrorCode() + "]" );
			}
			createdUser = null;
		}
		assertNull(
				"User has already been deleted. So a request for object should return Exception, however we didn't get the exception",
				createdUser );
	}

	@Test
	public void testUserPaginator() throws Exception
	{
		try
		{
			UserCreator userCreator = new UserCreator( 1 );
			TestUtils.executeJob( userCreator );

			RedmineDataPaginator userPaginator = redmineConnector.getUsersIterator( 0, 25, null, null );

			do
			{
				List<RedmineBDO> users = userPaginator.nextPageRecords();
				System.err.println( "############users-size[" + ( users != null ? users.size() : -1 ) + "]" );

				for( Iterator iterator = users.iterator(); iterator.hasNext(); )
				{
					User user = (User) iterator.next();
					// if( true )
					// {
					// throw new UnsupportedOperationException(
					// "Review this method carefully for Admin user check below. If it is correct, comment it "
					// + "and then run the test case. If it is wrong, it can delete Redmine Admin user also. "
					// + "Check carefully." );
					// }
					if( user.getLogin().indexOf( "admin" ) >= 0 || user.getId() == 1 )
					{
						LOGGER.debug( "GOT ADMIN>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" + user.getLogin()
								+ "---" + user.getId() );
						continue;
					}
					redmineConnector.deleteUser( user.getId() );
				}

			} while( userPaginator.hasMoreRecords() );

		}
		catch( Exception ex )
		{
			LOGGER.error( ex );
			ex.printStackTrace();
			fail( "Failed due to exception faced. Exception[" + ex.getMessage() + "]" );
		}
	}

	class UserCreator implements Runnable
	{

		private int		issueCount;
		private User	user;

		public UserCreator( int issuesCountPerJob )
		{
			this.issueCount = issuesCountPerJob;
		}

		public void run()
		{
			for( int i = 0; i < issueCount; i++ )
			{
				try
				{
					Thread.sleep( 1000 );
					User newUser = TestUtils.newUserInstance();
					redmineConnector.createUser( newUser );
				}
				catch( Exception e )
				{
					// TODO: this error does not fail the test case being in different thread. Do something.
					LOGGER.error( e );
					fail( e.getMessage() );
				}
			}
		}
	}

}


text:
'use strict';

// MODULES //

var logger = require( 'debug' );
var walk = require( 'acorn-walk' );
var isNamespaceAssignment = require( './is_namespace_assignment.js' );

// VARIABLES //

var debug = logger( 'lint-namespace-aliases:walk' );

// MAIN //

/**
* Walks an AST in search of namespace assignments.
*
* ## Notes
*
* -   We assume that a namespace assignment has the form
*
*     ```javascript
*     setReadOnly( namespace, '<name>', require( '<identifier>' ) );
*     ```
*
*
* @private
* @param {string} src - source string
* @param {Object} ast - AST
* @returns {(EmptyArray|ObjectArray)} results
*/
function walker( src, ast ) {
	var opts;
	var out;

	out = [];
	opts = {
		'CallExpression': callExpression
	};
	walk.recursive( ast, null, opts );

	return out;

	/**
	* Callback invoked upon visiting a `CallExpression` AST node.
	*
	* @private
	* @param {Node} node - AST node
	* @param {*} state - start state
	* @param {Callback} clbk - callback to continue walking a sub-node
	*/
	function callExpression( node ) {
		var alias;
		var arg;
		var id;

		if ( isNamespaceAssignment( node ) === false ) {
			return;
		}
		if ( node.arguments.length ) {
			arg = node.arguments[ 1 ];
			if ( arg && arg.type === 'Literal' ) {
				alias = arg.value;
				debug( 'Namespace property: %s', alias );
			}
			arg = node.arguments[ 2 ];
			if (
				arg &&
				arg.type === 'CallExpression' &&
				arg.callee.type === 'Identifier' &&
				arg.callee.name === 'require'
			) {
				id = arg.arguments[ 0 ].value;
				debug( 'Package identifer: %s', id );
			}
			if ( alias && id ) {
				debug( 'Found a namespace assignment.' );
				out.push({
					'id': id,
					'alias': alias
				});
			}
		}
	}
}

// EXPORTS //

module.exports = walker;


text:
require "/perfstat/build/serialize/create/ServiceConfig.pl";

#add create new service
$service = Service->new(	RRA => "RRA:AVERAGE:0.5:1:1728 RRA:AVERAGE:0.5:6:1296 RRA:AVERAGE:0.5:24:996 RRA:AVERAGE:0.5:144:730",
							rrdStep => "300",
							serviceName => "cpu",
						);

#add metric 0
$obj = Metric->new(	rrdIndex => 0,
					metricName => "usrPct",
					friendlyName => "User % Utilization",
					status => "nostatus",
					rrdDST => GAUGE,
					rrdHeartbeat => 600,
					rrdMin => 0,
					rrdMax => U,
					hasEvents => 1,
					warnThreshold => 75,
					critThreshold => 90,
					thresholdUnit => "Percent",
					);
$service->addMetric($obj);

#add metric 1
$obj = Metric->new(	rrdIndex => 1,
					metricName => "sysPct",
					friendlyName => "System % Utilization",
					status => "nostatus",
					rrdDST => GAUGE,
					rrdHeartbeat => 600,
					rrdMin => 0,
					rrdMax => U,
					hasEvents => 1,
					warnThreshold => 75,
					critThreshold => 90,
					thresholdUnit => "Percent",
					);
$service->addMetric($obj);

#add metric 2
$obj = Metric->new(	rrdIndex => 2,
					metricName => "idlePct",
					friendlyName => "Idle % Utilization",
					status => "nostatus",
					rrdDST => GAUGE,
					rrdHeartbeat => 600,
					rrdMin => 0,
					rrdMax => U,
					hasEvents => 1,
					warnThreshold => 75,
					critThreshold => 90,
					thresholdUnit => "Percent",
					);
$service->addMetric($obj);

#add metric 3
$obj = Metric->new(	rrdIndex => 3,
					metricName => "load1",
					friendlyName => "Load Average (1 Minute)",
					status => "nostatus",
					rrdDST => GAUGE,
					rrdHeartbeat => 600,
					rrdMin => 0,
					rrdMax => U,
					hasEvents => 1,
					warnThreshold => 3,
					critThreshold => 5,
					thresholdUnit => "Number",
					);
$service->addMetric($obj);

#add metric 4
$obj = Metric->new(	rrdIndex => 4,
					metricName => "load5",
					friendlyName => "Load Average (5 Minute)",
					status => "nostatus",
					rrdDST => GAUGE,
					rrdHeartbeat => 600,
					rrdMin => 0,
					rrdMax => U,
					hasEvents => 1,
					warnThreshold => 3,
					critThreshold => 5,
					thresholdUnit => "Number",
					);
$service->addMetric($obj);

#add metric 5
$obj = Metric->new(	rrdIndex => 5,
					metricName => "load15",
					friendlyName => "Load Average (15 Minute)",
					status => "nostatus",
					rrdDST => GAUGE,
					rrdHeartbeat => 600,
					rrdMin => 0,
					rrdMax => U,
					hasEvents => 1,
					warnThreshold => 3,
					critThreshold => 5,
					thresholdUnit => "Number",
					);
$service->addMetric($obj);

#add graph 0
$obj = Graph->new(	name   => "load",
					title   => "load average on",
					y_axis  => "Number",
					legend  => "",
					optionsArray => [qq{-u 1.0}],
					defArray => [q{DEF:load1=$RRD:load1:AVERAGE},q{DEF:load5=$RRD:load5:AVERAGE},q{DEF:load15=$RRD:load15:AVERAGE}],
					cdefArray => [],
					lineArray => [qq{LINE2:load1#FF0000:1 Min Load},qq{LINE2:load5#FFFF00:5 Min Load},qq{LINE2:load15#00CC00:15 Min Load}],
					text    => "",
					);
$service->addGraph($obj);

#add graph 1
$obj = Graph->new(	name => "usage",
					title   => "CPU usage on",
					y_axis  => "Number",
					legend  => "",
					optionsArray => [qq{-u 100},qq{-r}],,
					defArray => [q{DEF:idlePct=$RRD:idlePct:AVERAGE},q{DEF:usrPct=$RRD:usrPct:AVERAGE},q{DEF:sysPct=$RRD:sysPct:AVERAGE}],
					cdefArray => [],
					lineArray => [qq{AREA:sysPct#FF0000:System},qq{STACK:usrPct#FFFF00:User},qq{STACK:idlePct#00FF00:Idle}],
					text    => "",
					);
$service->addGraph($obj);

#print out this service
print ("Ref: ref($service)\n");

$serviceName = $service->getServiceName();
$RRA = $service->getRRA();
$rrdStep = $service->getRRDStep();
$lastUpdate = $service->getLastUpdate();
print ("serviceName: $serviceName\n");
print ("RRA: $RRA\n");
print ("rrdStep: $rrdStep\n");
print ("Last Update: $lastUpdate\n");

#print out this services metrics
$arrayLength = $service->getMetricArrayLength();
print ("metric Array Length = $arrayLength\n\n");

for ($counter=0; $counter < $arrayLength; $counter++)
{
	$metricObject = $service->{metricArray}->[$counter];

	$rrdIndex = $metricObject->getRRDIndex();
    $rrdDST = $metricObject->getRRDDST();
    $rrdHeartbeat = $metricObject->getRRDHeartbeat();
    $rrdMin = $metricObject->getRRDMin();
    $rrdMax = $metricObject->getRRDMax();
	$metricName = $metricObject->getMetricName();
	$friendlyName = $metricObject->getFriendlyName();
	$status = $metricObject->getStatus();
	$hasEvents = $metricObject->getHasEvents();
	$warnThreshold = $metricObject->getWarnThreshold();
	$critThreshold = $metricObject->getCritThreshold();
	$thresholdUnit	= $metricObject->getThresholdUnit();

	print ("rrdIndex: $rrdIndex\n");
    print ("rrdDST: $rrdDST\n");
    print ("rrdHeartbeat: $rrdHeartbeat\n");
    print ("rrdMin: $rrdMin\n");
    print ("rrdMax: $rrdMax\n");
	print ("metricName: $metricName\n");
	print ("friendlyName: $friendlyName\n");
    print ("status: $status\n");
	print ("hasEvents: $hasEvents\n");
	print ("warnThreshold: $warnThreshold\n");
	print ("critThreshold: $critThreshold\n");
	print ("threshUnit: $thresholdUnit\n\n");
}

#print out this services graphs
$arrayLength = $service->getGraphArrayLength();
print ("graph Array Length = $arrayLength\n\n");

for ($counter=0; $counter < $arrayLength; $counter++)
{
	$graphObject = $service->{graphArray}->[$counter];

	$name = $graphObject->getName();
	$title = $graphObject->getTitle();
	$y_axis = $graphObject->getYaxis();
	$legend = $graphObject->getLegend();
	$text = $graphObject->getText();

	print ("name: $name\n");
	print ("title: $title\n");
	print ("y_axis: $y_axis\n");
	print ("legend: $legend\n");
	print ("text: $text\n");

	$arrayLength2 = $graphObject->getOptionsArrayLength();
	for ($counter2=0; $counter2 < $arrayLength2; $counter2++)
	{
		print ("option: $graphObject->{optionsArray}->[$counter2]\n");
	}
	$arrayLength2 = $graphObject->getDefArrayLength();
	for ($counter2=0; $counter2 < $arrayLength2; $counter2++)
	{
		print ("def: $graphObject->{defArray}->[$counter2]\n");
	}
	$arrayLength2 = $graphObject->getCdefArrayLength();
	for ($counter2=0; $counter2 < $arrayLength2; $counter2++)
	{
		print ("cdef: $graphObject->{cdefArray}->[$counter2]\n");
	}
	$arrayLength2 = $graphObject->getLineArrayLength();
	for ($counter2=0; $counter2 < $arrayLength2; $counter2++)
	{
		print ("line: $graphObject->{lineArray}->[$counter2]\n");
	}
}

#Store the service
$service->store("$perfhome/etc/configs/Linux/$service->{serviceName}.ser") or die("can't store $service->{serviceName}.ser?\n");


text:
const {expect} = require('chai');
const EngineConfig = require('./engines');

describe('The \'engines\' configuration section', () => {
    it('can configure templating engines for an app', () => {
        const engines = {};
        const app = {
            engine(ext, callback) {
                engines[ext] = callback;
            },
        };
        const conf = {
            engines: {
                'jade': () => 'derp',
            },
        };

        new EngineConfig(app, conf).configure();
        expect(engines.jade).to.be.a.function;
        expect(engines.jade()).to.equal('derp');
    });
});


text:
import * as React from 'react';
import SidebarContainer from './sidebar.container';
import AppInitContainer from './app-init.container';
import SearchOverlayContainer from '../instance/search/search-overlay.container';
import SshContainer from '../instance/ssh/ssh.container';
import LogsContainer from '../instance/logs/logs.container';
import CreateAppFloatingButtonContainer from '../instance/create-app/floating-button/create-app-floating-button.container';
import CreateAppModalContainer from '../instance/create-app/create-app-modal.container';
import PurchaseContainer from '../instance/market/purchase/purchase.container';

const style = {
	container: {
		width: '100%',
		tableLayout: 'fixed'
	},
	sidebar: {
		width: 160,
		minWidth: 160
	},
	content: {
		marginRight: 10
	}
};

export class LayoutComponent extends React.Component<any, any> {

	constructor(props, context) {
		super(props, context);
	}

	render() {
		return (

				{
					this.props.settings.isLoggedIn ? (

										<SidebarContainer />

											<SearchOverlayContainer />
											<SshContainer />
											<LogsContainer />
											<CreateAppFloatingButtonContainer />
											<PurchaseContainer />
											{
												this.props.createApp.showCreateAppDialog ? (
														<CreateAppModalContainer />
													) : (

													)
											}
											{this.props.children}

						) : (
							<AppInitContainer />
						)
				}

		)
	}
}


text:
package com.example.recyclerview;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.ArrayList;

/**
 * Created by Administrator on 2016/9/21.
 */
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.RecyclerHolder> {

    private ArrayList<String> titles;
    private Context context;
    private OnItemClickListener listener;

    public RecyclerViewAdapter(Context context, ArrayList<String> titles){
        this.context = context;
        this.titles = titles;
    }

    /**
     * 创建ViewHolder
     * @param parent 父布局
     * @param viewType  类型
     * @return
     */
    @Override
    public RecyclerHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return new RecyclerHolder(View.inflate(context,R.layout.item_recyclerholder,null));
    }

    /**
     * 绑定Holder 根据item个数每次都会绑定
     * @param holder 每个item的hodler
     * @param position 角标
     */
    @Override
    public void onBindViewHolder(RecyclerHolder holder,final int position) {
        holder.titles.setText(titles.get(position));
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                listener.onItemClick(v,position);
            }
        });
    }

    /**
     * 获取多少个item
     * @return
     */
    @Override
    public int getItemCount() {
        return titles.size();
    }

    public interface OnItemClickListener{
        void onItemClick(View view,int position);
    }

    public void setOnItemClickListener(OnItemClickListener listener){
        this.listener = listener;
    }

    public static class RecyclerHolder extends RecyclerView.ViewHolder {

        public final ImageView images;
        public final TextView titles;

        public RecyclerHolder(View itemView) {
            super(itemView);
            images = (ImageView) itemView.findViewById(R.id.img_item);
            titles = (TextView) itemView.findViewById(R.id.tv_item);
        }
    }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<meta name="copyright" content="(C) Copyright 2005" />
<meta name="DC.rights.owner" content="(C) Copyright 2005" />
<meta content="public" name="security" />
<meta content="index,follow" name="Robots" />
<meta http-equiv="PICS-Label" content='(PICS-1.1 "http://www.icra.org/ratingsv02.html" l gen true r (cz 1 lz 1 nz 1 oz 1 vz 1) "http://www.rsac.org/ratingsv01.html" l gen true r (n 0 s 0 v 0 l 0) "http://www.classify.org/safesurf/" l gen true r (SS~~000 1))' />
<meta content="concept" name="DC.Type" />
<meta name="DC.Title" content="About this guide" />
<meta scheme="URI" name="DC.Relation" content="cadminpreface11181.html" />
<meta scheme="URI" name="DC.Relation" content="cadminpreface22460.html" />
<meta scheme="URI" name="DC.Relation" content="cadminpreface23947.html" />
<meta content="XHTML" name="DC.Format" />
<meta content="cadminpreface30074" name="DC.Identifier" />
<meta content="en-us" name="DC.Language" />
<link href="commonltr.css" type="text/css" rel="stylesheet" />
<title>About this guide</title>

About this guide

For general information about the
Derby documentation, such as
a complete list of books, conventions, and further reading, see
Getting Started with Derby.

For more information about
Derby, visit the
Derby website at
http://db.apache.org/derby.
The website provides pointers to the
Derby Wiki and other
resources, such as the derby-users mailing list, where you can ask questions
about issues not covered in the documentation.

Purpose of this guide

This guide explains how to use Derby in a multiple-client environment. It also provides information that a server administrator might need to keep Derby running with a high level of performance and reliability in a server framework or in a multiple-client application server environment.

Audience

This guide has two parts, each for a different audience.

How this guide is organized

This guide includes the following two parts.


text:
<?php
$lan = array(
  "This page can only be called from the commandline" => "Cette page ne peut être affichée que par ligne de commande",
  "Bounce processing error" => "Erreur dans le traitement des emails rejetés",
  "Bounce Processing info" => "Infos sur le traitement des emails rejetés",
  "error" => "erreur",
  "info" => "info",
  "system message bounced, user marked unconfirmed" => "le message envoyé par le système a été rejeté, l’utilisateur a été marqué comme étant non-confirmé",
  "Bounced system message" => "Message envoyé par le système et rejeté",
  "User marked unconfirmed" => "Utilisateur marqué comme non-confirmé",
  "View Bounce" => "Afficher message rejeté",
  "Cannot create POP3 connection to" => "Ne peut créer une connexion POP3 avec",
  "Cannot open mailbox file" => "Ne peut ouvrir le fichier mailbox",
  "bounces to fetch from the mailbox" => "messages rejetés qu’il faut récupérer de la boîte aux lettres (mailbox)",
  "Please do not interrupt this process" => "Merci de ne pas interrompre ce processus",
  "bounces to process" => "messages rejetés à traiter",
  "Processing first" => "Traitement des premiers",
  "bounces" => "messages rejetés",
  "Running in test mode, not deleting messages from mailbox" => "Vous êtes en mode test, les messages ne seront pas supprimés de la boîte aux lettres",
  "Processed messages will be deleted from mailbox" => "Les messages traités seront supprimés de la boîte aux lettres",
  "Deleting message" => "Suppression du message",
  "Closing mailbox, and purging messages" => "Fermeture de la boîte aux lettres et purge des messages",
  "IMAP is not included in your PHP installation, cannot continue" => "IMAP n’est pas inclu dans votre installation PHP, impossible de poursuivre",
  "Check out" => "Consulter",// or 'go look', 'consult', etc.
  "Bounce mechanism not properly configured" => "Le méchanisme de traitement des messages rejetés n’est pas correctement configuré",
  "bounce_protocol not supported" => "bounce_protocol n’est pas installé",
  "Identifying consecutive bounces" => "Identification de rejets successifs de messages",
  "Nothing to do" => "Rien à faire",
  "Process Killed by other process" => "Le processus a été arrêté par un autre processus",
// 3 lines below = one sentence
  "User" => "L’utilisateur",
  "has consecutive bounces" => "a des rejets de messages successifs",
  "over threshold, user marked unconfirmed" => "au-dessus de la limite, l’utilisateur a été marqué comme non-confirmé",
  "Auto Unsubscribed" => "Auto Désinscrit",
// 2 lines below = one sentence
  "User auto unsubscribed for" => "L’utilisateur a été autodésinscrit suite à",
  "consecutive bounces" => "rejets de messages successifs",
// 3 lines below = one sentence
  "Identifying consecutive bounces" => "Identification de messages rejetés consécutifs",
  "of" => "de",
  "users processed" => "utilisateurs traités",
'processing first' => 'traitement des premiers',
'Report:' => 'Rapport:',
'Below are users who have been marked unconfirmed. The number in [] is their userid, the number in () is the number of consecutive bounces' => 'Ci-dessous, les utilisateurs qui ont été marqués comme étant non-confirmés.  Le numéro entre crochets [] est leur userid, le numéro entre parenthèses () est le nombre de rejets de messages successifs',
  'system message bounced, but unknown user' => 'le message système a été rejeté, mais l’utilisateur n’existe pas',
'Processing bounces based on active bounce rules' => 'Traitement des messages rejetés en fonction des règles en vigueur pour les messages rejetés',
'bounce rule' => 'règle pour les messages rejetés',
'Auto Blacklisted' => 'Automatiquement mis sur liste noire',
'User auto blacklisted for' => 'Utilisateur automatiquement mis sur liste noir pour',
'bounces processed by advanced processing' => 'messages rejetés traités par le traitement avancé',
'bounces were not matched by advanced processing rules' => 'les messages rejetés ne correspondent pas au règles de traitement avancé',
'Report of advanced bounce processing:' => 'Rapport de traitement avancé des messages rejetés:',
);
?>


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Atlas des Champignons de l'Europe 39: 56 (1941)

#### Original name
Inonotus rheades var. rheades (Pers.) Bondartsev & Singer

### Remarks
null


text:
package com.github.mikhailerofeev.runity.domain.service;

import com.github.mikhailerofeev.runity.domain.entities.Employee;
import com.github.mikhailerofeev.runity.domain.entities.Structure;
import com.github.mikhailerofeev.runity.domain.repository.EmployeeRepository;
import com.github.mikhailerofeev.runity.domain.repository.StructureRepository;
import org.apache.commons.lang3.tuple.Pair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * Created by Максим on 27.04.2014.
 */
@Service
public class ParamRatingService {
    @Autowired
    EmployeeRepository employeeRepository;

    @Autowired
    StructureRepository structureRepository;

    public Employee upRatingParam(String id, String param, boolean like) throws Exception {
        Employee employee = getRatingOfParam(id, param);

        if(like){
            employee.increaseParamRating(param);
        } else{
            employee.decreaseParamRating(param);
        }
        return employeeRepository.save(employee);
    }

    public Employee getRatingOfParam(String id, String param) throws Exception {
        Employee employee = employeeRepository.findOne(id);
        if(employee == null) throw new NullPointerException(id);

        Map<String, Pair<Integer, Integer>> paramsRating = employee.getParamRating();

        if(!paramsRating.containsKey(param)) {
            employee.addParamRating(param);
        }
        return employeeRepository.save(employee);
    }

    public Structure upRatingParamStructure(String id, String param, boolean like) throws Exception {
        Structure structure = structureRepository.findOne(id);
        if(structure == null) throw new NullPointerException(id);

        Map<String, Pair<Integer, Integer>> paramsRating = structure.getParamRating();

        if(!paramsRating.containsKey(param)) {
            structure.addParamRating(param);
        }

        if(like){
            structure.increaseParamRating(param);
        } else{
            structure.decreaseParamRating(param);
        }
        return structureRepository.save(structure);
    }

}


text:
<?php

if (!CM_Db_Db::existsColumn('cm_user_online', 'offlineStamp')) {
    CM_Db_Db::exec("ALTER TABLE `cm_user_online` ADD `offlineStamp` int(10) unsigned DEFAULT NULL, ADD INDEX `offlineStamp` (`offlineStamp`)");
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Frameset//EN""http://www.w3.org/TR/REC-html40/frameset.dtd">

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
: Class  GeoCode
</TITLE>
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  SUMMARY:  INNER | FIELD | CONSTR | METHOD

DETAIL:  FIELD | CONSTR | METHOD

ru.yandex.yandexmapkit.map

Class  GeoCode

java.lang.Object
  |
  +--ru.yandex.yandexmapkit.map.GeoCode

public class GeoCode
extends java.lang.Object

GeoCode.java: Prepares a request for reverse geocoding.

This file is a part of the Yandex Map Kit.

 Version for Android © 2012 YANDEX

 You may not use this file except in compliance with the License.

 You may obtain a copy of the License at http://legal.yandex.ru/mapkit/

Field Summary

static java.lang.String
OBJECT_KIND_AREA

          Returns the regional (oblast) district.

static java.lang.String
OBJECT_KIND_BRIDGE

          Returns the name of the bridge.

static java.lang.String
OBJECT_KIND_CEMETERY

          Returns the name of the cemetery.

static java.lang.String
OBJECT_KIND_COUNTRY

          Returns the country name.

static java.lang.String
OBJECT_KIND_DISTRICT

          Returns the area district.

static java.lang.String
OBJECT_KIND_HOUSE

          Returns the house number.

static java.lang.String
OBJECT_KIND_HYDRO

          Returns the hydro resource.

static java.lang.String
OBJECT_KIND_KM

          Returns the closest kilometer sign (on a highway).

static java.lang.String
OBJECT_KIND_LOCALITY

          Returns the locality.

static java.lang.String
OBJECT_KIND_METRO

          Returns the subway station.

static java.lang.String
OBJECT_KIND_OTHER

          Returns any other type of place.

static java.lang.String
OBJECT_KIND_PROVINCE

          Returns the province.

static java.lang.String
OBJECT_KIND_RAILWAY

          Returns the railway station.

static java.lang.String
OBJECT_KIND_ROUTE

          Returns the route.

static java.lang.String
OBJECT_KIND_STREET

          Returns the street name.

static java.lang.String
OBJECT_KIND_VEGETATION

          Returns the vegetation (type of landscape).

Method Summary

 java.lang.String
getDisplayName()

          Returns the full geocoded address.

 GeoPoint
getGeoPoint()

          Returns the geographical point for which the reverse geocoding has been requested.

 java.lang.String
getKind()

          Returns the type of the object found.

 java.lang.String
getSubtitle()

          Returns the second address line (subtitle).

 java.lang.String
getTitle()

          Returns the first address line (title).

Field Detail

OBJECT_KIND_HOUSE

public static final java.lang.String OBJECT_KIND_HOUSE

Returns the house number.

OBJECT_KIND_STREET

public static final java.lang.String OBJECT_KIND_STREET

Returns the street name.

OBJECT_KIND_METRO

public static final java.lang.String OBJECT_KIND_METRO

Returns the subway station.

OBJECT_KIND_DISTRICT

public static final java.lang.String OBJECT_KIND_DISTRICT

Returns the area district.

OBJECT_KIND_LOCALITY

public static final java.lang.String OBJECT_KIND_LOCALITY

Returns the locality.

OBJECT_KIND_AREA

public static final java.lang.String OBJECT_KIND_AREA

Returns the regional (oblast) district.

OBJECT_KIND_PROVINCE

public static final java.lang.String OBJECT_KIND_PROVINCE

Returns the province.

OBJECT_KIND_COUNTRY

public static final java.lang.String OBJECT_KIND_COUNTRY

Returns the country name.

OBJECT_KIND_HYDRO

public static final java.lang.String OBJECT_KIND_HYDRO

Returns the hydro resource.

OBJECT_KIND_RAILWAY

public static final java.lang.String OBJECT_KIND_RAILWAY

Returns the railway station.

OBJECT_KIND_ROUTE

public static final java.lang.String OBJECT_KIND_ROUTE

Returns the route.

OBJECT_KIND_VEGETATION

public static final java.lang.String OBJECT_KIND_VEGETATION

Returns the vegetation (type of landscape).

OBJECT_KIND_CEMETERY

public static final java.lang.String OBJECT_KIND_CEMETERY

Returns the name of the cemetery.

OBJECT_KIND_BRIDGE

public static final java.lang.String OBJECT_KIND_BRIDGE

Returns the name of the bridge.

OBJECT_KIND_KM

public static final java.lang.String OBJECT_KIND_KM

Returns the closest kilometer sign (on a highway).

OBJECT_KIND_OTHER

public static final java.lang.String OBJECT_KIND_OTHER

Returns any other type of place.

Method Detail

getDisplayName

public java.lang.String getDisplayName()

Returns the full geocoded address.
 It is a combination of the first and the second address lines (title and subtitle).

Returns:
the full geocoded address, i.e. "Moscow, Russia, Leo Tolstoy St, 16"

getTitle

public java.lang.String getTitle()

Returns the first address line (title).

Returns:
the first address line (title) representing more detailed info, i.e. "Leo Tolstoy St, 16"

getSubtitle

public java.lang.String getSubtitle()

Returns the second address line (subtitle).

Returns:
the second address line (subtitle) representing more general info, i.e. "Moscow, Russia"

getKind

public java.lang.String getKind()

Returns the type of the object found.
 See descriptions of GeoCode object methods (OBJECT_KIND_***).

Returns:

getGeoPoint

public GeoPoint getGeoPoint()

Returns the geographical point for which the reverse geocoding has been requested.

Returns:
the geographical point for which the reverse geocoding has been requested

    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  SUMMARY:  INNER | FIELD | CONSTR | METHOD

DETAIL:  FIELD | CONSTR | METHOD


text:
# WCSAlertController

UIAlertController example with a few extra parameters and completion block.

## UIAlertControllerStyleActionSheet
    /*!
     *  @param buttons @[ STRING_CANCEL, STRING_OK ]
     *  @param controller SELF for UIViewController, NIL for rootViewController
     *  @param completion VALUES stores textfield values in order
     */
    + (void)action:(NSString*)title
           message:(NSString*)message
               tag:(NSInteger)tag
       destructive:(NSArray*)destructives
           buttons:(NSArray*)buttons
        controller:(UIViewController*)controller
          animated:(BOOL)animated
        completion:(void (^)(NSInteger buttonIndex))completion;

## UIAlertControllerStyleAlert

    /*!
     *  @param fields @[ @{ @"text":@"string",
                            @"placeholder":@"string",
                            @"secure":@NO, ,
                            @"keyboard":[NSNumber numberWithInteger:UIKeyboardTypeAlphabet]
                            } ]
     *  @param buttons @[ STRING_CANCEL, STRING_OK ]
     *  @param controller SELF for UIViewController, NIL for rootViewController
     *  @param completion VALUES stores textfield values in order
     */
    + (void)alert:(NSString*)title
          message:(NSString*)message
              tag:(NSInteger)tag
           fields:(NSArray*)fields
          buttons:(NSArray*)buttons
       controller:(UIViewController*)controller
         animated:(BOOL)animated
       completion:(void (^)(BOOL ok, NSArray * values))completion;

## Example login style alert

    [WCSAlertController alert:NSLocalizedString(@"Login style Alert", nil)
                      message:NSLocalizedString(@"This is an alert with a regular text field and a password field.", nil)
                          tag:0
                       fields:@[ @{ @"text":@"",
                                    @"placeholder":NSLocalizedString(@"Username", nil),
                                    @"secure":@NO,
                                    @"keyboard":[NSNumber numberWithInteger:UIKeyboardTypeAlphabet]
                                    },
                                 @{ @"text":@"",
                                    @"placeholder":NSLocalizedString(@"Password", nil),
                                    @"secure":@YES,
                                    @"keyboard":[NSNumber numberWithInteger:UIKeyboardTypeAlphabet]
                                    }]
                      buttons:@[ STRING_CANCEL, STRING_OK ]
                   controller:nil
                     animated:YES
                   completion:^(BOOL ok, NSArray * _Nonnull values) {
                       if ( ok )
                           NSLog(@"Username: %@, Password: %@", values[0], values[1]);
                       else
                           NSLog(@"Cancel pressed.");
                   }];


text:
package com.totango.discoveryagent.gson;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.totango.discoveryagent.model.Service;

public class ServiceDeserializer implements JsonDeserializer<Service> {

  @Override
  public Service deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
      throws JsonParseException {
    JsonObject jsonObj = (JsonObject) json;

    JsonObject nodeObject = (JsonObject)jsonObj.get("Node");
    String node = nodeObject.get("Node").getAsString();
    String nodeAddress = nodeObject.get("Address").getAsString();

    JsonObject serviceObject = (JsonObject)jsonObj.get("Service");
    String serviceId = serviceObject.get("ID").getAsString();
    String serviceName = serviceObject.get("Service").getAsString();
    String serviceAddress = serviceObject.get("Address").getAsString();
    int servicePort = serviceObject.get("Port").getAsInt();

    JsonArray tagsJsonArray = serviceObject.get("Tags").getAsJsonArray();
    List<String> serviceTags = new ArrayList<String>(tagsJsonArray.size());
    tagsJsonArray.forEach(element -> {
      serviceTags.add(element.getAsString());
    });

    return new Service(node, nodeAddress, serviceId, serviceName, serviceTags, serviceAddress, servicePort);
  }
}


text:
#include <hre/config.h>

#include <popt.h>

#include <pins2lts-sym/aux/options.h>

#if !SPEC_MT_SAFE || defined(PROB)
int USE_PARALLELISM = 0;
#else
int USE_PARALLELISM = 1;
#endif

int REL_PERF = SPEC_REL_PERF;

int MAYBE_AND_FALSE_IS_FALSE = SPEC_MAYBE_AND_FALSE_IS_FALSE;

strategy_t strategy = BFS_P;

sat_strategy_t sat_strategy = NO_SAT;

guide_strategy_t guide_strategy = UNGUIDED;

char** ctl_star_formulas = NULL;
char** ctl_formulas = NULL;
char** ltl_formulas = NULL;
int num_ctl_star = 0;
int num_ctl = 0;
int num_ltl = 0;
char** mu_formulas  = NULL;
int num_mu = 0;
int num_total = 0;
int mu_par = 0;
int mu_opt = 0;

char* dot_dir = NULL;
char* vset_dir = NULL;

char* trc_output = NULL;
char* trc_type   = "gcf";
int   dlk_detect = 0;
char* act_detect = NULL;
char** inv_detect = NULL;
int   num_inv = 0;
int   no_exit = 0;
int   no_matrix = 0;
int   peak_nodes = 0;
int   no_soundness_check = 0;
int   act_index;
int   act_label;
int   action_typeno;
int   ErrorActions = 0; // count number of found errors (action/deadlock/invariant)
int   precise = 0;
int   next_union = 0;

int   sat_granularity = 10;
int   save_sat_levels = 0;

int   pgsolve_flag = 0;
char* pg_output = NULL;

int inv_par = 0;
int inv_bin_par = 0;

size_t lace_n_workers = 0;
size_t lace_dqsize = 40960000; // can be very big, no problemo
size_t lace_stacksize = 0; // use default

static char* order = "bfs-prev";
static si_map_entry ORDER[] = {
    {"bfs-prev", BFS_P},
    {"bfs", BFS},
#ifdef HAVE_SYLVAN
    {"par", PAR},
    {"par-prev", PAR_P},
#endif
    {"chain-prev", CHAIN_P},
    {"chain", CHAIN},
    {"none", NONE},
    {NULL, 0}
};

static char* saturation = "none";
static si_map_entry SATURATION[] = {
    {"none", NO_SAT},
    {"sat-like", SAT_LIKE},
    {"sat-loop", SAT_LOOP},
    {"sat-fix", SAT_FIX},
    {"sat", SAT},
    {NULL, 0}
};

static char *guidance = "unguided";
static si_map_entry GUIDED[] = {
    {"unguided", UNGUIDED},
    {"directed", DIRECTED},
    {NULL, 0}
};

static const char invariant_long[]="invariant";
static const char ctl_star_long[]="ctl-star";
static const char ctl_long[]="ctl";
static const char ltl_long[]="ltl";
static const char mu_long[]="mu";
#define IF_LONG(long) if(((opt->longName)&&!strcmp(opt->longName,long)))

static void
reach_popt(poptContext con, enum poptCallbackReason reason,
               const struct poptOption * opt, const char * arg, void * data)
{
    (void)con; (void)opt; (void)arg; (void)data;

    switch (reason) {
    case POPT_CALLBACK_REASON_PRE:
        Abort("unexpected call to reach_popt");
    case POPT_CALLBACK_REASON_POST: {
        int res;

        res = linear_search(ORDER, order);
        if (res < 0) {
            Warning(lerror, "unknown exploration order %s", order);
            HREexitUsage(LTSMIN_EXIT_FAILURE);
        } else if (HREme(HREglobal())==0) {
            Warning(info, "Exploration order is %s", order);
        }
        strategy = res;

        res = linear_search(SATURATION, saturation);
        if (res < 0) {
            Warning(lerror, "unknown saturation strategy %s", saturation);
            HREexitUsage(LTSMIN_EXIT_FAILURE);
        } else if (HREme(HREglobal())==0) {
            Warning(info, "Saturation strategy is %s", saturation);
        }
        sat_strategy = res;

        res = linear_search(GUIDED, guidance);
        if (res < 0) {
            Warning(lerror, "unknown guided search strategy %s", guidance);
            HREexitUsage(LTSMIN_EXIT_FAILURE);
        } else if (HREme(HREglobal())==0) {
            Warning(info, "Guided search strategy is %s", guidance);
        }
        guide_strategy = res;

        if (trc_output != NULL && !dlk_detect && act_detect == NULL && HREme(HREglobal())==0)
            Warning(info, "Ignoring trace output");

        if (inv_bin_par == 1 && inv_par == 0) {
            Warning(lerror, "--inv-bin-par requires --inv-par");
            HREexitUsage(LTSMIN_EXIT_FAILURE);
        }

        return;
    }
    case POPT_CALLBACK_REASON_OPTION:
        IF_LONG(invariant_long) {
            num_inv++;
            inv_detect = (char**) RTrealloc(inv_detect, sizeof(char*) * num_inv);
            inv_detect[num_inv - 1] = (char*) RTmalloc(strlen(arg) + 1);
            memcpy(inv_detect[num_inv - 1], arg, strlen(arg) + 1);
        }
        IF_LONG(ctl_star_long) {
            num_ctl_star++;
            ctl_star_formulas = (char**) RTrealloc(ctl_star_formulas, sizeof(char*) * num_ctl_star);
            ctl_star_formulas[num_ctl_star - 1] = (char*) RTmalloc(strlen(arg) + 1);
            memcpy(ctl_star_formulas[num_ctl_star - 1], arg, strlen(arg) + 1);
        }
        IF_LONG(ctl_long) {
            num_ctl++;
            ctl_formulas = (char**) RTrealloc(ctl_formulas, sizeof(char*) * num_ctl);
            ctl_formulas[num_ctl - 1] = (char*) RTmalloc(strlen(arg) + 1);
            memcpy(ctl_formulas[num_ctl - 1], arg, strlen(arg) + 1);
        }
        IF_LONG(ltl_long) {
            num_ltl++;
            ltl_formulas = (char**) RTrealloc(ltl_formulas, sizeof(char*) * num_ltl);
            ltl_formulas[num_ltl - 1] = (char*) RTmalloc(strlen(arg) + 1);
            memcpy(ltl_formulas[num_ltl - 1], arg, strlen(arg) + 1);
        }
        IF_LONG(mu_long) {
            num_mu++;
            mu_formulas = (char**) RTrealloc(mu_formulas, sizeof(char*) * num_mu);
            mu_formulas[num_mu - 1] = (char*) RTmalloc(strlen(arg) + 1);
            memcpy(mu_formulas[num_mu - 1], arg, strlen(arg) + 1);
        }
        return;
    }
}

struct poptOption lace_options[] = {
    { "lace-workers", 0, POPT_ARG_INT|POPT_ARGFLAG_SHOW_DEFAULT, &lace_n_workers , 0 , "set number of Lace workers (threads for parallelization)","<workers>"},
    { "lace-dqsize",0, POPT_ARG_INT|POPT_ARGFLAG_SHOW_DEFAULT, &lace_dqsize , 0 , "set length of Lace task queue","<dqsize>"},
    { "lace-stacksize", 0, POPT_ARG_INT|POPT_ARGFLAG_SHOW_DEFAULT, &lace_stacksize, 0, "set size of program stack in kilo bytes (0=default stack size)", "<stacksize>"},
POPT_TABLEEND
};

struct poptOption options[] = {
    { NULL, 0 , POPT_ARG_CALLBACK|POPT_CBFLAG_POST , (void*)reach_popt , 0 , NULL , NULL },
    {   "order" , 0 , POPT_ARG_STRING|POPT_ARGFLAG_SHOW_DEFAULT , &order , 0 , "set the exploration strategy to a specific order" ,
        "<bfs-prev|bfs|chain-prev|chain"
#ifdef HAVE_SYLVAN
            "|par-prev|par"
#endif
            "|none>" },
#ifdef HAVE_SYLVAN
    { "inv-par", 0, POPT_ARG_VAL, &inv_par, 1, "parallelize invariant detection", NULL },
    { "inv-bin-par", 0, POPT_ARG_VAL, &inv_bin_par, 1, "also parallelize every binary operand, may be slow when lots of state labels are to be evaluated (requires --inv-par)", NULL },
    { "mu-par", 0, POPT_ARG_VAL, &mu_par, 1, "parallelize mu-calculus", NULL },
#endif
    { "mu-opt", 0, POPT_ARG_VAL, &mu_opt, 1, "optimize fix-point calculations in mu-calculus", NULL },

    { "saturation" , 0, POPT_ARG_STRING|POPT_ARGFLAG_SHOW_DEFAULT , &saturation , 0 , "select the saturation strategy" , "<none|sat-like|sat-loop|sat-fix|sat>" },
    { "sat-granularity" , 0 , POPT_ARG_INT|POPT_ARGFLAG_SHOW_DEFAULT, &sat_granularity , 0 , "set saturation granularity","<number>" },
    { "save-sat-levels", 0, POPT_ARG_VAL, &save_sat_levels, 1, "save previous states seen at saturation levels", NULL },
    { "guidance", 0 , POPT_ARG_STRING|POPT_ARGFLAG_SHOW_DEFAULT , &guidance, 0 , "select the guided search strategy" , "<unguided|directed>" },
    { "deadlock" , 'd' , POPT_ARG_VAL , &dlk_detect , 1 , "detect deadlocks" , NULL },
    { "action" , 0 , POPT_ARG_STRING , &act_detect , 0 , "detect action prefix" , "<action prefix>" },
    { invariant_long , 'i' , POPT_ARG_STRING , NULL , 0, "detect invariant violations (can be given multiple times)", NULL },
    { "no-exit", 'n', POPT_ARG_VAL, &no_exit, 1, "no exit on error, just count (for error counters use -v)", NULL },
    { "trace" , 0 , POPT_ARG_STRING , &trc_output , 0 , "file to write trace to" , "<lts-file>" },
    { "type", 0, POPT_ARG_STRING|POPT_ARGFLAG_SHOW_DEFAULT, &trc_type, 0, "trace type to write", "<aut|gcd|gcf|dir|fsm|bcg>" },
    { mu_long , 0 , POPT_ARG_STRING , NULL , 0 , "file with a MU-calculus formula  (can be given multiple times)" , "<mu-file>.mu" },
    { ctl_star_long , 0 , POPT_ARG_STRING , NULL , 0 , "file with a CTL* formula  (can be given multiple times)" , "<ctl-star-file>.ctl" },
    { ctl_long , 0 , POPT_ARG_STRING , NULL , 0 , "file with a CTL formula  (can be given multiple times)" , "<ctl-file>.ctl" },
    { ltl_long , 0 , POPT_ARG_STRING , NULL , 0 , "file with an LTL formula  (can be given multiple times)" , "<ltl-file>.ltl" },
    { "dot", 0, POPT_ARG_STRING, &dot_dir, 0, "directory to write dot representation of vector sets to", NULL },
    { "save-levels", 0, POPT_ARG_STRING, &vset_dir, 0, "directory to write vset snapshots of all levels to", NULL },
    { "pg-solve" , 0 , POPT_ARG_NONE , &pgsolve_flag, 0, "Solve the generated parity game (only for symbolic tool).","" },
    { NULL, 0 , POPT_ARG_INCLUDE_TABLE, spg_solve_options , 0, "Symbolic parity game solver options", NULL},
    { "pg-write" , 0 , POPT_ARG_STRING , &pg_output, 0, "file to write symbolic parity game to","<pg-file>.spg" },
#ifdef HAVE_SYLVAN
    { NULL, 0 , POPT_ARG_INCLUDE_TABLE, lace_options , 0 , "Lace options",NULL},
#endif
    { "no-matrix" , 0 , POPT_ARG_VAL , &no_matrix , 1 , "do not print the dependency matrix when -v (verbose) is used" , NULL},
    SPEC_POPT_OPTIONS,
    { NULL, 0 , POPT_ARG_INCLUDE_TABLE, greybox_options , 0 , "PINS options",NULL},
    { NULL, 0 , POPT_ARG_INCLUDE_TABLE, vset_options , 0 , "Vector set options",NULL},
    { "no-soundness-check", 0, POPT_ARG_VAL, &no_soundness_check, 1, "disable checking whether the model specification is sound for guards", NULL },
    { "precise", 0, POPT_ARG_NONE, &precise, 0, "Compute the final number of states precisely", NULL},
    { "next-union", 0, POPT_ARG_NONE, &next_union, 0, "While computing successor states; unify simultaneously with current states", NULL },
    { "peak-nodes", 0, POPT_ARG_NONE, &peak_nodes, 0, "record peak nodes and report after reachability analysis", NULL },
    {NULL, 0, POPT_ARG_INCLUDE_TABLE, maxsum_options, 0, "Integer arithmetic options", NULL},
    POPT_TABLEEND
};

/// GLOBALS

/*
  The inhibit and class matrices are used for maximal progress.
 */
matrix_t *inhibit_matrix=NULL;
matrix_t *class_matrix=NULL;
int inhibit_class_count=0;
vset_t *class_enabled = NULL;

bitvector_ll_t *seen_actions;
vset_t true_states;
vset_t false_states;

int var_pos = 0;
int var_type_no = 0;
int variable_projection = 0;
size_t true_index = 0;
size_t false_index = 1;
size_t num_vars = 0;
int* player = 0; // players of variables
int* priority = 0; // priorities of variables
int min_priority = INT_MAX;
int max_priority = INT_MIN;

ltsmin_expr_t* mu_exprs = NULL;
ltsmin_parse_env_t* mu_parse_env = NULL;

lts_type_t ltstype;
int N;
int eLbls;
int sLbls;
int nGuards;
int nGrps;
int max_sat_levels;
ci_list **r_projs = NULL;
ci_list **w_projs = NULL;
ci_list **l_projs = NULL;
vdom_t domain;
matrix_t *read_matrix;
matrix_t *write_matrix;
vset_t *levels = NULL;
int max_levels = 0;
int global_level;
long max_lev_count = 0;
long max_vis_count = 0;
long max_grp_count = 0;
long max_trans_count = 0;
long max_mu_count = 0;
model_t model;
vset_t initial, visited;
vrel_t *group_next;
vset_t *group_explored;
vset_t *group_tmp;
vset_t *label_false = NULL; // 0
vset_t *label_true = NULL;  // 1
vset_t *label_tmp;
rt_timer_t reach_timer;

int* label_locks = NULL;

ltsmin_parse_env_t* inv_parse_env;
ltsmin_expr_t* inv_expr;
ci_list **inv_proj = NULL;
vset_t* inv_set = NULL;
int* inv_violated = NULL;
bitvector_t* inv_deps = NULL;
bitvector_t* inv_sl_deps = NULL;
int num_inv_violated = 0;
bitvector_t state_label_used;

transitions_t transitions_short = NULL; // which function to call for the next states.


text:
package main_test

import (
	"io"

	"github.com/onsi/ginkgo"
	"github.com/onsi/gomega"
	"github.com/petergtz/bitsgo"

	"testing"
)

func TestBlobstores(t *testing.T) {
	gomega.RegisterFailHandler(ginkgo.Fail)
	ginkgo.RunSpecs(t, "Blobstores Contract Integration")
}

type blobstore interface {
	// Can't do the following until it is added in Go: (See also https://github.com/golang/go/issues/6977)
	// routes.Blobstore
	// routes.NoRedirectBlobstore

	// Instead doing:
	bitsgo.Blobstore
	Get(path string) (body io.ReadCloser, err error)

	bitsgo.ResourceSigner
}