#!/bin/sh
##
##  configure
##
##  This script is the front-end to the build system. It provides a similar
##  interface to standard configure scripts with some extra bits for dealing
##  with toolchains that differ from the standard POSIX interface and
##  for extracting subsets of the source tree. In theory, reusable parts
##  of this script were intended to live in build/make/configure.sh,
##  but in practice, the line is pretty blurry.
##
##  This build system is based in part on the FFmpeg configure script.
##

#source_path="`dirname \"$0\"`"
source_path=${0%/*}
. "${source_path}/build/make/configure.sh"

show_help(){
    show_help_pre
    cat << EOF
Advanced options:
  ${toggle_libs}                  libraries
  ${toggle_examples}              examples
  ${toggle_tools}                 tools
  ${toggle_docs}                  documentation
  ${toggle_unit_tests}            unit tests
  ${toggle_decode_perf_tests}     build decoder perf tests with unit tests
  ${toggle_encode_perf_tests}     build encoder perf tests with unit tests
  --cpu=CPU                       tune for the specified CPU (ARM: cortex-a8, X86: sse3)
  --libc=PATH                     path to alternate libc
  --size-limit=WxH                max size to allow in the decoder
  --as={yasm|nasm|auto}           use specified assembler [auto, yasm preferred]
  --sdk-path=PATH                 path to root of sdk (android builds only)
  ${toggle_codec_srcs}            in/exclude codec library source code
  ${toggle_debug_libs}            in/exclude debug version of libraries
  ${toggle_static_msvcrt}         use static MSVCRT (VS builds only)
  ${toggle_vp9_highbitdepth}      use VP9 high bit depth (10/12) profiles
  ${toggle_better_hw_compatibility}
                                  enable encoder to produce streams with better
                                  hardware decoder compatibility
  ${toggle_vp8}                   VP8 codec support
  ${toggle_vp9}                   VP9 codec support
  ${toggle_internal_stats}        output of encoder internal stats for debug, if supported (encoders)
  ${toggle_postproc}              postprocessing
  ${toggle_vp9_postproc}          vp9 specific postprocessing
  ${toggle_multithread}           multithreaded encoding and decoding
  ${toggle_spatial_resampling}    spatial sampling (scaling) support
  ${toggle_realtime_only}         enable this option while building for real-time encoding
  ${toggle_onthefly_bitpacking}   enable on-the-fly bitpacking in real-time encoding
  ${toggle_error_concealment}     enable this option to get a decoder which is able to conceal losses
  ${toggle_coefficient_range_checking}
                                  enable decoder to check if intermediate
                                  transform coefficients are in valid range
  ${toggle_runtime_cpu_detect}    runtime cpu detection
  ${toggle_shared}                shared library support
  ${toggle_static}                static library support
  ${toggle_small}                 favor smaller size over speed
  ${toggle_postproc_visualizer}   macro block / block level visualizers
  ${toggle_multi_res_encoding}    enable multiple-resolution encoding
  ${toggle_temporal_denoising}    enable temporal denoising and disable the spatial denoiser
  ${toggle_vp9_temporal_denoising}
                                  enable vp9 temporal denoising
  ${toggle_webm_io}               enable input from and output to WebM container
  ${toggle_libyuv}                enable libyuv

Codecs:
  Codecs can be selectively enabled or disabled individually, or by family:
      --disable-<codec>
  is equivalent to:
      --disable-<codec>-encoder
      --disable-<codec>-decoder

  Codecs available in this distribution:
EOF
#restore editor state '

    family="";
    last_family="";
    c="";
    str="";
    for c in ${CODECS}; do
        family=${c%_*}
        if [ "${family}" != "${last_family}" ]; then
            [ -z "${str}" ] || echo "${str}"
            str="$(printf '    %10s:' ${family})"
        fi
        str="${str} $(printf '%10s' ${c#*_})"
        last_family=${family}
    done
    echo "${str}"
    show_help_post
}

##
## BEGIN APPLICATION SPECIFIC CONFIGURATION
##

# all_platforms is a list of all supported target platforms. Maintain
# alphabetically by architecture, generic-gnu last.
all_platforms="${all_platforms} arm64-android-gcc"
all_platforms="${all_platforms} arm64-darwin-gcc"
all_platforms="${all_platforms} arm64-linux-gcc"
all_platforms="${all_platforms} armv7-android-gcc"   #neon Cortex-A8
all_platforms="${all_platforms} armv7-darwin-gcc"    #neon Cortex-A8
all_platforms="${all_platforms} armv7-linux-rvct"    #neon Cortex-A8
all_platforms="${all_platforms} armv7-linux-gcc"     #neon Cortex-A8
all_platforms="${all_platforms} armv7-none-rvct"     #neon Cortex-A8
all_platforms="${all_platforms} armv7-win32-vs11"
all_platforms="${all_platforms} armv7-win32-vs12"
all_platforms="${all_platforms} armv7-win32-vs14"
all_platforms="${all_platforms} armv7-win32-vs15"
all_platforms="${all_platforms} armv7s-darwin-gcc"
all_platforms="${all_platforms} armv8-linux-gcc"
all_platforms="${all_platforms} mips32-linux-gcc"
all_platforms="${all_platforms} mips64-linux-gcc"
all_platforms="${all_platforms} ppc64-linux-gcc"
all_platforms="${all_platforms} ppc64le-linux-gcc"
all_platforms="${all_platforms} sparc-solaris-gcc"
all_platforms="${all_platforms} x86-android-gcc"
all_platforms="${all_platforms} x86-darwin8-gcc"
all_platforms="${all_platforms} x86-darwin8-icc"
all_platforms="${all_platforms} x86-darwin9-gcc"
all_platforms="${all_platforms} x86-darwin9-icc"
all_platforms="${all_platforms} x86-darwin10-gcc"
all_platforms="${all_platforms} x86-darwin11-gcc"
all_platforms="${all_platforms} x86-darwin12-gcc"
all_platforms="${all_platforms} x86-darwin13-gcc"
all_platforms="${all_platforms} x86-darwin14-gcc"
all_platforms="${all_platforms} x86-darwin15-gcc"
all_platforms="${all_platforms} x86-darwin16-gcc"
all_platforms="${all_platforms} x86-iphonesimulator-gcc"
all_platforms="${all_platforms} x86-linux-gcc"
all_platforms="${all_platforms} x86-linux-icc"
all_platforms="${all_platforms} x86-os2-gcc"
all_platforms="${all_platforms} x86-solaris-gcc"
all_platforms="${all_platforms} x86-win32-gcc"
all_platforms="${all_platforms} x86-win32-vs10"
all_platforms="${all_platforms} x86-win32-vs11"
all_platforms="${all_platforms} x86-win32-vs12"
all_platforms="${all_platforms} x86-win32-vs14"
all_platforms="${all_platforms} x86-win32-vs15"
all_platforms="${all_platforms} x86_64-android-gcc"
all_platforms="${all_platforms} x86_64-darwin9-gcc"
all_platforms="${all_platforms} x86_64-darwin10-gcc"
all_platforms="${all_platforms} x86_64-darwin11-gcc"
all_platforms="${all_platforms} x86_64-darwin12-gcc"
all_platforms="${all_platforms} x86_64-darwin13-gcc"
all_platforms="${all_platforms} x86_64-darwin14-gcc"
all_platforms="${all_platforms} x86_64-darwin15-gcc"
all_platforms="${all_platforms} x86_64-darwin16-gcc"
all_platforms="${all_platforms} x86_64-iphonesimulator-gcc"
all_platforms="${all_platforms} x86_64-linux-gcc"
all_platforms="${all_platforms} x86_64-linux-icc"
all_platforms="${all_platforms} x86_64-solaris-gcc"
all_platforms="${all_platforms} x86_64-win64-gcc"
all_platforms="${all_platforms} x86_64-win64-vs10"
all_platforms="${all_platforms} x86_64-win64-vs11"
all_platforms="${all_platforms} x86_64-win64-vs12"
all_platforms="${all_platforms} x86_64-win64-vs14"
all_platforms="${all_platforms} x86_64-win64-vs15"
all_platforms="${all_platforms} generic-gnu"

# all_targets is a list of all targets that can be configured
# note that these should be in dependency order for now.
all_targets="libs examples tools docs"

# all targets available are enabled, by default.
for t in ${all_targets}; do
    [ -f "${source_path}/${t}.mk" ] && enable_feature ${t}
done

if ! diff --version >/dev/null; then
  die "diff missing: Try installing diffutils via your package manager."
fi

if ! perl --version >/dev/null; then
    die "Perl is required to build"
fi

if [ "`cd \"${source_path}\" && pwd`" != "`pwd`" ]; then
  # test to see if source_path already configured
  if [ -f "${source_path}/vpx_config.h" ]; then
    die "source directory already configured; run 'make distclean' there first"
  fi
fi

# check installed doxygen version
doxy_version=$(doxygen --version 2>/dev/null)
doxy_major=${doxy_version%%.*}
if [ ${doxy_major:-0} -ge 1 ]; then
    doxy_version=${doxy_version#*.}
    doxy_minor=${doxy_version%%.*}
    doxy_patch=${doxy_version##*.}

    [ $doxy_major -gt 1 ] && enable_feature doxygen
    [ $doxy_minor -gt 5 ] && enable_feature doxygen
    [ $doxy_minor -eq 5 ] && [ $doxy_patch -ge 3 ] && enable_feature doxygen
fi

# disable codecs when their source directory does not exist
[ -d "${source_path}/vp8" ] || disable_codec vp8
[ -d "${source_path}/vp9" ] || disable_codec vp9

# install everything except the sources, by default. sources will have
# to be enabled when doing dist builds, since that's no longer a common
# case.
enabled doxygen && enable_feature install_docs
enable_feature install_bins
enable_feature install_libs

enable_feature static
enable_feature optimizations
enable_feature dependency_tracking
enable_feature spatial_resampling
enable_feature multithread
enable_feature os_support
enable_feature temporal_denoising

CODECS="
    vp8_encoder
    vp8_decoder
    vp9_encoder
    vp9_decoder
"
CODEC_FAMILIES="
    vp8
    vp9
"

ARCH_LIST="
    arm
    mips
    x86
    x86_64
    ppc
"
ARCH_EXT_LIST_X86="
    mmx
    sse
    sse2
    sse3
    ssse3
    sse4_1
    avx
    avx2
    avx512
"

ARCH_EXT_LIST_LOONGSON="
    mmi
"

ARCH_EXT_LIST="
    neon
    neon_asm

    mips32
    dspr2
    msa
    mips64

    ${ARCH_EXT_LIST_X86}

    vsx

    ${ARCH_EXT_LIST_LOONGSON}
"
HAVE_LIST="
    ${ARCH_EXT_LIST}
    vpx_ports
    pthread_h
    unistd_h
"
EXPERIMENT_LIST="
    spatial_svc
    fp_mb_stats
    emulate_hardware
"
CONFIG_LIST="
    dependency_tracking
    external_build
    install_docs
    install_bins
    install_libs
    install_srcs
    debug
    gprof
    gcov
    rvct
    gcc
    msvs
    pic
    big_endian

    codec_srcs
    debug_libs

    dequant_tokens
    dc_recon
    runtime_cpu_detect
    postproc
    vp9_postproc
    multithread
    internal_stats
    ${CODECS}
    ${CODEC_FAMILIES}
    encoders
    decoders
    static_msvcrt
    spatial_resampling
    realtime_only
    onthefly_bitpacking
    error_concealment
    shared
    static
    small
    postproc_visualizer
    os_support
    unit_tests
    webm_io
    libyuv
    decode_perf_tests
    encode_perf_tests
    multi_res_encoding
    temporal_denoising
    vp9_temporal_denoising
    coefficient_range_checking
    vp9_highbitdepth
    better_hw_compatibility
    experimental
    size_limit
    always_adjust_bpm
    ${EXPERIMENT_LIST}
"
CMDLINE_SELECT="
    dependency_tracking
    external_build
    extra_warnings
    werror
    install_docs
    install_bins
    install_libs
    install_srcs
    debug
    gprof
    gcov
    pic
    optimizations
    ccache
    runtime_cpu_detect
    thumb

    libs
    examples
    tools
    docs
    libc
    as
    size_limit
    codec_srcs
    debug_libs

    dequant_tokens
    dc_recon
    postproc
    vp9_postproc
    multithread
    internal_stats
    ${CODECS}
    ${CODEC_FAMILIES}
    static_msvcrt
    spatial_resampling
    realtime_only
    onthefly_bitpacking
    error_concealment
    shared
    static
    small
    postproc_visualizer
    unit_tests
    webm_io
    libyuv
    decode_perf_tests
    encode_perf_tests
    multi_res_encoding
    temporal_denoising
    vp9_temporal_denoising
    coefficient_range_checking
    better_hw_compatibility
    vp9_highbitdepth
    experimental
    always_adjust_bpm
"

process_cmdline() {
    for opt do
        optval="${opt#*=}"
        case "$opt" in
        --disable-codecs)
          for c in ${CODEC_FAMILIES}; do disable_codec $c; done
          ;;
        --enable-?*|--disable-?*)
        eval `echo "$opt" | sed 's/--/action=/;s/-/ option=/;s/-/_/g'`
        if is_in ${option} ${EXPERIMENT_LIST}; then
            if enabled experimental; then
                ${action}_feature $option
            else
                log_echo "Ignoring $opt -- not in experimental mode."
            fi
        elif is_in ${option} "${CODECS} ${CODEC_FAMILIES}"; then
            ${action}_codec ${option}
        else
            process_common_cmdline $opt
        fi
        ;;
        *) process_common_cmdline "$opt"
        ;;
        esac
    done
}

post_process_cmdline() {
    c=""

    # Enable all detected codecs, if they haven't been disabled
    for c in ${CODECS}; do soft_enable $c; done

    # Enable the codec family if any component of that family is enabled
    for c in ${CODECS}; do
        enabled $c && enable_feature ${c%_*}
    done

    # Set the {en,de}coders variable if any algorithm in that class is enabled
    for c in ${CODECS}; do
        enabled ${c} && enable_feature ${c##*_}s
    done
}

process_targets() {
    enabled child || write_common_config_banner
    write_common_target_config_h ${BUILD_PFX}vpx_config.h
    write_common_config_targets

    # Calculate the default distribution name, based on the enabled features
    cf=""
    DIST_DIR=vpx
    for cf in $CODEC_FAMILIES; do
        if enabled ${cf}_encoder && enabled ${cf}_decoder; then
            DIST_DIR="${DIST_DIR}-${cf}"
        elif enabled ${cf}_encoder; then
            DIST_DIR="${DIST_DIR}-${cf}cx"
        elif enabled ${cf}_decoder; then
            DIST_DIR="${DIST_DIR}-${cf}dx"
        fi
    done
    enabled debug_libs && DIST_DIR="${DIST_DIR}-debug"
    enabled codec_srcs && DIST_DIR="${DIST_DIR}-src"
    ! enabled postproc && ! enabled vp9_postproc && DIST_DIR="${DIST_DIR}-nopost"
    ! enabled multithread && DIST_DIR="${DIST_DIR}-nomt"
    ! enabled install_docs && DIST_DIR="${DIST_DIR}-nodocs"
    DIST_DIR="${DIST_DIR}-${tgt_isa}-${tgt_os}"
    case "${tgt_os}" in
    win*) enabled static_msvcrt && DIST_DIR="${DIST_DIR}mt" || DIST_DIR="${DIST_DIR}md"
          DIST_DIR="${DIST_DIR}-${tgt_cc}"
          ;;
    esac
    if [ -f "${source_path}/build/make/version.sh" ]; then
        ver=`"$source_path/build/make/version.sh" --bare "$source_path"`
        DIST_DIR="${DIST_DIR}-${ver}"
        VERSION_STRING=${ver}
        ver=${ver%%-*}
        VERSION_PATCH=${ver##*.}
        ver=${ver%.*}
        VERSION_MINOR=${ver##*.}
        ver=${ver#v}
        VERSION_MAJOR=${ver%.*}
    fi
    enabled child || cat <<EOF >> config.mk

PREFIX=${prefix}
ifeq (\$(MAKECMDGOALS),dist)
DIST_DIR?=${DIST_DIR}
else
DIST_DIR?=\$(DESTDIR)${prefix}
endif
LIBSUBDIR=${libdir##${prefix}/}

VERSION_STRING=${VERSION_STRING}

VERSION_MAJOR=${VERSION_MAJOR}
VERSION_MINOR=${VERSION_MINOR}
VERSION_PATCH=${VERSION_PATCH}

CONFIGURE_ARGS=${CONFIGURE_ARGS}
EOF
    enabled child || echo "CONFIGURE_ARGS?=${CONFIGURE_ARGS}" >> config.mk

    #
    # Write makefiles for all enabled targets
    #
    for tgt in libs examples tools docs solution; do
        tgt_fn="$tgt-$toolchain.mk"

        if enabled $tgt; then
            echo "Creating makefiles for ${toolchain} ${tgt}"
            write_common_target_config_mk $tgt_fn ${BUILD_PFX}vpx_config.h
            #write_${tgt}_config
        fi
    done

}

process_detect() {
    if enabled shared; then
        # Can only build shared libs on a subset of platforms. Doing this check
        # here rather than at option parse time because the target auto-detect
        # magic happens after the command line has been parsed.
        case "${tgt_os}" in
        linux|os2|darwin*|iphonesimulator*)
            # Supported platforms
            ;;
        *)
            if enabled gnu; then
                echo "--enable-shared is only supported on ELF; assuming this is OK"
            else
                die "--enable-shared only supported on ELF, OS/2, and Darwin for now"
            fi
            ;;
        esac
    fi
    if [ -z "$CC" ] || enabled external_build; then
        echo "Bypassing toolchain for environment detection."
        enable_feature external_build
        check_header() {
            log fake_check_header "$@"
            header=$1
            shift
            var=`echo $header | sed 's/[^A-Za-z0-9_]/_/g'`
            disable_feature $var
            # Headers common to all environments
            case $header in
                stdio.h)
                    true;
                ;;
                *)
                    result=false
                    for d in "$@"; do
                        [ -f "${d##-I}/$header" ] && result=true && break
                    done
                    ${result:-true}
            esac && enable_feature $var

            # Specialize windows and POSIX environments.
            case $toolchain in
                *-win*-*)
                    # Don't check for any headers in Windows builds.
                    false
                ;;
                *)
                    case $header in
                        pthread.h) true;;
                        unistd.h) true;;
                        *) false;;
                    esac && enable_feature $var
            esac
            enabled $var
        }
        check_ld() {
            true
        }
    fi
    check_header stdio.h || die "Unable to invoke compiler: ${CC} ${CFLAGS}"
    check_ld <<EOF || die "Toolchain is unable to link executables"
int main(void) {return 0;}
EOF
    # check system headers
    check_header pthread.h
    check_header unistd.h # for sysconf(3) and friends.

    check_header vpx/vpx_integer.h -I${source_path} && enable_feature vpx_ports
}

process_toolchain() {
    process_common_toolchain

    # Enable some useful compiler flags
    if enabled gcc; then
        enabled werror && check_add_cflags -Werror
        check_add_cflags -Wall
        check_add_cflags -Wdeclaration-after-statement
        check_add_cflags -Wdisabled-optimization
        check_add_cflags -Wfloat-conversion
        check_add_cflags -Wparentheses-equality
        check_add_cflags -Wpointer-arith
        check_add_cflags -Wtype-limits
        check_add_cflags -Wcast-qual
        check_add_cflags -Wvla
        check_add_cflags -Wimplicit-function-declaration
        check_add_cflags -Wuninitialized
        check_add_cflags -Wunused
        # -Wextra has some tricky cases. Rather than fix them all now, get the
        # flag for as many files as possible and fix the remaining issues
        # piecemeal.
        # https://bugs.chromium.org/p/webm/issues/detail?id=1069
        check_add_cflags -Wextra
        # check_add_cflags also adds to cxxflags. gtest does not do well with
        # -Wundef so add it explicitly to CFLAGS only.
        check_cflags -Wundef && add_cflags_only -Wundef
        if enabled mips || [ -z "${INLINE}" ]; then
          enabled extra_warnings || check_add_cflags -Wno-unused-function
        fi
        # Avoid this warning for third_party C++ sources. Some reorganization
        # would be needed to apply this only to test/*.cc.
        check_cflags -Wshorten-64-to-32 && add_cflags_only -Wshorten-64-to-32
    fi

    if enabled icc; then
        enabled werror && check_add_cflags -Werror
        check_add_cflags -Wall
        check_add_cflags -Wpointer-arith

        # ICC has a number of floating point optimizations that we disable
        # in favor of deterministic output WRT to other compilers
        add_cflags -fp-model precise
    fi

    # Enable extra, harmless warnings. These might provide additional insight
    # to what the compiler is doing and why, but in general, but they shouldn't
    # be treated as fatal, even if we're treating warnings as errors.
    GCC_EXTRA_WARNINGS="
        -Wdisabled-optimization
        -Winline
    "
    enabled gcc && EXTRA_WARNINGS="${GCC_EXTRA_WARNINGS}"
    RVCT_EXTRA_WARNINGS="
        --remarks
    "
    enabled rvct && EXTRA_WARNINGS="${RVCT_EXTRA_WARNINGS}"
    if enabled extra_warnings; then
        for w in ${EXTRA_WARNINGS}; do
            check_add_cflags ${w}
            enabled gcc && enabled werror && check_add_cflags -Wno-error=${w}
        done
    fi

    # ccache only really works on gcc toolchains
    enabled gcc || soft_disable ccache
    if enabled mips; then
        enable_feature dequant_tokens
        enable_feature dc_recon
    fi

    if enabled internal_stats; then
        enable_feature vp9_postproc
    fi

    # Enable the postbuild target if building for visual studio.
    case "$tgt_cc" in
        vs*) enable_feature msvs
             enable_feature solution
             vs_version=${tgt_cc##vs}
             VCPROJ_SFX=vcxproj
             gen_vcproj_cmd=${source_path}/build/make/gen_msvs_vcxproj.sh
             enabled werror && gen_vcproj_cmd="${gen_vcproj_cmd} --enable-werror"
             all_targets="${all_targets} solution"
             INLINE="__inline"
        ;;
    esac

    # Other toolchain specific defaults
    case $toolchain in x86*) soft_enable postproc;; esac

    if enabled postproc_visualizer; then
        enabled postproc || die "postproc_visualizer requires postproc to be enabled"
    fi

    # Enable unit tests by default if we have a working C++ compiler.
    case "$toolchain" in
        *-vs*)
            soft_enable unit_tests
            soft_enable webm_io
            soft_enable libyuv
        ;;
        *-android-*)
            soft_enable webm_io
            soft_enable libyuv
            # GTestLog must be modified to use Android logging utilities.
        ;;
        *-darwin-*)
            # iOS/ARM builds do not work with gtest. This does not match
            # x86 targets.
        ;;
        *-iphonesimulator-*)
            soft_enable webm_io
            soft_enable libyuv
        ;;
        *-win*)
            # Some mingw toolchains don't have pthread available by default.
            # Treat these more like visual studio where threading in gtest
            # would be disabled for the same reason.
            check_cxx "$@" <<EOF && soft_enable unit_tests
int z;
EOF
            check_cxx "$@" <<EOF && soft_enable webm_io
int z;
EOF
            check_cxx "$@" <<EOF && soft_enable libyuv
int z;
EOF
        ;;
        *)
            enabled pthread_h && check_cxx "$@" <<EOF && soft_enable unit_tests
int z;
EOF
            check_cxx "$@" <<EOF && soft_enable webm_io
int z;
EOF
            check_cxx "$@" <<EOF && soft_enable libyuv
int z;
EOF
        ;;
    esac
    # libwebm needs to be linked with C++ standard library
    enabled webm_io && LD=${CXX}

    # append any user defined extra cflags
    if [ -n "${extra_cflags}" ] ; then
        check_add_cflags ${extra_cflags} || \
        die "Requested extra CFLAGS '${extra_cflags}' not supported by compiler"
    fi
    if [ -n "${extra_cxxflags}" ]; then
        check_add_cxxflags ${extra_cxxflags} || \
        die "Requested extra CXXFLAGS '${extra_cxxflags}' not supported by compiler"
    fi
}

##
## END APPLICATION SPECIFIC CONFIGURATION
##
CONFIGURE_ARGS="$@"
process "$@"
print_webm_license ${BUILD_PFX}vpx_config.c "/*" " */"
cat <<EOF >> ${BUILD_PFX}vpx_config.c
#include "vpx/vpx_codec.h"
static const char* const cfg = "$CONFIGURE_ARGS";
const char *vpx_codec_build_config(void) {return cfg;}
EOF

{'repo_name': 'artclarke/humble-video', 'stars': '450', 'repo_language': 'C', 'file_name': 'head', 'mime_type': 'text/x-shellscript', 'hash': 7458357789761334138, 'source_dataset': 'data'}


# [20170706 码农日报](http://hao.caibaojian.com/date/2017/07/06)

[前端日报](http://caibaojian.com/c/news)栏目数据来自[码农头条](http://hao.caibaojian.com/)（我开发的爬虫），每日分享前端、移动开发、设计、资源和资讯等，为开发者提供动力，点击Star按钮来关注这个项目，点击Watch来收听每日的更新[Github主页](https://github.com/kujian/frontendDaily)
* [TiDB 最佳实践](http://hao.caibaojian.com/43648.html) （开发者头条）
* [iOS 逆向工程之 fishhook](http://hao.caibaojian.com/43637.html) （开发者头条）
* [【工具】git笔记（一）](http://hao.caibaojian.com/43629.html) （SegmentFault）
* [随方逐圆 — 全面理解 CSS 媒体查询](http://hao.caibaojian.com/43591.html) （稀土掘金）
* [前端面试之htm5新特性](http://hao.caibaojian.com/43581.html) （稀土掘金）

***
* [浅谈JavaScript中的闭包](http://hao.caibaojian.com/43630.html) （SegmentFault）
* [PHP结合layer处理弹出窗口提交的值](http://hao.caibaojian.com/43620.html) （SegmentFault）
* [ECMAScript简史 和 JavaScript的未来（译）](http://hao.caibaojian.com/43621.html) （SegmentFault）
* [关于chrome点击上传反应慢的问题](http://hao.caibaojian.com/43622.html) （SegmentFault）
* [容器化部署 OpenStack 的正确姿势](http://hao.caibaojian.com/43654.html) （开发者头条）

***
* [JavaScript の 整理下Git](http://hao.caibaojian.com/43633.html) （SegmentFault）
* [Scala 类型的类型（四）](http://hao.caibaojian.com/43655.html) （开发者头条）
* [vue-manager：基于 iView / ECharts 的 Vue 管理平台](http://hao.caibaojian.com/43647.html) （开发者头条）
* [一个关于 Django Rest Framework 的梦](http://hao.caibaojian.com/43626.html) （SegmentFault）
* [单Activity架构，丝滑般享受](http://hao.caibaojian.com/43676.html) （慕课网）

***
* [JavaScript 正则表达式–从入门到精分](http://hao.caibaojian.com/43588.html) （稀土掘金）
* [Android 程序员必须掌握的三种自动化测试方法](http://hao.caibaojian.com/43687.html) （程序员俱乐部）
* [我他喵的到底要怎样才能在生产环境中用上 ES6 模块化？](http://hao.caibaojian.com/43616.html) （SegmentFault）
* [什么是跳跃表](http://hao.caibaojian.com/43698.html) （伯乐在线官方微博）
* [【翻译】基于 Create React App路由4.0的异步组件加载（Code Splitting）](http://hao.caibaojian.com/43627.html) （SegmentFault）

***
* [MongoDB学习资源分享](http://hao.caibaojian.com/43677.html) （慕课网）
* [彻底搞清楚 JavaScript 中的 require、import 和 export](http://hao.caibaojian.com/43589.html) （稀土掘金）
* [听滴滴大神给你讲 Redis Cluster 迁移遇到的坑](http://hao.caibaojian.com/43638.html) （开发者头条）
* [提高代码质量必看的5本书籍](http://hao.caibaojian.com/43688.html) （IT程序猿）
* [SegmentFault 社区访谈 | 有位公子在奇舞](http://hao.caibaojian.com/43617.html) （SegmentFault）

***
* [携程新风控数据平台建设](http://hao.caibaojian.com/43649.html) （开发者头条）
* [性能优化知多少](http://hao.caibaojian.com/43699.html) （伯乐在线官方微博）
* [vuedraggable实际开发中的细节问题](http://hao.caibaojian.com/43628.html) （SegmentFault）
* [基于Docker的CI/CD流水线实践](http://hao.caibaojian.com/43678.html) （Docker精选）
* [重新介绍 JavaScript（JS全面系列教程）](http://hao.caibaojian.com/43590.html) （稀土掘金）

日报维护作者：[前端博客](http://caibaojian.com/)

{'repo_name': 'kujian/frontendDaily', 'stars': '1545', 'repo_language': 'HTML', 'file_name': '03.md', 'mime_type': 'text/plain', 'hash': -5669606700358416852, 'source_dataset': 'data'}


require 'spec_helper'

describe RubyLint::VirtualMachine do
  describe 'hash assignments' do
    it 'assigns an empty hash' do
      defs  = build_definitions('numbers = {}')
      value = defs.lookup(:lvar, 'numbers').value

      value.type.should      == :hash
      value.instance?.should == true

      value.has_definition?(:instance_method, 'each').should == true
    end

    it 'assigns a hash with values' do
      defs    = build_definitions('numbers = {:one => 1, :two => 2}')
      hash    = defs.lookup(:lvar, 'numbers').value
      members = {'one' => 1, 'two' => 2}

      members.each do |name, value|
        member = hash.lookup(:member, name)

        member.name.should        == name
        member.value.type.should  == :int
        member.value.value.should == value
      end
    end

    it 'processes single key assignments' do
      defs   = build_definitions('numbers = {}; numbers[:one] = 1')
      hash   = defs.lookup(:lvar, 'numbers').value
      member = hash.lookup(:member, 'one')

      member.value.type.should  == :int
      member.value.value.should == 1
    end

    it 'processes key assignments using variables' do
      code = <<-CODE
key          = :two
numbers      = {:one => 1}
numbers[key] = 2
      CODE

      defs = build_definitions(code)
      hash = defs.lookup(:lvar, 'numbers').value

      hash.lookup(:member, 'one').value.value.should == 1
      hash.lookup(:member, 'two').value.value.should == 2
    end
  end
end

{'repo_name': 'YorickPeterse/ruby-lint', 'stars': '727', 'repo_language': 'Ruby', 'file_name': 'flow.dot', 'mime_type': 'text/plain', 'hash': 6291538339213609001, 'source_dataset': 'data'}


/* Copyright 2007-2010 Jozsef Kadlecsik (kadlec@blackhole.kfki.hu)
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2 as
 * published by the Free Software Foundation.
 */
#include <libipset/data.h>			/* IPSET_OPT_* */
#include <libipset/parse.h>			/* parser functions */
#include <libipset/print.h>			/* printing functions */
#include <libipset/types.h>			/* prototypes */

/* Parse commandline arguments */
static const struct ipset_arg bitmap_ip_create_args[] = {
	{ .name = { "range", NULL },
	  .has_arg = IPSET_MANDATORY_ARG,	.opt = IPSET_OPT_IP,
	  .parse = ipset_parse_netrange,	.print = ipset_print_ip,
	},
	{ .name = { "netmask", NULL },
	  .has_arg = IPSET_MANDATORY_ARG,	.opt = IPSET_OPT_NETMASK,
	  .parse = ipset_parse_netmask,		.print = ipset_print_number,
	},
	{ .name = { "timeout", NULL },
	  .has_arg = IPSET_MANDATORY_ARG,	.opt = IPSET_OPT_TIMEOUT,
	  .parse = ipset_parse_uint32,		.print = ipset_print_number,
	},
	/* Backward compatibility */
	{ .name = { "from", NULL },
	  .has_arg = IPSET_MANDATORY_ARG,	.opt = IPSET_OPT_IP,
	  .parse = ipset_parse_single_ip,
	},
	{ .name = { "to", NULL },
	  .has_arg = IPSET_MANDATORY_ARG,	.opt = IPSET_OPT_IP_TO,
	  .parse = ipset_parse_single_ip,
	},
	{ .name = { "network", NULL },
	  .has_arg = IPSET_MANDATORY_ARG,	.opt = IPSET_OPT_IP,
	  .parse = ipset_parse_net,
	},
	{ },
};

static const struct ipset_arg bitmap_ip_add_args[] = {
	{ .name = { "timeout", NULL },
	  .has_arg = IPSET_MANDATORY_ARG,	.opt = IPSET_OPT_TIMEOUT,
	  .parse = ipset_parse_uint32,		.print = ipset_print_number,
	},
	{ },
};

static const char bitmap_ip_usage[] =
"create SETNAME bitmap:ip range IP/CIDR|FROM-TO\n"
"               [netmask CIDR] [timeout VALUE]\n"
"add    SETNAME IP|IP/CIDR|FROM-TO [timeout VALUE]\n"
"del    SETNAME IP|IP/CIDR|FROM-TO\n"
"test   SETNAME IP\n\n"
"where IP, FROM and TO are IPv4 addresses (or hostnames),\n"
"      CIDR is a valid IPv4 CIDR prefix.\n";

struct ipset_type ipset_bitmap_ip0 = {
	.name = "bitmap:ip",
	.alias = { "ipmap", NULL },
	.revision = 0,
	.family = AF_INET,
	.dimension = IPSET_DIM_ONE,
	.elem = {
		[IPSET_DIM_ONE] = {
			.parse = ipset_parse_ip,
			.print = ipset_print_ip,
			.opt = IPSET_OPT_IP
		},
	},
	.args = {
		[IPSET_CREATE] = bitmap_ip_create_args,
		[IPSET_ADD] = bitmap_ip_add_args,
	},
	.mandatory = {
		[IPSET_CREATE] = IPSET_FLAG(IPSET_OPT_IP)
			| IPSET_FLAG(IPSET_OPT_IP_TO),
		[IPSET_ADD] = IPSET_FLAG(IPSET_OPT_IP),
		[IPSET_DEL] = IPSET_FLAG(IPSET_OPT_IP),
		[IPSET_TEST] = IPSET_FLAG(IPSET_OPT_IP),
	},
	.full = {
		[IPSET_CREATE] = IPSET_FLAG(IPSET_OPT_IP)
			| IPSET_FLAG(IPSET_OPT_IP_TO)
			| IPSET_FLAG(IPSET_OPT_NETMASK)
			| IPSET_FLAG(IPSET_OPT_TIMEOUT),
		[IPSET_ADD] = IPSET_FLAG(IPSET_OPT_IP)
			| IPSET_FLAG(IPSET_OPT_IP_TO)
			| IPSET_FLAG(IPSET_OPT_TIMEOUT),
		[IPSET_DEL] = IPSET_FLAG(IPSET_OPT_IP)
			| IPSET_FLAG(IPSET_OPT_IP_TO),
		[IPSET_TEST] = IPSET_FLAG(IPSET_OPT_IP),
	},

	.usage = bitmap_ip_usage,
};

{'repo_name': 'ewust/telex', 'stars': '132', 'repo_language': 'C++', 'file_name': 'ssl.h', 'mime_type': 'text/x-c', 'hash': -1375684471485010377, 'source_dataset': 'data'}


/* SPDX-License-Identifier: BSD-3-Clause
 * Copyright(c) 2010-2014 Intel Corporation
 */

#include <sys/cdefs.h>
__FBSDID("$FreeBSD$");

#include <sys/param.h>
#include <sys/bio.h>
#include <sys/bus.h>
#include <sys/conf.h>
#include <sys/kernel.h>
#include <sys/malloc.h>
#include <sys/module.h>
#include <sys/proc.h>
#include <sys/rwlock.h>
#include <sys/systm.h>
#include <sys/sysctl.h>
#include <sys/vmmeter.h>

#include <machine/bus.h>

#include <vm/vm.h>
#include <vm/pmap.h>
#include <vm/vm_param.h>
#include <vm/vm_object.h>
#include <vm/vm_page.h>
#include <vm/vm_pager.h>
#include <vm/vm_phys.h>

struct contigmem_buffer {
	void           *addr;
	int             refcnt;
	struct mtx      mtx;
};

struct contigmem_vm_handle {
	int             buffer_index;
};

static int              contigmem_load(void);
static int              contigmem_unload(void);
static int              contigmem_physaddr(SYSCTL_HANDLER_ARGS);

static d_mmap_single_t  contigmem_mmap_single;
static d_open_t         contigmem_open;
static d_close_t        contigmem_close;

static int              contigmem_num_buffers = RTE_CONTIGMEM_DEFAULT_NUM_BUFS;
static int64_t          contigmem_buffer_size = RTE_CONTIGMEM_DEFAULT_BUF_SIZE;

static eventhandler_tag contigmem_eh_tag;
static struct contigmem_buffer contigmem_buffers[RTE_CONTIGMEM_MAX_NUM_BUFS];
static struct cdev     *contigmem_cdev = NULL;
static int              contigmem_refcnt;

TUNABLE_INT("hw.contigmem.num_buffers", &contigmem_num_buffers);
TUNABLE_QUAD("hw.contigmem.buffer_size", &contigmem_buffer_size);

static SYSCTL_NODE(_hw, OID_AUTO, contigmem, CTLFLAG_RD, 0, "contigmem");

SYSCTL_INT(_hw_contigmem, OID_AUTO, num_buffers, CTLFLAG_RD,
	&contigmem_num_buffers, 0, "Number of contigmem buffers allocated");
SYSCTL_QUAD(_hw_contigmem, OID_AUTO, buffer_size, CTLFLAG_RD,
	&contigmem_buffer_size, 0, "Size of each contiguous buffer");
SYSCTL_INT(_hw_contigmem, OID_AUTO, num_references, CTLFLAG_RD,
	&contigmem_refcnt, 0, "Number of references to contigmem");

static SYSCTL_NODE(_hw_contigmem, OID_AUTO, physaddr, CTLFLAG_RD, 0,
	"physaddr");

MALLOC_DEFINE(M_CONTIGMEM, "contigmem", "contigmem(4) allocations");

static int contigmem_modevent(module_t mod, int type, void *arg)
{
	int error = 0;

	switch (type) {
	case MOD_LOAD:
		error = contigmem_load();
		break;
	case MOD_UNLOAD:
		error = contigmem_unload();
		break;
	default:
		break;
	}

	return error;
}

moduledata_t contigmem_mod = {
	"contigmem",
	(modeventhand_t)contigmem_modevent,
	0
};

DECLARE_MODULE(contigmem, contigmem_mod, SI_SUB_DRIVERS, SI_ORDER_ANY);
MODULE_VERSION(contigmem, 1);

static struct cdevsw contigmem_ops = {
	.d_name         = "contigmem",
	.d_version      = D_VERSION,
	.d_flags        = D_TRACKCLOSE,
	.d_mmap_single  = contigmem_mmap_single,
	.d_open         = contigmem_open,
	.d_close        = contigmem_close,
};

static int
contigmem_load()
{
	char index_string[8], description[32];
	int  i, error = 0;
	void *addr;

	if (contigmem_num_buffers > RTE_CONTIGMEM_MAX_NUM_BUFS) {
		printf("%d buffers requested is greater than %d allowed\n",
				contigmem_num_buffers, RTE_CONTIGMEM_MAX_NUM_BUFS);
		error = EINVAL;
		goto error;
	}

	if (contigmem_buffer_size < PAGE_SIZE ||
			(contigmem_buffer_size & (contigmem_buffer_size - 1)) != 0) {
		printf("buffer size 0x%lx is not greater than PAGE_SIZE and "
				"power of two\n", contigmem_buffer_size);
		error = EINVAL;
		goto error;
	}

	for (i = 0; i < contigmem_num_buffers; i++) {
		addr = contigmalloc(contigmem_buffer_size, M_CONTIGMEM, M_ZERO,
			0, BUS_SPACE_MAXADDR, contigmem_buffer_size, 0);
		if (addr == NULL) {
			printf("contigmalloc failed for buffer %d\n", i);
			error = ENOMEM;
			goto error;
		}

		printf("%2u: virt=%p phys=%p\n", i, addr,
			(void *)pmap_kextract((vm_offset_t)addr));

		mtx_init(&contigmem_buffers[i].mtx, "contigmem", NULL, MTX_DEF);
		contigmem_buffers[i].addr = addr;
		contigmem_buffers[i].refcnt = 0;

		snprintf(index_string, sizeof(index_string), "%d", i);
		snprintf(description, sizeof(description),
				"phys addr for buffer %d", i);
		SYSCTL_ADD_PROC(NULL,
				&SYSCTL_NODE_CHILDREN(_hw_contigmem, physaddr), OID_AUTO,
				index_string, CTLTYPE_U64 | CTLFLAG_RD,
				(void *)(uintptr_t)i, 0, contigmem_physaddr, "LU",
				description);
	}

	contigmem_cdev = make_dev_credf(0, &contigmem_ops, 0, NULL, UID_ROOT,
			GID_WHEEL, 0600, "contigmem");

	return 0;

error:
	for (i = 0; i < contigmem_num_buffers; i++) {
		if (contigmem_buffers[i].addr != NULL)
			contigfree(contigmem_buffers[i].addr,
				contigmem_buffer_size, M_CONTIGMEM);
		if (mtx_initialized(&contigmem_buffers[i].mtx))
			mtx_destroy(&contigmem_buffers[i].mtx);
	}

	return error;
}

static int
contigmem_unload()
{
	int i;

	if (contigmem_refcnt > 0)
		return EBUSY;

	if (contigmem_cdev != NULL)
		destroy_dev(contigmem_cdev);

	if (contigmem_eh_tag != NULL)
		EVENTHANDLER_DEREGISTER(process_exit, contigmem_eh_tag);

	for (i = 0; i < RTE_CONTIGMEM_MAX_NUM_BUFS; i++) {
		if (contigmem_buffers[i].addr != NULL)
			contigfree(contigmem_buffers[i].addr,
				contigmem_buffer_size, M_CONTIGMEM);
		if (mtx_initialized(&contigmem_buffers[i].mtx))
			mtx_destroy(&contigmem_buffers[i].mtx);
	}

	return 0;
}

static int
contigmem_physaddr(SYSCTL_HANDLER_ARGS)
{
	uint64_t	physaddr;
	int		index = (int)(uintptr_t)arg1;

	physaddr = (uint64_t)vtophys(contigmem_buffers[index].addr);
	return sysctl_handle_64(oidp, &physaddr, 0, req);
}

static int
contigmem_open(struct cdev *cdev, int fflags, int devtype,
		struct thread *td)
{

	atomic_add_int(&contigmem_refcnt, 1);

	return 0;
}

static int
contigmem_close(struct cdev *cdev, int fflags, int devtype,
		struct thread *td)
{

	atomic_subtract_int(&contigmem_refcnt, 1);

	return 0;
}

static int
contigmem_cdev_pager_ctor(void *handle, vm_ooffset_t size, vm_prot_t prot,
		vm_ooffset_t foff, struct ucred *cred, u_short *color)
{
	struct contigmem_vm_handle *vmh = handle;
	struct contigmem_buffer *buf;

	buf = &contigmem_buffers[vmh->buffer_index];

	atomic_add_int(&contigmem_refcnt, 1);

	mtx_lock(&buf->mtx);
	if (buf->refcnt == 0)
		memset(buf->addr, 0, contigmem_buffer_size);
	buf->refcnt++;
	mtx_unlock(&buf->mtx);

	return 0;
}

static void
contigmem_cdev_pager_dtor(void *handle)
{
	struct contigmem_vm_handle *vmh = handle;
	struct contigmem_buffer *buf;

	buf = &contigmem_buffers[vmh->buffer_index];

	mtx_lock(&buf->mtx);
	buf->refcnt--;
	mtx_unlock(&buf->mtx);

	free(vmh, M_CONTIGMEM);

	atomic_subtract_int(&contigmem_refcnt, 1);
}

static int
contigmem_cdev_pager_fault(vm_object_t object, vm_ooffset_t offset, int prot,
		vm_page_t *mres)
{
	vm_paddr_t paddr;
	vm_page_t m_paddr, page;
	vm_memattr_t memattr, memattr1;

	memattr = object->memattr;

	VM_OBJECT_WUNLOCK(object);

	paddr = offset;

	m_paddr = vm_phys_paddr_to_vm_page(paddr);
	if (m_paddr != NULL) {
		memattr1 = pmap_page_get_memattr(m_paddr);
		if (memattr1 != memattr)
			memattr = memattr1;
	}

	if (((*mres)->flags & PG_FICTITIOUS) != 0) {
		/*
		 * If the passed in result page is a fake page, update it with
		 * the new physical address.
		 */
		page = *mres;
		VM_OBJECT_WLOCK(object);
		vm_page_updatefake(page, paddr, memattr);
	} else {
		vm_page_t mret;
		/*
		 * Replace the passed in reqpage page with our own fake page and
		 * free up the original page.
		 */
		page = vm_page_getfake(paddr, memattr);
		VM_OBJECT_WLOCK(object);
		mret = vm_page_replace(page, object, (*mres)->pindex);
		KASSERT(mret == *mres,
		    ("invalid page replacement, old=%p, ret=%p", *mres, mret));
		vm_page_lock(mret);
		vm_page_free(mret);
		vm_page_unlock(mret);
		*mres = page;
	}

	page->valid = VM_PAGE_BITS_ALL;

	return VM_PAGER_OK;
}

static struct cdev_pager_ops contigmem_cdev_pager_ops = {
	.cdev_pg_ctor = contigmem_cdev_pager_ctor,
	.cdev_pg_dtor = contigmem_cdev_pager_dtor,
	.cdev_pg_fault = contigmem_cdev_pager_fault,
};

static int
contigmem_mmap_single(struct cdev *cdev, vm_ooffset_t *offset, vm_size_t size,
		struct vm_object **obj, int nprot)
{
	struct contigmem_vm_handle *vmh;
	uint64_t buffer_index;

	/*
	 * The buffer index is encoded in the offset.  Divide the offset by
	 *  PAGE_SIZE to get the index of the buffer requested by the user
	 *  app.
	 */
	buffer_index = *offset / PAGE_SIZE;
	if (buffer_index >= contigmem_num_buffers)
		return EINVAL;

	if (size > contigmem_buffer_size)
		return EINVAL;

	vmh = malloc(sizeof(*vmh), M_CONTIGMEM, M_NOWAIT | M_ZERO);
	if (vmh == NULL)
		return ENOMEM;
	vmh->buffer_index = buffer_index;

	*offset = (vm_ooffset_t)vtophys(contigmem_buffers[buffer_index].addr);
	*obj = cdev_pager_allocate(vmh, OBJT_DEVICE, &contigmem_cdev_pager_ops,
			size, nprot, *offset, curthread->td_ucred);

	return 0;
}

{'repo_name': 'tiglabs/jupiter', 'stars': '277', 'repo_language': 'C', 'file_name': 'Makefile', 'mime_type': 'text/x-makefile', 'hash': 8378252053505567171, 'source_dataset': 'data'}


fileFormatVersion: 2
guid: ca10d4d976d6c284ca530b8cf78faddf
TextureImporter:
  internalIDToNameTable: []
  externalObjects: {}
  serializedVersion: 11
  mipmaps:
    mipMapMode: 1
    enableMipMap: 1
    sRGBTexture: 0
    linearTexture: 0
    fadeOut: 0
    borderMipMap: 0
    mipMapsPreserveCoverage: 0
    alphaTestReferenceValue: 0.5
    mipMapFadeDistanceStart: 1
    mipMapFadeDistanceEnd: 3
  bumpmap:
    convertToNormalMap: 0
    externalNormalMap: 0
    heightScale: 0.25
    normalMapFilter: 0
  isReadable: 0
  streamingMipmaps: 0
  streamingMipmapsPriority: 0
  grayScaleToAlpha: 0
  generateCubemap: 6
  cubemapConvolution: 0
  seamlessCubemap: 0
  textureFormat: 1
  maxTextureSize: 2048
  textureSettings:
    serializedVersion: 2
    filterMode: 2
    aniso: 4
    mipBias: -100
    wrapU: -1
    wrapV: -1
    wrapW: -1
  nPOTScale: 1
  lightmap: 0
  compressionQuality: 50
  spriteMode: 0
  spriteExtrude: 1
  spriteMeshType: 1
  alignment: 0
  spritePivot: {x: 0.5, y: 0.5}
  spritePixelsToUnits: 100
  spriteBorder: {x: 0, y: 0, z: 0, w: 0}
  spriteGenerateFallbackPhysicsShape: 1
  alphaUsage: 1
  alphaIsTransparency: 0
  spriteTessellationDetail: -1
  textureType: 1
  textureShape: 1
  singleChannelComponent: 0
  maxTextureSizeSet: 0
  compressionQualitySet: 0
  textureFormatSet: 0
  applyGammaDecoding: 1
  platformSettings:
  - serializedVersion: 3
    buildTarget: DefaultTexturePlatform
    maxTextureSize: 2048
    resizeAlgorithm: 0
    textureFormat: -1
    textureCompression: 2
    compressionQuality: 50
    crunchedCompression: 0
    allowsAlphaSplitting: 0
    overridden: 0
    androidETC2FallbackOverride: 0
    forceMaximumCompressionQuality_BC6H_BC7: 1
  - serializedVersion: 3
    buildTarget: Standalone
    maxTextureSize: 2048
    resizeAlgorithm: 0
    textureFormat: 27
    textureCompression: 1
    compressionQuality: 50
    crunchedCompression: 0
    allowsAlphaSplitting: 0
    overridden: 1
    androidETC2FallbackOverride: 0
    forceMaximumCompressionQuality_BC6H_BC7: 0
  - serializedVersion: 3
    buildTarget: PS4
    maxTextureSize: 2048
    resizeAlgorithm: 0
    textureFormat: 27
    textureCompression: 1
    compressionQuality: 50
    crunchedCompression: 0
    allowsAlphaSplitting: 0
    overridden: 1
    androidETC2FallbackOverride: 0
    forceMaximumCompressionQuality_BC6H_BC7: 0
  - serializedVersion: 3
    buildTarget: XboxOne
    maxTextureSize: 2048
    resizeAlgorithm: 0
    textureFormat: -1
    textureCompression: 2
    compressionQuality: 50
    crunchedCompression: 0
    allowsAlphaSplitting: 0
    overridden: 0
    androidETC2FallbackOverride: 0
    forceMaximumCompressionQuality_BC6H_BC7: 1
  spriteSheet:
    serializedVersion: 2
    sprites: []
    outline: []
    physicsShape: []
    bones: []
    spriteID:
    internalID: 0
    vertices: []
    indices:
    edges: []
    weights: []
    secondaryTextures: []
  spritePackingTag:
  pSDRemoveMatte: 0
  pSDShowRemoveMatteOption: 0
  userData:
  assetBundleName:
  assetBundleVariant:

{'repo_name': 'Unity-Technologies/FontainebleauDemo', 'stars': '364', 'repo_language': 'C#', 'file_name': 'Settings.json', 'mime_type': 'text/plain', 'hash': 1360870251752473498, 'source_dataset': 'data'}


// 这个文件是 MCF 的一部分。
// 有关具体授权说明，请参阅 MCFLicense.txt。
// Copyleft 2013 - 2018, LH_Mouse. All wrongs reserved.

#include "_mopthread.h"
#include "mutex.h"
#include "avl_tree.h"
#include "mcfwin.h"
#include "heap.h"
#include "condition_variable.h"
#include "inline_mem.h"
#include "bail.h"
#include "expect.h"
#include <ntdef.h>

#undef GetCurrentProcess
#define GetCurrentProcess()  ((HANDLE)-1)

#undef GetCurrentThread
#define GetCurrentThread()   ((HANDLE)-2)

__attribute__((__dllimport__, __stdcall__)) extern NTSTATUS NtDuplicateObject(HANDLE hSourceProcess, HANDLE hSource, HANDLE hTargetProcess, HANDLE *pTarget, ACCESS_MASK dwDesiredAccess, ULONG dwAttributes, DWORD dwOptions);

static const _MCFCRT_ThreadHandle g_hPseudoSelfHandle = (_MCFCRT_ThreadHandle)GetCurrentThread();

static _MCFCRT_Mutex   g_mtxControl    = { 0 };
static _MCFCRT_AvlRoot g_avlControlMap = _MCFCRT_NULLPTR;

static intptr_t TerminationUnlockCallback(intptr_t nContext){
	_MCFCRT_Mutex *const pMutex = (void *)nContext;

	_MCFCRT_SignalMutex(pMutex);
	return 1;
}
static void TerminationRelockCallback(intptr_t nContext, intptr_t nUnlocked){
	_MCFCRT_Mutex *const pMutex = (void *)nContext;

	_MCFCRT_ASSERT((size_t)nUnlocked == 1);
	_MCFCRT_WaitForMutexForever(pMutex, _MCFCRT_MUTEX_SUGGESTED_SPIN_COUNT);
}

typedef enum tagMopthreadState {
	kStateJoinable,
	kStateZombie,
	kStateJoining,
	kStateJoined,
	kStateDetached,
} MopthreadState;

typedef struct tagMopthreadControl {
	_MCFCRT_AvlNodeHeader avlhTidIndex;

	MopthreadState eState;
	size_t uRefCount;
	_MCFCRT_ConditionVariable condTermination;

	uintptr_t uTid;
	_MCFCRT_ThreadHandle hThread;

	void (*pfnProc)(void *);
	size_t uSizeOfParams;
	unsigned char abyParams[];
} MopthreadControl;

static inline int MopthreadControlComparatorNodeOther(const _MCFCRT_AvlNodeHeader *pNodeSelf, intptr_t nTidOther){
	const uintptr_t uTidSelf = (uintptr_t)(((const MopthreadControl *)pNodeSelf)->uTid);
	const uintptr_t uTidOther = (uintptr_t)nTidOther;
	if(uTidSelf != uTidOther){
		return (uTidSelf < uTidOther) ? -1 : 1;
	}
	return 0;
}
static inline int MopthreadControlComparatorNodes(const _MCFCRT_AvlNodeHeader *pNodeSelf, const _MCFCRT_AvlNodeHeader *pNodeOther){
	return MopthreadControlComparatorNodeOther(pNodeSelf, (intptr_t)(((const MopthreadControl *)pNodeOther)->uTid));
}

static unsigned char g_abyInitialControlStorage[sizeof(MopthreadControl) + sizeof(void *) * 3]; // XXX: This should suffice for both gthread and c11thread.
static_assert(sizeof(g_abyInitialControlStorage) == sizeof(void *) * 17, "??");

// The caller must have the global mutex locked!
static void DropControlRefUnsafe(MopthreadControl *restrict pControl){
	_MCFCRT_ASSERT(pControl->uRefCount > 0);
	if(--(pControl->uRefCount) == 0){
		_MCFCRT_ASSERT(pControl->eState == kStateJoined);
		_MCFCRT_AvlDetach((_MCFCRT_AvlNodeHeader *)pControl);
		_MCFCRT_CloseThread(pControl->hThread);
#ifndef NDEBUG
		pControl->hThread = (HANDLE)0xDEADBEEF;
#endif
		if(pControl != (void *)g_abyInitialControlStorage){
			_MCFCRT_free(pControl);
		}
	}
}

// *** WARNING: No other threads shall be running when calling these functions. ***
static void AttachInitialThread(void){
	MopthreadControl *const restrict pControl = (void *)g_abyInitialControlStorage;

	pControl->pfnProc       = _MCFCRT_NULLPTR;
	pControl->uSizeOfParams = sizeof(g_abyInitialControlStorage) - sizeof(MopthreadControl);
	_MCFCRT_inline_mempset_fwd(pControl->abyParams, 0, pControl->uSizeOfParams);
	pControl->eState        = kStateJoinable;
	pControl->uRefCount     = 2;
	_MCFCRT_InitializeConditionVariable(&(pControl->condTermination));

	HANDLE hThread;
	NTSTATUS lStatus = NtDuplicateObject(GetCurrentProcess(), GetCurrentThread(), GetCurrentProcess(), &hThread, 0, 0, DUPLICATE_SAME_ACCESS);
	if(!NT_SUCCESS(lStatus)){
		_MCFCRT_Bail(L"NtDuplicateObject() 失败：无法获取主线程句柄。");
	}
	pControl->uTid    = (uintptr_t)GetCurrentThreadId();
	pControl->hThread = (HANDLE)hThread;

	_MCFCRT_AvlAttach(&g_avlControlMap, (_MCFCRT_AvlNodeHeader *)pControl, &MopthreadControlComparatorNodes);
}
static void DetachInitialThread(void){
	MopthreadControl *const restrict pControl = (void *)g_abyInitialControlStorage;

	switch(pControl->eState){
	case kStateJoinable:
		pControl->eState = kStateDetached;
		goto jJoinSuccess;
	case kStateZombie:
		pControl->eState = kStateJoined;
		goto jJoinSuccess;
	case kStateJoining:
	case kStateJoined:
	case kStateDetached:
		break;
	default:
		_MCFCRT_ASSERT(false);
	jJoinSuccess:
		DropControlRefUnsafe(pControl);
		// bSuccess = true;
		break;
	}
}

__attribute__((__noreturn__)) static inline void SignalMutexAndExitThread(_MCFCRT_Mutex *restrict pMutex, MopthreadControl *restrict pControl, void (*pfnModifier)(void *, size_t, intptr_t), intptr_t nContext){
	switch(pControl->eState){
	case kStateJoinable:
		if(pfnModifier){
			(*pfnModifier)(pControl->abyParams, pControl->uSizeOfParams, nContext);
		}
		pControl->eState = kStateZombie;
		break;
	case kStateZombie:
		_MCFCRT_ASSERT(false);
	case kStateJoining:
		if(pfnModifier){
			(*pfnModifier)(pControl->abyParams, pControl->uSizeOfParams, nContext);
		}
		pControl->eState = kStateJoined;
		_MCFCRT_BroadcastConditionVariable(&(pControl->condTermination));
		break;
	case kStateJoined:
		_MCFCRT_ASSERT(false);
	case kStateDetached:
		pControl->eState = kStateJoined;
		break;
	default:
		_MCFCRT_ASSERT(false);
	}
	DropControlRefUnsafe(pControl);
	_MCFCRT_SignalMutex(pMutex);

	ExitThread(0);
	__builtin_unreachable();
}

bool __MCFCRT_MopthreadInit(void){
	AttachInitialThread();
	return true;
}
void __MCFCRT_MopthreadUninit(void){
	DetachInitialThread();
}

static unsigned long MopthreadProc(void *pParam){
	MopthreadControl *const restrict pControl = pParam;
	_MCFCRT_DEBUG_CHECK(pControl);
	(*(pControl->pfnProc))(pControl->abyParams);
	return 0;
}
__attribute__((__noreturn__, __stdcall__)) static unsigned long NativeMopthreadProc(void *pParam){
	MopthreadControl *const restrict pControl = pParam;
	_MCFCRT_DEBUG_CHECK(pControl);
	_MCFCRT_WrapThreadProcWithSehTop(&MopthreadProc, pControl);
	_MCFCRT_WaitForMutexForever(&g_mtxControl, _MCFCRT_MUTEX_SUGGESTED_SPIN_COUNT);
	SignalMutexAndExitThread(&g_mtxControl, pControl, _MCFCRT_NULLPTR, 0);
}

static inline uintptr_t ReallyCreateMopthread(void (*pfnProc)(void *), const void *pParams, size_t uSizeOfParams, bool bJoinable){
	const size_t uSizeToAlloc = sizeof(MopthreadControl) + uSizeOfParams;
	if(uSizeToAlloc < sizeof(MopthreadControl)){
		return 0;
	}
	MopthreadControl *const restrict pControl = _MCFCRT_malloc(uSizeToAlloc);
	if(!pControl){
		return 0;
	}
	pControl->pfnProc       = pfnProc;
	pControl->uSizeOfParams = uSizeOfParams;
	if(pParams){
		_MCFCRT_inline_mempcpy_fwd(pControl->abyParams, pParams, uSizeOfParams);
	} else {
		_MCFCRT_inline_mempset_fwd(pControl->abyParams, 0, uSizeOfParams);
	}
	if(bJoinable){
		pControl->eState    = kStateJoinable;
		pControl->uRefCount = 2;
	} else {
		pControl->eState    = kStateDetached;
		pControl->uRefCount = 1;
	}
	_MCFCRT_InitializeConditionVariable(&(pControl->condTermination));

	uintptr_t uTid;
	const _MCFCRT_ThreadHandle hThread = _MCFCRT_CreateNativeThread(&NativeMopthreadProc, pControl, true, &uTid);
	if(!hThread){
		_MCFCRT_free(pControl);
		return 0;
	}
	pControl->uTid    = uTid;
	pControl->hThread = hThread;
	// XXX: Note that at the moment you must attach the control block unconditionally, because the thread could call
	//      `__MCFCRT_MopthreadExit()` which must be able to get a valid pointer to it by thread ID.
	_MCFCRT_WaitForMutexForever(&g_mtxControl, _MCFCRT_MUTEX_SUGGESTED_SPIN_COUNT);
	{
		_MCFCRT_AvlAttach(&g_avlControlMap, (_MCFCRT_AvlNodeHeader *)pControl, &MopthreadControlComparatorNodes);
	}
	_MCFCRT_SignalMutex(&g_mtxControl);

	_MCFCRT_ResumeThread(hThread);
	return uTid;
}

uintptr_t __MCFCRT_MopthreadCreate(void (*pfnProc)(void *), const void *pParams, size_t uSizeOfParams){
	return ReallyCreateMopthread(pfnProc, pParams, uSizeOfParams, true);
}
uintptr_t __MCFCRT_MopthreadCreateDetached(void (*pfnProc)(void *), const void *pParams, size_t uSizeOfParams){
	return ReallyCreateMopthread(pfnProc, pParams, uSizeOfParams, false);
}
__attribute__((__noreturn__)) void __MCFCRT_MopthreadExit(void (*pfnModifier)(void *, size_t, intptr_t), intptr_t nContext){
	const uintptr_t uTid = _MCFCRT_GetCurrentThreadId();

	_MCFCRT_WaitForMutexForever(&g_mtxControl, _MCFCRT_MUTEX_SUGGESTED_SPIN_COUNT);
	MopthreadControl *const restrict pControl = (MopthreadControl *)_MCFCRT_AvlFind(&g_avlControlMap, (intptr_t)uTid, &MopthreadControlComparatorNodeOther);
	if(!pControl){
		_MCFCRT_Bail(L"Calling thread of __MCFCRT_MopthreadExit() was not created using __MCFCRT_MopthreadCreate().");
	}
	SignalMutexAndExitThread(&g_mtxControl, pControl, pfnModifier, nContext);
}
bool __MCFCRT_MopthreadJoin(uintptr_t uTid, void *restrict pParams, size_t *restrict puSizeOfParams){
	bool bSuccess = false;

	_MCFCRT_WaitForMutexForever(&g_mtxControl, _MCFCRT_MUTEX_SUGGESTED_SPIN_COUNT);
	{
		MopthreadControl *const restrict pControl = (MopthreadControl *)_MCFCRT_AvlFind(&g_avlControlMap, (intptr_t)uTid, &MopthreadControlComparatorNodeOther);
		if(pControl){
			switch(pControl->eState){
			case kStateJoinable:
				pControl->eState = kStateJoining;
				do {
					_MCFCRT_WaitForConditionVariableForever(&(pControl->condTermination), &TerminationUnlockCallback, &TerminationRelockCallback, (intptr_t)&g_mtxControl, 0);
				} while(pControl->eState != kStateJoined);
				goto jJoinSuccess;
			case kStateZombie:
				pControl->eState = kStateJoined;
				goto jJoinSuccess;
			case kStateJoining:
			case kStateJoined:
			case kStateDetached:
				break;
			default:
				_MCFCRT_ASSERT(false);
			jJoinSuccess:
				_MCFCRT_WaitForThreadForever(pControl->hThread);
				if(pParams){
					const size_t uSizeCopied = (pControl->uSizeOfParams < *puSizeOfParams) ? pControl->uSizeOfParams : *puSizeOfParams;
					_MCFCRT_inline_mempcpy_fwd(pParams, pControl->abyParams, uSizeCopied);
					*puSizeOfParams = uSizeCopied;
				}
				DropControlRefUnsafe(pControl);
				bSuccess = true;
				break;
			}
		}
	}
	_MCFCRT_SignalMutex(&g_mtxControl);

	return bSuccess;
}
bool __MCFCRT_MopthreadDetach(uintptr_t uTid){
	bool bSuccess = false;

	_MCFCRT_WaitForMutexForever(&g_mtxControl, _MCFCRT_MUTEX_SUGGESTED_SPIN_COUNT);
	{
		MopthreadControl *const restrict pControl = (MopthreadControl *)_MCFCRT_AvlFind(&g_avlControlMap, (intptr_t)uTid, &MopthreadControlComparatorNodeOther);
		if(pControl){
			switch(pControl->eState){
			case kStateJoinable:
				pControl->eState = kStateDetached;
				goto jJoinSuccess;
			case kStateZombie:
				pControl->eState = kStateJoined;
				goto jJoinSuccess;
			case kStateJoining:
			case kStateJoined:
			case kStateDetached:
				break;
			default:
				_MCFCRT_ASSERT(false);
			jJoinSuccess:
				DropControlRefUnsafe(pControl);
				bSuccess = true;
				break;
			}
		}
	}
	_MCFCRT_SignalMutex(&g_mtxControl);

	return bSuccess;
}

const _MCFCRT_ThreadHandle * __MCFCRT_MopthreadLockHandle(uintptr_t uTid){
	if(_MCFCRT_EXPECT_NOT(uTid == 0)){
		return _MCFCRT_NULLPTR;
	}

	if(_MCFCRT_EXPECT(uTid == _MCFCRT_GetCurrentThreadId())){
		// Return a pseudo handle.
		return &g_hPseudoSelfHandle;
	}

	// Increment the reference count and return a real handle.
	const _MCFCRT_ThreadHandle *phThread = _MCFCRT_NULLPTR;

	_MCFCRT_WaitForMutexForever(&g_mtxControl, _MCFCRT_MUTEX_SUGGESTED_SPIN_COUNT);
	{
		MopthreadControl *const restrict pControl = (MopthreadControl *)_MCFCRT_AvlFind(&g_avlControlMap, (intptr_t)uTid, &MopthreadControlComparatorNodeOther);
		if(pControl){
			switch(pControl->eState){
			case kStateJoinable:
			case kStateZombie:
			case kStateJoining:
				_MCFCRT_ASSERT(pControl->uRefCount > 0);
				++(pControl->uRefCount);
				phThread = &(pControl->hThread);
				break;
			case kStateJoined:
			case kStateDetached:
				break;
			default:
				_MCFCRT_ASSERT(false);
			}
		}
	}
	_MCFCRT_SignalMutex(&g_mtxControl);

	return phThread;
}
void __MCFCRT_MopthreadUnlockHandle(const _MCFCRT_ThreadHandle *phThread){
	if(!phThread){
		return;
	}

	if(_MCFCRT_EXPECT(phThread == &g_hPseudoSelfHandle)){
		// Don't close the pseudo handle.
		return;
	}

	_MCFCRT_WaitForMutexForever(&g_mtxControl, _MCFCRT_MUTEX_SUGGESTED_SPIN_COUNT);
	{
		MopthreadControl *const restrict pControl = (void *)((char *)phThread - __builtin_offsetof(MopthreadControl, hThread));
		_MCFCRT_ASSERT(pControl);
		DropControlRefUnsafe(pControl);
	}
	_MCFCRT_SignalMutex(&g_mtxControl);
}

{'repo_name': 'lhmouse/MCF', 'stars': '181', 'repo_language': 'C++', 'file_name': 'string_template.h', 'mime_type': 'text/x-c', 'hash': 856623156951591670, 'source_dataset': 'data'}


/**
 ******************************************************************************
 * @addtogroup PIOS PIOS Core hardware abstraction layer
 * @{
 * @addtogroup PIOS_COM COM MSG layer functions
 * @brief Hardware communication layer
 * @{
 *
 * @file       pios_com_msg_priv.h
 * @author     The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010.
 * @brief      COM MSG private definitions.
 * @see        The GNU Public License (GPL) Version 3
 *
 *****************************************************************************/
/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
 * for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 */

#ifndef PIOS_COM_MSG_PRIV_H
#define PIOS_COM_MSG_PRIV_H

#include <stdint.h>		/* uint*_t */
#include "pios_com_priv.h"	/* struct pios_com_driver */

extern int32_t PIOS_COM_MSG_Init(uintptr_t * com_id, const struct pios_com_driver * driver, uint32_t lower_id);

#endif /* PIOS_COM_MSG_PRIV_H */

/**
  * @}
  * @}
  */

{'repo_name': 'TauLabs/TauLabs', 'stars': '426', 'repo_language': 'C', 'file_name': 'usb_conf.h', 'mime_type': 'text/x-c', 'hash': -8413485264399675069, 'source_dataset': 'data'}


/*******************************************************************************
* Copyright 2015-2016 Juan Francisco Crespo Galán
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*   http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/

#include "fx/Source.h"

#include <cmath>

AUD_NAMESPACE_BEGIN
Source::Source(float azimuth, float elevation, float distance) :
	m_elevation(elevation), m_distance(distance)
{
	azimuth = std::fmod(azimuth, 360);
	if(azimuth < 0)
		azimuth += 360;
	m_azimuth = azimuth;
}

float Source::getAzimuth()
{
	return m_azimuth;
}

float Source::getElevation()
{
	return m_elevation;
}

float Source::getDistance()
{
	return m_distance;
}

float Source::getVolume()
{
	float volume = 1.0f - m_distance;
	if(volume < 0.0f)
		volume = 0.0f;
	return volume;
}

void Source::setAzimuth(float azimuth)
{
	azimuth = std::fmod(azimuth, 360);
	if(azimuth < 0)
		azimuth += 360;
	m_azimuth = azimuth;
}

void Source::setElevation(float elevation)
{
	m_elevation = elevation;
}

void Source::setDistance(float distance)
{
	m_distance = distance;
}
AUD_NAMESPACE_END

{'repo_name': 'sobotka/blender', 'stars': '556', 'repo_language': 'C', 'file_name': 'userdef_default.c', 'mime_type': 'text/x-c', 'hash': 280333138688581569, 'source_dataset': 'data'}


/*
 * Copyright 2014 Advanced Micro Devices, Inc.
 * Copyright 2008 Red Hat Inc.
 * Copyright 2009 Jerome Glisse.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 *
 */
#include <drm/drmP.h>
#include "amdgpu.h"
#include "amdgpu_gfx.h"

/*
 * GPU scratch registers helpers function.
 */
/**
 * amdgpu_gfx_scratch_get - Allocate a scratch register
 *
 * @adev: amdgpu_device pointer
 * @reg: scratch register mmio offset
 *
 * Allocate a CP scratch register for use by the driver (all asics).
 * Returns 0 on success or -EINVAL on failure.
 */
int amdgpu_gfx_scratch_get(struct amdgpu_device *adev, uint32_t *reg)
{
	int i;

	i = ffs(adev->gfx.scratch.free_mask);
	if (i != 0 && i <= adev->gfx.scratch.num_reg) {
		i--;
		adev->gfx.scratch.free_mask &= ~(1u << i);
		*reg = adev->gfx.scratch.reg_base + i;
		return 0;
	}
	return -EINVAL;
}

/**
 * amdgpu_gfx_scratch_free - Free a scratch register
 *
 * @adev: amdgpu_device pointer
 * @reg: scratch register mmio offset
 *
 * Free a CP scratch register allocated for use by the driver (all asics)
 */
void amdgpu_gfx_scratch_free(struct amdgpu_device *adev, uint32_t reg)
{
	adev->gfx.scratch.free_mask |= 1u << (reg - adev->gfx.scratch.reg_base);
}

/**
 * amdgpu_gfx_parse_disable_cu - Parse the disable_cu module parameter
 *
 * @mask: array in which the per-shader array disable masks will be stored
 * @max_se: number of SEs
 * @max_sh: number of SHs
 *
 * The bitmask of CUs to be disabled in the shader array determined by se and
 * sh is stored in mask[se * max_sh + sh].
 */
void amdgpu_gfx_parse_disable_cu(unsigned *mask, unsigned max_se, unsigned max_sh)
{
	unsigned se, sh, cu;
	const char *p;

	memset(mask, 0, sizeof(*mask) * max_se * max_sh);

	if (!amdgpu_disable_cu || !*amdgpu_disable_cu)
		return;

	p = amdgpu_disable_cu;
	for (;;) {
		char *next;
		int ret = sscanf(p, "%u.%u.%u", &se, &sh, &cu);
		if (ret < 3) {
			DRM_ERROR("amdgpu: could not parse disable_cu\n");
			return;
		}

		if (se < max_se && sh < max_sh && cu < 16) {
			DRM_INFO("amdgpu: disabling CU %u.%u.%u\n", se, sh, cu);
			mask[se * max_sh + sh] |= 1u << cu;
		} else {
			DRM_ERROR("amdgpu: disable_cu %u.%u.%u is out of range\n",
				  se, sh, cu);
		}

		next = strchr(p, ',');
		if (!next)
			break;
		p = next + 1;
	}
}

{'repo_name': 'ValveSoftware/steamos_kernel', 'stars': '292', 'repo_language': 'C', 'file_name': 'Kconfig', 'mime_type': 'text/plain', 'hash': -1822981899025757408, 'source_dataset': 'data'}


a{color:#009a61;text-decoration:none}
a:focus,a:hover{color:#004e31;text-decoration:underline;}
.navbar-inverse{background-color:#2a8c70;border-color:#2b7a5c}
.navbar-inverse .navbar-nav>li>a{color:#fff}
.navbar-inverse .navbar-nav>.active>a,.navbar-inverse .navbar-nav>.active>a:focus,.navbar-inverse .navbar-nav>.active>a:hover{background-color:#2b7a5c}
.navbar-inverse .navbar-nav>.open>a,.navbar-inverse .navbar-nav>.open>a:focus,.navbar-inverse .navbar-nav>.open>a:hover{background-color:#008151}
.navbar-inverse .navbar-toggle:focus,.navbar-inverse .navbar-toggle:hover{background-color:#008151}
.navbar-inverse .navbar-toggle{border-color:#008151}
.navbar-inverse .navbar-collapse,.navbar-inverse .navbar-form{border-color:#008151}
.header-response .bottom-nav .active{color:#009a61}
.header-response .fa-user,.header-response .fa-search{color:#fff;}
@media (max-width: 767px){.navbar-inverse .navbar-nav .open .dropdown-menu>li>a {color: #fff;}}
@media (max-width: 767px){.navbar-inverse .navbar-nav .open .dropdown-menu .divider {background-color: #2b7a5c;}}
.nav-child .tag.active{background-color:#017E66;color:#fff;text-decoration:none}
.nav-pills>li.active>a, .nav-pills>li.active>a:focus, .nav-pills>li.active>a:hover{background-color:#017e66;}
.space-nav li.active a{background-color:#F6F6F6;color:#2a8c70}

.list-group-item.active,.list-group-item.active:focus,.list-group-item.active:hover{z-index:2;color:#fff;background-color:#009a61;border-color:#009a61}
.list-group-item.active .list-group-item-text,.list-group-item.active:focus .list-group-item-text,.list-group-item.active:hover .list-group-item-text{color:#67ffc7}
.widget-links-item a{margin-right:6px;color:#333;}
.widget-links-item a:hover{text-decoration:underline;}
.widget-message-item.active, .widget-messages-item:hover {text-decoration: none;color: #008E59;background-color: #F6F6F6}
.widget-message-item.active .badge, .widget-message-item:hover .badge {background-color: #008E59}
.tag{display:inline-block;padding:0 8px;color:#017e66;background-color:#E7F2ED;height:24px;line-height:24px;font-weight:400;font-size:13px;text-align:center}
.tag[href]:focus,.tag[href]:hover{background-color:#017e66;color:#fff;text-decoration:none}
.widget-category .list a{display:block;padding:0 10px;text-decoration:none;}
.widget-category .list a:hover{color:#004e31;}
.widget-category .active a{background:#017e66;border-color:#017e66;color:#fff;border-radius: 5px;}
.widget-category .active a:hover{color:#e3faf3}
.stream-list-item .title a{color:#333}
.stream-list-item .title a:hover{color:#017e66}
.stream-list-item .title a:visited{font-weight:400}
.streams-item .title a{color:#333;}
.streams-item .title a:hover{color:#017e66;}
.bookmark-rank .answered,.qa-rank .answered{background-color:#009a61;color:#fff}
/*buttons*/
.btn-primary{border-color:#008151;background-color:#009a61;color:#fff;}
.btn-primary.active,.btn-primary:active,.btn-primary:focus,.btn-primary:hover,.open>.btn-primary.dropdown-toggle{border-color:#00432a;background-color:#006741;color:#fff;}
.btn-primary.active,.btn-primary:active,.open>.btn-primary.dropdown-toggle{background-image:none;}
.btn-primary.disabled,.btn-primary.disabled.active,.btn-primary.disabled:active,.btn-primary.disabled:focus,.btn-primary.disabled:hover,.btn-primary[disabled],.btn-primary[disabled].active,.btn-primary[disabled]:active,.btn-primary[disabled]:focus,.btn-primary[disabled]:hover,fieldset[disabled] .btn-primary,fieldset[disabled] .btn-primary.active,fieldset[disabled] .btn-primary:active,fieldset[disabled] .btn-primary:focus,fieldset[disabled] .btn-primary:hover{border-color:#008151;background-color:#009a61;}
.btn-primary .badge{background-color:#fff;color:#009a61;}
.btn-success{border-color:#4cae4c;background-color:#5cb85c;color:#fff;}

.pagination>li>a,.pagination>li>span{position:relative;float:left;margin-left:-1px;padding:6px 12px;border:1px solid #ddd;background-color:#fff;color:#009a61;text-decoration:none;line-height:1.5;}
.pagination>li>a:focus,.pagination>li>a:hover,.pagination>li>span:focus,.pagination>li>span:hover{border-color:#ddd;background-color:#eee;color:#004e31;}
.pagination>.active>a,.pagination>.active>a:focus,.pagination>.active>a:hover,.pagination>.active>span,.pagination>.active>span:focus,.pagination>.active>span:hover{z-index:2;border-color:#009a61;background-color:#009a61;color:#fff;cursor:default;}

{'repo_name': 'sdfsky/tipask', 'stars': '264', 'repo_language': 'JavaScript', 'file_name': 'common.js', 'mime_type': 'text/plain', 'hash': 502586510987518834, 'source_dataset': 'data'}


<!DOCTYPE HTML>

  <title>Test for Bug 731777</title>

  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>

{'repo_name': 'Feodor2/Mypal', 'stars': '149', 'repo_language': 'None', 'file_name': 'moz.build', 'mime_type': 'text/plain', 'hash': -2804544271246621447, 'source_dataset': 'data'}


# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.

from odoo import api, fields, models, _
from odoo.tools import html2plaintext

class Stage(models.Model):

    _name = "note.stage"
    _description = "Note Stage"
    _order = 'sequence'

    name = fields.Char('Stage Name', translate=True, required=True)
    sequence = fields.Integer(help="Used to order the note stages", default=1)
    user_id = fields.Many2one('res.users', string='Owner', required=True, ondelete='cascade', default=lambda self: self.env.uid, help="Owner of the note stage")
    fold = fields.Boolean('Folded by Default')

class Tag(models.Model):

    _name = "note.tag"
    _description = "Note Tag"

    name = fields.Char('Tag Name', required=True, translate=True)
    color = fields.Integer('Color Index')

    _sql_constraints = [
        ('name_uniq', 'unique (name)', "Tag name already exists !"),
    ]

class Note(models.Model):

    _name = 'note.note'
    _inherit = ['mail.thread', 'mail.activity.mixin']
    _description = "Note"
    _order = 'sequence'

    def _get_default_stage_id(self):
        return self.env['note.stage'].search([('user_id', '=', self.env.uid)], limit=1)

    name = fields.Text(compute='_compute_name', string='Note Summary', store=True)
    user_id = fields.Many2one('res.users', string='Owner', default=lambda self: self.env.uid)
    memo = fields.Html('Note Content')
    sequence = fields.Integer('Sequence')
    stage_id = fields.Many2one('note.stage', compute='_compute_stage_id',
        inverse='_inverse_stage_id', string='Stage', default=_get_default_stage_id)
    stage_ids = fields.Many2many('note.stage', 'note_stage_rel', 'note_id', 'stage_id',
        string='Stages of Users',  default=_get_default_stage_id)
    open = fields.Boolean(string='Active', default=True)
    date_done = fields.Date('Date done')
    color = fields.Integer(string='Color Index')
    tag_ids = fields.Many2many('note.tag', 'note_tags_rel', 'note_id', 'tag_id', string='Tags')
    message_partner_ids = fields.Many2many(
        comodel_name='res.partner', string='Followers (Partners)',
        compute='_get_followers', search='_search_follower_partners',
        compute_sudo=True)
    message_channel_ids = fields.Many2many(
        comodel_name='mail.channel', string='Followers (Channels)',
        compute='_get_followers', search='_search_follower_channels',
        compute_sudo=True)

    @api.depends('memo')
    def _compute_name(self):
        """ Read the first line of the memo to determine the note name """
        for note in self:
            text = html2plaintext(note.memo) if note.memo else ''
            note.name = text.strip().replace('*', '').split("\n")[0]

    def _compute_stage_id(self):
        first_user_stage = self.env['note.stage'].search([('user_id', '=', self.env.uid)], limit=1)
        for note in self:
            for stage in note.stage_ids.filtered(lambda stage: stage.user_id == self.env.user):
                note.stage_id = stage
            # note without user's stage
            if not note.stage_id:
                note.stage_id = first_user_stage

    def _inverse_stage_id(self):
        for note in self.filtered('stage_id'):
            note.stage_ids = note.stage_id + note.stage_ids.filtered(lambda stage: stage.user_id != self.env.user)

    @api.model
    def name_create(self, name):
        return self.create({'memo': name}).name_get()[0]

    @api.model
    def read_group(self, domain, fields, groupby, offset=0, limit=None, orderby=False, lazy=True):
        if groupby and groupby[0] == "stage_id":
            stages = self.env['note.stage'].search([('user_id', '=', self.env.uid)])
            if stages:  # if the user has some stages
                result = [{  # notes by stage for stages user
                    '__context': {'group_by': groupby[1:]},
                    '__domain': domain + [('stage_ids.id', '=', stage.id)],
                    'stage_id': (stage.id, stage.name),
                    'stage_id_count': self.search_count(domain + [('stage_ids', '=', stage.id)]),
                    '__fold': stage.fold,
                } for stage in stages]

                # note without user's stage
                nb_notes_ws = self.search_count(domain + [('stage_ids', 'not in', stages.ids)])
                if nb_notes_ws:
                    # add note to the first column if it's the first stage
                    dom_not_in = ('stage_ids', 'not in', stages.ids)
                    if result and result[0]['stage_id'][0] == stages[0].id:
                        dom_in = result[0]['__domain'].pop()
                        result[0]['__domain'] = domain + ['|', dom_in, dom_not_in]
                        result[0]['stage_id_count'] += nb_notes_ws
                    else:
                        # add the first stage column
                        result = [{
                            '__context': {'group_by': groupby[1:]},
                            '__domain': domain + [dom_not_in],
                            'stage_id': (stages[0].id, stages[0].name),
                            'stage_id_count': nb_notes_ws,
                            '__fold': stages[0].name,
                        }] + result
            else:  # if stage_ids is empty, get note without user's stage
                nb_notes_ws = self.search_count(domain)
                if nb_notes_ws:
                    result = [{  # notes for unknown stage
                        '__context': {'group_by': groupby[1:]},
                        '__domain': domain,
                        'stage_id': False,
                        'stage_id_count': nb_notes_ws
                    }]
                else:
                    result = []
            return result
        return super(Note, self).read_group(domain, fields, groupby, offset=offset, limit=limit, orderby=orderby, lazy=lazy)

    def action_close(self):
        return self.write({'open': False, 'date_done': fields.date.today()})

    def action_open(self):
        return self.write({'open': True})

{'repo_name': 'odoo/odoo', 'stars': '18107', 'repo_language': 'JavaScript', 'file_name': 'format', 'mime_type': 'text/plain', 'hash': 2216045789882134141, 'source_dataset': 'data'}


(ns resources.ns-with-rename
  "This is a docstring for the ns

  It contains an \"escaped string\"."
  {:author "Winnie the pooh"}
  (:refer-clojure :exclude [macroexpand-1 read read-string])
  (:gen-class
   :name com.domain.tiny
   :extends java.lang.Exception
   :methods [[binomial [int int] double]])
  (:require
   [clojure.instant :as inst :refer [read-instant-date] :reload true]
   [clojure.walk :refer [prewalk postwalk]]
   (clojure data edn)
   [clojure.pprint :refer [get-pretty-writer formatter cl-format]]
   clojure.test.junit
   [clojure.xml])
  (:use clojure.test
        clojure.test
        [clojure.string :rename {replace foo split bar} :reload-all true :reload true])
  (:import java.util.Random
           java.io.PushbackReader
           java.io.PushbackReader
           java.io.FilenameFilter
           java.io.Closeable
           [java.util Date Date Calendar]
           (java.util Date Calendar)))

(foo "s" "match" "replacement")

{'repo_name': 'clojure-emacs/refactor-nrepl', 'stars': '191', 'repo_language': 'Clojure', 'file_name': 'config.yml', 'mime_type': 'text/plain', 'hash': 1749518483627776909, 'source_dataset': 'data'}


/* English/UK initialisation for the jQuery UI date picker plugin. */
/* Written by Stuart. */
(function( factory ) {
	if ( typeof define === "function" && define.amd ) {

		// AMD. Register as an anonymous module.
		define([ "../datepicker" ], factory );
	} else {

		// Browser globals
		factory( jQuery.datepicker );
	}
}(function( datepicker ) {

datepicker.regional['en-GB'] = {
	closeText: 'Done',
	prevText: 'Prev',
	nextText: 'Next',
	currentText: 'Today',
	monthNames: ['January','February','March','April','May','June',
	'July','August','September','October','November','December'],
	monthNamesShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
	'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
	dayNames: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
	dayNamesShort: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
	dayNamesMin: ['Su','Mo','Tu','We','Th','Fr','Sa'],
	weekHeader: 'Wk',
	dateFormat: 'dd/mm/yy',
	firstDay: 1,
	isRTL: false,
	showMonthAfterYear: false,
	yearSuffix: ''};
datepicker.setDefaults(datepicker.regional['en-GB']);

return datepicker.regional['en-GB'];

}));

{'repo_name': 'funtl/ssm-my-shop', 'stars': '181', 'repo_language': 'JavaScript', 'file_name': 'ConstantUtils.java', 'mime_type': 'text/plain', 'hash': -3321035204777838172, 'source_dataset': 'data'}


//app.js
App({
  globalData:{
    userInfo: null,
    apiUrl: "http://114.55.102.33:8081/api/"
  },
  getUserInfo:function(cb){
    var that = this
    if(this.globalData.userInfo) {
      typeof cb == "function" && cb(this.globalData.userInfo)
    } else {
      //调用登录接口
      wx.login({
        success: function () {
          wx.getUserInfo({
            success: function (res) {
              that.globalData.userInfo = res.userInfo
              typeof cb == "function" && cb(that.globalData.userInfo)
            }
          })
        }
      })
    }
  },
})

{'repo_name': 'ritaswc/wechat_app_template', 'stars': '185', 'repo_language': 'JavaScript', 'file_name': 'bson.js', 'mime_type': 'text/plain', 'hash': -6974257846857872221, 'source_dataset': 'data'}


//=============================================================================
//  MuseScore
//  Music Composition & Notation
//
//  Copyright (C) 2020 MuseScore BVBA and others
//
//  This program is free software; you can redistribute it and/or modify
//  it under the terms of the GNU General Public License version 2.
//
//  This program is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.
//
//  You should have received a copy of the GNU General Public License
//  along with this program; if not, write to the Free Software
//  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
//=============================================================================
#ifndef MU_EXTENSIONS_EXTENSIONSERRORS_H
#define MU_EXTENSIONS_EXTENSIONSERRORS_H

#include "ret.h"
#include "translation.h"

namespace mu {
namespace extensions {
enum class Err {
    Undefined       = int(Ret::Code::Undefined),
    NoError         = int(Ret::Code::Ok),
    UnknownError    = int(Ret::Code::ExtensionsFirst),

    ErrorParseConfig,
    ErrorLoadingExtension,
    ErrorExtensionNotFound,
    ErrorRemoveExtensionDirectory,

    UnpackDestinationReadOnly,
    UnpackNoFreeSpace,
    UnpackInvalidStructure,
    UnpackInvalidOldExtension,
    UnpackPreviousVersionExists,
    UnpackErrorRemovePreviousVersion,
    UnpackNoActualVersion,
    UnpackError
};

inline Ret make_ret(Err e)
{
    int retCode = static_cast<int>(e);

    switch (e) {
    case Err::Undefined: return Ret(retCode);
    case Err::NoError: return Ret(retCode);
    case Err::UnknownError: return Ret(retCode);
    case Err::ErrorParseConfig: return Ret(retCode, trc("extensions", "Error parsing response from server"));
    case Err::ErrorLoadingExtension: return Ret(retCode, trc("extensions", "Error loading extension"));
    case Err::ErrorExtensionNotFound: return Ret(retCode, trc("extensions", "Extension not found"));
    case Err::ErrorRemoveExtensionDirectory: return Ret(retCode, trc("extensions", "Error remove extension directory"));
    case Err::UnpackDestinationReadOnly: return Ret(retCode, trc("extensions", "Cannot import extension on read-only storage"));
    case Err::UnpackNoFreeSpace: return Ret(retCode, trc("extensions", "Cannot import extension on full storage"));
    case Err::UnpackInvalidStructure: return Ret(retCode, trc("extensions", "Invalid archive structure"));
    case Err::UnpackInvalidOldExtension: return Ret(retCode, trc("extensions", "Invalid old extension"));
    case Err::UnpackPreviousVersionExists: return Ret(retCode, trc("extensions", "Previous version of extension exists"));
    case Err::UnpackErrorRemovePreviousVersion: return Ret(retCode, trc("extensions", "Error removing previous version"));
    case Err::UnpackNoActualVersion: return Ret(retCode, trc("extensions", "A newer version is already installed"));
    case Err::UnpackError: return Ret(retCode, trc("extensions", "Error unpacking extension"));
    }

    return Ret(static_cast<int>(e));
}
}
}

#endif // MU_EXTENSIONS_EXTENSIONSERRORS_H

{'repo_name': 'musescore/MuseScore', 'stars': '4930', 'repo_language': 'C++', 'file_name': 'CMakeLists.txt', 'mime_type': 'text/plain', 'hash': -3525269514588989507, 'source_dataset': 'data'}


import React from 'react';
import { Command } from 'gg-editor';
import upperFirst from 'lodash/upperFirst';
import IconFont from '../../common/IconFont';
import styles from './index.less';

const MenuItem = (props) => {
  const { command, icon, text } = props;

  return (
    <Command name={command}>

        <IconFont type={`icon-${icon || command}`} />
        {text || upperFirst(command)}

    </Command>
  );
};

export default MenuItem;

{'repo_name': 'seata/seata', 'stars': '16500', 'repo_language': 'Java', 'file_name': 'DataBaseLockStoreDAOTest.java', 'mime_type': 'text/x-java', 'hash': -1158717070027372152, 'source_dataset': 'data'}


:m superclass

:browse superclass

:t (fromInteger 42 + zero)
:t (trunc (recip (fromInteger 5)))
:t (\x -> x < fromInteger (floor (recip x)))
:t (\x -> x == zero /. x)
:t (zero == ~zero)
:t (\x -> toInteger (x + zero))
:t (\x y -> x < y \/ x == y)

{'repo_name': 'GaloisInc/cryptol', 'stars': '883', 'repo_language': 'Haskell', 'file_name': 'SHA512.cry', 'mime_type': 'text/plain', 'hash': -669208438970472456, 'source_dataset': 'data'}


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

#ifndef NET_HTTP_HTTP_REQUEST_INFO_H__
#define NET_HTTP_HTTP_REQUEST_INFO_H__

#include <string>

#include "base/optional.h"
#include "net/base/net_export.h"
#include "net/base/network_isolation_key.h"
#include "net/base/privacy_mode.h"
#include "net/http/http_request_headers.h"
#include "net/socket/socket_tag.h"
#include "net/traffic_annotation/network_traffic_annotation.h"
#include "url/gurl.h"

namespace net {

class UploadDataStream;

struct NET_EXPORT HttpRequestInfo {
  HttpRequestInfo();
  HttpRequestInfo(const HttpRequestInfo& other);
  ~HttpRequestInfo();

  // The requested URL.
  GURL url;

  // The method to use (GET, POST, etc.).
  std::string method;

  // This key is used to isolate requests from different contexts in accessing
  // shared network resources like the cache.
  NetworkIsolationKey network_isolation_key;

  // Any extra request headers (including User-Agent).
  HttpRequestHeaders extra_headers;

  // Any upload data.
  UploadDataStream* upload_data_stream;

  // Any load flags (see load_flags.h).
  int load_flags;

  // If enabled, then request must be sent over connection that cannot be
  // tracked by the server (e.g. without channel id).
  PrivacyMode privacy_mode;

  // Whether secure DNS should be disabled for the request.
  bool disable_secure_dns;

  // Tag applied to all sockets used to service request.
  SocketTag socket_tag;

  // Network traffic annotation received from URL request.
  net::MutableNetworkTrafficAnnotationTag traffic_annotation;

  // Reporting upload nesting depth of this request.
  //
  // If the request is not a Reporting upload, the depth is 0.
  //
  // If the request is a Reporting upload, the depth is the max of the depth
  // of the requests reported within it plus 1.
  int reporting_upload_depth;
};

}  // namespace net

#endif  // NET_HTTP_HTTP_REQUEST_INFO_H__

{'repo_name': 'klzgrad/naiveproxy', 'stars': '737', 'repo_language': 'C++', 'file_name': 'f123c08d0a46b72fa8989296e82e7aa25ebf16f8', 'mime_type': 'text/plain', 'hash': 6653485987420053958, 'source_dataset': 'data'}


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

  <title>Docs for page SimpleEventDispatcher.php</title>
  <link rel="stylesheet" href="../../media/stylesheet.css" />

<link id="webfx-tab-style-sheet" type="text/css" rel="stylesheet" href="../../media/lib/tab.webfx.css" />

File: /vendors/swiftMailer/classes/Swift/Events/SimpleEventDispatcher.php

Description

Classes defined in this file

CLASS NAME

DESCRIPTION

			Swift_Events_SimpleEventDispatcher
			The EventDispatcher which handles the event dispatching layer.

Include/Require Statements

Global Variables

Constants

Functions

		Documentation generated on Fri, 12 Nov 2010 20:45:29 +0000 by phpDocumentor 1.4.3

{'repo_name': 'RosYama/RosYama.2', 'stars': '103', 'repo_language': 'HTML', 'file_name': 'index.php', 'mime_type': 'text/html', 'hash': 8210965888146339894, 'source_dataset': 'data'}


{'repo_name': 'linwh1115/react-native-cnodejs', 'stars': '124', 'repo_language': 'JavaScript', 'file_name': 'index.ios.js', 'mime_type': 'text/x-java', 'hash': -1385763395502989494, 'source_dataset': 'data'}


/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

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

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

#ifndef TENSORFLOW_GRAPH_SUBGRAPH_H_
#define TENSORFLOW_GRAPH_SUBGRAPH_H_

#include <string>

#include "tensorflow/core/framework/device_attributes.pb.h"
#include "tensorflow/core/graph/graph.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/lib/gtl/array_slice.h"

namespace tensorflow {
namespace subgraph {

// Rewrite the graph structure of "*g" to deal with feeding node
// outputs, fetching node outputs, and only running a subset of the
// graph.  "fed_outputs" and "fetch_outputs" are both lists of
// output tensor identifiers in the form of
// "<name>[:<optional_output_index>]", and "target_nodes_str" is a
// lists of target node names in "*g" "g".
//
// In the resulting graph "*g", output edges in "fed_outputs" have
// been redirected to special "_recv" nodes introduced into the graph.
// If these fed nodes are not needed in order to compute the effects
// of the nodes in "targets_nodes" and "fetch_outputs", then these may
// be omitted from the graph.
//
// In the resulting graph "*g", additional "_send" nodes are connected
// to every output in "fetch_outputs".  These "_send" nodes are set up
// to execute on the device described by device_info.
//
// On success, returns OK, and sets "*g" to a version of "*g"
// that represents the portions of the graph necessary for producing
// the output of all nodes listed in "target_node_names" and fetching the
// specific node outputs specified in "fetch_outputs".
//
// On failure, returns the error status. Possible errors include:
//    - fed output "node:output_index" does not exist in "*g"
//    - fetch output "node:output_index" does not exist in "*g"
//    - target node "node" does not exist in "*g"
Status RewriteGraphForExecution(
    Graph* g, const gtl::ArraySlice<string>& fed_outputs,
    const gtl::ArraySlice<string>& fetch_outputs,
    const gtl::ArraySlice<string>& target_node_names,
    const DeviceAttributes& device_info);

typedef std::unordered_map<StringPiece, Node*, StringPiece::Hasher> NameIndex;

// Augment "*g" by adding special "fetch" nodes that connect to the
// tensor outputs specified in "fetch_outputs" to retrieve the output
// of the tensors.  The new nodes added are set up to execute on
// "client_device_name", and are returned in "*fetch_nodes".
//
// Return OK on success.  On error, return false and sets *error to
// an appropriate error message (and *g is left in an indeterminate
// state).
Status FetchOutputs(Graph* g, const DeviceAttributes& device_info,
                    const gtl::ArraySlice<string>& fetch_outputs,
                    NameIndex* name_index, std::vector<Node*>* fetch_nodes);

}  // namespace subgraph
}  // namespace tensorflow

#endif  // TENSORFLOW_GRAPH_SUBGRAPH_H_

{'repo_name': 'natanielruiz/android-yolo', 'stars': '574', 'repo_language': 'C++', 'file_name': 'workspace.xml', 'mime_type': 'text/xml', 'hash': -6865670467271853595, 'source_dataset': 'data'}


<!DOCTYPE html>

<title>Bug 1114329 testcase</title>

This text should appear BELOW the green and red blocks.

{'repo_name': 'mozilla/positron', 'stars': '514', 'repo_language': 'None', 'file_name': 'moz.build', 'mime_type': 'text/plain', 'hash': 6125274305813132725, 'source_dataset': 'data'}