text:
package mqtt

import (
	"bytes"
	"testing"

	"github.com/dataence/assert"
)

func TestConnackMessageFields(t *testing.T) {
	msg := NewConnackMessage()

	msg.SetSessionPresent(true)
	assert.True(t, true, msg.SessionPresent(), "Error setting session present flag.")

	msg.SetSessionPresent(false)
	assert.False(t, true, msg.SessionPresent(), "Error setting session present flag.")

	msg.SetReturnCode(ConnectionAccepted)
	assert.Equal(t, true, ConnectionAccepted, msg.ReturnCode(), "Error setting return code.")
}

func TestConnackMessageDecode(t *testing.T) {
	msgBytes := []byte{
		byte(CONNACK << 4),
		2,
		0, // session not present
		0, // connection accepted
	}

	src := bytes.NewBuffer(msgBytes)
	msg := NewConnackMessage()

	n, err := msg.Decode(src)
	assert.NoError(t, true, err, "Error decoding message.")

	assert.Equal(t, true, len(msgBytes), n, "Error decoding message.")

	assert.False(t, true, msg.SessionPresent(), "Error decoding session present flag.")

	assert.Equal(t, true, ConnectionAccepted, msg.ReturnCode(), "Error decoding return code.")
}

// testing wrong message length
func TestConnackMessageDecode2(t *testing.T) {
	msgBytes := []byte{
		byte(CONNACK << 4),
		3,
		0, // session not present
		0, // connection accepted
	}

	src := bytes.NewBuffer(msgBytes)
	msg := NewConnackMessage()

	_, err := msg.Decode(src)
	assert.Error(t, true, err, "Error decoding message.")
}

// testing wrong message size
func TestConnackMessageDecode3(t *testing.T) {
	msgBytes := []byte{
		byte(CONNACK << 4),
		2,
		0, // session not present
	}

	src := bytes.NewBuffer(msgBytes)
	msg := NewConnackMessage()

	_, err := msg.Decode(src)
	assert.Error(t, true, err, "Error decoding message.")
}

// testing wrong reserve bits
func TestConnackMessageDecode4(t *testing.T) {
	msgBytes := []byte{
		byte(CONNACK << 4),
		2,
		64, // <- wrong size
		0,  // connection accepted
	}

	src := bytes.NewBuffer(msgBytes)
	msg := NewConnackMessage()

	_, err := msg.Decode(src)
	assert.Error(t, true, err, "Error decoding message.")
}

// testing invalid return code
func TestConnackMessageDecode5(t *testing.T) {
	msgBytes := []byte{
		byte(CONNACK << 4),
		2,
		0,
		6, // <- wrong code
	}

	src := bytes.NewBuffer(msgBytes)
	msg := NewConnackMessage()

	_, err := msg.Decode(src)
	assert.Error(t, true, err, "Error decoding message.")
}

func TestConnackMessageEncode(t *testing.T) {
	msgBytes := []byte{
		byte(CONNACK << 4),
		2,
		1, // session present
		0, // connection accepted
	}

	msg := NewConnackMessage()
	msg.SetReturnCode(ConnectionAccepted)
	msg.SetSessionPresent(true)

	dst, n, err := msg.Encode()
	assert.NoError(t, true, err, "Error decoding message.")

	assert.Equal(t, true, len(msgBytes), n, "Error encoding message.")

	assert.Equal(t, true, msgBytes, dst.(*bytes.Buffer).Bytes(), "Error encoding connack message.")
}


text:
package com.hazelcast.config;

import com.hazelcast.internal.eviction.EvictionConfiguration;
import com.hazelcast.internal.eviction.EvictionPolicyComparator;
import com.hazelcast.internal.eviction.EvictionPolicyType;
import com.hazelcast.internal.eviction.EvictionStrategyType;
import com.hazelcast.nio.ObjectDataInput;
import com.hazelcast.nio.ObjectDataOutput;
import com.hazelcast.nio.serialization.DataSerializable;
import com.hazelcast.nio.serialization.BinaryInterface;

import java.io.IOException;
import java.io.Serializable;

import static com.hazelcast.util.Preconditions.checkNotNull;
import static com.hazelcast.util.Preconditions.checkPositive;

/**
 * Configuration for eviction.
 * You can set a limit for number of entries or total memory cost of entries.
 *

 * The default values of the eviction configuration are
 *

 *
{@link EvictionPolicy#LRU} as eviction policy

 *
{@link EvictionConfig.MaxSizePolicy#ENTRY_COUNT} as max size policy

 *
{@value DEFAULT_MAX_ENTRY_COUNT_FOR_ON_HEAP_MAP} as maximum size for on-heap {@link com.hazelcast.core.IMap}

 *
{@value DEFAULT_MAX_ENTRY_COUNT} as maximum size for all other data structures and configurations

 *

 */
@BinaryInterface
public class EvictionConfig implements EvictionConfiguration, DataSerializable, Serializable {

    /**
     * Default maximum entry count.
     */
    public static final int DEFAULT_MAX_ENTRY_COUNT = 10000;

    /**
     * Default maximum entry count for Map on-heap Near Caches.
     */
    public static final int DEFAULT_MAX_ENTRY_COUNT_FOR_ON_HEAP_MAP = Integer.MAX_VALUE;

    /**
     * Default Max-Size Policy.
     */
    public static final MaxSizePolicy DEFAULT_MAX_SIZE_POLICY = MaxSizePolicy.ENTRY_COUNT;

    /**
     * Default Eviction Policy.
     */
    public static final EvictionPolicy DEFAULT_EVICTION_POLICY = EvictionPolicy.LRU;

    /**
     * Maximum Size Policy
     */
    public enum MaxSizePolicy {
        /**
         * Policy based on maximum number of entries stored per data structure (map, cache etc)
         */
        ENTRY_COUNT,
        /**
         * Policy based on maximum used native memory in megabytes per data structure (map, cache etc)
         * on each Hazelcast instance
         */
        USED_NATIVE_MEMORY_SIZE,
        /**
         * Policy based on maximum used native memory percentage per data structure (map, cache etc)
         * on each Hazelcast instance
         */
        USED_NATIVE_MEMORY_PERCENTAGE,
        /**
         * Policy based on minimum free native memory in megabytes per Hazelcast instance
         */
        FREE_NATIVE_MEMORY_SIZE,
        /**
         * Policy based on minimum free native memory percentage per Hazelcast instance
         */
        FREE_NATIVE_MEMORY_PERCENTAGE
    }

    protected int size = DEFAULT_MAX_ENTRY_COUNT;
    protected MaxSizePolicy maxSizePolicy = DEFAULT_MAX_SIZE_POLICY;
    protected EvictionPolicy evictionPolicy = DEFAULT_EVICTION_POLICY;
    protected String comparatorClassName;
    protected EvictionPolicyComparator comparator;

    protected EvictionConfig readOnly;

    /**
     * Used by the {@link NearCacheConfigAccessor} to initialize the proper default value for on-heap maps.
     */
    boolean sizeConfigured;

    public EvictionConfig() {
    }

    public EvictionConfig(int size, MaxSizePolicy maxSizePolicy, EvictionPolicy evictionPolicy) {
        this.sizeConfigured = true;
        this.size = checkPositive(size, "Size must be positive number!");
        this.maxSizePolicy = checkNotNull(maxSizePolicy, "Max-Size policy cannot be null!");
        this.evictionPolicy = checkNotNull(evictionPolicy, "Eviction policy cannot be null!");
    }

    public EvictionConfig(int size, MaxSizePolicy maxSizePolicy, String comparatorClassName) {
        this.sizeConfigured = true;
        this.size = checkPositive(size, "Size must be positive number!");
        this.maxSizePolicy = checkNotNull(maxSizePolicy, "Max-Size policy cannot be null!");
        this.comparatorClassName = checkNotNull(comparatorClassName, "Comparator classname cannot be null!");
    }

    public EvictionConfig(int size, MaxSizePolicy maxSizePolicy, EvictionPolicyComparator comparator) {
        this.sizeConfigured = true;
        this.size = checkPositive(size, "Size must be positive number!");
        this.maxSizePolicy = checkNotNull(maxSizePolicy, "Max-Size policy cannot be null!");
        this.comparator = checkNotNull(comparator, "Comparator cannot be null!");
    }

    public EvictionConfig(EvictionConfig config) {
        this.sizeConfigured = true;
        this.size = checkPositive(config.size, "Size must be positive number!");
        this.maxSizePolicy = checkNotNull(config.maxSizePolicy, "Max-Size policy cannot be null!");
        if (config.evictionPolicy != null) {
            this.evictionPolicy = config.evictionPolicy;
        }
        // Eviction policy comparator class name is not allowed to be null
        if (config.comparatorClassName != null) {
            this.comparatorClassName = config.comparatorClassName;
        }
        // Eviction policy comparator is not allowed to be null
        if (config.comparator != null) {
            this.comparator = config.comparator;
        }
    }

    /**
     * Gets immutable version of this configuration.
     *
     * @return immutable version of this configuration
     * @deprecated this method will be removed in 4.0; it is meant for internal usage only
     */
    public EvictionConfig getAsReadOnly() {
        if (readOnly == null) {
            readOnly = new EvictionConfigReadOnly(this);
        }
        return readOnly;
    }

    /**
     * Returns the size which is used by the {@link MaxSizePolicy}.
     *

     * The interpretation of the value depends on the configured {@link MaxSizePolicy}.
     *
     * @return the size which is used by the {@link MaxSizePolicy}
     */
    public int getSize() {
        return size;
    }

    /**
     * Sets the size which is used by the {@link MaxSizePolicy}.
     *

     * The interpretation of the value depends on the configured {@link MaxSizePolicy}.
     *

     * Accepts any positive number. The default value is {@value #DEFAULT_MAX_ENTRY_COUNT}.
     *
     * @param size the size which is used by the {@link MaxSizePolicy}
     * @return this EvictionConfig instance
     */
    public EvictionConfig setSize(int size) {
        this.sizeConfigured = true;
        this.size = checkPositive(size, "size must be positive number!");
        return this;
    }

    /**
     * Returns the {@link MaxSizePolicy} of this eviction configuration.
     *
     * @return the {@link MaxSizePolicy} of this eviction configuration
     */
    public MaxSizePolicy getMaximumSizePolicy() {
        return maxSizePolicy;
    }

    /**
     * Sets the {@link MaxSizePolicy} of this eviction configuration.
     *
     * @param maxSizePolicy the {@link MaxSizePolicy} of this eviction configuration
     * @return this EvictionConfig instance
     */
    public EvictionConfig setMaximumSizePolicy(MaxSizePolicy maxSizePolicy) {
        this.maxSizePolicy = checkNotNull(maxSizePolicy, "maxSizePolicy cannot be null!");
        return this;
    }

    /**
     * Returns the {@link EvictionPolicy} of this eviction configuration.
     *
     * @return the {@link EvictionPolicy} of this eviction configuration
     */
    @Override
    public EvictionPolicy getEvictionPolicy() {
        return evictionPolicy;
    }

    /**
     * Sets the {@link EvictionPolicy} of this eviction configuration.
     *
     * @param evictionPolicy the {@link EvictionPolicy} of this eviction configuration
     * @return this EvictionConfig instance
     */
    public EvictionConfig setEvictionPolicy(EvictionPolicy evictionPolicy) {
        this.evictionPolicy = checkNotNull(evictionPolicy, "Eviction policy cannot be null!");
        return this;
    }

    /**
     * Returns the {@link EvictionStrategyType} of this eviction configuration.
     *
     * @return the {@link EvictionStrategyType} of this eviction configuration
     */
    @Override
    public EvictionStrategyType getEvictionStrategyType() {
        return EvictionStrategyType.DEFAULT_EVICTION_STRATEGY;
    }

    /**
     * Returns the {@link EvictionPolicyType} of this eviction configuration.
     *
     * @return the {@link EvictionPolicyType} of this eviction configuration
     * @deprecated since 3.9, please use {@link #getEvictionPolicy()}
     */
    @Deprecated
    public EvictionPolicyType getEvictionPolicyType() {
        switch (evictionPolicy) {
            case LFU:
                return EvictionPolicyType.LFU;
            case LRU:
                return EvictionPolicyType.LRU;
            case RANDOM:
                return EvictionPolicyType.RANDOM;
            case NONE:
                return EvictionPolicyType.NONE;
            default:
                return null;
        }
    }

    /**
     * Returns the class name of the configured {@link EvictionPolicyComparator} implementation.
     *
     * @return the class name of the configured {@link EvictionPolicyComparator} implementation
     */
    @Override
    public String getComparatorClassName() {
        return comparatorClassName;
    }

    /**
     * Sets the class name of the configured {@link EvictionPolicyComparator} implementation.
     *

     * Only one of the {@code comparator class name} and {@code comparator} can be configured in the eviction configuration.
     *
     * @param comparatorClassName the class name of the configured {@link EvictionPolicyComparator} implementation
     * @return this EvictionConfig instance
     */
    public EvictionConfig setComparatorClassName(String comparatorClassName) {
        this.comparatorClassName = checkNotNull(comparatorClassName, "Eviction policy comparator class name cannot be null!");
        return this;
    }

    /**
     * Returns the instance of the configured {@link EvictionPolicyComparator} implementation.
     *
     * @return the instance of the configured {@link EvictionPolicyComparator} implementation
     */
    @Override
    public EvictionPolicyComparator getComparator() {
        return comparator;
    }

    /**
     * Sets the instance of the configured {@link EvictionPolicyComparator} implementation.
     *

     * Only one of the {@code comparator class name} and {@code comparator} can be configured in the eviction configuration.
     *
     * @param comparator the instance of the configured {@link EvictionPolicyComparator} implementation
     * @return this EvictionConfig instance
     */
    public EvictionConfig setComparator(EvictionPolicyComparator comparator) {
        this.comparator = checkNotNull(comparator, "Eviction policy comparator cannot be null!");
        return this;
    }

    @Override
    public void writeData(ObjectDataOutput out) throws IOException {
        out.writeInt(size);
        out.writeUTF(maxSizePolicy.toString());
        out.writeUTF(evictionPolicy.toString());
        out.writeUTF(comparatorClassName);
        out.writeObject(comparator);
    }

    @Override
    public void readData(ObjectDataInput in) throws IOException {
        size = in.readInt();
        maxSizePolicy = MaxSizePolicy.valueOf(in.readUTF());
        evictionPolicy = EvictionPolicy.valueOf(in.readUTF());
        comparatorClassName = in.readUTF();
        comparator = in.readObject();
    }

    @Override
    public String toString() {
        return "EvictionConfig{"
                + "size=" + size
                + ", maxSizePolicy=" + maxSizePolicy
                + ", evictionPolicy=" + evictionPolicy
                + ", comparatorClassName=" + comparatorClassName
                + ", comparator=" + comparator
                + '}';
    }

    @Override
    @SuppressWarnings({"checkstyle:cyclomaticcomplexity", "checkstyle:npathcomplexity"})
    public final boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (!(o instanceof EvictionConfig)) {
            return false;
        }

        EvictionConfig that = (EvictionConfig) o;

        if (size != that.size) {
            return false;
        }
        if (maxSizePolicy != that.maxSizePolicy) {
            return false;
        }
        if (evictionPolicy != that.evictionPolicy) {
            return false;
        }
        if (comparatorClassName != null
                ? !comparatorClassName.equals(that.comparatorClassName) : that.comparatorClassName != null) {
            return false;
        }
        return comparator != null ? comparator.equals(that.comparator) : that.comparator == null;
    }

    @Override
    public final int hashCode() {
        int result = size;
        result = 31 * result + (maxSizePolicy != null ? maxSizePolicy.hashCode() : 0);
        result = 31 * result + (evictionPolicy != null ? evictionPolicy.hashCode() : 0);
        result = 31 * result + (comparatorClassName != null ? comparatorClassName.hashCode() : 0);
        result = 31 * result + (comparator != null ? comparator.hashCode() : 0);
        return result;
    }
}

redpajama_set_name: RedPajamaGithub


text:
var config = require('./config.json');
var mysql = require('mysql');
var App = require('./lib/app');
//
// MySQL connection pool
//
exports.DbConnection = mysql.createPool(config.db_conn);

//
// Environments
//
exports.Env = {
	// main || duplicate
	"mode" : "main"
}

//
// Application Instance
//
var app_;
exports.getApp = function (){
	if (!app_){
		app_ = new App(exports.Env);

		// initialize and hook process.exit events
		app_.init();
	}

	return app_;
}


text:
/**
 *
 * @example
        $('.ui-pages').pages({
            total : 50, // 总记录数
            size: 2, // 每页显示记录数
            index : 26, // 当前页
            url : '#!{page}', // 非ajax情况下分类的链接地址
            // 点击分页时的回调,返回被点击的页数
            click : function(e){
                console.log(e);
            }
        });
 */
;(function($){
    var defaults = {
        'total': 100, // 条目总数,异步分页时必填,模拟分页时为数组的长度
        'size': 10, // 每页的条目数
        'index': 1,// 初始化时选定的页数
        'cls' : '', // 分页容器ul上面的出class名
        'input': false,//页码跳转输入框
        'button': false,//页码跳转按钮
        'range': 2, // 可见的页码范围,即当前页码两边的页码数量。比如当前是第 6 页,设置 pageRange 为 2,则页码条显示为 '1... 4 5 6 7 8'
        'handle': '.pagination-handle' , // 加载分页的容器
        'click' : null, // 点击分页后事件绑定
        'container': '.pagination-container', // 存放分页数据内容的容器
        'url' : null // 分页按钮的链接
    };
    var methods = {
        init : function(){},
        data: function(len){
            if(len <= 0 ){
                return [];
            }
            return new Array(len || 100);
        },
        template: function(str){}
    };

    $.fn.pages = function(options){
        if(options && options.total <= 1){
            return this;
        }
        return this.each(function(){
            var that = $(this);

            if(typeof options == 'number'){
                that.pagination(options);
                return that;
            }
            var settings = $.extend({}, defaults, options);
            settings.handle = that;
            var _opt = {
                dataSource: methods.data(settings.total),
                totalNumber: settings.total,   // 条目总数,异步分页时必填,模拟分页时为数组的长度
                pageNumber: settings.index,  // 指定初始化时加载哪一页的数据
                pageSize: settings.size, // 每页的条目数
                showGoInput:settings.input,
                showGoButton:settings.button,
                pageRange: settings.range, // 可见的页码范围,即当前页码两边的页码数量。比如当前是第 6 页,设置 pageRange 为 2,则页码条显示为 '1... 4 5 6 7 8'
                ulClassName: 'pagination ' + settings.cls,
                callback: function(data, pagination){
                    try{
                        settings.callback(pagination);
                    }catch(e){}
                }
            };
            if(typeof settings.click == 'function'){
                _opt.afterPageOnClick = _opt.afterNextOnClick = _opt.afterPreviousOnClick = function(){
                    settings.click(settings.handle.pagination('getSelectedPageNum'));
                };
                _opt.pageLink  = '#';
            }
            if(settings.url){
                _opt.pageLink  = settings.url;
            }

//            that.pagination('destroy').pagination(_opt);
              that.pagination(_opt);

            return that;
        });
//        var settings = $.extend({}, defaults, options);
//
//        settings.handle = this;
//        var _opt = {
//            dataSource: methods.data(settings.total),
//            totalNumber: settings.total,   // 条目总数,异步分页时必填,模拟分页时为数组的长度
//            pageNumber: settings.index,  // 指定初始化时加载哪一页的数据
//            pageSize: settings.size, // 每页的条目数
//            pageRange: settings.range, // 可见的页码范围,即当前页码两边的页码数量。比如当前是第 6 页,设置 pageRange 为 2,则页码条显示为 '1... 4 5 6 7 8'
//            ulClassName: 'pagination ' + settings.cls,
//            callback: function(data, pagination){
//                try{
//                    settings.callback(pagination);
//                }catch(e){}
//            }
//        };
//        if(typeof settings.click == 'function'){
//            _opt.afterPageOnClick = _opt.afterNextOnClick = _opt.afterPreviousOnClick = function(){
//                settings.click(settings.handle.pagination('getSelectedPageNum'));
//            };
//        }
//        if(settings.url){
//            _opt.pageLink  = settings.url;
//        }
//
//        this.pagination(_opt);
//
//        return this;
    };

})(jQuery);

/*
 * pagination.js 2.0.7
 *
 * Released under the MIT license.
 */

(function(global, $) {

    if (typeof $ === 'undefined') {
        throwError('Pagination requires jQuery.');
    }

    var pluginName = 'pagination';

    var pluginHookMethod = 'addHook';

    var eventPrefix = '__pagination-';

    // Conflict, use backup
    if ($.fn.pagination) {
        pluginName = 'pagination2';
    }

    $.fn[pluginName] = function(options) {

        if (typeof options === 'undefined') {
            return this;
        }

        var container = $(this);

        var pagination = {

            initialize: function() {
                var self = this;

                // 保存当前实例的属性
                if (!container.data('pagination')) {
                    container.data('pagination', {});
                }

                // 初始化之前
                if (self.callHook('beforeInit') === false) return;

                // 如果分页已经初始化,摧毁它
                if (container.data('pagination').initialized) {
                    $('.paginationjs', container).remove();
                }

                // 初始化是否禁用分页
                self.disabled = !!attributes.disabled;

                // 传递给回调函数
                var model = self.model = {
                    pageRange: attributes.pageRange,
                    pageSize: attributes.pageSize
                };

                // "dataSource"的类型是未知的,解析它找到真正的数据
                self.parseDataSource(attributes.dataSource, function(dataSource) {

                    // 分页是否同步模式
                    self.sync = Helpers.isArray(dataSource);
                    if (self.sync) {
                        model.totalNumber = attributes.totalNumber = dataSource.length;
                    }

                    // 获取页面的总数
                    model.totalPage = self.getTotalPage();

                    // 不到一页
                    if (attributes.hideWhenLessThanOnePage) {
                        if (model.totalPage <= 1) return;
                    }

                    var el = self.render(true);

                    // 额外的类名
                    if (attributes.className) {
                        el.addClass(attributes.className);
                    }

                    model.el = el;

                    // 加载模板
                    container[attributes.position === 'bottom' ? 'append' : 'prepend'](el);

                    // 绑定事件
                    self.observer();

                    // 初始化标志
                    container.data('pagination').initialized = true;

                    // 初始化之后
                    self.callHook('afterInit', el);

                });

            },

            render: function(isBoot) {

                var self = this;
                var model = self.model;
                var el = model.el || $('

');
                var isForced = isBoot !== true;

                // 渲染之前
                self.callHook('beforeRender', isForced);

                var currentPage = model.pageNumber || attributes.pageNumber;
                var pageRange = attributes.pageRange;
                var totalPage = model.totalPage;

                var rangeStart = currentPage - pageRange;
                var rangeEnd = currentPage + pageRange;

                if (rangeEnd > totalPage) {
                    rangeEnd = totalPage;
                    rangeStart = totalPage - pageRange * 2;
                    rangeStart = rangeStart < 1 ? 1 : rangeStart;
                }

                if (rangeStart <= 1) {
                    rangeStart = 1;

                    rangeEnd = Math.min(pageRange * 2 + 1, totalPage);
                }

                el.html(self.createTemplate({
                    currentPage: currentPage,
                    pageRange: pageRange,
                    totalPage: totalPage,
                    rangeStart: rangeStart,
                    rangeEnd: rangeEnd
                }));

                // 渲染之后
                self.callHook('afterRender', isForced);

                return el;
            },

            // 创建模板
            createTemplate: function(args) {

                var self = this;
                var currentPage = args.currentPage;
                var totalPage = args.totalPage;
                var rangeStart = args.rangeStart;
                var rangeEnd = args.rangeEnd;

                var totalNumber = attributes.totalNumber;

                var showPrevious = attributes.showPrevious;
                var showNext = attributes.showNext;
                var showPageNumbers = attributes.showPageNumbers;
                var showNavigator = attributes.showNavigator;
                var showGoInput = attributes.showGoInput;
                var showGoButton = attributes.showGoButton;

                var pageLink = attributes.pageLink;
                var prevText = attributes.prevText;
                var nextText = attributes.nextText;
                var ellipsisText = attributes.ellipsisText;
                var goButtonText = attributes.goButtonText;

                var classPrefix = attributes.classPrefix;
                var activeClassName = attributes.activeClassName;
                var disableClassName = attributes.disableClassName;
                var ulClassName = attributes.ulClassName;

                var formatNavigator = $.isFunction(attributes.formatNavigator) ? attributes.formatNavigator() : attributes.formatNavigator;
                var formatGoInput = $.isFunction(attributes.formatGoInput) ? attributes.formatGoInput() : attributes.formatGoInput;
                var formatGoButton = $.isFunction(attributes.formatGoButton) ? attributes.formatGoButton() : attributes.formatGoButton;

                var autoHidePrevious = $.isFunction(attributes.autoHidePrevious) ? attributes.autoHidePrevious() : attributes.autoHidePrevious;
                var autoHideNext = $.isFunction(attributes.autoHideNext) ? attributes.autoHideNext() : attributes.autoHideNext;

                var header = $.isFunction(attributes.header) ? attributes.header() : attributes.header;
                var footer = $.isFunction(attributes.footer) ? attributes.footer() : attributes.footer;

                var html = '';
                var goInput = '<input type="text" class="J-paginationjs-go-pagenumber">';
                var goButton = '<input type="button" class="J-paginationjs-go-button" value="'+ goButtonText +'">';
                var formattedString;
                var i, pageUrl;

                if (header) {

                    formattedString = self.replaceVariables(header, {
                        currentPage: currentPage,
                        totalPage: totalPage,
                        totalNumber: totalNumber
                    });

                    html += formattedString;
                }

                if (showPrevious || showPageNumbers || showNext) {

                    html += '
';

                    if (ulClassName) {
                        html += '
';
                    }
                    else{
                        html += '
';
                    }

                    // 上一页按钮
                    if (showPrevious) {
                        if (currentPage === 1) {
                            if (!autoHidePrevious) {
                                html += '
'+ prevText +'<\/a><\/li>';
                            }
                        }
                        else{
                            pageUrl = pageLink.replace('{page}', (currentPage - 1));
                            html += '
'+ prevText +'<\/a><\/li>';
                        }
                    }

                    // 页码
                    if (showPageNumbers) {
                        if (rangeStart <= 3) {
                            for(i = 1; i < rangeStart; i++) {
                                if (i == currentPage) {
                                    html += '
'+ i +'<\/a><\/li>';
                                }
                                else{
                                    pageUrl = pageLink.replace('{page}', i);
                                    html += '
'+ i +'<\/a><\/li>';
                                }
                            }
                        }
                        else{
                            if (attributes.showFirstOnEllipsisShow) {
                                pageUrl = pageLink.replace('{page}', 1);
                                html += '
1<\/a><\/li>';
                            }

                            html += '
'+ ellipsisText +'<\/a><\/li>';
                        }

                        // 主循环
                        for(i = rangeStart; i <= rangeEnd; i++) {
                            if (i == currentPage) {
                                html += '
'+ i +'<\/a><\/li>';
                            }
                            else{
                                pageUrl = pageLink.replace('{page}', i);
                                html += '
'+ i +'<\/a><\/li>';
                            }
                        }

                        if (rangeEnd >= totalPage - 2) {
                            for(i = rangeEnd + 1; i <= totalPage; i++) {
                                pageUrl = pageLink.replace('{page}', i);
                                html += '
'+ i +'<\/a><\/li>';
                            }
                        }
                        else{
                            html += '
'+ ellipsisText +'<\/a><\/li>';

                            if (attributes.showLastOnEllipsisShow) {
                                pageUrl = pageLink.replace('{page}', totalPage);
                                html += '
'+ totalPage +'<\/a><\/li>';
                            }
                        }
                    }

                    // 下一页按钮
                    if (showNext) {
                        if (currentPage == totalPage) {
                            if (!autoHideNext) {
                                html += '
'+ nextText +'<\/a><\/li>';
                            }
                        }
                        else{
                            pageUrl = pageLink.replace('{page}', (currentPage + 1));
                            html += '
'+ nextText +'<\/a><\/li>';
                        }
                    }

                    html += '<\/ul><\/div>';

                }

                // 导航条
                if (showNavigator) {

                    if (formatNavigator) {

                        formattedString = self.replaceVariables(formatNavigator, {
                            currentPage: currentPage,
                            totalPage: totalPage,
                            totalNumber: totalNumber
                        });

                        html += '
'+ formattedString +'<\/div>';
                    }
                }

                // 跳转输入框
                if (showGoInput) {

                    if (formatGoInput) {

                        formattedString = self.replaceVariables(formatGoInput, {
                            currentPage: currentPage,
                            totalPage: totalPage,
                            totalNumber: totalNumber,
                            input: goInput
                        });

                        html += '
'+ formattedString +'
';
                    }
                }

                // 跳转按钮
                if (showGoButton) {

                    if (formatGoButton) {

                        formattedString = self.replaceVariables(formatGoButton, {
                            currentPage: currentPage,
                            totalPage: totalPage,
                            totalNumber: totalNumber,
                            button: goButton
                        });

                        html += '
'+ formattedString +'
';
                    }
                }

                if (footer) {

                    formattedString = self.replaceVariables(footer, {
                        currentPage: currentPage,
                        totalPage: totalPage,
                        totalNumber: totalNumber
                    });

                    html += formattedString;
                }

                return html;
            },

            // 跳转到指定的页面
            go: function(number, callback) {

                var self = this;
                var model = self.model;

                if (self.disabled) return;

                var pageNumber = number;
                var pageSize = attributes.pageSize;
                var totalPage = model.totalPage;

                pageNumber = parseInt(pageNumber);

                // 页码范围
                if (!pageNumber || pageNumber < 1 || pageNumber > totalPage) return;

                // 同步模式
                if (self.sync) {
                    render(self.getDataSegment(pageNumber));
                    return;
                }

                var postData = {};
                var alias = attributes.alias || {};

                postData[alias.pageSize ? alias.pageSize : 'pageSize'] = pageSize;
                postData[alias.pageNumber ? alias.pageNumber : 'pageNumber'] = pageNumber;

                var formatAjaxParams = {
                    type: 'get',
                    cache: false,
                    data: {},
                    contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
                    dataType: 'json',
                    async: true
                };

                $.extend(true, formatAjaxParams, attributes.ajax);
                $.extend(formatAjaxParams.data || {}, postData);

                formatAjaxParams.url = attributes.dataSource;
                formatAjaxParams.success = function(response) {
                    render(self.filterDataByLocator(response));
                };
                formatAjaxParams.error = function(jqXHR, textStatus, errorThrown) {
                    attributes.formatAjaxError && attributes.formatAjaxError(jqXHR, textStatus, errorThrown);
                    self.enable();
                };

                self.disable();

                $.ajax(formatAjaxParams);

                function render(data) {

                    // 分页之前
                    if (self.callHook('beforePaging', pageNumber) === false) return false;

                    // Pagination direction
                    model.direction = typeof model.pageNumber === 'undefined' ? 0 : (pageNumber > model.pageNumber ? 1 : -1);

                    model.pageNumber = pageNumber;

                    self.render();

                    if (self.disabled && !self.sync) {
                        // enable
                        self.enable();
                    }

                    // 缓存模型数据
                    container.data('pagination').model = model;

                    // 格式结果之前执行的回调函数
                    if ($.isFunction(attributes.formatResult)) {
                        var cloneData = $.extend(true, [], data);
                        if (!Helpers.isArray(data = attributes.formatResult(cloneData))) {
                            data = cloneData;
                        }
                    }

                    container.data('pagination').currentPageData = data;

                    // callback
                    self.doCallback(data, callback);

                    // 分页之后
                    self.callHook('afterPaging', pageNumber);

                    // 已经是第一页
                    if (pageNumber == 1) {
                        self.callHook('afterIsFirstPage');
                    }

                    // 已经是最后一页
                    if (pageNumber == model.totalPage) {
                        self.callHook('afterIsLastPage');
                    }

                }
            },

            doCallback: function(data, customCallback) {
                var self = this;
                var model = self.model;

                if ($.isFunction(customCallback)) {
                    customCallback(data, model);
                }
                else if ($.isFunction(attributes.callback)) {
                    attributes.callback(data, model);
                }
            },

            destroy: function() {

                // 销毁之前
                if (this.callHook('beforeDestroy') === false) return;

                this.model.el.remove();
                container.off();

                // 删除样式元素
                $('#paginationjs-style').remove();

                // 销毁之后
                this.callHook('afterDestroy');
            },

            previous: function(callback) {
                this.go(this.model.pageNumber - 1, callback);
            },

            next: function(callback) {
                this.go(this.model.pageNumber + 1, callback);
            },

            disable: function() {
                var self = this;
                var source = self.sync ? 'sync' : 'async';

                // 禁用之前
                if (self.callHook('beforeDisable', source) === false) return;

                self.disabled = true;
                self.model.disabled = true;

                // 禁用之后
                self.callHook('afterDisable', source);
            },

            enable: function() {
                var self = this;
                var source = self.sync ? 'sync' : 'async';

                // 启用之前
                if (self.callHook('beforeEnable', source) === false) return;

                self.disabled = false;
                self.model.disabled = false;

                // 启用之后
                self.callHook('afterEnable', source);
            },

            refresh: function(callback) {
                this.go(this.model.pageNumber, callback);
            },

            show: function() {
                var self = this;

                if (self.model.el.is(':visible')) return;

                self.model.el.show();
            },

            hide: function() {
                var self = this;

                if (!self.model.el.is(':visible')) return;

                self.model.el.hide();
            },

            // 替换变量的模板
            replaceVariables: function(template, variables) {

                var formattedString;

                for(var key in variables) {
                    var value = variables[key];
                    var regexp = new RegExp('<%=\\s*'+ key +'\\s*%>', 'img');

                    formattedString = (formattedString || template).replace(regexp, value);
                }

                return formattedString;
            },
            // 替换pageLink中的页面
            replacePageLink : function(template, variables){
                var formattedString;

                for(var key in variables) {
                    var value = variables[key];
                    var regexp = new RegExp('{'+ key +'}', 'img');

                    formattedString = (formattedString || template).replace(regexp, value);
                }

                return formattedString;
            },

            // 获取数据段
            getDataSegment: function(number) {
                var pageSize = attributes.pageSize;
                var dataSource = attributes.dataSource;
                var totalNumber = attributes.totalNumber;

                var start = pageSize * (number - 1) + 1;
                var end = Math.min(number * pageSize, totalNumber);

                return dataSource.slice(start - 1, end);
            },

            // 获取总页数
            getTotalPage: function() {
                return Math.ceil(attributes.totalNumber / attributes.pageSize);
            },

            // 获取数据定位
            getLocator: function(locator) {
                var result;

                if (typeof locator === 'string') {
                    result = locator;
                }
                else if ($.isFunction(locator)) {
                    result = locator();
                }
                else{
                    throwError('"locator" is incorrect. (String | Function)');
                }

                return result;
            },

            // 通过 "locator" 过滤数据
            filterDataByLocator: function(dataSource) {

                var locator = this.getLocator(attributes.locator);
                var filteredData;

                // dataSource 是一个对象,使用 "locator" 来定位真正的数据
                if (Helpers.isObject(dataSource)) {
                    try{
                        $.each(locator.split('.'), function(index, item) {
                            filteredData = (filteredData ? filteredData : dataSource)[item];
                        });
                    }
                    catch(e) {}

                    if (!filteredData) {
                        throwError('dataSource.'+ locator +' is undefined.');
                    }
                    else if (!Helpers.isArray(filteredData)) {
                        throwError('dataSource.'+ locator +' must be an Array.');
                    }
                }

                return filteredData || dataSource;
            },

            // 解析 dataSource
            parseDataSource: function(dataSource, callback) {

                var self = this;
                var args = arguments;

                if (Helpers.isObject(dataSource)) {
                    callback(attributes.dataSource = self.filterDataByLocator(dataSource));
                }
                else if (Helpers.isArray(dataSource)) {
                    callback(attributes.dataSource = dataSource);
                }
                else if ($.isFunction(dataSource)) {
                    attributes.dataSource(function(data) {
                        if ($.isFunction(data)) {
                            throwError('Unexpect parameter of the "done" Function.');
                        }

                        args.callee.call(self, data, callback);
                    });
                }
                else if (typeof dataSource === 'string') {
                    if (/^https?|file:/.test(dataSource)) {
                        attributes.ajaxDataType = 'jsonp';
                    }

                    callback(dataSource);
                }
                else{
                    throwError('Unexpect data type of the "dataSource".');
                }
            },

            callHook: function(hook) {
                var paginationData = container.data('pagination');
                var result;

                var args = Array.prototype.slice.apply(arguments);
                args.shift();

                if (attributes[hook] && $.isFunction(attributes[hook])) {
                    if (attributes[hook].apply(global, args) === false) {
                        result = false;
                    }
                }

                if (paginationData.hooks && paginationData.hooks[hook]) {
                    $.each(paginationData.hooks[hook], function(index, item) {
                        if (item.apply(global, args) === false) {
                            result = false;
                        }
                    });
                }

                return result !== false;
            },

            observer: function() {

                var self = this;
                var el = self.model.el;

                // Go to page
                container.on(eventPrefix + 'go', function(event, pageNumber, done) {

                    pageNumber = parseInt($.trim(pageNumber));

                    if (!pageNumber) return;

                    if (!$.isNumeric(pageNumber)) {
                        throwError('"pageNumber" is incorrect. (Number)');
                    }

                    self.go(pageNumber, done);
                });

                // Page click
                el.delegate('.J-paginationjs-page', 'click', function(event) {
                    var current = $(event.currentTarget);
                    var pageNumber = $.trim(current.attr('data-num'));

                    if (!pageNumber || current.hasClass(attributes.disableClassName) || current.hasClass(attributes.activeClassName)) return;

                    // 页面按钮点击之前
                    if (self.callHook('beforePageOnClick', event, pageNumber) === false) return false;

                    self.go(pageNumber);

                    // 页面按钮点击之后
                    self.callHook('afterPageOnClick', event, pageNumber);

                    if (!attributes.pageLink) return false;
                });

                // Previous click
                el.delegate('.J-paginationjs-previous', 'click', function(event) {
                    var current = $(event.currentTarget);
                    var pageNumber = $.trim(current.attr('data-num'));

                    if (!pageNumber || current.hasClass(attributes.disableClassName)) return;

                    // 上一页点击之前
                    if (self.callHook('beforePreviousOnClick', event, pageNumber) === false) return false;

                    self.go(pageNumber);

                    // 上一页点击之后
                    self.callHook('afterPreviousOnClick', event, pageNumber);

                    if (!attributes.pageLink) return false;
                });

                // Next click
                el.delegate('.J-paginationjs-next', 'click', function(event) {
                    var current = $(event.currentTarget);
                    var pageNumber = $.trim(current.attr('data-num'));

                    if (!pageNumber || current.hasClass(attributes.disableClassName)) return;

                    // 下一页点击之前
                    if (self.callHook('beforeNextOnClick', event, pageNumber) === false) return false;

                    self.go(pageNumber);

                    // 下一页点击之后
                    self.callHook('afterNextOnClick', event, pageNumber);

                    if (!attributes.pageLink) return false;
                });

                // Go button click
                el.delegate('.J-paginationjs-go-button', 'click', function() {
                    var pageNumber = $('.J-paginationjs-go-pagenumber', el).val();

                    // 跳转按钮点击之前
                    if (self.callHook('beforeGoButtonOnClick', event, pageNumber) === false) return false;

                    container.trigger(eventPrefix + 'go', pageNumber);

                    // 跳转按钮点击之后
                    self.callHook('afterGoButtonOnClick', event, pageNumber);
                });

                // go input enter
                el.delegate('.J-paginationjs-go-pagenumber', 'keyup', function(event) {
                    if (event.which === 13) {
                        var pageNumber = $(event.currentTarget).val();

                        // 输入之前
                        if (self.callHook('beforeGoInputOnEnter', event, pageNumber) === false) return false;

                        container.trigger(eventPrefix + 'go', pageNumber);

                        // 重新获取焦点
                        $('.J-paginationjs-go-pagenumber', el).focus();

                        // 输入之后
                        self.callHook('afterGoInputOnEnter', event, pageNumber);
                    }
                });

                // 上一页
                container.on(eventPrefix + 'previous', function(event, done) {
                    self.previous(done);
                });

                // 下一页
                container.on(eventPrefix + 'next', function(event, done) {
                    self.next(done);
                });

                // 禁用
                container.on(eventPrefix + 'disable', function() {
                    self.disable();
                });

                // 启用
                container.on(eventPrefix + 'enable', function() {
                    self.enable();
                });

                // 刷新
                container.on(eventPrefix + 'refresh', function(event, done) {
                    self.refresh(done);
                });

                // 显示
                container.on(eventPrefix + 'show', function() {
                    self.show();
                });

                // 隐藏
                container.on(eventPrefix + 'hide', function() {
                    self.hide();
                });

                // 销毁
                container.on(eventPrefix + 'destroy', function() {
                    self.destroy();
                });

                // 是否加载默认页面
                if (attributes.triggerPagingOnInit) {
                    container.trigger(eventPrefix + 'go', Math.min(attributes.pageNumber, self.model.totalPage));
                }
            }
        };

        // If initial
        if (container.data('pagination') && container.data('pagination').initialized === true) {

            // 处理事件
            if ($.isNumeric(options)) {
                // container.pagination(5)
                container.trigger.call(this, eventPrefix + 'go', options, arguments[1]);
                return this;
            }
            else if (typeof options === 'string') {

                var args = Array.prototype.slice.apply(arguments);
                args[0] = eventPrefix + args[0];

                switch(options) {
                    case 'previous':
                    case 'next':
                    case 'go':
                    case 'disable':
                    case 'enable':
                    case 'refresh':
                    case 'show':
                    case 'hide':
                    case 'destroy':
                        container.trigger.apply(this, args);
                        break;

                    // 得到选中页码
                    case 'getSelectedPageNum':
                        if (container.data('pagination').model) {
                            return container.data('pagination').model.pageNumber;
                        }
                        else{
                            return container.data('pagination').attributes.pageNumber;
                        }

                    // 得到总页面
                    case 'getTotalPage':
                        return container.data('pagination').model.totalPage;

                    // 得到选中的页面数据
                    case 'getSelectedPageData':
                        return container.data('pagination').currentPageData;

                    // 分页是否被禁用
                    case 'isDisabled':
                        return container.data('pagination').model.disabled === true;

                    default:
                        throwError('Pagination do not provide action: ' + options);
                }

                return this;
            } else {
                // 卸载旧实例之前初始化一个新的
                uninstallPlugin(container);
            }
        }
        else{
            if (!Helpers.isObject(options)) {
                throwError('Illegal options');
            }
        }

        // 属性
        var attributes = $.extend({}, arguments.callee.defaults, options);

        // 检查参数
        parameterChecker(attributes);

        pagination.initialize();

        return this;
    };

    // 实例的默认值
    $.fn[pluginName].defaults = {

        // Data source
        // Array | String | Function | Object
        //dataSource: '',

        // String | Function
        //locator: 'data',

        // 总条目,必须指定分页是异步的
        totalNumber: 1,

        // 默认页数
        pageNumber: 1,

        // 每页的条目
        pageSize: 10,

        // 页面范围(当前页的两边)
        pageRange: 2,

        // 是否显示 'Previous' 按钮
        showPrevious: true,

        // 是否显示 'Next' 按钮
        showNext: true,

        // 是否显示分页按钮
        showPageNumbers: true,

        showNavigator: false,

        // 是否显示 'Go' 输入框
        showGoInput: false,

        // 是否显示 'Go' 按钮
        showGoButton: false,

        // 页面链接
        pageLink: '',

        // 'Previous' 文本
        prevText: '«',

        // 'Next' 文本
        nextText: '»',

        // 省略号文本
        ellipsisText: '...',

        // 'Go' 按钮文本
        goButtonText: 'Go',

        // 额外分页元素的样式名称
        //className: '',

        classPrefix: 'paginationjs',

        // 默认当前页的样式名
        activeClassName: 'active',

        // 默认禁用的样式名
        disableClassName: 'disabled',

        // 分页中ul的样式名
        //ulClassName: '',

        // 是否插入内联样式
        inlineStyle: true,

        formatNavigator: '<%= currentPage %> / <%= totalPage %>',

        formatGoInput: '<%= input %>',

        formatGoButton: '<%= button %>',

        // 分页元素在容器中的位置
        position: 'bottom',

        // 当第一页时自动隐藏上一页按钮
        autoHidePrevious: false,

        // 当最后一页时自动隐藏下一页按钮
        autoHideNext: false,

        //header: '',

        //footer: '',

        // 别名为自定义分页参数
        //alias: {},

        // 是否在初始化时触发分页
        triggerPagingOnInit: true,

        // 当不到一页的时候是否隐藏分页
        hideWhenLessThanOnePage: false,

        showFirstOnEllipsisShow: true,

        showLastOnEllipsisShow: true,

        // 分页回调
        callback: function() {}
    };

    // 注册钩子
    $.fn[pluginHookMethod] = function(hook, callback) {

        if (arguments.length < 2) {
            throwError('Missing argument.');
        }

        if (!$.isFunction(callback)) {
            throwError('callback must be a function.');
        }

        var container = $(this);
        var paginationData = container.data('pagination');

        if (!paginationData) {
            container.data('pagination', {});
            paginationData = container.data('pagination');
        }

        !paginationData.hooks && (paginationData.hooks = {});

        //paginationData.hooks[hook] = callback;
        paginationData.hooks[hook] = paginationData.hooks[hook] || [];
        paginationData.hooks[hook].push(callback);

    };

    // 静态方法
    $[pluginName] = function(selector, options) {

        if (arguments.length < 2) {
            throwError('Requires two parameters.');
        }

        var container;

        // 'selector' is a jQuery object
        if (typeof selector !== 'string' && selector instanceof jQuery) {
            container = selector;
        }
        else{
            container = $(selector);
        }

        if (!container.length) return;

        container.pagination(options);

        return container;

    };

    // ============================================================
    // helpers
    // ============================================================

    var Helpers = {};

    // Throw error
    function throwError(content) {
        throw new Error('Pagination: '+ content);
    }

    // 检查参数
    function parameterChecker(args) {

        if (!args.dataSource) {
            throwError('"dataSource" is required.');
        }

        if (typeof args.dataSource === 'string') {
            if (typeof args.totalNumber === 'undefined') {
                throwError('"totalNumber" is required.');
            }
            else if (!$.isNumeric(args.totalNumber)) {
                throwError('"totalNumber" is incorrect. (Number)');
            }
        }
        else if (Helpers.isObject(args.dataSource)) {
            if (typeof args.locator === 'undefined') {
                throwError('"dataSource" is an Object, please specify "locator".');
            }
            else if (typeof args.locator !== 'string' && !$.isFunction(args.locator)) {
                throwError(''+ args.locator +' is incorrect. (String | Function)');
            }
        }
    }

    // 卸载插件
    function uninstallPlugin(target) {
        var events = ['go', 'previous', 'next', 'disable', 'enable', 'refresh', 'show', 'hide', 'destroy'];

        // off events of old instance
        $.each(events, function(index, value) {
            target.off(eventPrefix + value);
        });

        // reset pagination data
        target.data('pagination', {});

        // remove old
        $('.paginationjs', target).remove();
    }

    // 对象类型检测
    function getObjectType(object, tmp) {
        return ( (tmp = typeof(object)) == "object" ? object == null && "null" || Object.prototype.toString.call(object).slice(8, -1) : tmp ).toLowerCase();
    }
    $.each(['Object', 'Array'], function(index, name) {
        Helpers['is' + name] = function(object) {
            return getObjectType(object) === name.toLowerCase();
        };
    });

    /*
     * export via AMD or CommonJS
     * */
    if (typeof define === 'function' && define.amd) {
        define(function() {
            return $;
        });
    }

})(this, window.jQuery);


text:
description: Integrate UCP with Docker Trusted Registry
keywords: trusted, registry, integrate, UCP, DTR
title: Integrate with Docker Trusted Registry
---

Once you deploy Docker Trusted Registry (DTR), you can use it to store your Docker
images and deploy services to UCP using those images.
[Learn how deploy DTR](/datacenter/dtr/2.1/guides/install/index.md).

Docker UCP integrates out of the box with Docker Trusted Registry (DTR).
This means that you can deploy services from the UCP web UI, using Docker
images that are stored in DTR. You can also use a
[UCP client bundle](../access-ucp/cli-based-access.md) to do the same from the
CLI.

If you've configured DTR to use TLS certificates issued by a globally-trusted
certificate authority you can skip this since all clients will automatically
trust the TLS certificates used by DTR.

If you're using the DTR default configurations or configured DTR to use
self-signed certificates, you need to configure all hosts that want to push
or pull Docker images from DTR. This includes:

* All UCP nodes
* Your local computer or any other that wants to push or pull Docker images from DTR

If your host is not configured to trust the DTR TLS certificates, you see an
error like:

```none
docker login dtr.example.org

x509: certificate signed by unknown authority
```

## 1. Configure your local computer

If you want to use your local computer to interact with DTR, you need to
configure it to trust the DTR TLS certificates. This depends on the operating
system:

* For macOS:

  In your browser navigate to `https://<dtr-url>/ca` to download the TLS
  certificate used by DTR. Then
  [add that certificate to the macOS trust store](https://support.apple.com/kb/PH18677?locale=en_US).

* For Windows:

  In your browser navigate to `https://<dtr-url>/ca` to download the TLS
  certificate used by DTR. Then
  [add that certificate to the Windows trust store](https://technet.microsoft.com/en-us/library/cc754841(v=ws.11).aspx).

* For Ubuntu:

  ```bash
  # Download the DTR CA certificate
  $ sudo curl -k https://<dtr-url>/ca -o /usr/local/share/ca-certificates/<dtr-domain-name>.crt

  # Refresh the list of certificates to trust
  $ sudo update-ca-certificates

  # Restart the Docker daemon
  $ sudo service docker restart
  ```

* For CentOS or RHEL:

  ```bash
  # Download the DTR CA certificate
  $ sudo curl -k https://<dtr-url>/ca -o /etc/pki/ca-trust/source/anchors/<dtr-domain-name>.crt

  # Refresh the list of certificates to trust
  $ sudo update-ca-trust

  # Restart the Docker daemon
  $ sudo /bin/systemctl restart docker.service
  ```

## 2. Test your local setup

The best way to confirm that your computer is correctly configured, is by
trying to pull and push images from your local Docker installation to DTR.

1.  Create a test repository on DTR.

    Navigate to the **DTR web UI**, and create a new **hello-world** repository
    so that you can push and pull images. Set it as **private**, and save
    the changes.

    ![](../images/dtr-integration-1.png)

2.  Pull the `hello-world` image from Docker Store, re-tag it, and push it to the
DTR repository you created.

    ```none
    # Pull hello-world from Docker Store
    docker pull hello-world:latest

    # Re-tag it
    docker tag hello-world:latest <dtr-domain>/<user>/hello-world:latest

    # Log into DTR
    docker login <dtr-domain>

    # Push your image to DTR
    docker push <dtr-domain>/<user>/hello-world:latest
    ```

3.  Validate that your image is now stored in DTR.

    When successfully pushing the image you should see a result like:

    ```none
    The push refers to a repository [dtr/username/hello-world]
    5f70bf18a086: Pushed
    33e7801ac047: Pushed
    1: digest: sha256:7d9e482c0cc9e68c7f07bf76e0aafcb1869d32446547909200db990e7bc5461a size: 1930
    ```

    You can also check that the tag exists on the DTR web UI.

    ![](../images/dtr-integration-2.png)

## 3. Configure UCP Docker Engines

You also need to configure the Docker Engine on every UCP node to trust the
DTR TLS certificates. This allows you do deploy services to UCP using images
that are stored in DTR.

For each UCP node:

1.  Log into the node as an administrator, using ssh
2.  Configure the system to trust the DTR TLS certificates, following the same
steps as you used to configure your local computer.

## Where to go next

* [use your own externally-signed TLS certificates](index.md#customize-the-ucp-tls-certificates)


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Matsush. Mycol. Mem. , no. 2 2: 2 (1981)

#### Original name
Berkleasmium micronesiacum Matsush., 1981

### Remarks
null


text:
// This file is automatically generated.

package adila.db;

/*
 * Sharp PANTONE 6 SoftBank 200SH
 *
 * DEVICE: SBM200SH
 * MODEL: SBM200SH
 */
final class sbm200sh_sbm200sh {
    public static final String DATA = "Sharp|PANTONE 6 SoftBank 200SH|";
}


text:
if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
    module.exports = BulmaInitExternalFieldsTrait;
}

/**
 * Bulma init for some external fields
 */
function BulmaInitExternalFieldsTrait() {
    this.initExternalSourceSelect = function(ractive, element, field, jmespath) {
        var variant = this;
        var input = new DomElement(element);
        var valueField = input.attr('value_field') || input.attr('label_field');
        var labelField = input.attr('label_field');
        var jmespathRequest = input.attr('jmespath');
        var useValue = input.attr('url').indexOf('%value%') !== -1;
        var name = field.name;
        var value = ractive.get(name);
        var options = [];

        input.attr('data-validate', 'false');

        var choices = new Choices(element, {
            maxItemCount: 1,
            addItems: false,
            duplicateItemsAllowed: false,
            searchChoices: !useValue,
            renderSelectedChoices: 'always'
        }).enable();

        input.closest('.select').addClass('with-choices');
        element.choices = choices;

        input.on('search', function(e) {
            var value = e.detail.value;
            var value2 = input.val();

            if (!useValue) return;

            choices.setChoices(function() {
                return doRequest(value);
            }, valueField, labelField, true);
        });

        input.on('choice', function(e) {
            ractive.validation.validateField(input);
            input.trigger('change');
        });

        input.on('blur', function(e) {
            if (typeof e.detail === 'undefined' || typeof e.detail.value === 'undefined') return;

            ractive.validation.validateField(input);
            input.trigger('change');
        });

        //As we do not allow adding values, this is only executed on removing value
        input.on('change', function(e) {
            if (typeof e.detail === 'undefined' || typeof e.detail.value === 'undefined') return;

            var value = e.detail.value;
            if (value === null || value === '') {
                ractive.set(name, null);
            }

            ractive.validation.validateField(input);
            input.trigger('change');
        });

        var setNull =
            (value && typeof value === 'object' && typeof value[valueField] === 'undefined') ||
            typeof value === 'undefined';

        if (setNull) {
            value = null;
        }

        var setValue = (typeof value === 'object' && value) ? value[valueField] : value;
        var promise = doRequest(setValue);

        choices.setChoices(function() {
            return promise;
        }, valueField, labelField, true);

        if (setValue) {
            Promise.all([promise]).then(function() {
                choices.setChoiceByValue(setValue);
            });
        }

        function doRequest(value) {
            var url = ractive.get(escapeDots(field.url_field));
            if (useValue) url = ltriToUrl(url).replace('%value%', encodeURIComponent(value));
            url = clearComputedUrl(url);

            var headers = combineHeadersNamesAndValues(field.headerName || [], field.headerValue || []);
            var promise = ajaxRequest(url, {headers})
                .then(function(response) {
                    response = JSON.parse(response);
                    response = ractive.applyJMESPath(response, jmespathRequest, jmespath);

                    return response;
                });

            return promise;
        }
    };

    this.triggerExternalSourceSelectLoad = function(element) {
        var choices = element.choices;
        if (!choices) return;

        element = new DomElement(element);
        element.trigger('search');
    }

    this.isExternalSourceSelectInitialized = function(element) {
        return (new DomElement(element)).hasClass('choices__input');
    }
}


text:
<?php
namespace Centreon\Domain\Repository;

use Centreon\Infrastructure\CentreonLegacyDB\ServiceEntityRepository;

class DowntimeServiceGroupRelationRepository extends ServiceEntityRepository
{
    /**
     * Export
     *
     * @param int[] $pollerIds
     * @param array $serviceTemplateChain
     * @return array
     */
    public function export(array $pollerIds, array $serviceTemplateChain = null): array
    {
        // prevent SQL exception
        if (!$pollerIds) {
            return [];
        }

        $ids = join(',', $pollerIds);
        $serviceList = join(',', $serviceTemplateChain ?? []);
        $sqlFilterServiceList = $serviceList ? " OR dsgr.sg_sg_id IN ({$serviceList})" : '';

        $sql = <<<SQL
SELECT
    t.dt_id
FROM downtime AS t
INNER JOIN downtime_servicegroup_relation AS dsgr ON dsgr.dt_id = t.dt_id
    AND dsgr.sg_sg_id IN (SELECT t1a.host_host_id
        FROM
            ns_host_relation AS t1a
        WHERE
            t1a.nagios_server_id IN ({$ids})
        GROUP BY t1a.host_host_id){$sqlFilterServiceList}
GROUP BY t.dt_id
SQL;

        $stmt = $this->db->prepare($sql);
        $stmt->execute();

        $result = [];

        while ($row = $stmt->fetch()) {
            $result[] = $row;
        }

        return $result;
    }
}


text:
/**
 * @file
 *   This file implements link quality information processing and storage.
 */

#include "link_quality.hpp"

#include <stdio.h>

#include "common/code_utils.hpp"
#include "common/instance.hpp"
#include "common/locator-getters.hpp"

namespace ot {

// This array gives the decimal point digits representing 0/8, 1/8, ..., 7/8 (does not include the '.').
static const char *const kDigitsString[8] = {
    // 0/8,  1/8,   2/8,   3/8,   4/8,   5/8,   6/8,   7/8
    "0", "125", "25", "375", "5", "625", "75", "875"};

void SuccessRateTracker::AddSample(bool aSuccess, uint16_t aWeight)
{
    uint32_t oldAverage = mFailureRate;
    uint32_t newValue   = (aSuccess) ? 0 : kMaxRateValue;
    uint32_t n          = aWeight;

    // `n/2` is added to the sum to ensure rounding the value to the nearest integer when dividing by `n`
    // (e.g., 1.2 -> 1, 3.5 -> 4).

    mFailureRate = static_cast<uint16_t>(((oldAverage * (n - 1)) + newValue + (n / 2)) / n);
}

void RssAverager::Reset(void)
{
    mAverage = 0;
    mCount   = 0;
}

otError RssAverager::Add(int8_t aRss)
{
    otError  error = OT_ERROR_NONE;
    uint16_t newValue;
    uint16_t oldAverage;

    VerifyOrExit(aRss != OT_RADIO_RSSI_INVALID, error = OT_ERROR_INVALID_ARGS);

    // Restrict the RSS value to the closed range [0, -128] so the RSS times precision multiple can fit in 11 bits.
    if (aRss > 0)
    {
        aRss = 0;
    }

    // Multiply the RSS value by a precision multiple (currently -8).

    newValue = static_cast<uint16_t>(-aRss);
    newValue <<= kPrecisionBitShift;

    oldAverage = mAverage;

    if (mCount == 0)
    {
        mCount++;
        mAverage = newValue;
    }
    else if (mCount < (1 << kCoeffBitShift) - 1)
    {
        mCount++;

        // Maintain arithmetic mean.
        // newAverage = newValue * (1/mCount) + oldAverage * ((mCount -1)/mCount)
        mAverage = static_cast<uint16_t>(((oldAverage * (mCount - 1)) + newValue) / mCount);
    }
    else
    {
        // Maintain exponentially weighted moving average using coefficient of (1/2^kCoeffBitShift).
        // newAverage = + newValue * 1/2^j + oldAverage * (1 - 1/2^j), for j = kCoeffBitShift.

        mAverage = static_cast<uint16_t>(((oldAverage << kCoeffBitShift) - oldAverage + newValue) >> kCoeffBitShift);
    }

exit:
    return error;
}

int8_t RssAverager::GetAverage(void) const
{
    int8_t average;

    VerifyOrExit(mCount != 0, average = OT_RADIO_RSSI_INVALID);

    average = -static_cast<int8_t>(mAverage >> kPrecisionBitShift);

    // Check for possible round up (e.g., average of -71.5 --> -72)

    if ((mAverage & kPrecisionBitMask) >= (kPrecision >> 1))
    {
        average--;
    }

exit:
    return average;
}

RssAverager::InfoString RssAverager::ToString(void) const
{
    InfoString string;

    VerifyOrExit(mCount != 0, OT_NOOP);
    IgnoreError(string.Set("%d.%s", -(mAverage >> kPrecisionBitShift), kDigitsString[mAverage & kPrecisionBitMask]));

exit:
    return string;
}

void LinkQualityInfo::Clear(void)
{
    mRssAverager.Reset();
    SetLinkQuality(0);
    mLastRss = OT_RADIO_RSSI_INVALID;

    mFrameErrorRate.Reset();
    mMessageErrorRate.Reset();
}

void LinkQualityInfo::AddRss(int8_t aRss)
{
    uint8_t oldLinkQuality = kNoLinkQuality;

    VerifyOrExit(aRss != OT_RADIO_RSSI_INVALID, OT_NOOP);

    mLastRss = aRss;

    if (mRssAverager.HasAverage())
    {
        oldLinkQuality = GetLinkQuality();
    }

    SuccessOrExit(mRssAverager.Add(aRss));

    SetLinkQuality(CalculateLinkQuality(GetLinkMargin(), oldLinkQuality));

exit:
    return;
}

uint8_t LinkQualityInfo::GetLinkMargin(void) const
{
    return ConvertRssToLinkMargin(Get<Mac::SubMac>().GetNoiseFloor(), GetAverageRss());
}

LinkQualityInfo::InfoString LinkQualityInfo::ToInfoString(void) const
{
    return InfoString("aveRss:%s, lastRss:%d, linkQuality:%d", mRssAverager.ToString().AsCString(), GetLastRss(),
                      GetLinkQuality());
}

uint8_t LinkQualityInfo::ConvertRssToLinkMargin(int8_t aNoiseFloor, int8_t aRss)
{
    int8_t linkMargin = aRss - aNoiseFloor;

    if (linkMargin < 0 || aRss == OT_RADIO_RSSI_INVALID)
    {
        linkMargin = 0;
    }

    return static_cast<uint8_t>(linkMargin);
}

uint8_t LinkQualityInfo::ConvertLinkMarginToLinkQuality(uint8_t aLinkMargin)
{
    return CalculateLinkQuality(aLinkMargin, kNoLinkQuality);
}

uint8_t LinkQualityInfo::ConvertRssToLinkQuality(int8_t aNoiseFloor, int8_t aRss)
{
    return ConvertLinkMarginToLinkQuality(ConvertRssToLinkMargin(aNoiseFloor, aRss));
}

int8_t LinkQualityInfo::ConvertLinkQualityToRss(int8_t aNoiseFloor, uint8_t aLinkQuality)
{
    uint8_t linkmargin = 0;

    switch (aLinkQuality)
    {
    case 3:
        linkmargin = kLinkQuality3LinkMargin;
        break;

    case 2:
        linkmargin = kLinkQuality2LinkMargin;
        break;

    case 1:
        linkmargin = kLinkQuality1LinkMargin;
        break;

    default:
        linkmargin = kLinkQuality0LinkMargin;
        break;
    }

    return linkmargin + aNoiseFloor;
}

uint8_t LinkQualityInfo::CalculateLinkQuality(uint8_t aLinkMargin, uint8_t aLastLinkQuality)
{
    uint8_t threshold1, threshold2, threshold3;
    uint8_t linkQuality = 0;

    threshold1 = kThreshold1;
    threshold2 = kThreshold2;
    threshold3 = kThreshold3;

    // Apply the hysteresis threshold based on the last link quality value.

    switch (aLastLinkQuality)
    {
    case 0:
        threshold1 += kHysteresisThreshold;

        // fall-through

    case 1:
        threshold2 += kHysteresisThreshold;

        // fall-through

    case 2:
        threshold3 += kHysteresisThreshold;

        // fall-through

    default:
        break;
    }

    if (aLinkMargin > threshold3)
    {
        linkQuality = 3;
    }
    else if (aLinkMargin > threshold2)
    {
        linkQuality = 2;
    }
    else if (aLinkMargin > threshold1)
    {
        linkQuality = 1;
    }

    return linkQuality;
}

} // namespace ot


text:
<!-- Do not edit this file. It is automatically generated by API Documenter. -->

[Home](./index.md) > [puppeteer](./puppeteer.md) > [Protocol](./puppeteer.protocol.md) > [Network](./puppeteer.protocol.network.md) > [ResourceTiming](./puppeteer.protocol.network.resourcetiming.md) > [connectStart](./puppeteer.protocol.network.resourcetiming.connectstart.md)

## Protocol.Network.ResourceTiming.connectStart property

Started connecting to the remote host.

<b>Signature:</b>

```typescript
connectStart: number;
```


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE369_Divide_by_Zero__int_listen_socket_divide_12.c
Label Definition File: CWE369_Divide_by_Zero__int.label.xml
Template File: sources-sinks-12.tmpl.c
*/
/*
 * @description
 * CWE: 369 Divide by Zero
 * BadSource: listen_socket Read data using a listen socket (server side)
 * GoodSource: Non-zero
 * Sinks: divide
 *    GoodSink: Check for zero before dividing
 *    BadSink : Divide a constant by data
 * Flow Variant: 12 Control flow: if(globalReturnsTrueOrFalse())
 *
 * */

#include "std_testcase.h"

#ifdef _WIN32
#include <winsock2.h>
#include <windows.h>
#include <direct.h>
#pragma comment(lib, "ws2_32") /* include ws2_32.lib when linking */
#define CLOSE_SOCKET closesocket
#else
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#define INVALID_SOCKET -1
#define SOCKET_ERROR -1
#define CLOSE_SOCKET close
#define SOCKET int
#endif

#define TCP_PORT 27015
#define LISTEN_BACKLOG 5
#define CHAR_ARRAY_SIZE (3 * sizeof(data) + 2)

#ifndef OMITBAD

void CWE369_Divide_by_Zero__int_listen_socket_divide_12_bad()
{
    int data;
    /* Initialize data */
    data = -1;
    if(globalReturnsTrueOrFalse())
    {
        {
#ifdef _WIN32
            WSADATA wsaData;
            int wsaDataInit = 0;
#endif
            int recvResult;
            struct sockaddr_in service;
            SOCKET listenSocket = INVALID_SOCKET;
            SOCKET acceptSocket = INVALID_SOCKET;
            char inputBuffer[CHAR_ARRAY_SIZE];
            do
            {
#ifdef _WIN32
                if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR)
                {
                    break;
                }
                wsaDataInit = 1;
#endif
                /* POTENTIAL FLAW: Read data using a listen socket */
                listenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
                if (listenSocket == INVALID_SOCKET)
                {
                    break;
                }
                memset(&service, 0, sizeof(service));
                service.sin_family = AF_INET;
                service.sin_addr.s_addr = INADDR_ANY;
                service.sin_port = htons(TCP_PORT);
                if (bind(listenSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR)
                {
                    break;
                }
                if (listen(listenSocket, LISTEN_BACKLOG) == SOCKET_ERROR)
                {
                    break;
                }
                acceptSocket = accept(listenSocket, NULL, NULL);
                if (acceptSocket == SOCKET_ERROR)
                {
                    break;
                }
                /* Abort on error or the connection was closed */
                recvResult = recv(acceptSocket, inputBuffer, CHAR_ARRAY_SIZE - 1, 0);
                if (recvResult == SOCKET_ERROR || recvResult == 0)
                {
                    break;
                }
                /* NUL-terminate the string */
                inputBuffer[recvResult] = '\0';
                /* Convert to int */
                data = atoi(inputBuffer);
            }
            while (0);
            if (listenSocket != INVALID_SOCKET)
            {
                CLOSE_SOCKET(listenSocket);
            }
            if (acceptSocket != INVALID_SOCKET)
            {
                CLOSE_SOCKET(acceptSocket);
            }
#ifdef _WIN32
            if (wsaDataInit)
            {
                WSACleanup();
            }
#endif
        }
    }
    else
    {
        /* FIX: Use a value not equal to zero */
        data = 7;
    }
    if(globalReturnsTrueOrFalse())
    {
        /* POTENTIAL FLAW: Possibly divide by zero */
        printIntLine(100 / data);
    }
    else
    {
        /* FIX: test for a zero denominator */
        if( data != 0 )
        {
            printIntLine(100 / data);
        }
        else
        {
            printLine("This would result in a divide by zero");
        }
    }
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodB2G() - use badsource and goodsink by changing the first "if" so that
   both branches use the BadSource and the second "if" so that both branches
   use the GoodSink */
static void goodB2G()
{
    int data;
    /* Initialize data */
    data = -1;
    if(globalReturnsTrueOrFalse())
    {
        {
#ifdef _WIN32
            WSADATA wsaData;
            int wsaDataInit = 0;
#endif
            int recvResult;
            struct sockaddr_in service;
            SOCKET listenSocket = INVALID_SOCKET;
            SOCKET acceptSocket = INVALID_SOCKET;
            char inputBuffer[CHAR_ARRAY_SIZE];
            do
            {
#ifdef _WIN32
                if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR)
                {
                    break;
                }
                wsaDataInit = 1;
#endif
                /* POTENTIAL FLAW: Read data using a listen socket */
                listenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
                if (listenSocket == INVALID_SOCKET)
                {
                    break;
                }
                memset(&service, 0, sizeof(service));
                service.sin_family = AF_INET;
                service.sin_addr.s_addr = INADDR_ANY;
                service.sin_port = htons(TCP_PORT);
                if (bind(listenSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR)
                {
                    break;
                }
                if (listen(listenSocket, LISTEN_BACKLOG) == SOCKET_ERROR)
                {
                    break;
                }
                acceptSocket = accept(listenSocket, NULL, NULL);
                if (acceptSocket == SOCKET_ERROR)
                {
                    break;
                }
                /* Abort on error or the connection was closed */
                recvResult = recv(acceptSocket, inputBuffer, CHAR_ARRAY_SIZE - 1, 0);
                if (recvResult == SOCKET_ERROR || recvResult == 0)
                {
                    break;
                }
                /* NUL-terminate the string */
                inputBuffer[recvResult] = '\0';
                /* Convert to int */
                data = atoi(inputBuffer);
            }
            while (0);
            if (listenSocket != INVALID_SOCKET)
            {
                CLOSE_SOCKET(listenSocket);
            }
            if (acceptSocket != INVALID_SOCKET)
            {
                CLOSE_SOCKET(acceptSocket);
            }
#ifdef _WIN32
            if (wsaDataInit)
            {
                WSACleanup();
            }
#endif
        }
    }
    else
    {
        {
#ifdef _WIN32
            WSADATA wsaData;
            int wsaDataInit = 0;
#endif
            int recvResult;
            struct sockaddr_in service;
            SOCKET listenSocket = INVALID_SOCKET;
            SOCKET acceptSocket = INVALID_SOCKET;
            char inputBuffer[CHAR_ARRAY_SIZE];
            do
            {
#ifdef _WIN32
                if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR)
                {
                    break;
                }
                wsaDataInit = 1;
#endif
                /* POTENTIAL FLAW: Read data using a listen socket */
                listenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
                if (listenSocket == INVALID_SOCKET)
                {
                    break;
                }
                memset(&service, 0, sizeof(service));
                service.sin_family = AF_INET;
                service.sin_addr.s_addr = INADDR_ANY;
                service.sin_port = htons(TCP_PORT);
                if (bind(listenSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR)
                {
                    break;
                }
                if (listen(listenSocket, LISTEN_BACKLOG) == SOCKET_ERROR)
                {
                    break;
                }
                acceptSocket = accept(listenSocket, NULL, NULL);
                if (acceptSocket == SOCKET_ERROR)
                {
                    break;
                }
                /* Abort on error or the connection was closed */
                recvResult = recv(acceptSocket, inputBuffer, CHAR_ARRAY_SIZE - 1, 0);
                if (recvResult == SOCKET_ERROR || recvResult == 0)
                {
                    break;
                }
                /* NUL-terminate the string */
                inputBuffer[recvResult] = '\0';
                /* Convert to int */
                data = atoi(inputBuffer);
            }
            while (0);
            if (listenSocket != INVALID_SOCKET)
            {
                CLOSE_SOCKET(listenSocket);
            }
            if (acceptSocket != INVALID_SOCKET)
            {
                CLOSE_SOCKET(acceptSocket);
            }
#ifdef _WIN32
            if (wsaDataInit)
            {
                WSACleanup();
            }
#endif
        }
    }
    if(globalReturnsTrueOrFalse())
    {
        /* FIX: test for a zero denominator */
        if( data != 0 )
        {
            printIntLine(100 / data);
        }
        else
        {
            printLine("This would result in a divide by zero");
        }
    }
    else
    {
        /* FIX: test for a zero denominator */
        if( data != 0 )
        {
            printIntLine(100 / data);
        }
        else
        {
            printLine("This would result in a divide by zero");
        }
    }
}

/* goodG2B() - use goodsource and badsink by changing the first "if" so that
   both branches use the GoodSource and the second "if" so that both branches
   use the BadSink */
static void goodG2B()
{
    int data;
    /* Initialize data */
    data = -1;
    if(globalReturnsTrueOrFalse())
    {
        /* FIX: Use a value not equal to zero */
        data = 7;
    }
    else
    {
        /* FIX: Use a value not equal to zero */
        data = 7;
    }
    if(globalReturnsTrueOrFalse())
    {
        /* POTENTIAL FLAW: Possibly divide by zero */
        printIntLine(100 / data);
    }
    else
    {
        /* POTENTIAL FLAW: Possibly divide by zero */
        printIntLine(100 / data);
    }
}

void CWE369_Divide_by_Zero__int_listen_socket_divide_12_good()
{
    goodB2G();
    goodG2B();
}

#endif /* OMITGOOD */

/* Below is the main(). It is only used when building this testcase on
   its own for testing or for building a binary to use in testing binary
   analysis tools. It is not used when compiling all the testcases as one
   application, which is how source code analysis tools are tested. */

#ifdef INCLUDEMAIN

int main(int argc, char * argv[])
{
    /* seed randomness */
    srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
    printLine("Calling good()...");
    CWE369_Divide_by_Zero__int_listen_socket_divide_12_good();
    printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
    printLine("Calling bad()...");
    CWE369_Divide_by_Zero__int_listen_socket_divide_12_bad();
    printLine("Finished bad()");
#endif /* OMITBAD */
    return 0;
}

#endif


text:
package net.snowflake.client.core.arrow;

import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.*;

import java.math.BigDecimal;
import java.nio.ByteBuffer;
import java.util.*;
import net.snowflake.client.TestUtil;
import net.snowflake.client.core.SFException;
import net.snowflake.client.jdbc.ErrorCode;
import org.apache.arrow.memory.BufferAllocator;
import org.apache.arrow.memory.RootAllocator;
import org.apache.arrow.vector.IntVector;
import org.apache.arrow.vector.types.Types;
import org.apache.arrow.vector.types.pojo.FieldType;
import org.junit.Test;

public class IntToFixedConverterTest extends BaseConverterTest {
  /** allocator for arrow */
  private BufferAllocator allocator = new RootAllocator(Long.MAX_VALUE);

  /** Random seed */
  private Random random = new Random();

  private ByteBuffer bb;

  @Test
  public void testFixedNoScale() throws SFException {
    final int rowCount = 1000;
    List<Integer> expectedValues = new ArrayList<>();
    Set<Integer> nullValIndex = new HashSet<>();
    for (int i = 0; i < rowCount; i++) {
      expectedValues.add(random.nextInt());
    }

    Map<String, String> customFieldMeta = new HashMap<>();
    customFieldMeta.put("logicalType", "FIXED");
    customFieldMeta.put("precision", "10");
    customFieldMeta.put("scale", "0");

    FieldType fieldType = new FieldType(true, Types.MinorType.INT.getType(), null, customFieldMeta);

    IntVector vector = new IntVector("col_one", fieldType, allocator);
    for (int i = 0; i < rowCount; i++) {
      boolean isNull = random.nextBoolean();
      if (isNull) {
        vector.setNull(i);
        nullValIndex.add(i);
      } else {
        vector.setSafe(i, expectedValues.get(i));
      }
    }

    ArrowVectorConverter converter = new IntToFixedConverter(vector, 0, this);

    for (int i = 0; i < rowCount; i++) {
      int intVal = converter.toInt(i);
      Object longObj = converter.toObject(i);
      String intString = converter.toString(i);
      if (intString != null) {
        assertFalse(converter.isNull(i));
      } else {
        assertTrue(converter.isNull(i));
      }

      if (nullValIndex.contains(i)) {
        assertThat(intVal, is(0));
        assertThat(longObj, is(nullValue()));
        assertThat(intString, is(nullValue()));
        assertThat(converter.toBytes(i), is(nullValue()));
      } else {
        assertThat(intVal, is(expectedValues.get(i)));
        assertEquals(longObj, (long) expectedValues.get(i));
        assertThat(intString, is(expectedValues.get(i).toString()));
        bb = ByteBuffer.wrap(converter.toBytes(i));
        assertThat(intVal, is(bb.getInt()));
      }
    }
    vector.clear();
  }

  @Test
  public void testFixedWithScale() throws SFException {
    final int rowCount = 1000;
    List<Integer> expectedValues = new ArrayList<>();
    Set<Integer> nullValIndex = new HashSet<>();
    for (int i = 0; i < rowCount; i++) {
      expectedValues.add(random.nextInt());
    }

    Map<String, String> customFieldMeta = new HashMap<>();
    customFieldMeta.put("logicalType", "FIXED");
    customFieldMeta.put("precision", "10");
    customFieldMeta.put("scale", "3");

    FieldType fieldType = new FieldType(true, Types.MinorType.INT.getType(), null, customFieldMeta);

    IntVector vector = new IntVector("col_one", fieldType, allocator);
    for (int i = 0; i < rowCount; i++) {
      boolean isNull = random.nextBoolean();
      if (isNull) {
        vector.setNull(i);
        nullValIndex.add(i);
      } else {
        vector.setSafe(i, expectedValues.get(i));
      }
    }

    ArrowVectorConverter converter = new IntToScaledFixedConverter(vector, 0, this, 3);

    for (int i = 0; i < rowCount; i++) {
      BigDecimal bigDecimalVal = converter.toBigDecimal(i);
      Object objectVal = converter.toObject(i);
      String stringVal = converter.toString(i);

      if (nullValIndex.contains(i)) {
        assertThat(bigDecimalVal, nullValue());
        assertThat(objectVal, nullValue());
        assertThat(stringVal, nullValue());
        assertThat(converter.toBytes(i), is(nullValue()));
      } else {
        BigDecimal expectedVal = BigDecimal.valueOf(expectedValues.get(i), 3);
        assertThat(bigDecimalVal, is(expectedVal));
        assertThat(objectVal, is(expectedVal));
        assertThat(stringVal, is(expectedVal.toString()));
        assertThat(converter.toBytes(i), is(notNullValue()));
      }
    }

    vector.clear();
  }

  @Test
  public void testInvalidConversion() {
    // try convert to int/long/byte/short with scale > 0
    Map<String, String> customFieldMeta = new HashMap<>();
    customFieldMeta.put("logicalType", "FIXED");
    customFieldMeta.put("precision", "10");
    customFieldMeta.put("scale", "3");

    FieldType fieldType = new FieldType(true, Types.MinorType.INT.getType(), null, customFieldMeta);

    IntVector vector = new IntVector("col_one", fieldType, allocator);
    vector.setSafe(0, 33000);

    final ArrowVectorConverter converter = new IntToScaledFixedConverter(vector, 0, this, 3);
    final int invalidConversionErrorCode = ErrorCode.INVALID_VALUE_CONVERT.getMessageCode();

    TestUtil.assertSFException(invalidConversionErrorCode, () -> converter.toBoolean(0));
    TestUtil.assertSFException(invalidConversionErrorCode, () -> converter.toLong(0));
    TestUtil.assertSFException(invalidConversionErrorCode, () -> converter.toInt(0));
    TestUtil.assertSFException(invalidConversionErrorCode, () -> converter.toShort(0));
    TestUtil.assertSFException(invalidConversionErrorCode, () -> converter.toByte(0));
    TestUtil.assertSFException(
        invalidConversionErrorCode, () -> converter.toDate(0, getTimeZone(), false));
    TestUtil.assertSFException(invalidConversionErrorCode, () -> converter.toTime(0));
    TestUtil.assertSFException(
        invalidConversionErrorCode, () -> converter.toTimestamp(0, TimeZone.getDefault()));
    vector.clear();
  }

  @Test
  public void testGetSmallerIntegralType() throws SFException {
    // try convert to int/long/byte/short with scale > 0
    Map<String, String> customFieldMeta = new HashMap<>();
    customFieldMeta.put("logicalType", "FIXED");
    customFieldMeta.put("precision", "10");
    customFieldMeta.put("scale", "0");

    FieldType fieldType = new FieldType(true, Types.MinorType.INT.getType(), null, customFieldMeta);

    // test value which is out of range of int, but falls in long
    IntVector vectorFoo = new IntVector("col_one", fieldType, allocator);
    vectorFoo.setSafe(0, 33000);
    vectorFoo.setSafe(1, -33000);

    final ArrowVectorConverter converterFoo = new IntToFixedConverter(vectorFoo, 0, this);
    final int invalidConversionErrorCode = ErrorCode.INVALID_VALUE_CONVERT.getMessageCode();

    TestUtil.assertSFException(invalidConversionErrorCode, () -> converterFoo.toShort(0));
    TestUtil.assertSFException(invalidConversionErrorCode, () -> converterFoo.toByte(0));
    TestUtil.assertSFException(invalidConversionErrorCode, () -> converterFoo.toShort(1));
    TestUtil.assertSFException(invalidConversionErrorCode, () -> converterFoo.toByte(1));

    assertThat(converterFoo.toLong(0), is(33000L));
    assertThat(converterFoo.toLong(1), is(-33000L));
    vectorFoo.clear();

    // test value which is in range of byte, all get method should return
    IntVector vectorBar = new IntVector("col_one", fieldType, allocator);
    // set value which is out of range of int, but falls in long
    vectorBar.setSafe(0, 10);
    vectorBar.setSafe(1, -10);

    final ArrowVectorConverter converterBar = new IntToFixedConverter(vectorBar, 0, this);

    assertThat(converterBar.toByte(0), is((byte) 10));
    assertThat(converterBar.toByte(1), is((byte) -10));
    assertThat(converterBar.toShort(0), is((short) 10));
    assertThat(converterBar.toShort(1), is((short) -10));
    assertThat(converterBar.toLong(0), is(10L));
    assertThat(converterBar.toLong(1), is(-10L));
    vectorBar.clear();
  }

  @Test
  public void testGetBooleanNoScale() throws SFException {
    Map<String, String> customFieldMeta = new HashMap<>();
    customFieldMeta.put("logicalType", "FIXED");
    customFieldMeta.put("precision", "10");
    customFieldMeta.put("scale", "0");

    FieldType fieldType = new FieldType(true, Types.MinorType.INT.getType(), null, customFieldMeta);

    IntVector vector = new IntVector("col_one", fieldType, allocator);
    vector.setSafe(0, 0);
    vector.setSafe(1, 1);
    vector.setNull(2);
    vector.setSafe(3, 5);

    ArrowVectorConverter converter = new IntToFixedConverter(vector, 0, this);

    assertThat(false, is(converter.toBoolean(0)));
    assertThat(true, is(converter.toBoolean(1)));
    assertThat(false, is(converter.toBoolean(2)));
    TestUtil.assertSFException(invalidConversionErrorCode, () -> converter.toBoolean(3));

    vector.close();
  }

  @Test
  public void testGetBooleanWithScale() throws SFException {
    Map<String, String> customFieldMeta = new HashMap<>();
    customFieldMeta.put("logicalType", "FIXED");
    customFieldMeta.put("precision", "10");
    customFieldMeta.put("scale", "3");

    FieldType fieldType = new FieldType(true, Types.MinorType.INT.getType(), null, customFieldMeta);

    IntVector vector = new IntVector("col_one", fieldType, allocator);
    vector.setSafe(0, 0);
    vector.setSafe(1, 1);
    vector.setNull(2);
    vector.setSafe(3, 5);

    final ArrowVectorConverter converter = new IntToScaledFixedConverter(vector, 0, this, 3);

    assertThat(false, is(converter.toBoolean(0)));
    TestUtil.assertSFException(invalidConversionErrorCode, () -> converter.toBoolean(3));
    assertThat(false, is(converter.toBoolean(2)));
    TestUtil.assertSFException(invalidConversionErrorCode, () -> converter.toBoolean(3));

    vector.close();
  }
}


text:
package com.xmomen.module.resource.entity;

import com.xmomen.framework.mybatis.model.BaseMybatisModel;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Version;

@Entity
@Table(name = "cd_resource")
public class Resource extends BaseMybatisModel {
    /**
     *
     */
    private String id;

    /**
     *
     */
    private String entityType;

    /**
     *
     */
    private String entityId;

    /**
     *
     */
    private String path;

    /**
     *
     */
    private String resourceType;

    /**
     *
     */
    private Integer isDefault;

    @Column(name = "ID")
    @Id
    @GeneratedValue(generator = "UUIDGenerator")
    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
        if(id == null){
              removeValidField("id");
              return;
        }
        addValidField("id");
    }

    @Column(name = "ENTITY_TYPE")
    public String getEntityType() {
        return entityType;
    }

    public void setEntityType(String entityType) {
        this.entityType = entityType;
        if(entityType == null){
              removeValidField("entityType");
              return;
        }
        addValidField("entityType");
    }

    @Column(name = "ENTITY_ID")
    public String getEntityId() {
        return entityId;
    }

    public void setEntityId(String entityId) {
        this.entityId = entityId;
        if(entityId == null){
              removeValidField("entityId");
              return;
        }
        addValidField("entityId");
    }

    @Column(name = "PATH")
    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
        if(path == null){
              removeValidField("path");
              return;
        }
        addValidField("path");
    }

    @Column(name = "RESOURCE_TYPE")
    public String getResourceType() {
        return resourceType;
    }

    public void setResourceType(String resourceType) {
        this.resourceType = resourceType;
        if(resourceType == null){
              removeValidField("resourceType");
              return;
        }
        addValidField("resourceType");
    }

    @Column(name = "IS_DEFAULT")
    public Integer getIsDefault() {
        return isDefault;
    }

    public void setIsDefault(Integer isDefault) {
        this.isDefault = isDefault;
        if(isDefault == null){
              removeValidField("isDefault");
              return;
        }
        addValidField("isDefault");
    }
}