text:
set -e -u

# Prints the absolute path of a directory to stdout
abs_path() {
    local _path="$1"
    # Unset CDPATH because it causes havok: it makes the destination unpredictable
    # and triggers 'cd' to print the path to stdout. Route `cd`'s output to /dev/null
    # for good measure.
    (unset CDPATH && cd "$_path" > /dev/null && pwd)
}

S="$(abs_path $(dirname $0))"

TMP_DIR="$S/tmp"
MOCK_DIST_DIR="$S/tmp/mock-dist"

# Clean out the tmp dir
if [ -n "${NO_REBUILD_MOCKS-}" ]; then
    mv "$MOCK_DIST_DIR" ./mock-backup
fi
rm -Rf "$TMP_DIR"
mkdir "$TMP_DIR"
if [ -n "${NO_REBUILD_MOCKS-}" ]; then
    mv ./mock-backup "$MOCK_DIST_DIR"
fi

TEST_DIR="$S/test"
TEST_SECRET_KEY="$TEST_DIR/secret-key.gpg"
TEST_PUBLIC_KEY="$TEST_DIR/public-key.gpg"
RUSTUP_GPG_KEY="$TEST_DIR/public-key.asc"
WORK_DIR="$S/tmp/work"
MOCK_BUILD_DIR="$S/tmp/mock-build"
TEST_PREFIX="$S/tmp/prefix"
RUSTUP_HOME="$(abs_path "$TMP_DIR")/rustup"

say() {
    echo "test: $1"
}

pre() {
    echo "test: $1"
    rm -Rf "$RUSTUP_HOME"
    rm -Rf "$WORK_DIR"
    mkdir -p "$WORK_DIR"
}

need_ok() {
    if [ $? -ne 0 ]
    then
	echo
	echo "TEST FAILED!"
	echo
	exit 1
    fi
}

fail() {
    echo
    echo "$1"
    echo
    echo "TEST FAILED!"
    echo
    exit 1
}

try() {
    set +e
    _cmd="$@"
    _output=`$@ 2>&1`
    if [ $? -ne 0 ]; then
	echo \$ "$_cmd"
	# Using /bin/echo to avoid escaping
	/bin/echo "$_output"
	echo
	echo "TEST FAILED!"
	echo
	exit 1
    else
	if [ -n "${VERBOSE-}" -o -n "${VERBOSE_CMD-}" ]; then
	    echo \$ "$_cmd"
	fi
	if [ -n "${VERBOSE-}" -o -n "${VERBOSE_OUTPUT-}" ]; then
	    /bin/echo "$_output"
	fi
    fi
    set -e
}

expect_fail() {
    set +e
    _cmd="$@"
    _output=`$@ 2>&1`
    if [ $? -eq 0 ]; then
	echo \$ "$_cmd"
	# Using /bin/echo to avoid escaping
	/bin/echo "$_output"
	echo
	echo "TEST FAILED!"
	echo
	exit 1
    else
	if [ -n "${VERBOSE-}" -o -n "${VERBOSE_CMD-}" ]; then
	    echo \$ "$_cmd"
	fi
	if [ -n "${VERBOSE-}" -o -n "${VERBOSE_OUTPUT-}" ]; then
	    /bin/echo "$_output"
	fi
    fi
    set -e
}

expect_output_ok() {
    set +e
    local _expected="$1"
    shift 1
    _cmd="$@"
    _output=`$@ 2>&1`
    if [ $? -ne 0 ]; then
	echo \$ "$_cmd"
	# Using /bin/echo to avoid escaping
	/bin/echo "$_output"
	echo
	echo "TEST FAILED!"
	echo
	exit 1
    elif ! echo "$_output" | grep -q "$_expected"; then
	echo \$ "$_cmd"
	/bin/echo "$_output"
	echo
	echo "missing expected output '$_expected'"
	echo
	echo
	echo "TEST FAILED!"
	echo
	exit 1
    else
	if [ -n "${VERBOSE-}" -o -n "${VERBOSE_CMD-}" ]; then
	    echo \$ "$_cmd"
	fi
	if [ -n "${VERBOSE-}" -o -n "${VERBOSE_OUTPUT-}" ]; then
	    /bin/echo "$_output"
	fi
    fi
    set -e
}

expect_output_fail() {
    set +e
    local _expected="$1"
    shift 1
    _cmd="$@"
    _output=`$@ 2>&1`
    if [ $? -eq 0 ]; then
	echo \$ "$_cmd"
	# Using /bin/echo to avoid escaping
	/bin/echo "$_output"
	echo
	echo "TEST FAILED!"
	echo
	exit 1
    elif ! echo "$_output" | grep -q "$_expected"; then
	echo \$ "$_cmd"
	/bin/echo "$_output"
	echo
	echo "missing expected output '$_expected'"
	echo
	echo
	echo "TEST FAILED!"
	echo
	exit 1
    else
	if [ -n "${VERBOSE-}" -o -n "${VERBOSE_CMD-}" ]; then
	    echo \$ "$_cmd"
	fi
	if [ -n "${VERBOSE-}" -o -n "${VERBOSE_OUTPUT-}" ]; then
	    /bin/echo "$_output"
	fi
    fi
    set -e
}

expect_not_output_ok() {
    set +e
    local _expected="$1"
    shift 1
    _cmd="$@"
    _output=`$@ 2>&1`
    if [ $? -ne 0 ]; then
	echo \$ "$_cmd"
	# Using /bin/echo to avoid escaping
	/bin/echo "$_output"
	echo
	echo "TEST FAILED!"
	echo
	exit 1
    elif echo "$_output" | grep -q "$_expected"; then
	echo \$ "$_cmd"
	/bin/echo "$_output"
	echo
	echo "unexpected output '$_expected'"
	echo
	echo
	echo "TEST FAILED!"
	echo
	exit 1
    else
	if [ -n "${VERBOSE-}" -o -n "${VERBOSE_CMD-}" ]; then
	    echo \$ "$_cmd"
	fi
	if [ -n "${VERBOSE-}" -o -n "${VERBOSE_OUTPUT-}" ]; then
	    /bin/echo "$_output"
	fi
    fi
    set -e
}

runtest() {
    local _testname="$1"
    if [ -n "${TESTNAME-}" ]; then
        if ! echo "$_testname" | grep -q "$TESTNAME"; then
            return 0
        fi
    fi

    pre "$_testname"
    "$_testname"
}

get_architecture() {

    local _ostype="$(uname -s)"
    local _cputype="$(uname -m)"

    if [ "$_ostype" = Darwin -a "$_cputype" = i386 ]; then
	# Darwin `uname -s` lies
	if sysctl hw.optional.x86_64 | grep -q ': 1'; then
	    local _cputype=x86_64
	fi
    fi

    case "$_ostype" in

	Linux)
	    local _ostype=unknown-linux-gnu
	    ;;

	FreeBSD)
	    local _ostype=unknown-freebsd
	    ;;

	DragonFly)
	    local _ostype=unknown-dragonfly
	    ;;

	Darwin)
	    local _ostype=apple-darwin
	    ;;

	MINGW* | MSYS*)
	    err "unimplemented windows arch detection"
	    ;;

	*)
	    err "unrecognized OS type: $_ostype"
	    ;;

    esac

    case "$_cputype" in

	i386 | i486 | i686 | i786 | x86)
            local _cputype=i686
            ;;

	xscale | arm)
	    local _cputype=arm
            ;;

	armv7l)
            local _cputype=arm
            local _ostype="${_ostype}eabihf"
            ;;

	x86_64 | x86-64 | x64 | amd64)
            local _cputype=x86_64
            ;;

	*)
            err "unknown CPU type: $CFG_CPUTYPE"

    esac

    # Detect 64-bit linux with 32-bit userland
    if [ $_ostype = unknown-linux-gnu -a $_cputype = x86_64 ]; then
	file -L "$SHELL" | grep -q "x86[_-]64"
	if [ $? != 0 ]; then
	    local _cputype=i686
	fi
    fi

    local _arch="$_cputype-$_ostype"

    RETVAL="$_arch"
}

build_mock_bin() {
    local _name="$1"
    local _version="$2"
    local _version_hash="$3"
    local _dir="$4"

    cat "$TEST_DIR/mock.sh" | \
	sed s/@@TEMPLATE_BIN_NAME@@/"$_name"/ | \
	sed s/@@TEMPLATE_VERSION@@/"$_version"/ | \
	sed s/@@TEMPLATE_HASH@@/"$_version_hash"/ > "$_dir/$_name"

    chmod a+x "$_dir/$_name"
}

build_mock_rustc_installer() {
    local _version="$1"
    local _version_hash="$2"
    local _package="$3"

    local _image="$MOCK_BUILD_DIR/image/rustc"
    mkdir -p "$_image/bin"
    build_mock_bin rustc "$_version" "$_version_hash" "$_image/bin"
    build_mock_bin rustdoc "$_version" "$_version_hash" "$_image/bin"

    get_architecture
    local _arch="$RETVAL"

    mkdir -p "$MOCK_BUILD_DIR/pkg"
    try sh "$S/rust-installer/gen-installer.sh" \
	--product-name=Rust \
	--rel-manifest-dir=rustlib \
	--image-dir="$_image" \
	--work-dir="$MOCK_BUILD_DIR/work" \
	--output-dir="$MOCK_BUILD_DIR/pkg" \
        --package-name="rustc-$_package-$_arch" \
	--component-name=rustc
}

build_mock_cargo_installer() {
    local _version="$1"
    local _version_hash="$2"
    local _package="$3"

    local _image="$MOCK_BUILD_DIR/image/cargo"
    mkdir -p "$_image/bin"
    build_mock_bin cargo "$_version" "$_version_hash" "$_image/bin"

    get_architecture
    local _arch="$RETVAL"

    mkdir -p "$MOCK_BUILD_DIR/pkg"
    try sh "$S/rust-installer/gen-installer.sh" \
	--product-name=Cargo \
	--rel-manifest-dir=rustlib \
	--image-dir="$_image" \
	--work-dir="$MOCK_BUILD_DIR/work" \
	--output-dir="$MOCK_BUILD_DIR/pkg" \
        --package-name="cargo-$_package-$_arch" \
	--component-name=cargo
}

build_mock_rust_docs_installer() {
    local _package="$1"

    local _image="$MOCK_BUILD_DIR/image/docs"
    mkdir -p "$_image/share/doc/rust/html"
    echo "test" > "$_image/share/doc/rust/html/index.html"

    get_architecture
    local _arch="$RETVAL"

    mkdir -p "$MOCK_BUILD_DIR/pkg"
    try sh "$S/rust-installer/gen-installer.sh" \
	--product-name=Rust-documentation \
	--rel-manifest-dir=rustlib \
	--image-dir="$_image" \
	--work-dir="$MOCK_BUILD_DIR/work" \
	--output-dir="$MOCK_BUILD_DIR/pkg" \
        --package-name="rust-docs-$_package-$_arch" \
	--component-name=rust-docs
}

build_mock_combined_installer() {
    local _package="$1"

    get_architecture
    local _arch="$RETVAL"

    local _rustc_tarball="$MOCK_BUILD_DIR/pkg/rustc-$_package-$_arch.tar.gz"
    local _cargo_tarball="$MOCK_BUILD_DIR/pkg/cargo-$_package-$_arch.tar.gz"
    local _docs_tarball="$MOCK_BUILD_DIR/pkg/rust-docs-$_package-$_arch.tar.gz"
    local _inputs="$_rustc_tarball,$_cargo_tarball,$_docs_tarball"

    mkdir -p "$MOCK_BUILD_DIR/dist"
    try sh "$S/rust-installer/combine-installers.sh" \
	--product-name=Rust \
	--rel-manifest-dir=rustlib \
	--work-dir="$MOCK_BUILD_DIR/work" \
	--output-dir="$MOCK_BUILD_DIR/dist" \
	--package-name="rust-$_package-$_arch" \
	--input-tarballs="$_inputs"
}

build_mock_dist_channel() {
    local _channel="$1"
    local _date="$2"

    (cd "$MOCK_BUILD_DIR/dist" && ls * > channel-rust-"$_channel")
    if command -v gpg > /dev/null 2>&1; then
	(cd "$MOCK_BUILD_DIR/dist" && for i in *; do
		gpg --no-default-keyring --secret-keyring "$TEST_SECRET_KEY" \
		    --keyring "$TEST_PUBLIC_KEY" \
		    --no-tty --yes -a --detach-sign "$i"
		done)
    else
	say "gpg not found. not testing signature verification"
	(cd "$MOCK_BUILD_DIR/dist" && for i in *; do echo "nosig" > "$i.asc"; done)
    fi
    (cd "$MOCK_BUILD_DIR/dist" && for i in *; do shasum -a256 $i > $i.sha256; done)
}

build_mock_channel() {
    local _version="$1"
    local _version_hash="$2"
    local _package="$3"
    local _channel="$4"
    local _date="$5"

    rm -Rf "$MOCK_BUILD_DIR"
    mkdir -p "$MOCK_BUILD_DIR"

    say "building mock channel $_version $_version_hash $_package $_channel $_date"
    build_mock_rustc_installer "$_version" "$_version_hash" "$_package"
    build_mock_cargo_installer "$_version" "$_version_hash" "$_package"
    build_mock_rust_docs_installer "$_package"
    build_mock_combined_installer "$_package"
    build_mock_dist_channel "$_channel" "$_date"

    mkdir -p "$MOCK_DIST_DIR/dist/$_date"
    cp "$MOCK_BUILD_DIR/dist"/* "$MOCK_DIST_DIR/dist/$_date/"
    cp "$MOCK_BUILD_DIR/dist"/* "$MOCK_DIST_DIR/dist/"
    # Copy the intermediate installers too, though without manifests, checksums, etc.
    cp "$MOCK_BUILD_DIR/pkg"/* "$MOCK_DIST_DIR/dist/$_date/"
    cp "$MOCK_BUILD_DIR/pkg"/* "$MOCK_DIST_DIR/dist/"
}

build_mocks() {
    if [ -z "${NO_REBUILD_MOCKS-}" ]; then
	build_mock_channel 1.0.0-nightly hash-nightly-1 nightly nightly 2015-01-01
	build_mock_channel 1.0.0-beta hash-beta-1 1.0.0-beta beta 2015-01-01
	build_mock_channel 1.0.0 hash-stable-1 1.0.0 stable 2015-01-01

	build_mock_channel 1.1.0-nightly hash-nightly-2 nightly nightly 2015-01-02
	build_mock_channel 1.1.0-beta hash-beta-2 1.1.0-beta beta 2015-01-02
	build_mock_channel 1.1.0 hash-stable-2 1.1.0 stable 2015-01-02
    fi
}

set_current_dist_date() {
    local _dist_date="$1"
    cp "$MOCK_DIST_DIR/dist/$_dist_date"/* "$MOCK_DIST_DIR/dist/"
}

build_mock_bin() {
    local _name="$1"
    local _version="$2"
    local _version_hash="$3"
    local _dir="$4"

    cat "$TEST_DIR/mock.sh" | \
	sed s/@@TEMPLATE_BIN_NAME@@/"$_name"/ | \
	sed s/@@TEMPLATE_VERSION@@/"$_version"/ | \
	sed s/@@TEMPLATE_HASH@@/"$_version_hash"/ > "$_dir/$_name"

    chmod a+x "$_dir/$_name"
}

build_mock_rustc_installer() {
    local _version="$1"
    local _version_hash="$2"
    local _package="$3"

    local _image="$MOCK_BUILD_DIR/image/rustc"
    mkdir -p "$_image/bin"
    build_mock_bin rustc "$_version" "$_version_hash" "$_image/bin"
    build_mock_bin rustdoc "$_version" "$_version_hash" "$_image/bin"

    get_architecture
    local _arch="$RETVAL"

    mkdir -p "$MOCK_BUILD_DIR/pkg"
    try sh "$S/rust-installer/gen-installer.sh" \
	--product-name=Rust \
	--rel-manifest-dir=rustlib \
	--image-dir="$_image" \
	--work-dir="$MOCK_BUILD_DIR/work" \
	--output-dir="$MOCK_BUILD_DIR/pkg" \
        --package-name="rustc-$_package-$_arch" \
	--component-name=rustc
}

build_mock_cargo_installer() {
    local _version="$1"
    local _version_hash="$2"
    local _package="$3"

    local _image="$MOCK_BUILD_DIR/image/cargo"
    mkdir -p "$_image/bin"
    build_mock_bin cargo "$_version" "$_version_hash" "$_image/bin"

    get_architecture
    local _arch="$RETVAL"

    mkdir -p "$MOCK_BUILD_DIR/pkg"
    try sh "$S/rust-installer/gen-installer.sh" \
	--product-name=Cargo \
	--rel-manifest-dir=rustlib \
	--image-dir="$_image" \
	--work-dir="$MOCK_BUILD_DIR/work" \
	--output-dir="$MOCK_BUILD_DIR/pkg" \
        --package-name="cargo-$_package-$_arch" \
	--component-name=cargo
}

build_mock_rust_docs_installer() {
    local _package="$1"

    local _image="$MOCK_BUILD_DIR/image/docs"
    mkdir -p "$_image/share/doc/rust/html"
    echo "test" > "$_image/share/doc/rust/html/index.html"

    get_architecture
    local _arch="$RETVAL"

    mkdir -p "$MOCK_BUILD_DIR/pkg"
    try sh "$S/rust-installer/gen-installer.sh" \
	--product-name=Rust-documentation \
	--rel-manifest-dir=rustlib \
	--image-dir="$_image" \
	--work-dir="$MOCK_BUILD_DIR/work" \
	--output-dir="$MOCK_BUILD_DIR/pkg" \
        --package-name="rust-docs-$_package-$_arch" \
	--component-name=rust-docs
}

build_mock_combined_installer() {
    local _package="$1"

    get_architecture
    local _arch="$RETVAL"

    local _rustc_tarball="$MOCK_BUILD_DIR/pkg/rustc-$_package-$_arch.tar.gz"
    local _cargo_tarball="$MOCK_BUILD_DIR/pkg/cargo-$_package-$_arch.tar.gz"
    local _docs_tarball="$MOCK_BUILD_DIR/pkg/rust-docs-$_package-$_arch.tar.gz"
    local _inputs="$_rustc_tarball,$_cargo_tarball,$_docs_tarball"

    mkdir -p "$MOCK_BUILD_DIR/dist"
    try sh "$S/rust-installer/combine-installers.sh" \
	--product-name=Rust \
	--rel-manifest-dir=rustlib \
	--work-dir="$MOCK_BUILD_DIR/work" \
	--output-dir="$MOCK_BUILD_DIR/dist" \
	--package-name="rust-$_package-$_arch" \
	--input-tarballs="$_inputs"
}

build_mock_dist_channel() {
    local _channel="$1"
    local _date="$2"

    (cd "$MOCK_BUILD_DIR/dist" && ls * > channel-rust-"$_channel")
    if command -v gpg > /dev/null 2>&1; then
	(cd "$MOCK_BUILD_DIR/dist" && for i in *; do
		gpg --no-default-keyring --secret-keyring "$TEST_SECRET_KEY" \
		    --keyring "$TEST_PUBLIC_KEY" \
		    --no-tty --yes -a --detach-sign "$i"
		done)
    else
	say "gpg not found. not testing signature verification"
	(cd "$MOCK_BUILD_DIR/dist" && for i in *; do echo "nosig" > "$i.asc"; done)
    fi
    (cd "$MOCK_BUILD_DIR/dist" && for i in *; do shasum -a256 $i > $i.sha256; done)
}

build_mock_channel() {
    local _version="$1"
    local _version_hash="$2"
    local _package="$3"
    local _channel="$4"
    local _date="$5"

    rm -Rf "$MOCK_BUILD_DIR"
    mkdir -p "$MOCK_BUILD_DIR"

    say "building mock channel $_version $_version_hash $_package $_channel $_date"
    build_mock_rustc_installer "$_version" "$_version_hash" "$_package"
    build_mock_cargo_installer "$_version" "$_version_hash" "$_package"
    build_mock_rust_docs_installer "$_package"
    build_mock_combined_installer "$_package"
    build_mock_dist_channel "$_channel" "$_date"

    mkdir -p "$MOCK_DIST_DIR/dist/$_date"
    cp "$MOCK_BUILD_DIR/dist"/* "$MOCK_DIST_DIR/dist/$_date/"
    cp "$MOCK_BUILD_DIR/dist"/* "$MOCK_DIST_DIR/dist/"
    # Copy the intermediate installers too, though without manifests, checksums, etc.
    cp "$MOCK_BUILD_DIR/pkg"/* "$MOCK_DIST_DIR/dist/$_date/"
    cp "$MOCK_BUILD_DIR/pkg"/* "$MOCK_DIST_DIR/dist/"
}

build_mocks() {
    if [ -z "${NO_REBUILD_MOCKS-}" ]; then
	build_mock_channel 1.0.0-nightly hash-nightly-1 nightly nightly 2015-01-01
	build_mock_channel 1.0.0-beta hash-beta-1 1.0.0-beta beta 2015-01-01
	build_mock_channel 1.0.0 hash-stable-1 1.0.0 stable 2015-01-01

	build_mock_channel 1.1.0-nightly hash-nightly-2 nightly nightly 2015-01-02
	build_mock_channel 1.1.0-beta hash-beta-2 1.1.0-beta beta 2015-01-02
	build_mock_channel 1.1.0 hash-stable-2 1.1.0 stable 2015-01-02
    fi
}

set_current_dist_date() {
    local _dist_date="$1"
    cp "$MOCK_DIST_DIR/dist/$_dist_date"/* "$MOCK_DIST_DIR/dist/"
}

# Build the mock revisions
build_mocks

# Tell rustup where to store temporary stuff
export RUSTUP_HOME
# Tell rustup what key to use to verify sigs
export RUSTUP_GPG_KEY

# Tell rustup where to download stuff from
RUSTUP_DIST_SERVER="file://$(abs_path "$MOCK_DIST_DIR")"
export RUSTUP_DIST_SERVER

# Set up the PATH to find rustup.sh
PATH="$S:$PATH"
export PATH
try test -e "$S/rustup.sh"

run_rustup() {
    rustup.sh "$@" --disable-sudo -y
}

basic_install() {
    try run_rustup --prefix="$TEST_PREFIX"
    try test -e "$TEST_PREFIX/bin/rustc"
}
runtest basic_install

basic_uninstall() {
    try run_rustup --prefix="$TEST_PREFIX"
    try test -e "$TEST_PREFIX/bin/rustc"
    try run_rustup --prefix="$TEST_PREFIX" --uninstall
    try test ! -e "$TEST_PREFIX/bin/rustc"
}
runtest basic_uninstall

uninstall_not_installed() {
    expect_output_ok "no toolchain installed" run_rustup --prefix="$TEST_PREFIX" --uninstall
}
runtest uninstall_not_installed

with_date() {
    try run_rustup --prefix="$TEST_PREFIX" --date=2015-01-01
    expect_output_ok "hash-stable-1" "$TEST_PREFIX/bin/rustc" --version
}
runtest with_date

with_channel() {
    try run_rustup --prefix="$TEST_PREFIX" --channel=nightly
    expect_output_ok "hash-nightly-2" "$TEST_PREFIX/bin/rustc" --version
}
runtest with_channel

with_channel_and_date() {
    try run_rustup --prefix="$TEST_PREFIX" --date=2015-01-01 --channel=nightly
    expect_output_ok "hash-nightly-1" "$TEST_PREFIX/bin/rustc" --version
}
runtest with_channel_and_date

save_without_date() {
    try run_rustup --prefix="$TEST_PREFIX" --save
    try test -e "$TEST_PREFIX/bin/rustc"
    try run_rustup --prefix="$TEST_PREFIX" --save
    try test -e "$TEST_PREFIX/bin/rustc"
}
runtest save_without_date

save_with_date() {
    try run_rustup --prefix="$TEST_PREFIX" --save --date=2015-01-01
    try test -e "$TEST_PREFIX/bin/rustc"
    try run_rustup --prefix="$TEST_PREFIX" --save --date=2015-01-01
    try test -e "$TEST_PREFIX/bin/rustc"
}
runtest save_with_date

out_of_date_metadata() {
    try run_rustup --prefix="$TEST_PREFIX" --save
    echo "bogus" > "$RUSTUP_HOME/rustup-version"
    expect_output_ok "metadata is out of date" run_rustup --prefix="$TEST_PREFIX" --save
}
runtest out_of_date_metadata

remove_metadata_if_not_save() {
    try run_rustup --prefix="$TEST_PREFIX"
    try test ! -e "$RUSTUP_HOME/rustup-version"
}
runtest remove_metadata_if_not_save

leave_metadata_if_save() {
    try run_rustup --prefix="$TEST_PREFIX" --save
    try test -e "$RUSTUP_HOME/rustup-version"
}
runtest leave_metadata_if_save

obey_RUST_PREFIX() {
    export RUSTUP_PREFIX="$TEST_PREFIX"
    try run_rustup
    try test -e "$TEST_PREFIX/bin/rustc"
    unset RUSTUP_PREFIX
}
runtest obey_RUST_PREFIX

install_to_prefix_that_does_not_exist() {
    try run_rustup --prefix="$TEST_PREFIX/a/b"
    try test -e "$TEST_PREFIX/a/b/bin/rustc"
}
runtest install_to_prefix_that_does_not_exist

# Existing directories that do not contain the rustup-version file
# indicate user error.
suspicious_RUSTUP_HOME() {
    local _old_rustup_home="$RUSTUP_HOME"
    export RUSTUP_HOME="$TMP_DIR"
    expect_output_fail "rustup home dir exists" run_rustup
    export RUSTUP_HOME="$_old_rustup_home"
}
runtest suspicious_RUSTUP_HOME

shasum_fallback() {
    export __RUSTUP_MOCK_SHA256SUM=bogus
    try run_rustup --prefix="$TEST_PREFIX"
    try test -e "$TEST_PREFIX/bin/rustc"
    expect_output_ok "falling back to shasum" run_rustup --prefix="$TEST_PREFIX" --verbose
    unset __RUSTUP_MOCK_SHA256SUM
}
runtest shasum_fallback

validate_channel() {
    expect_output_fail "channel must be either 'stable', 'beta', or 'nightly'" run_rustup --channel=pah
}
runtest validate_channel

validate_date() {
    expect_output_fail "date must be in YYYY-MM-DD format" run_rustup --date=foo
}
runtest validate_date

explicit_version() {
    try run_rustup --prefix="$TEST_PREFIX" --revision=1.0.0
    try test -e "$TEST_PREFIX/bin/rustc"
}
runtest explicit_version

explicit_version_with_channel() {
    expect_output_fail "the --revision flag may not be combined with --channel" run_rustup --prefix="$TEST_PREFIX" --revision=1.0.0 --channel=nightly
}
runtest explicit_version_with_channel

explicit_version_with_date() {
    expect_output_fail "the --revision flag may not be combined with --date" run_rustup --prefix="$TEST_PREFIX" --revision=1.0.0 --date=2015-01-01
}
runtest explicit_version_with_date

save_and_no_save() {
    # Run with --save to create the rustup directory, and save the downloaded installer
    try run_rustup --prefix="$TEST_PREFIX" --revision=1.0.0 --save
    local _cache_dir="$(ls "$RUSTUP_HOME/dl")"
    try test -n "$_cache_dir"
    try test -e "$RUSTUP_HOME/dl/$_cache_dir/*.tar.gz"
    # This time it will delete the downloaded files
    try run_rustup --prefix="$TEST_PREFIX" --revision=1.0.0
    local _dirlisting="$(ls "$RUSTUP_HOME/dl")"
    try test -z "$_dirlisting"
}
runtest save_and_no_save

install_from_spec() {
    try run_rustup --prefix="$TEST_PREFIX" --spec=nightly
    expect_output_ok "hash-nightly-2" "$TEST_PREFIX/bin/rustc" --version
    try run_rustup --prefix="$TEST_PREFIX" --spec=nightly-2015-01-01
    expect_output_ok "hash-nightly-1" "$TEST_PREFIX/bin/rustc" --version
    try run_rustup --prefix="$TEST_PREFIX" --spec=1.0.0
    expect_output_ok "hash-stable-1" "$TEST_PREFIX/bin/rustc" --version
}
runtest install_from_spec

update_hash_file() {
    try run_rustup --prefix="$TEST_PREFIX" --spec=nightly --update-hash-file="$TMP_DIR/update-hash"
    expect_output_ok "'nightly' is already up to date" run_rustup --prefix="$TEST_PREFIX" --spec=nightly --update-hash-file="$TMP_DIR/update-hash"
}
runtest update_hash_file

update_hash_file2() {
    set_current_dist_date 2015-01-01
    try run_rustup --prefix="$TEST_PREFIX" --spec=nightly --update-hash-file="$TMP_DIR/update-hash"
    # Since the date changed, there's an update, and we should *not* see the short-circuit
    set_current_dist_date 2015-01-02
    expect_not_output_ok "'nightly' is already up to date" run_rustup --prefix="$TEST_PREFIX" --spec=nightly --update-hash-file="$TMP_DIR/update-hash"
}
runtest update_hash_file2

abort_if_multirust_is_installed() {
    try mkdir -p "$TEST_PREFIX/bin"
    try touch "$TEST_PREFIX/bin/multirust"
    expect_output_fail "installing rust over multirust will result in breakage" run_rustup --prefix="$TEST_PREFIX" --spec=nightly --update-hash-file="$TMP_DIR/update-hash"
    # If an uninstall script exists rustup will suggest running it
    try mkdir -p "$TEST_PREFIX/lib/rustlib"
    try touch "$TEST_PREFIX/lib/rustlib/uninstall.sh"
    expect_output_fail "consider uninstalling multirust first" run_rustup --prefix="$TEST_PREFIX" --spec=nightly --update-hash-file="$TMP_DIR/update-hash"
    try rm "$TEST_PREFIX/bin/multirust"
}
runtest abort_if_multirust_is_installed

disable_ldconfig() {
    try run_rustup --prefix="$TEST_PREFIX" --spec=nightly --disable-ldconfig
}
runtest disable_ldconfig

echo
echo "SUCCESS"
echo


text:
package org.hl7.rim.decorators;

import org.hl7.rim.NonPersonLivingSubject;
import org.hl7.rim.decorators.LivingSubjectDecorator;
import org.hl7.types.ED;
import org.hl7.types.CE;

import org.hl7.types.impl.EDnull;
import org.hl7.types.impl.CEnull;
import /*org.hl7.rim.AssociationSet*/java.util.List;
import java.util.Collections;

/** Implementation of org.hl7.rim.NonPersonLivingSubject as an abstract decorator, i.e., a class that returns NULL/NA or nothing for all property accessprs amd that raises UnsupportedOperationExceptions for all mutators. This is used to adapt custom application classes to the RIM class interfaces and only bother about mapping those properties that actually apply to the application class. This can be done in one of two ways: (1) the client class can extend the decorator directly, and implement the applicable properties, or (2) the abstract decorator can be extend to a concrete decorator, which would hold a reference to the client object and method bodies to delegate and adapt the applicable properties.
 @see org.hl7.rim.NonPersonLivingSubject
  */
public abstract class NonPersonLivingSubjectDecorator extends org.hl7.rim.decorators.LivingSubjectDecorator implements NonPersonLivingSubject {
  /** Property accessor, returns NULL/NA if not overloaded.strainText.
      @see org.hl7.rim.NonPersonLivingSubject#getStrainText
  */
  public ED getStrainText() { return EDnull.NI; /* should be NA, but that causes trouble for string-literal hibernated properties. */ }
  /** Property mutator, does nothing if not overloaded.strainText.
      @see org.hl7.rim.NonPersonLivingSubject#setStrainText
  */
  public void setStrainText(ED strainText) { /*throw new UnsupportedOperationException();*/ }
  /** Property accessor, returns NULL/NA if not overloaded.genderStatusCode.
      @see org.hl7.rim.NonPersonLivingSubject#getGenderStatusCode
  */
  public CE getGenderStatusCode() { return CEnull.NI; /* should be NA, but that causes trouble for string-literal hibernated properties. */ }
  /** Property mutator, does nothing if not overloaded.genderStatusCode.
      @see org.hl7.rim.NonPersonLivingSubject#setGenderStatusCode
  */
  public void setGenderStatusCode(CE genderStatusCode) { /*throw new UnsupportedOperationException();*/ }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace net\authorize\api\contract\v1;

/**
 * Class representing ValidateCustomerPaymentProfileRequest
 */
class ValidateCustomerPaymentProfileRequest extends ANetApiRequestType
{

    /**
     * @property string $customerProfileId
     */
    private $customerProfileId = null;

    /**
     * @property string $customerPaymentProfileId
     */
    private $customerPaymentProfileId = null;

    /**
     * @property string $customerShippingAddressId
     */
    private $customerShippingAddressId = null;

    /**
     * @property string $cardCode
     */
    private $cardCode = null;

    /**
     * @property string $validationMode
     */
    private $validationMode = null;

    /**
     * Gets as customerProfileId
     *
     * @return string
     */
    public function getCustomerProfileId()
    {
        return $this->customerProfileId;
    }

    /**
     * Sets a new customerProfileId
     *
     * @param string $customerProfileId
     * @return self
     */
    public function setCustomerProfileId($customerProfileId)
    {
        $this->customerProfileId = $customerProfileId;
        return $this;
    }

    /**
     * Gets as customerPaymentProfileId
     *
     * @return string
     */
    public function getCustomerPaymentProfileId()
    {
        return $this->customerPaymentProfileId;
    }

    /**
     * Sets a new customerPaymentProfileId
     *
     * @param string $customerPaymentProfileId
     * @return self
     */
    public function setCustomerPaymentProfileId($customerPaymentProfileId)
    {
        $this->customerPaymentProfileId = $customerPaymentProfileId;
        return $this;
    }

    /**
     * Gets as customerShippingAddressId
     *
     * @return string
     */
    public function getCustomerShippingAddressId()
    {
        return $this->customerShippingAddressId;
    }

    /**
     * Sets a new customerShippingAddressId
     *
     * @param string $customerShippingAddressId
     * @return self
     */
    public function setCustomerShippingAddressId($customerShippingAddressId)
    {
        $this->customerShippingAddressId = $customerShippingAddressId;
        return $this;
    }

    /**
     * Gets as cardCode
     *
     * @return string
     */
    public function getCardCode()
    {
        return $this->cardCode;
    }

    /**
     * Sets a new cardCode
     *
     * @param string $cardCode
     * @return self
     */
    public function setCardCode($cardCode)
    {
        $this->cardCode = $cardCode;
        return $this;
    }

    /**
     * Gets as validationMode
     *
     * @return string
     */
    public function getValidationMode()
    {
        return $this->validationMode;
    }

    /**
     * Sets a new validationMode
     *
     * @param string $validationMode
     * @return self
     */
    public function setValidationMode($validationMode)
    {
        $this->validationMode = $validationMode;
        return $this;
    }

}


text:
//
//  arrangeView.m
//  sparkledoctor
//
//  Created by wangyunrui on 16/5/21.
//  Copyright © 2016年 sparkletech. All rights reserved.
//

#import "arrangeView.h"

@implementation arrangeView

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end


text:
define([], function() {
    "use strict";
	console.log("Module2.js Loaded...");

    var Module2 = function() {
		console.log("Module2 instantiated...");
		this.init = function() {
			console.log("Module2 > init...");
			addEvents();
		};

		this.update = function() {
			console.log("Module2 > update...");
			// Publisher
			//$.Topic("module2Updated").publish("module2 > update > done...");
			//$.Deferred().done( $.Topic("module2Updated").publish).resolve("module2 > update > done...");
			appGlobals.globals.publish("module2Updated", {"name":"module2 > update > done..."});
		};

		var addEvents = function(){
			console.log("Module2 > addEvents...");
		};

		this.add = function(a, b) {
			console.log("Module2 > add...");
			if(a<0 || b<0){
				return 0;
			}else{
				return a+b;
			}
		};

	};
	return Module2;
});


text:
import AppDefinitions from '../modules/app.definitions';

export default function RunConfig($rootScope, AppDefinitions) {
     //$rootScope.APP = AppDefinitions;
}

RunConfig.$inject = ['$rootScope'];


text:
define(['leaflet'], function(L) {
    return L.FeatureGroup.extend({
        initialize: function(options) {
            L.setOptions(this, options);
            L.FeatureGroup.prototype.initialize.apply(this, arguments)
            this.options.collection.on('upd', this.update.bind(this));
            this._features = [];
            this.update();
        },
        clear: function() {
            while (this._features.length) {
                var marker = this._features.pop();
                marker.off('click');
                this.removeLayer(marker);
            }
        }
    });
});


text:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
        xmlns:android="http://schemas.android.com/apk/res/android">

    <Preference
            android:layout="@layout/about_teaser"/>
    <Preference
            android:key="about_version"
            android:title="@string/antennapod_version"
            android:icon="@drawable/ic_star"
            android:summary="1.7.2 (asd8qs)"/>
    <Preference
            android:key="about_contributors"
            android:icon="@drawable/ic_settings"
            android:summary="@string/contributors_summary"
            android:title="@string/contributors"/>
    <Preference
            android:key="about_privacy_policy"
            android:icon="@drawable/ic_questionmark"
            android:summary="www.antennapod.org/privacy"
            android:title="@string/privacy_policy"/>
    <Preference
            android:key="about_licenses"
            android:icon="@drawable/ic_info"
            android:summary="@string/licenses_summary"
            android:title="@string/licenses"/>

</PreferenceScreen>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ABSharp.Internal
{
    public interface IErrorLogger
    {
        void LogError(Exception ex);
    }
}


text:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

// Define the Items schema
var Items = new Schema ({
	type: Number,  // A key to determine the item type: informs which fields are displayed
	speaker: mongoose.Schema.ObjectId, // Reference to a Member object
	topic: String, // of a talk
	duration: Number, // of a talk
	guestspeaker: String,
	testimony: mongoose.Schema.ObjectId, // Reference to a Member object
	guesttestimony: String,
	hymn: mongoose.Schema.ObjectId,
	position: Number
});

// Define the Sunday schema
var Sunday = new Schema({
	date : Date,
	unit: Number,
	items: [Items]
});

// Export the Mongoose model
module.exports = mongoose.model('Sunday', Sunday);


text:
package org.kuali.kfs.module.purap.document.validation.impl;

import org.kuali.kfs.module.purap.businessobject.PurApAccountingLine;
import org.kuali.kfs.module.purap.businessobject.PurApItem;
import org.kuali.kfs.sys.document.validation.GenericValidation;
import org.kuali.kfs.sys.document.validation.event.AttributedDocumentEvent;
import org.kuali.rice.krad.util.ObjectUtils;

public class PaymentRequestProcessAccountValidation extends GenericValidation {

    private PurchasingAccountsPayableHasAccountsValidation hasAccountsValidation;
    private PurchasingAccountsPayableAccountPercentValidation accountPercentValidation;
    private PurchasingAccountsPayableAccountTotalValidation accountTotalValidation;
    private PurchasingAccountsPayableUniqueAccountingStringsValidation accountingStringsValidation;
    private PurApItem itemForValidation;
    private PurchasingAccountsPayableAccountAtleastOneLineHasPercentValidation accountHasAtleastOnePercentValidation;
    private PurchasingAccountingLineAmountValidation accountLineAmountValidation;

    @Override
    public boolean validate(AttributedDocumentEvent event) {
        boolean valid = true;

        if (ObjectUtils.isNull(itemForValidation)) {
            return valid;
        }

        hasAccountsValidation.setItemForValidation(itemForValidation);
        valid &= hasAccountsValidation.validate(event);

        if(valid){
            accountPercentValidation.setItemForValidation(itemForValidation);
            valid &= accountPercentValidation.validate(event);
        }

        if(valid){
                accountTotalValidation.setItemForValidation(itemForValidation);
                valid &= accountTotalValidation.validate(event);
        }

        accountingStringsValidation.setItemForValidation(itemForValidation);
        valid &= accountingStringsValidation.validate(event);

        if (valid) {
            getAccountHasAtlestOnePercentValidation().setItemForValidation(itemForValidation);
            valid &= getAccountHasAtlestOnePercentValidation().validate(event);
        }

        if(valid){
            for (PurApAccountingLine account : itemForValidation.getSourceAccountingLines()) {
                getAccountLineAmountValidation().setUpdatedAccountingLine(account);
                valid &= getAccountLineAmountValidation().validate(event);
                if (!valid) {
                    break;
                }
            }
        }

        return valid;
    }

    public PurchasingAccountsPayableHasAccountsValidation getHasAccountsValidation() {
        return hasAccountsValidation;
    }

    public void setHasAccountsValidation(PurchasingAccountsPayableHasAccountsValidation hasAccountsValidation) {
        this.hasAccountsValidation = hasAccountsValidation;
    }

    public PurchasingAccountsPayableAccountTotalValidation getAccountTotalValidation() {
        return accountTotalValidation;
    }

    public void setAccountTotalValidation(PurchasingAccountsPayableAccountTotalValidation accountTotalValidation) {
        this.accountTotalValidation = accountTotalValidation;
    }

    public PurchasingAccountsPayableUniqueAccountingStringsValidation getAccountingStringsValidation() {
        return accountingStringsValidation;
    }

    public void setAccountingStringsValidation(PurchasingAccountsPayableUniqueAccountingStringsValidation accountingStringsValidation) {
        this.accountingStringsValidation = accountingStringsValidation;
    }

    public PurApItem getItemForValidation() {
        return itemForValidation;
    }

    public void setItemForValidation(PurApItem itemForValidation) {
        this.itemForValidation = itemForValidation;
    }

    /**
     * @return Returns the accountHasAtleastOnePercentValidation
     */

    public PurchasingAccountsPayableAccountAtleastOneLineHasPercentValidation getAccountHasAtlestOnePercentValidation() {
        return accountHasAtleastOnePercentValidation;
    }

    /**
     * Sets the accountHasAtleastOnePercentValidation attribute.
     *
     * @param accountHasAtleastOnePercentValidation The accountHasAtleastOnePercentValidation to set.
     */
    public void setAccountHasAtleastOnePercentValidation(PurchasingAccountsPayableAccountAtleastOneLineHasPercentValidation accountHasAtleastOnePercentValidation) {
        this.accountHasAtleastOnePercentValidation = accountHasAtleastOnePercentValidation;
    }

    /**
     * Gets the accountLineAmountValidation attribute.
     *
     * @return Returns the accountLineAmountValidation
     */

    public PurchasingAccountingLineAmountValidation getAccountLineAmountValidation() {
        return accountLineAmountValidation;
    }

    /**
     * Sets the accountLineAmountValidation attribute.
     *
     * @param accountLineAmountValidation The accountLineAmountValidation to set.
     */
    public void setAccountLineAmountValidation(PurchasingAccountingLineAmountValidation accountLineAmountValidation) {
        this.accountLineAmountValidation = accountLineAmountValidation;
    }

    public PurchasingAccountsPayableAccountPercentValidation getAccountPercentValidation() {
        return accountPercentValidation;
    }

    public void setAccountPercentValidation(PurchasingAccountsPayableAccountPercentValidation accountPercentValidation) {
        this.accountPercentValidation = accountPercentValidation;
    }

}


text:
Rails.application.routes.draw do
  devise_for :users, path: 'admin'
  namespace :admin do
    root to: "home#index"
    resources :home, only: [:index]
    resources :countries
    resources :event_requests, only: [:index, :show, :destroy]
    resources :tasks
    resources :events
    resources :campaigns do
      member do
        post :move
      end
    end
    resources :users
  end

  resources :tags, only: [:index, :show]

  namespace :api do
    namespace :v1 do
      resources :events, only: [:show, :index]
      resources :campaigns, only: [:show, :index]
      resources :tasks, only: [:show, :index]
      resources :countries, only: [:show, :index]
    end
  end

  scope "(/:locale)", locale: /en|pt|fr/ do
    resources :campaigns, only: [:show, :index] do
      resources :events, only: [:index]
      resources :tasks, only: [:index]
    end
    resources :events, only: [:show, :index] do
      resources :tasks, only: [:index]
    end
    resources :tasks, only: [:show, :index]
    resources :event_requests, only: [:new, :create]
    get :leaderboards, to: "leaderboards#index"
    get :map, to: "map#index"
  end

  get "/:locale", to: "home#index", as: :locale_root
  root 'home#index'
end


text:
<BODY>
Virtual Reality simulation of orbital plane change using the moon</BODY>


text:
{-# LANGUAGE OverloadedStrings, MultiParamTypeClasses #-}
module Haste.App.Client
  ( Client, MonadClient (..)
  , runClient
  ) where
import Control.Monad ((<=<))
import Haste.Serialize
import Haste.JSON
import Haste.Concurrent
import Haste.WebSockets
import qualified Haste.JSString as JSS (concat)
import Haste.App.Client.Type
import Haste.App.Transport
import Haste.App.Protocol
import Haste.App.Routing (Node (..))
import Haste (toJSString)
import Haste.App.Sandbox (callSandbox)

instance MonadClient Client where
  remoteCall ep@(LocalNode{}) pkt n = do
    liftCIO $ callSandbox n ep pkt
  remoteCall ep@(WebSocket{}) pkt n = do
      reply <- liftCIO $ do
        (v, conf) <- mkConfig ep
        Just ws <- wsOpen conf
        wsSend ws pkt
        reply <- (fromJSON <=< decodeJSON) <$> takeMVar v
        wsClose ws
        return reply
      case reply of
        Right (ServerReply _ reply) -> return reply
        Right (ServerEx _ m)        -> throwError $ ClientError m
        Left e                      -> throwError $ ClientError (show e)
    where
      mkConfig (WebSocket host port) = do
        v <- newEmptyMVar
        return (v, WebSocketConfig
          { wsOpenURL = JSS.concat ["ws://", toJSString host, ":", toJSString port]
          , wsOnMessage = \_ x -> putMVar v x
          })


text:
<?xml version="1.0" encoding="UTF-8"?>
<project name="HmiOpenGLTest" default="run" >
   <import file="../../hmibuild/build.xml" />
</project>


text:
/* Includes ------------------------------------------------------------------*/
#include "stm8l15x_dac.h"

/** @addtogroup STM8L15x_StdPeriph_Driver
  * @{
  */

/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/* Private functions ---------------------------------------------------------*/

/**
    * @addtogroup DAC_Public_Functions
    * @{
    */

/**
  * @brief  Deinitializes the DAC peripheral registers to their default reset values.
  * @param  None
  * @retval None
  */
void DAC_DeInit(void)
{
  /*  Set Channel1  the Configuration registers to their reset values */
  DAC->CH1CR1 = DAC_CR1_RESET_VALUE;
  DAC->CH1CR2 = DAC_CR2_RESET_VALUE;

  /*  Set Channel2  the Configuration registers to their reset values */
  DAC->CH2CR1 = DAC_CR1_RESET_VALUE;
  DAC->CH2CR2 = DAC_CR2_RESET_VALUE;

  /*  Set the Software Trigger configuration registers to their reset values */
  DAC->SWTRIGR = DAC_SWTRIGR_RESET_VALUE;

  /*  Set the Status registers to their reset values */
  DAC->SR = (uint8_t)~DAC_SR_RESET_VALUE;

  /*  Set the Channel1 Data holding registers to their reset values */
  DAC->CH1RDHRH = DAC_RDHRH_RESET_VALUE;
  DAC->CH1RDHRL = DAC_RDHRL_RESET_VALUE;
  DAC->CH1LDHRH = DAC_LDHRH_RESET_VALUE;
  DAC->CH1LDHRL = DAC_LDHRL_RESET_VALUE;
  DAC->CH1DHR8 = DAC_DHR8_RESET_VALUE;

  /*  Set the Channel2 Data holding registers to their reset values */
  DAC->CH2RDHRH = DAC_RDHRH_RESET_VALUE;
  DAC->CH2RDHRL = DAC_RDHRL_RESET_VALUE;
  DAC->CH2LDHRH = DAC_LDHRH_RESET_VALUE;
  DAC->CH2LDHRL = DAC_LDHRL_RESET_VALUE;
  DAC->CH2DHR8 = DAC_DHR8_RESET_VALUE;

  /*  Set the Dual mode 12bit Right Data holding registers to their reset values */
  DAC->DCH1RDHRH = DAC_RDHRH_RESET_VALUE;
  DAC->DCH1RDHRL = DAC_RDHRL_RESET_VALUE;
  DAC->DCH2RDHRH = DAC_RDHRH_RESET_VALUE;
  DAC->DCH2RDHRL = DAC_RDHRL_RESET_VALUE;

  /*  Set the Dual mode 12bit Left Data holding registers to their reset values */
  DAC->DCH1LDHRH = DAC_LDHRH_RESET_VALUE;
  DAC->DCH1LDHRL = DAC_LDHRL_RESET_VALUE;
  DAC->DCH2LDHRH = DAC_LDHRH_RESET_VALUE;
  DAC->DCH2LDHRL = DAC_LDHRL_RESET_VALUE;

  /*  Set the Dual mode 8bit Data holding registers to their reset values */
  DAC->DCH1DHR8 = DAC_DHR8_RESET_VALUE;
  DAC->DCH2DHR8 = DAC_DHR8_RESET_VALUE;
}

/**
  * @brief  Initializes the DAC according to the specified parameters.
  * @param  DAC_Channel : the selected DAC channel from @ref DAC_Channel_TypeDef
  *         enumeration.
  * @param  DAC_Trigger : the selected DAC trigger from @ref DAC_Trigger_TypeDef
  *         enumeration.
  * @param  DAC_OutputBuffer : the status of DAC load Buffer from
  *         @ref DAC_OutputBuffer_TypeDef enumeration.
  * @retval None
  */
void DAC_Init(DAC_Channel_TypeDef DAC_Channel,
              DAC_Trigger_TypeDef DAC_Trigger,
              DAC_OutputBuffer_TypeDef DAC_OutputBuffer)
{
  uint8_t tmpreg = 0;
  uint16_t tmpreg2 = 0;

  /* Check the DAC parameters */
  assert_param(IS_DAC_CHANNEL(DAC_Channel));
  assert_param(IS_DAC_TRIGGER(DAC_Trigger));
  assert_param(IS_DAC_OUTPUT_BUFFER_STATE(DAC_OutputBuffer));

  /* Get the DAC CHxCR1 value */
  tmpreg2 =  (uint16_t)((uint8_t)((uint8_t)DAC_Channel << 1));
  tmpreg = *(uint8_t*)((uint16_t)(DAC_BASE + CR1_Offset + tmpreg2));

  /* Clear BOFFx, TENx, TSELx bits */
  tmpreg &= (uint8_t)~(DAC_CR1_BOFF | DAC_CR1_TEN | DAC_CR1_TSEL );

  /* Set BOFFx bit according to DAC_OutputBuffer value */
  tmpreg |= (uint8_t)(DAC_OutputBuffer);

  /* Configure for the selected DAC channel trigger*/
  if (DAC_Trigger != DAC_Trigger_None)
  {
    /* Set TSELx and TEN  bits according to DAC_Trigger value */
    tmpreg |= (uint8_t)(DAC_CR1_TEN | DAC_Trigger) ;
  }

  /* Write to DAC CHxCR1 */
  *(uint8_t*)((uint16_t)(DAC_BASE + CR1_Offset + tmpreg2)) = (uint8_t)tmpreg;
}

/**
  * @brief  Enables or disables DAC Wave Generation according to the specified
  *         parameters.
  * @param  DAC_Channel : the selected DAC channel from @ref DAC_Channel_TypeDef
  *         enumeration.
  * @param  DAC_Wave : the selected waveform from @ref DAC_Wave_TypeDef enumeration.
  * @retval None
  */
void DAC_WaveGenerationCmd(DAC_Channel_TypeDef DAC_Channel,
                           DAC_Wave_TypeDef DAC_Wave,
                           FunctionalState NewState)
{
  uint8_t tmpreg = 0;

  /* Check the DAC parameters */
  assert_param(IS_DAC_CHANNEL(DAC_Channel));
  assert_param(IS_DAC_WAVE(DAC_Wave));
  assert_param(IS_FUNCTIONAL_STATE(NewState));

  /* Get the DAC CHxCR1 value & Clear WAVEN bits */
  tmpreg = (uint8_t)((*(uint8_t*)(uint16_t)(DAC_BASE + CR1_Offset + (uint8_t)((uint8_t)DAC_Channel << 1))) & (uint8_t)~(DAC_CR1_WAVEN));

  if (NewState != DISABLE)
  {
    tmpreg |= (uint8_t)(DAC_Wave);
  }

  /* Write to DAC CHxCR1 */
  (*(uint8_t*) (uint16_t)(DAC_BASE + CR1_Offset +  (uint8_t)((uint8_t)DAC_Channel << 1))) = tmpreg;

}

/**
  * @brief  Select DAC Noise Wave Generation LFSR according to the specified
  *         parameters.
  * @param  DAC_Channel : the selected DAC channel from @ref DAC_Channel_TypeDef
  *         enumeration.
  * @param  DAC_LFSRUnmask : the selected unmasked bit from
  *         @ref DAC_LFSRUnmask_TypeDef enumeration.
  * @retval None
  */
void DAC_NoiseWaveLFSR(DAC_Channel_TypeDef DAC_Channel, DAC_LFSRUnmask_TypeDef DAC_LFSRUnmask)
{
  uint8_t tmpreg = 0;
  uint16_t cr2addr = 0;

  /* Check the DAC parameters */
  assert_param(IS_DAC_CHANNEL(DAC_Channel));
  assert_param(IS_DAC_LFSR_UNMASK_TRIANGLE_AMPLITUDE(DAC_LFSRUnmask));

  /* Get the DAC CHxCR2 value  &  Clear MAMPx bits */
  cr2addr = (uint16_t)(DAC_BASE + CR2_Offset + (uint8_t)((uint8_t)DAC_Channel << 1));
  tmpreg = (uint8_t)((*(uint8_t*)(cr2addr)) & (uint8_t)~(DAC_CR2_MAMPx));

  /* Write to DAC CHxCR2 */
  (*(uint8_t*)(cr2addr)) = (uint8_t)( tmpreg | DAC_LFSRUnmask);
}
/**
  * @brief  Select DAC Triangle Wave Generation Amplitude according
  *         to the specified parameters.
  * @param  DAC_Channel : the selected DAC channel from
  *         @ref DAC_Channel_TypeDef enumeration.
  * @param  DAC_TriangleAmplitude : the selected Amplitude from
  *         @ref DAC_TriangleAmplitude_TypeDef enumeration.
  * @retval None
  */
void DAC_TriangleWaveAmplitude(DAC_Channel_TypeDef DAC_Channel, DAC_TriangleAmplitude_TypeDef DAC_TriangleAmplitude)
{
  uint8_t tmpreg = 0;
  uint16_t cr2addr = 0;

  /* Check the DAC parameters */
  assert_param(IS_DAC_CHANNEL(DAC_Channel));
  assert_param(IS_DAC_LFSR_UNMASK_TRIANGLE_AMPLITUDE(DAC_TriangleAmplitude));

  /* Get the DAC CHxCR2 value  &  Clear MAMPx bits */
  cr2addr = (uint16_t)(DAC_BASE + CR2_Offset + (uint8_t)((uint8_t)DAC_Channel << 1));
  tmpreg = (uint8_t)((*(uint8_t*)(cr2addr)) & (uint8_t)~(DAC_CR2_MAMPx));

  /* Write to DAC CHxCR2 */
  (*(uint8_t*)(cr2addr)) = (uint8_t)( tmpreg | DAC_TriangleAmplitude);
}
/**
  * @brief  Enables or disables the specified DAC channel.
  * @param  DAC_Channel : the selected DAC channel from
  *         @ref DAC_Channel_TypeDef enumeration.
  * @param  NewState : new state of the DAC channel.
  *         This parameter can be: ENABLE or DISABLE.
  * @retval None
  */
void DAC_Cmd(DAC_Channel_TypeDef DAC_Channel, FunctionalState NewState)
{
  uint16_t cr1addr = 0;
  /* Check the parameters */
  assert_param(IS_DAC_CHANNEL(DAC_Channel));
  assert_param(IS_FUNCTIONAL_STATE(NewState));

  /* Find CHxCR1 register Address */
  cr1addr = DAC_BASE + CR1_Offset + (uint8_t)((uint8_t)DAC_Channel << 1);

  if (NewState != DISABLE)
  {
    /* Enable the selected DAC channel */
    (*(uint8_t*)(cr1addr)) |= DAC_CR1_EN;
  }
  else
  {
    /* Disable the selected DAC channel */
    (*(uint8_t*)(cr1addr)) &= (uint8_t) ~(DAC_CR1_EN);
  }
}

/**
  * @brief  Enables or disables the specified DAC interrupts.
  * @param  DAC_Channel : the selected DAC channel from
  *         @ref DAC_Channel_TypeDef enumeration.
  * @param  DAC_IT : the selected DAC interrupt from
  *         @ref DAC_IT_TypeDef enumeration.
  * @param  NewState : new state of the DAC interrupt .
  *         This parameter can be: ENABLE or DISABLE.
  * @retval None
  */
void DAC_ITConfig(DAC_Channel_TypeDef DAC_Channel, DAC_IT_TypeDef DAC_IT,
                  FunctionalState NewState)
{
  uint16_t cr2addr = 0;

  /* Check the parameters */
  assert_param(IS_DAC_CHANNEL(DAC_Channel));
  assert_param(IS_FUNCTIONAL_STATE(NewState));
  assert_param(IS_DAC_IT(DAC_IT));

  /* Find CHxCR2 register Address */
  cr2addr = DAC_BASE + CR2_Offset + (uint8_t)((uint8_t)DAC_Channel << 1);

  if (NewState != DISABLE)
  {
    /* Enable the selected DAC interrupts */
    (*(uint8_t*)(cr2addr)) |=  (uint8_t)(DAC_IT);
  }
  else
  {
    /* Disable the selected DAC interrupts */
    (*(uint8_t*)(cr2addr)) &= (uint8_t)(~(DAC_IT));
  }
}

/**
  * @brief  Enables or disables the specified DAC channel DMA request.
  * @param  DAC_Channel : the selected DAC channel from
  *         @ref DAC_Channel_TypeDef enumeration.
  * @param  NewState : new state of the selected DAC channel DMA request.
  *         This parameter can be: ENABLE or DISABLE.
  * @retval None.
  */
void DAC_DMACmd(DAC_Channel_TypeDef DAC_Channel, FunctionalState NewState)
{
  uint16_t cr2addr = 0;

  /* Check the parameters */
  assert_param(IS_DAC_CHANNEL(DAC_Channel));
  assert_param(IS_FUNCTIONAL_STATE(NewState));

  /* Find CHxCR2 register Address */
  cr2addr = DAC_BASE + CR2_Offset + (uint8_t)((uint8_t)DAC_Channel << 1);

  if (NewState != DISABLE)
  {
    /* Enable the selected DAC channel DMA request */
    (*(uint8_t*)(cr2addr)) |= DAC_CR2_DMAEN;
  }
  else
  {
    /* Disable the selected DAC channel DMA request */
    (*(uint8_t*)(cr2addr)) &= (uint8_t)~(DAC_CR2_DMAEN);
  }
}

/**
  * @brief  Enables or disables the selected DAC channel software trigger.
  * @param  DAC_Channel : the selected DAC channel from
  *         @ref DAC_Channel_TypeDef enumeration.
  * @param  NewState : new state of the selected DAC channel software trigger.
  *         This parameter can be: ENABLE or DISABLE.
  * @retval None.
  */
void DAC_SoftwareTriggerCmd(DAC_Channel_TypeDef DAC_Channel, FunctionalState NewState)
{
  /* Check the parameters */
  assert_param(IS_DAC_CHANNEL(DAC_Channel));
  assert_param(IS_FUNCTIONAL_STATE(NewState));

  if (NewState != DISABLE)
  {
    /* Enable software trigger for the selected DAC channel */
    DAC->SWTRIGR |= (uint8_t)(DAC_SWTRIGR_SWTRIG1 << DAC_Channel);
  }
  else
  {
    /* Disable software trigger for the selected DAC channel */
    DAC->SWTRIGR &= (uint8_t)~((uint8_t)(DAC_SWTRIGR_SWTRIG1 << DAC_Channel));
  }
}

/**
  * @brief  Enables or disables the dual channel DAC  software triggers.
  * @param  NewState : new state of the  DAC channels software triggers.
  *         This parameter can be: ENABLE or DISABLE.
  * @retval None.
  */
void DAC_DualSoftwareTriggerCmd(FunctionalState NewState)
{
  /* Check the parameters */
  assert_param(IS_FUNCTIONAL_STATE(NewState));

  if (NewState != DISABLE)
  {
    /* Enable software trigger for both DAC channels */
    DAC->SWTRIGR |= (DAC_SWTRIGR_SWTRIG1 | DAC_SWTRIGR_SWTRIG2) ;
  }
  else
  {
    /* Disable software trigger for both DAC channels */
    DAC->SWTRIGR &= (uint8_t)~(DAC_SWTRIGR_SWTRIG1 | DAC_SWTRIGR_SWTRIG2);
  }
}

/**
  * @brief  Set the specified data holding register value for DAC channel1.
  * @param  DAC_Align : Specifies the data alignement for DAC channel1 from
  *         @ref DAC_Align_TypeDef enumeration.
  * @param  DAC_Data : Data to be loaded in the selected data holding register.
  * @retval None.
  */
void DAC_SetChannel1Data(DAC_Align_TypeDef DAC_Align, uint16_t DAC_Data)
{
  /* Check the parameters */
  assert_param(IS_DAC_ALIGN(DAC_Align));

  if (DAC_Align != DAC_Align_8b_R)
  {
    /* Set the DAC channel1 selected data holding register */
    *(uint8_t*)((uint16_t)(DAC_BASE + CH1RDHRH_Offset + DAC_Align )) = (uint8_t)(((uint16_t)DAC_Data) >> 8);
    *(uint8_t*)((uint16_t)(DAC_BASE + CH1RDHRH_Offset + 1 + DAC_Align )) = (uint8_t)DAC_Data;
  }
  else
  {
    /* Check the parameter */
    assert_param(IS_DAC_DATA_08R(DAC_Data));

    /* Set the DAC channel1 selected data holding register */
    DAC->CH1DHR8 = (uint8_t)(DAC_Data);
  }
}

/**
  * @brief  Set the specified data holding register value for DAC channel2.
  * @param  DAC_Align : Specifies the data alignement for DAC channel2 from
  *         @ref DAC_Align_TypeDef enumeration.
  * @param  DAC_Data : Data to be loaded in the selected data holding register.
  * @retval None.
  */
void DAC_SetChannel2Data(DAC_Align_TypeDef DAC_Align, uint16_t DAC_Data)
{
  /* Check the parameters */
  assert_param(IS_DAC_ALIGN(DAC_Align));

  if (DAC_Align != DAC_Align_8b_R)
  {
    /* Set the DAC channel2 selected data holding register */
    *(uint8_t*)((uint16_t)(DAC_BASE + CH2RDHRH_Offset + DAC_Align )) = (uint8_t)(((uint16_t)DAC_Data) >> 8);
    *(uint8_t*)((uint16_t)(DAC_BASE + CH2RDHRH_Offset + 1 + DAC_Align )) = (uint8_t)DAC_Data;
  }
  else
  {
    /* Check the parameter */
    assert_param(IS_DAC_DATA_08R(DAC_Data));

    /* Set the DAC channel2 selected data holding register */
    DAC->CH2DHR8 = (uint8_t)(DAC_Data);
  }
}

/**
  * @brief  Set the specified data holding register value for DAC Dual channels data.
  * @param  DAC_Align : Specifies the data alignement for DAC channel2 from
  *         @ref DAC_Align_TypeDef enumeration.
  * @param  DAC_Data2 : Data to be loaded in the selected data holding register
  *         for channel 2.
  * @param  DAC_Data1 : Data to be loaded in the selected data holding register
  *         for channel 1.
  * @retval None.
  */
void DAC_SetDualChannelData(DAC_Align_TypeDef DAC_Align,
                            uint16_t DAC_Data2,
                            uint16_t DAC_Data1)
{
  uint16_t dchxrdhrhaddr = 0;

  /* Check the parameters */
  assert_param(IS_DAC_ALIGN(DAC_Align));

  if (DAC_Align != DAC_Align_8b_R)
  {
    /* Identify the DCHxRDHRH address*/
    dchxrdhrhaddr = (uint16_t)(DAC_BASE + DCH1RDHRH_Offset + DAC_Align);

    /* Set the DAC channels Dual data holding registers */
    *(uint8_t*)(uint16_t)dchxrdhrhaddr = (uint8_t)(((uint16_t)DAC_Data1) >> 8);
    *(uint8_t*)(uint16_t)(dchxrdhrhaddr + 1) = (uint8_t)DAC_Data1;
    *(uint8_t*)(uint16_t)(dchxrdhrhaddr + 2) = (uint8_t)(((uint16_t)DAC_Data2) >> 8);
    *(uint8_t*)(uint16_t)(dchxrdhrhaddr + 3) = (uint8_t)DAC_Data2;
  }
  else
  {
    /* Check the parameter */
    assert_param(IS_DAC_DATA_08R(DAC_Data1 | DAC_Data2));

    /* Set the DAC channels Dual data holding registers */
    DAC->DCH1DHR8 = (uint8_t)(DAC_Data1);
    DAC->DCH2DHR8 = (uint8_t)(DAC_Data2);
  }
}
/**
  * @brief  Returns the last data output value of the selected DAC channel.
  * @param  DAC_Channel : the selected DAC channel from @ref DAC_Channel_TypeDef
  *         enumeration.
  * @retval The selected DAC channel data output value.
  */
uint16_t DAC_GetDataOutputValue(DAC_Channel_TypeDef DAC_Channel)
{
  uint16_t outputdata = 0;
  uint16_t tmp = 0;

  /* Check the parameters */
  assert_param(IS_DAC_CHANNEL(DAC_Channel));

  if ( DAC_Channel ==  DAC_Channel_1)
  {
    /* Returns the DAC channel data output register value */
    tmp = (uint16_t)((uint16_t)DAC->CH1DORH << 8);
    outputdata = (uint16_t)(tmp | (DAC->CH1DORL));
  }
  else
  {
    /* Returns the DAC channel data output register value */
    tmp = (uint16_t)((uint16_t)DAC->CH2DORH << 8);
    outputdata = (uint16_t)(tmp | (DAC->CH2DORL));
  }

  /* return the selected DAC channel data output value.*/
  return (uint16_t)outputdata;
}
/**
  * @brief  Checks whether the specified DAC flag is set or not.
  * @param  DAC_Channel : the selected DAC channel from @ref DAC_Channel_TypeDef
  *         enumeration.
  * @param  DAC_FLAG : specifies the flag to check from @ref DAC_FLAG_TypeDef
  *         enumeration.
  * @retval FlagStatus The new state of DAC_FLAG (SET or RESET).
  */
FlagStatus DAC_GetFlagStatus(DAC_Channel_TypeDef DAC_Channel, DAC_FLAG_TypeDef DAC_FLAG)
{
  FlagStatus flagstatus = RESET;
  uint8_t flag = 0;

  /* Check the parameters */
  assert_param(IS_DAC_CHANNEL(DAC_Channel));
  assert_param(IS_DAC_FLAG(DAC_FLAG));

  flag = (uint8_t)(DAC_FLAG << DAC_Channel);

  /* Check the status of the specified DAC flag */
  if ((DAC->SR & flag ) != (uint8_t)RESET)
  {
    /* DAC FLAG is set */
    flagstatus = SET;
  }
  else
  {
    /* DAC FLAG is reset */
    flagstatus = RESET;
  }

  /* Return the DAC FLAG status */
  return  flagstatus;
}

/**
  * @brief  Clears the DAC channelx's pending flags.
  * @param  DAC_Channel : the selected DAC channel from @ref DAC_Channel_TypeDef
  *         enumeration.
  * @param  DAC_FLAG : specifies the flag to clear from @ref DAC_FLAG_TypeDef
  *         enumeration.
  * @retval None.
  */
void DAC_ClearFlag(DAC_Channel_TypeDef DAC_Channel, DAC_FLAG_TypeDef DAC_FLAG)
{
  uint8_t flag = 0;

  /* Check the parameters */
  assert_param(IS_DAC_CHANNEL(DAC_Channel));
  assert_param(IS_DAC_FLAG(DAC_FLAG));

  /* identify the selected flag*/
  flag = (uint8_t)(DAC_FLAG << DAC_Channel);

  /* Clear the selected DAC flag */
  DAC->SR = (uint8_t)(~flag);
}
/**
  * @brief  Checks whether the specified DAC interrupt has occurred or not.
  * @param  DAC_Channel : the selected DAC channel from @ref DAC_Channel_TypeDef
  *         enumeration.
  * @param  DAC_IT : specifies the DAC interrupt source to check from
  *         @ref DAC_IT_TypeDef enumeration.
  * @retval ITStatus The new state of DAC_IT (SET or RESET).
  */
ITStatus DAC_GetITStatus(DAC_Channel_TypeDef DAC_Channel, DAC_IT_TypeDef DAC_IT)
{
  ITStatus itstatus = RESET;
  uint8_t enablestatus = 0;
  uint8_t flagstatus = 0;
  uint8_t tempreg = 0;

  /* Check the parameters */
  assert_param(IS_DAC_CHANNEL(DAC_Channel));
  assert_param(IS_DAC_IT(DAC_IT));

  /* identify the status of the IT and its correspondent flag*/
  tempreg = *(uint8_t*)(uint16_t)(DAC_BASE + CR2_Offset + (uint8_t)((uint8_t)DAC_Channel << 2));
  enablestatus = (uint8_t)( tempreg & (uint8_t)((uint8_t)DAC_IT << DAC_Channel));
  flagstatus = (uint8_t)(DAC->SR & (uint8_t)(DAC_IT >> ((uint8_t)0x05 - DAC_Channel)));

  /* Check the status of the specified DAC interrupt */
  if (((flagstatus) != (uint8_t)RESET) && enablestatus)
  {
    /* DAC IT is set */
    itstatus = SET;
  }
  else
  {
    /* DAC IT is reset */
    itstatus = RESET;
  }

  /* Return the DAC IT status */
  return  itstatus;
}

/**
  * @brief   Clears the DAC channelx's interrupt pending bits.
  * @param  DAC_Channel : the selected DAC channel from @ref DAC_Channel_TypeDef
  *         enumeration.
  * @param  DAC_IT : specifies the DAC interrupt pending bit to clear from
  *         @ref DAC_IT_TypeDef enumeration.
  * @retval None.
  */
void DAC_ClearITPendingBit(DAC_Channel_TypeDef DAC_Channel, DAC_IT_TypeDef DAC_IT)
{
  /* Check the parameters */
  assert_param(IS_DAC_CHANNEL(DAC_Channel));
  assert_param(IS_DAC_IT(DAC_IT));

  /* Clear the selected DAC interrupt pending bits */
  DAC->SR = (uint8_t)~(uint8_t)((uint8_t)DAC_IT >> (0x05 - DAC_Channel));
}

/**
    * @}
    */

/**
  * @}
  */

/******************* (C) COPYRIGHT 2010 STMicroelectronics *****END OF FILE****/


text:
import Ember from 'ember';
import layout from 'ember-tooltips/templates/components/lazy-render-wrapper';

const { computed, get, $ } = Ember;

// https://github.com/emberjs/rfcs/issues/168
// https://github.com/emberjs/ember.js/pull/12500
function getParent(view) {
  if (get(view, 'tagName') === '') {
    // Beware: use of private API! :(
    if (Ember.ViewUtils && Ember.ViewUtils.getViewBounds) {
      return $(Ember.ViewUtils.getViewBounds(view).parentElement);
    } else {
      return $(view._renderNode.contextualElement);
    }
  } else {
    return view.$().parent();
  }
}

const PASSABLE_PROPERTIES = [
	'delay',
	'delayOnChange',
	'duration',
	'effect',
	'event',
	'hideOn',
	'keepInWindow',
	'side',
	'showOn',
	'spacing',
	'isShown',
	'tooltipIsVisible',
	'hideDelay',
	'target',
	'text',

	// non-publicized attributes
	'updateFor',
	'targetAttachment',
	'attachment',
	'role',
	'tabindex',
	'_shouldTargetGrandparentView',
];

const PASSABLE_ACTIONS = [
	'onDestroy',
	'onHide',
	'onRender',
	'onShow',

	// deprecated lifecycle actions
	'onTooltipDestroy',
	'onTooltipHide',
	'onTooltipRender',
	'onTooltipShow',
];

const PASSABLE_OPTIONS = PASSABLE_PROPERTIES.concat(PASSABLE_ACTIONS);

export default Ember.Component.extend({
	tagName: '',
	layout,

	passedPropertiesObject: computed(...PASSABLE_OPTIONS, function() {
		return PASSABLE_OPTIONS.reduce((passablePropertiesObject, key) => {
			// if a property has been declared by Component extension ( TooltipOnElement.extend )
			// or by handlebars instantiation ( {{tooltip-on-element}} ) then that property needs
			// to be passed from this wrapper to the lazy-rendered tooltip or popover component

			let value = this.get(key);

			if (!Ember.isNone(value)) {
				if (PASSABLE_ACTIONS.indexOf(key) >= 0) {
					// if a user has declared a lifecycle action property (onShow='someFunc')
					// then we must pass down the correctly-scoped action instead of value

					passablePropertiesObject[key] = () => this.sendAction(key);
				} else {
					passablePropertiesObject[key] = value;
				}
			}

			return passablePropertiesObject;
		}, {});
	}),

	enableLazyRendering: false,
	_hasUserInteracted: false,
	_hasRendered: false,
	_shouldRender: computed('isShown', 'tooltipIsVisible', 'enableLazyRendering', '_hasUserInteracted', function() {
		// if isShown, tooltipIsVisible, !enableLazyRendering, or _hasUserInteracted then
		// we return true and set _hasRendered to true because
		// there is never a scenario where this wrapper should destroy the tooltip

		if (this.get('_hasRendered')) {

			return true;

		} else if (this.get('isShown') || this.get('tooltipIsVisible')) {

			this.set('_hasRendered', true);
			return true;

		} else if (!this.get('enableLazyRendering')) {

			this.set('_hasRendered', true);
			return true;

		} else if (this.get('_hasUserInteracted')) {

			this.set('_hasRendered', true);
			return true;

		}

		return false;
	}),
	_shouldShowOnRender: false,

	event: 'hover', // hover, click, focus, none
	entryInteractionEvents: computed('event', function() {
		// the lazy-render wrapper will only render the tooltip when
		// the $parent element is interacted with. This CP defines which
		// events will trigger the rendering. We always include focusin
		// to keep the component accessible.
		let entryInteractionEvents = ['focusin'];
		let event = this.get('event');
		if (event === 'hover') {
			entryInteractionEvents.push('mouseenter');
		} else if (event === 'click') {
			entryInteractionEvents.push('click');
		}

		return entryInteractionEvents;
	}),

	didInsertElement() {
		this._super(...arguments);

		if (this.get('_shouldRender')) {
			// if the tooltip _shouldRender then we don't need
			// any special $parent event handling
			return;
		}

		const $parent = getParent(this);

		if (this.get('event') === 'hover') {
			// We've seen instances where a user quickly mouseenter and mouseleave the $parent.
			// By providing this event handler we ensure that the tooltip will only *show*
			// if the user has mouseenter and not mouseleave immediately afterwards.
			$parent.on('mouseleave.target-lazy-render-wrapper', () => {
				this.set('_shouldShowOnRender', false);
			});
		}

		this.get('entryInteractionEvents').forEach((entryInteractionEvent) => {
			$parent.on(`${entryInteractionEvent}.target-lazy-render-wrapper`, () => {
				if (this.get('_hasUserInteracted')) {
					$parent.off(`${entryInteractionEvent}.target-lazy-render-wrapper`);
				} else {
					this.set('_hasUserInteracted', true);
					this.set('_shouldShowOnRender', true);
				}
			});
		});
	},

	childView: null, // this is set during the childView's didRender and is needed for the hide action
	actions: {
		hide() {
			const childView = this.get('childView');

			// childView.actions is not available in Ember 1.13
			// We will use childView._actions until we drop support for Ember 1.13
			if (childView && childView._actions && childView._actions.hide) {
				childView.send('hide');
			}
		},
	},

	willDestroyElement() {
		this._super(...arguments);

		const $parent = getParent(this);
		this.get('entryInteractionEvents').forEach((entryInteractionEvent) => {
			$parent.off(`${entryInteractionEvent}.target-lazy-render-wrapper`);
		});

		$parent.off('mouseleave.target-lazy-render-wrapper');
	},
});


text:
//
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
namespace Sample.Microsoft.HelloKeyVault
{
    enum KeyOperationType
    {
        CREATE_KEY,
        IMPORT_KEY,
        GET_KEY,
        LIST_KEYVERSIONS,
        UPDATE_KEY,
        DELETE_KEY,
        BACKUP_RESTORE,
        SIGN_VERIFY,
        ENCRYPT_DECRYPT,
        WRAP_UNWRAP,
        CREATE_SECRET,
        GET_SECRET,
        LIST_SECRETS,
        DELETE_SECRET,
        ENCRYPT,
        DECRYPT,
        CREATE_CERTIFICATE,
        IMPORT_CERTIFICATE,
        EXPORT_CERTIFICATE,
        LIST_CERTIFICATEVERSIONS,
        LIST_CERTIFICATES,
        DELETE_CERTIFICATE
    }
}


text:
<?php

namespace Zend\Mvc\Controller;

use Zend\Http\Response as HttpResponse;
use Zend\Mvc\Exception;
use Zend\Mvc\MvcEvent;
use Zend\View\Model\ConsoleModel;
use Zend\View\Model\ViewModel;

/**
 * Basic action controller
 */
abstract class AbstractActionController extends AbstractController
{
    /**
     * @var string
     */
    protected $eventIdentifier = __CLASS__;

    /**
     * Default action if none provided
     *
     * @return array
     */
    public function indexAction()
    {
        return new ViewModel(array(
            'content' => 'Placeholder page'
        ));
    }

    /**
     * Action called if matched action does not exist
     *
     * @return array
     */
    public function notFoundAction()
    {
        $response   = $this->response;
        $event      = $this->getEvent();
        $routeMatch = $event->getRouteMatch();
        $routeMatch->setParam('action', 'not-found');

        if ($response instanceof HttpResponse) {
            return $this->createHttpNotFoundModel($response);
        }
        return $this->createConsoleNotFoundModel($response);
    }

    /**
     * Execute the request
     *
     * @param  MvcEvent $e
     * @return mixed
     * @throws Exception\DomainException
     */
    public function onDispatch(MvcEvent $e)
    {
        $routeMatch = $e->getRouteMatch();
        if (!$routeMatch) {
            /**
             * @todo Determine requirements for when route match is missing.
             *       Potentially allow pulling directly from request metadata?
             */
            throw new Exception\DomainException('Missing route matches; unsure how to retrieve action');
        }

        $action = $routeMatch->getParam('action', 'not-found');
        $method = static::getMethodFromAction($action);

        if (!method_exists($this, $method)) {
            $method = 'notFoundAction';
        }

        $actionResponse = $this->$method();

        $e->setResult($actionResponse);

        return $actionResponse;
    }

    /**
     * Create an HTTP view model representing a "not found" page
     *
     * @param  HttpResponse $response
     * @return ViewModel
     */
    protected function createHttpNotFoundModel(HttpResponse $response)
    {
        $response->setStatusCode(404);
        return new ViewModel(array(
            'content' => 'Page not found',
        ));
    }

    /**
     * Create a console view model representing a "not found" action
     *
     * @param  \Zend\Stdlib\ResponseInterface $response
     * @return ConsoleModel
     */
    protected function createConsoleNotFoundModel($response)
    {
        $viewModel = new ConsoleModel();
        $viewModel->setErrorLevel(1);
        $viewModel->setResult('Page not found');
        return $viewModel;
    }
}


text:
#include "tensorflow/compiler/xla/client/local_client.h"

#include <utility>

#include "external/llvm/include/llvm/ADT/Triple.h"
#include "tensorflow/compiler/xla/ptr_util.h"
#include "tensorflow/compiler/xla/service/backend.h"
#include "tensorflow/compiler/xla/service/llvm_ir/llvm_util.h"
#include "tensorflow/compiler/xla/service/service_executable_run_options.h"
#include "tensorflow/compiler/xla/status_macros.h"

namespace se = ::perftools::gputools;

namespace xla {

ExecutableBuildOptions& ExecutableBuildOptions::set_platform(
    perftools::gputools::Platform* platform) {
  platform_ = platform;
  return *this;
}

perftools::gputools::Platform* ExecutableBuildOptions::platform() const {
  return platform_;
}

ExecutableBuildOptions& ExecutableBuildOptions::set_device_ordinal(
    int device_ordinal) {
  device_ordinal_ = device_ordinal;
  return *this;
}

int ExecutableBuildOptions::device_ordinal() const { return device_ordinal_; }

ExecutableBuildOptions& ExecutableBuildOptions::set_result_layout(
    const Shape& shape_with_layout) {
  result_layout_set_ = true;
  result_layout_ = shape_with_layout;
  return *this;
}

const Shape* ExecutableBuildOptions::result_layout() const {
  return result_layout_set_ ? &result_layout_ : nullptr;
}

ExecutableBuildOptions& ExecutableBuildOptions::set_has_hybrid_result(
    bool has_hybrid_result) {
  has_hybrid_result_ = has_hybrid_result;
  return *this;
}

bool ExecutableBuildOptions::has_hybrid_result() const {
  return has_hybrid_result_;
}

namespace {
StatusOr<Backend::StreamPtr> BorrowStreamForDevice(int device_ordinal,
                                                   Backend* backend) {
  if (device_ordinal < 0) {
    device_ordinal = backend->default_device_ordinal();
  }
  return backend->BorrowStream(device_ordinal);
}
}  // namespace

LocalExecutable::LocalExecutable(std::unique_ptr<Executable> executable,
                                 Backend* backend, int device_ordinal,
                                 const ExecutableBuildOptions& build_options)
    : executable_(std::move(executable)),
      backend_(backend),
      build_device_ordinal_(device_ordinal),
      build_options_(build_options) {}

tensorflow::Status LocalExecutable::ValidateExecutionOptions(
    const tensorflow::gtl::ArraySlice<const ShapedBuffer*> arguments,
    const ExecutableRunOptions& options, const Backend& backend) {
  const ComputationLayout& computation_layout =
      executable_->module_config().entry_computation_layout();

  // Check argument number, shapes, and layouts.
  if (arguments.size() != computation_layout.parameter_count()) {
    return InvalidArgument(
        "invalid number of arguments for computation: expected %d, got %zu",
        computation_layout.parameter_count(), arguments.size());
  }
  for (int i = 0; i < arguments.size(); ++i) {
    if (!computation_layout.parameter_layout(i).MatchesLayoutInShape(
            arguments[i]->shape())) {
      return InvalidArgument(
          "argument does not match shape or layout of computation parameter "
          "%d: expected %s, got %s",
          i,
          ShapeUtil::HumanString(computation_layout.parameter_layout(i).shape())
              .c_str(),
          ShapeUtil::HumanString(arguments[i]->shape()).c_str());
    }
  }

  if (options.stream() != nullptr) {
    if (!options.stream()->ok()) {
      return InvalidArgument("stream is uninitialized or in an error state");
    }

    // Check stream matches service platform.
    const se::Platform* stream_platform =
        options.stream()->parent()->platform();
    if (stream_platform != backend_->platform()) {
      return InvalidArgument(
          "stream is for platform %s, but service targets platform %s",
          stream_platform->Name().c_str(),
          backend_->platform()->Name().c_str());
    }

    // Cannot specify device_ordinal with a stream. The stream determines these
    // values.
    if (options.device_ordinal() != -1) {
      return InvalidArgument(
          "cannot set both device ordinal and stream options in "
          "ExecutableRunOptions; the stream determines the device ordinal");
    }
  }

  // Verify that the device the executable was built for is equivalent to the
  // device it will run on.
  int run_device_ordinal = options.device_ordinal() == -1
                               ? backend_->default_device_ordinal()
                               : options.device_ordinal();
  TF_ASSIGN_OR_RETURN(
      bool devices_equivalent,
      backend_->devices_equivalent(run_device_ordinal, build_device_ordinal_));
  if (!devices_equivalent) {
    TF_ASSIGN_OR_RETURN(se::StreamExecutor * run_executor,
                        backend_->stream_executor(run_device_ordinal));
    TF_ASSIGN_OR_RETURN(se::StreamExecutor * build_executor,
                        backend_->stream_executor(build_device_ordinal_));
    return InvalidArgument(
        "executable is built for device %s of type \"%s\"; cannot run it on "
        "device %s of type \"%s\"",
        backend_->device_name(build_device_ordinal_).c_str(),
        build_executor->GetDeviceDescription().name().c_str(),
        backend_->device_name(run_device_ordinal).c_str(),
        run_executor->GetDeviceDescription().name().c_str());
  }

  if (!options.allocator()) {
    return InvalidArgument("an allocator must be provided to ExecuteLocally");
  }

  if (options.allocator()->platform() != backend.platform()) {
    return InvalidArgument(
        "allocator platform (%s) does not match service platform (%s)",
        options.allocator()->platform()->Name().c_str(),
        backend.platform()->Name().c_str());
  }

  return tensorflow::Status::OK();
}

StatusOr<std::unique_ptr<ShapedBuffer>> LocalExecutable::Run(
    const tensorflow::gtl::ArraySlice<const ShapedBuffer*> arguments,
    const ExecutableRunOptions& options) {
  TF_RETURN_IF_ERROR(ValidateExecutionOptions(arguments, options, *backend_));

  ExecutableRunOptions actual_options = options;
  Backend::StreamPtr stream;
  if (options.stream() == nullptr) {
    TF_ASSIGN_OR_RETURN(
        stream, BorrowStreamForDevice(options.device_ordinal(), backend_));
    actual_options.set_stream(stream.get());
  }
  if (options.allocator() == nullptr) {
    actual_options.set_allocator(backend_->memory_allocator());
  }
  ServiceExecutableRunOptions service_options(actual_options,
                                              backend_->StreamBorrower());

  if (executable_->dumping()) {
    return ExecuteAndDump(&service_options, arguments);
  }
  return Service::ExecuteOnStreamWrapper<
      StatusOr<std::unique_ptr<ShapedBuffer>>>(
      executable_.get(), &service_options, options.execution_profile(),
      backend_,
      [&arguments](Executable* executable,
                   const ServiceExecutableRunOptions* run_options,
                   HloExecutionProfile* hlo_execution_profile) {
        return executable->ExecuteOnStream(run_options, arguments,
                                           hlo_execution_profile);
      });
}

StatusOr<std::unique_ptr<ShapedBuffer>> LocalExecutable::ExecuteAndDump(
    const ServiceExecutableRunOptions* run_options,
    const tensorflow::gtl::ArraySlice<const ShapedBuffer*> arguments) {
  executable_->session_module()->set_execution_platform(
      backend_->platform()->Name());
  TF_RETURN_IF_ERROR(RecordArguments(arguments, executable_->session_module()));
  TF_ASSIGN_OR_RETURN(
      std::unique_ptr<ShapedBuffer> result,
      executable_->ExecuteOnStream(run_options, arguments,
                                   /*hlo_execution_profile=*/nullptr));
  TF_RETURN_IF_ERROR(RecordResult(result.get(), executable_->session_module()));
  TF_RETURN_IF_ERROR(executable_->DumpSessionModule());
  return std::move(result);
}

tensorflow::Status LocalExecutable::RecordArguments(
    const tensorflow::gtl::ArraySlice<const ShapedBuffer*> arguments,
    SessionModule* session_module) {
  session_module->clear_arguments();
  for (const ShapedBuffer* argument : arguments) {
    TF_RETURN_IF_ERROR(
        LiteralFromShapedBuffer(*argument, session_module->add_arguments()));
  }
  return tensorflow::Status::OK();
}

tensorflow::Status LocalExecutable::RecordResult(
    const ShapedBuffer* result, SessionModule* session_module) {
  session_module->clear_result();
  return LiteralFromShapedBuffer(*result, session_module->mutable_result());
}

tensorflow::Status LocalExecutable::LiteralFromShapedBuffer(
    const ShapedBuffer& shaped_buffer, Literal* literal) {
  TF_ASSIGN_OR_RETURN(
      se::StreamExecutor * executor,
      backend_->stream_executor(shaped_buffer.device_ordinal()));
  return backend_->transfer_manager()->TransferLiteralFromDevice(
      executor, shaped_buffer.buffer({}), shaped_buffer.shape(),
      shaped_buffer.shape(), literal);
}

StatusOr<std::unique_ptr<GlobalData>> LocalClient::AllocateBufferOnDevice(
    const Shape& shape, int device_ordinal, bool allocate_space_for_deep_copy) {
  TF_ASSIGN_OR_RETURN(GlobalDataHandle handle,
                      local_service_->AllocateBufferOnDevice(
                          shape, device_ordinal, allocate_space_for_deep_copy));
  return std::unique_ptr<GlobalData>(new GlobalData(local_service_, handle));
}

tensorflow::Status LocalClient::ResolveArguments(
    const tensorflow::gtl::ArraySlice<const GlobalDataHandle*> arguments,
    int device_ordinal,
    std::vector<perftools::gputools::DeviceMemoryBase>* argument_ptrs) {
  return local_service_->ResolveArguments(arguments, device_ordinal,
                                          argument_ptrs);
}

StatusOr<std::vector<std::unique_ptr<AotCompilationResult>>>
LocalClient::CompileAheadOfTime(
    const tensorflow::gtl::ArraySlice<AheadOfTimeComputationInstance>
        computations,
    const AotCompilationOptions& options) {
  std::vector<LocalService::AheadOfTimeComputationInstance> service_instances;
  service_instances.reserve(computations.size());
  for (const AheadOfTimeComputationInstance& instance : computations) {
    service_instances.push_back({});
    LocalService::AheadOfTimeComputationInstance& service_instance =
        service_instances.back();
    TF_RET_CHECK(instance.computation != nullptr);
    service_instance.computation = instance.computation->handle();
    service_instance.argument_layouts = instance.argument_layouts;
    service_instance.result_layout = instance.result_layout;
  }
  return local_service_->CompileAheadOfTime(service_instances, options);
}

int64 LocalClient::PointerSizeForTriple(tensorflow::StringPiece target_triple) {
  llvm::Triple triple(
      llvm::Triple::normalize(llvm_ir::AsStringRef(target_triple)));
  if (triple.isArch64Bit()) {
    return 8;
  } else if (triple.isArch32Bit()) {
    return 4;
  } else {
    CHECK(triple.isArch16Bit());
    return 2;
  }
}

se::Platform* LocalClient::platform() const {
  return local_service_->backend().platform();
}

int LocalClient::device_count() const {
  return local_service_->backend().device_count();
}

bool LocalClient::device_ordinal_supported(int device_ordinal) const {
  return local_service_->backend().device_ordinal_supported(device_ordinal);
}

int LocalClient::default_device_ordinal() const {
  return local_service_->backend().default_device_ordinal();
}

StatusOr<std::unique_ptr<LocalExecutable>> LocalClient::Compile(
    const Computation& computation,
    const tensorflow::gtl::ArraySlice<const Shape*> argument_layouts,
    const ExecutableBuildOptions& options) {
  int device_ordinal = options.device_ordinal() == -1
                           ? default_device_ordinal()
                           : options.device_ordinal();
  TF_ASSIGN_OR_RETURN(
      std::unique_ptr<Executable> executable,
      local_service_->CompileExecutable(computation.handle(), argument_layouts,
                                        options.result_layout(), device_ordinal,
                                        options.has_hybrid_result()));
  return WrapUnique(new LocalExecutable(std::move(executable),
                                        local_service_->mutable_backend(),
                                        device_ordinal, options));
}

}  // namespace xla