text:
local bit = require "bit"
local ffi = require "ffi"

local band = bit.band
local rshift = bit.rshift
local lib = ffi.C
local ffi_str = ffi.string
local concat = table.concat
local has_table_new, new_tab = pcall(require, "table.new")
if not has_table_new or type(new_tab) ~= "function" then
    new_tab = function () return {} end
end

local _M = {
    _VERSION = "0.1",
}

-- common utils/constants
local IS_64_BIT = ffi.abi('64bit')
local ERANGE = 'Result too large'

ffi.cdef([[
    char* strerror(int errnum);
]])

local function errno()
    return ffi_str(lib.strerror(ffi.errno()))
end

local OS = ffi.os
-- sys/syslimits.h
local MAXPATH
local wchar_t
if OS == 'Windows' then
    MAXPATH = 260
    ffi.cdef([[
        typedef int mbstate_t;
        /*
        In VC2015, M$ change the definition of mbstate_t to this and breaks the ABI.
        */
        typedef struct _Mbstatet
        { // state of a multibyte translation
            unsigned long _Wchar;
            unsigned short _Byte, _State;
        } _Mbstatet;
        typedef _Mbstatet mbstate_t;

        size_t mbrtowc(wchar_t* pwc,
            const char* s,
            size_t n,
            mbstate_t* ps);
    ]])

    function wchar_t(s)
        local mbstate = ffi.new('mbstate_t[1]')
        local wcs = ffi.new('wchar_t[?]', #s + 1)
        local i = 0
        local offset = 0
        local len = #s
        while true do
            local processed = lib.mbrtowc(
                wcs + i, ffi.cast('const char *', s) + offset, len, mbstate)
            if processed <= 0 then break end
            i = i + 1
            offset = offset + processed
            len = len - processed
        end
        return wcs
    end

elseif OS == 'Linux' then
    MAXPATH = 4096
else
    MAXPATH = 1024
end

-- misc
if OS == "Windows" then
    local utime_def
    if IS_64_BIT then
        utime_def = [[
            typedef __int64 time_t;
            struct __utimebuf64 {
                time_t actime;
                time_t modtime;
            };
            typedef struct __utimebuf64 utimebuf;
            int _utime64(unsigned char *file, utimebuf *times);
        ]]
    else
        utime_def = [[
            typedef __int32 time_t;
            struct __utimebuf32 {
                time_t actime;
                time_t modtime;
            };
            typedef struct __utimebuf32 utimebuf;
            int _utime632(unsigned char *file, utimebuf *times);
        ]]
    end

    ffi.cdef([[
        char *_getcwd(char *buf, size_t size);
        int _chdir(const char *path);
        int _rmdir(const char *pathname);
        int _mkdir(const char *pathname);
        ]] .. utime_def .. [[
        typedef wchar_t* LPTSTR;
        typedef unsigned char BOOLEAN;
        typedef unsigned long DWORD;
        BOOLEAN CreateSymbolicLinkW(
            LPTSTR lpSymlinkFileName,
            LPTSTR lpTargetFileName,
            DWORD dwFlags
        );

        int _fileno(struct FILE *stream);
        int _setmode(int fd, int mode);
    ]])

    function _M.chdir(path)
        if type(path) ~= 'string' then
            error('path should be a string')
        end
        if lib._chdir(path) == 0 then
            return true
        end
        return nil, errno()
    end

    function _M.currentdir()
        local size = MAXPATH
        while true do
            local buf = ffi.new("char[?]", size)
            if lib._getcwd(buf, size) ~= nil then
                return ffi_str(buf)
            end
            local err = errno()
            if err ~= ERANGE then
                return nil, err
            end
            size = size * 2
        end
    end

    function _M.mkdir(path)
        if type(path) ~= 'string' then
            error('path should be a string')
        end
        if lib._mkdir(path) == 0 then
            return true
        end
        return nil, errno()
    end

    function _M.rmdir(path)
        if type(path) ~= 'string' then
            error('path should be a string')
        end
        if lib._rmdir(path) == 0 then
            return true
        end
        return nil, errno()
    end

    function _M.touch(path, actime, modtime)
        local buf

        if type(actime) == "number" then
            modtime = modtime or actime
            buf = ffi.new("utimebuf")
            buf.actime  = actime
            buf.modtime = modtime
        end

        local p = ffi.new("unsigned char[?]", #path + 1)
        ffi.copy(p, path)
        local utime = IS_64_BIT and lib._utime64 or lib._utime32
        if utime(p, buf) == 0 then
            return true
        end
        return nil, errno()
    end

    function _M.setmode(file, mode)
        if io.type(file) ~= 'file' then
            error("setmode: invalid file")
        end
        if mode ~= nil and (mode ~= 'text' and mode ~= 'binary') then
            error('setmode: invalid mode')
        end
        mode = (mode == 'text') and 0x4000 or 0x8000
        local prev_mode = lib._setmode(lib._fileno(file), mode)
        if prev_mode == -1 then
            return nil, errno()
        end
        return true, (prev_mode == 0x4000) and 'text' or 'binary'
    end

    local function check_is_dir(path)
        return _M.attributes(path, 'mode') == 'directory' and 1 or 0
    end

    function _M.link(old, new)
        local is_dir = check_is_dir(old)
        if lib.CreateSymbolicLinkW(
                wchar_t(new),
                wchar_t(old), is_dir) ~= 0 then
            return true
        end
        return nil, errno()
    end

    local findfirst
    local findnext
    if IS_64_BIT then
        ffi.cdef([[
            typedef struct _finddata64_t {
                uint64_t  attrib;
                uint64_t  time_create;
                uint64_t  time_access;
                uint64_t  time_write;
                uint64_t  size;
                char      name[]] .. MAXPATH ..[[];
            } _finddata_t;
            int _findfirst64(const char *filespec, _finddata_t *fileinfo);
            int _findnext64(int handle, _finddata_t *fileinfo);
            int _findclose(int handle);
        ]])
        findfirst = lib._findfirst64
        findnext = lib._findnext64
    else
        ffi.cdef([[
            typedef struct _finddata32_t {
                uint32_t  attrib;
                uint32_t  time_create;
                uint32_t  time_access;
                uint32_t  time_write;
                uint32_t  size;
                char      name[]] .. MAXPATH ..[[];
            } _finddata_t;
            int _findfirst32(const char* filespec, _finddata_t* fileinfo);
            int _findnext32(int handle, _finddata_t *fileinfo);
            int _findclose(int handle);
        ]])
        findfirst = lib._findfirst32
        findnext = lib._findnext32
    end

    local function findclose(dentry)
        if dentry and dentry.handle ~= -1 then
            lib._findclose(dentry.handle)
            dentry.handle = -1
        end
    end

    local dir_type = ffi.metatype("struct {int handle;}", {
        __gc = findclose
    })

    local function close(dir)
        findclose(dir._dentry)
        dir.closed = true
    end

    local function iterator(dir)
        if dir.closed ~= false then error("closed directory") end
        local entry = ffi.new("_finddata_t")
        if not dir._dentry then
            dir._dentry = ffi.new(dir_type)
            dir._dentry.handle = findfirst(dir._pattern, entry)
            if dir._dentry.handle == -1 then
                dir.closed = true
                return nil, errno()
            end
            return ffi_str(entry.name)
        end

        if findnext(dir._dentry.handle, entry) == 0 then
            return ffi_str(entry.name)
        end
        close(dir)
        return nil
    end

    local dirmeta = {__index = {
        next = iterator,
        close = close,
    }}

    function _M.dir(path)
        if #path > MAXPATH - 2 then
            error('path too long: ' .. path)
        end
        local dir_obj = setmetatable({
            _pattern = path..'/*',
            closed  = false,
        }, dirmeta)
        return iterator, dir_obj
    end

    ffi.cdef([[
        int _fileno(struct FILE *stream);
        int fseek(struct FILE *stream, long offset, int origin);
        long ftell(struct FILE *stream);
        int _locking(int fd, int mode, long nbytes);
    ]])

    local mode_ltype_map = {
        r = 2, -- LK_NBLCK
        w = 2, -- LK_NBLCK
        u = 0, -- LK_UNLCK
    }
    local SEEK_SET = 0
    local SEEK_END = 2

    local function lock(fh, mode, start, len)
        local lkmode = mode_ltype_map[mode]
        if not len or len <= 0 then
            if lib.fseek(fh, 0, SEEK_END) ~= 0 then
                return nil, errno()
            end
            len = lib.ftell(fh)
        end
        if not start or start <= 0 then
            start = 0
        end
        if lib.fseek(fh, start, SEEK_SET) ~= 0 then
            return nil, errno()
        end
        local fd = lib._fileno(fh)
        if lib._locking(fd, lkmode, len) == -1 then
            return nil, errno()
        end
        return true
    end

    function _M.lock(filehandle, mode, start, length)
        if mode ~= 'r' and mode ~= 'w' then
            error("lock: invalid mode")
        end
        if io.type(filehandle) ~= 'file' then
            error("lock: invalid file")
        end
        local ok, err = lock(filehandle, mode, start, length)
        if not ok then
            return nil, err
        end
        return true
    end

    function _M.unlock(filehandle, start, length)
        if io.type(filehandle) ~= 'file' then
            error("unlock: invalid file")
        end
        local ok, err = lock(filehandle, 'u', start, length)
        if not ok then
            return nil, err
        end
        return true
    end
else
    ffi.cdef([[
        char *getcwd(char *buf, size_t size);
        int chdir(const char *path);
        int rmdir(const char *pathname);
        typedef unsigned int mode_t;
        int mkdir(const char *pathname, mode_t mode);
        typedef size_t time_t;
        struct utimebuf {
            time_t actime;
            time_t modtime;
        };
        int utime(const char *file, const struct utimebuf *times);
        int link(const char *oldpath, const char *newpath);
        int symlink(const char *oldpath, const char *newpath);
    ]])

    function _M.chdir(path)
        if lib.chdir(path) == 0 then
            return true
        end
        return nil, errno()
    end

    function _M.currentdir()
        local size = MAXPATH
        while true do
            local buf = ffi.new("char[?]", size)
            if lib.getcwd(buf, size) ~= nil then
                return ffi_str(buf)
            end
            local err = errno()
            if err ~= ERANGE then
                return nil, err
            end
            size = size * 2
        end
    end

    function _M.mkdir(path, mode)
        if lib.mkdir(path, mode or 509) == 0 then
            return true
        end
        return nil, errno()
    end

    function _M.rmdir(path)
        if lib.rmdir(path) == 0 then
            return true
        end
        return nil, errno()
    end

    function _M.touch(path, actime, modtime)
        local buf

        if type(actime) == "number" then
            modtime = modtime or actime
            buf = ffi.new("struct utimebuf")
            buf.actime  = actime
            buf.modtime = modtime
        end

        local p = ffi.new("unsigned char[?]", #path + 1)
        ffi.copy(p, path)

        if lib.utime(p, buf) == 0 then
            return true
        end
        return nil, errno()
    end

    function _M.setmode()
        return true, "binary"
    end

    function _M.link(old, new, symlink)
        local f = symlink and lib.symlink or lib.link
        if f(old, new) == 0 then
            return true
        end
        return nil, errno()
    end

    local dirent_def
    if OS == 'OSX' or OS == 'BSD' then
        dirent_def = [[
            /* _DARWIN_FEATURE_64_BIT_INODE is NOT defined here? */
            struct dirent {
                uint32_t d_ino;
                uint16_t d_reclen;
                uint8_t  d_type;
                uint8_t  d_namlen;
                char d_name[256];
            };
        ]]
    else
        dirent_def = [[
            struct dirent {
                int64_t           d_ino;
                size_t           d_off;
                unsigned short  d_reclen;
                unsigned char   d_type;
                char            d_name[256];
            };
        ]]
    end
    ffi.cdef(dirent_def .. [[
        typedef struct  __dirstream DIR;
        DIR *opendir(const char *name);
        struct dirent *readdir(DIR *dirp);
        int closedir(DIR *dirp);
    ]])

    local function close(dir)
        if dir._dentry ~= nil then
            lib.closedir(dir._dentry)
            dir._dentry = nil
            dir.closed = true
        end
    end

    local function iterator(dir)
        if dir.closed ~= false then error("closed directory") end

        local entry = lib.readdir(dir._dentry)
        if entry ~= nil then
            return ffi_str(entry.d_name)
        else
            close(dir)
            return nil
        end
    end

    local dir_obj_type = ffi.metatype([[
        struct {
            DIR *_dentry;
            bool closed;
        }
    ]],
    {__index = {
        next = iterator,
        close = close,
    }, __gc = close
    })

    function _M.dir(path)
        local dentry = lib.opendir(path)
        if dentry == nil then
            error("cannot open "..path.." : "..errno())
        end
        local dir_obj = ffi.new(dir_obj_type)
        dir_obj._dentry = dentry
        dir_obj.closed = false;
        return iterator, dir_obj
    end

    local SEEK_SET = 0
    local F_SETLK = (OS == 'Linux') and 6 or 8
    local mode_ltype_map
    local flock_def
    if OS == 'Linux' then
        flock_def = [[
            struct flock {
                short int l_type;
                short int l_whence;
                int64_t l_start;
                int64_t l_len;
                int l_pid;
            };
        ]]
        mode_ltype_map = {
            r = 0, -- F_RDLCK
            w = 1, -- F_WRLCK
            u = 2, -- F_UNLCK
        }
    else
        flock_def = [[
            struct flock {
                int64_t	l_start;
                int64_t	l_len;
                int32_t	l_pid;
                short	l_type;
                short	l_whence;
            };
        ]]
        mode_ltype_map = {
            r = 1, -- F_RDLCK
            u = 2, -- F_UNLCK
            w = 3, -- F_WRLCK
        }
    end

    ffi.cdef(flock_def..[[
        int fileno(struct FILE *stream);
        int fcntl(int fd, int cmd, ... /* arg */ );
        int unlink(const char *path);
    ]])

    local function lock(fd, mode, start, len)
        local flock = ffi.new('struct flock')
        flock.l_type = mode_ltype_map[mode]
        flock.l_whence = SEEK_SET
        flock.l_start = start or 0
        flock.l_len = len or 0
        if lib.fcntl(fd, F_SETLK, flock) == -1 then
            return nil, errno()
        end
        return true
    end

    function _M.lock(filehandle, mode, start, length)
        if mode ~= 'r' and mode ~= 'w' then
            error("lock: invalid mode")
        end
        if io.type(filehandle) ~= 'file' then
            error("lock: invalid file")
        end
        local fd = lib.fileno(filehandle)
        local ok, err = lock(fd, mode, start, length)
        if not ok then
            return nil, err
        end
        return true
    end

    function _M.unlock(filehandle, start, length)
        if io.type(filehandle) ~= 'file' then
            error("unlock: invalid file")
        end
        local fd = lib.fileno(filehandle)
        local ok, err = lock(fd, 'u', start, length)
        if not ok then
            return nil, err
        end
        return true
    end
end

-- lock related
local dir_lock_struct
local create_lockfile
local delete_lockfile

if OS == 'Windows' then
    ffi.cdef([[
        typedef const wchar_t* LPCWSTR;
        typedef struct _SECURITY_ATTRIBUTES {
            DWORD nLength;
            void *lpSecurityDescriptor;
            int bInheritHandle;
        } SECURITY_ATTRIBUTES;
        typedef SECURITY_ATTRIBUTES *LPSECURITY_ATTRIBUTES;
        void *CreateFileW(
            LPCWSTR lpFileName,
            DWORD dwDesiredAccess,
            DWORD dwShareMode,
            LPSECURITY_ATTRIBUTES lpSecurityAttributes,
            DWORD dwCreationDisposition,
            DWORD dwFlagsAndAttributes,
            void *hTemplateFile
        );

        int CloseHandle(void *hObject);
    ]])

    local GENERIC_WRITE = 0x40000000
    local CREATE_NEW = 1
    local FILE_NORMAL_DELETE_ON_CLOSE = 0x04000080

    dir_lock_struct = 'struct {void *lockname;}'

    function create_lockfile(dir_lock, _, lockname)
        lockname = wchar_t(lockname)
        dir_lock.lockname = lib.CreateFileW(lockname, GENERIC_WRITE, 0, nil, CREATE_NEW,
                FILE_NORMAL_DELETE_ON_CLOSE, nil)
        return dir_lock.lockname ~= ffi.cast('void*', -1)
    end

    function delete_lockfile(dir_lock)
        return lib.CloseHandle(dir_lock.lockname)
    end
else
    dir_lock_struct = 'struct {char *lockname;}'
    function create_lockfile(dir_lock, path, lockname)
        dir_lock.lockname = ffi.new('char[?]', #lockname + 1)
        ffi.copy(dir_lock.lockname, lockname)
        return lib.symlink(path, lockname) == 0
    end

    function delete_lockfile(dir_lock)
        return lib.unlink(dir_lock.lockname)
    end
end

local function unlock_dir(dir_lock)
    if dir_lock.lockname ~= nil then
        dir_lock:delete_lockfile()
        dir_lock.lockname = nil
    end
    return true
end

local dir_lock_type = ffi.metatype(dir_lock_struct,
    {__gc = unlock_dir,
    __index = {
        free = unlock_dir,
        create_lockfile = create_lockfile,
        delete_lockfile = delete_lockfile,
    }}
)

function _M.lock_dir(path, _)
    -- It's interesting that the lock_dir from vanilla lfs just ignores second paramter.
    -- So, I follow this behavior too :)
    local dir_lock = ffi.new(dir_lock_type)
    local lockname = path .. '/lockfile.lfs'
    if not dir_lock:create_lockfile(path, lockname) then
        return nil, errno()
    end
    return dir_lock
end

-- stat related
local stat_func
local lstat_func
if OS == 'Linux' then
    ffi.cdef([[
        long syscall(int number, ...);
    ]])
    local ARCH = ffi.arch
    -- Taken from justincormack/ljsyscall
    local stat_syscall_num
    local lstat_syscall_num
    if ARCH == 'x64' then
        ffi.cdef([[
            typedef struct {
                unsigned long   st_dev;
                unsigned long   st_ino;
                unsigned long   st_nlink;
                unsigned int    st_mode;
                unsigned int    st_uid;
                unsigned int    st_gid;
                unsigned int    __pad0;
                unsigned long   st_rdev;
                long            st_size;
                long            st_blksize;
                long            st_blocks;
                unsigned long   st_atime;
                unsigned long   st_atime_nsec;
                unsigned long   st_mtime;
                unsigned long   st_mtime_nsec;
                unsigned long   st_ctime;
                unsigned long   st_ctime_nsec;
                long            __unused[3];
            } stat;
        ]])
        stat_syscall_num = 4
        lstat_syscall_num = 6
    elseif ARCH == 'x86' then
        ffi.cdef([[
            typedef struct {
                unsigned long long      st_dev;
                unsigned char   __pad0[4];
                unsigned long   __st_ino;
                unsigned int    st_mode;
                unsigned int    st_nlink;
                unsigned long   st_uid;
                unsigned long   st_gid;
                unsigned long long      st_rdev;
                unsigned char   __pad3[4];
                long long       st_size;
                unsigned long   st_blksize;
                unsigned long long      st_blocks;
                unsigned long   st_atime;
                unsigned long   st_atime_nsec;
                unsigned long   st_mtime;
                unsigned int    st_mtime_nsec;
                unsigned long   st_ctime;
                unsigned long   st_ctime_nsec;
                unsigned long long      st_ino;
            } stat;
        ]])
        stat_syscall_num = IS_64_BIT and 106 or 195
        lstat_syscall_num = IS_64_BIT and 107 or 196
    elseif ARCH == 'arm' then
        if IS_64_BIT then
            ffi.cdef([[
                typedef struct {
                    unsigned long   st_dev;
                    unsigned long   st_ino;
                    unsigned int    st_mode;
                    unsigned int    st_nlink;
                    unsigned int    st_uid;
                    unsigned int    st_gid;
                    unsigned long   st_rdev;
                    unsigned long   __pad1;
                    long            st_size;
                    int             st_blksize;
                    int             __pad2;
                    long            st_blocks;
                    long            st_atime;
                    unsigned long   st_atime_nsec;
                    long            st_mtime;
                    unsigned long   st_mtime_nsec;
                    long            st_ctime;
                    unsigned long   st_ctime_nsec;
                    unsigned int    __unused4;
                    unsigned int    __unused5;
                } stat;
            ]])
            stat_syscall_num = 106
            lstat_syscall_num = 107
        else
            ffi.cdef([[
                typedef struct {
                    unsigned long long      st_dev;
                    unsigned char   __pad0[4];
                    unsigned long   __st_ino;
                    unsigned int    st_mode;
                    unsigned int    st_nlink;
                    unsigned long   st_uid;
                    unsigned long   st_gid;
                    unsigned long long      st_rdev;
                    unsigned char   __pad3[4];
                    long long       st_size;
                    unsigned long   st_blksize;
                    unsigned long long      st_blocks;
                    unsigned long   st_atime;
                    unsigned long   st_atime_nsec;
                    unsigned long   st_mtime;
                    unsigned int    st_mtime_nsec;
                    unsigned long   st_ctime;
                    unsigned long   st_ctime_nsec;
                    unsigned long long      st_ino;
                } stat;
            ]])
            stat_syscall_num = 195
            lstat_syscall_num = 196
        end
    elseif ARCH == 'ppc' or ARCH == 'ppcspe' then
        ffi.cdef([[
            typedef struct {
                unsigned long long st_dev;
                unsigned long long st_ino;
                unsigned int    st_mode;
                unsigned int    st_nlink;
                unsigned int    st_uid;
                unsigned int    st_gid;
                unsigned long long st_rdev;
                unsigned long long __pad1;
                long long       st_size;
                int             st_blksize;
                int             __pad2;
                long long       st_blocks;
                int             st_atime;
                unsigned int    st_atime_nsec;
                int             st_mtime;
                unsigned int    st_mtime_nsec;
                int             st_ctime;
                unsigned int    st_ctime_nsec;
                unsigned int    __unused4;
                unsigned int    __unused5;
            } stat;
        ]])
        stat_syscall_num = IS_64_BIT and 106 or 195
        lstat_syscall_num = IS_64_BIT and 107 or 196
    elseif ARCH == 'mips' or ARCH == 'mipsel' then
        ffi.cdef([[
            typedef struct {
                unsigned long   st_dev;
                unsigned long   __st_pad0[3];
                unsigned long long      st_ino;
                mode_t          st_mode;
                nlink_t         st_nlink;
                uid_t           st_uid;
                gid_t           st_gid;
                unsigned long   st_rdev;
                unsigned long   __st_pad1[3];
                long long       st_size;
                time_t          st_atime;
                unsigned long   st_atime_nsec;
                time_t          st_mtime;
                unsigned long   st_mtime_nsec;
                time_t          st_ctime;
                unsigned long   st_ctime_nsec;
                unsigned long   st_blksize;
                unsigned long   __st_pad2;
                long long       st_blocks;
                long __st_padding4[14];
            } stat;
        ]])
        stat_syscall_num = IS_64_BIT and 4106 or 4213
        lstat_syscall_num = IS_64_BIT and 4107 or 4214
    end

    if stat_syscall_num then
        stat_func = function(filepath, buf)
            return lib.syscall(stat_syscall_num, filepath, buf)
        end
        lstat_func = function(filepath, buf)
            return lib.syscall(lstat_syscall_num, filepath, buf)
        end
    else
        ffi.cdef('typedef struct {} stat;')
        stat_func = function() error("TODO support other Linux architectures") end
        lstat_func = stat_func
    end
elseif OS == 'Windows' then
    ffi.cdef([[
        typedef struct {
            unsigned int        st_dev;
            unsigned short      st_ino;
            unsigned short      st_mode;
            short               st_nlink;
            short               st_uid;
            short               st_gid;
            unsigned int        st_rdev;
            int64_t             st_size;
            long long           st_atime;
            long long           st_mtime;
            long long           st_ctime;
        } stat;
        int _stat64(const char *path, stat *buffer);
    ]])

    stat_func = lib._stat64
    lstat_func = stat_func
elseif OS == 'OSX' then
    ffi.cdef([[
        struct timespec {
            time_t tv_sec;
            long tv_nsec;
        };
        typedef struct {
            uint32_t           st_dev;
            uint16_t          st_mode;
            uint16_t         st_nlink;
            uint64_t         st_ino;
            uint32_t           st_uid;
            uint32_t           st_gid;
            uint32_t           st_rdev;
            struct timespec st_atimespec;
            struct timespec st_mtimespec;
            struct timespec st_ctimespec;
            struct timespec st_birthtimespec;
            int64_t           st_size;
            int64_t        st_blocks;
            int32_t       st_blksize;
            uint32_t        st_flags;
            uint32_t        st_gen;
            int32_t         st_lspare;
            int64_t         st_qspare[2];
        } stat;
        int stat64(const char *path, stat *buf);
        int lstat64(const char *path, stat *buf);
    ]])
    stat_func = lib.stat64
    lstat_func = lib.lstat64
else
    ffi.cdef('typedef struct {} stat;')
    stat_func = function() error('TODO: support other posix system') end
    lstat_func = stat_func
end

local STAT = {
    FMT   = 0xF000,
    FSOCK = 0xC000,
    FLNK  = 0xA000,
    FREG  = 0x8000,
    FBLK  = 0x6000,
    FDIR  = 0x4000,
    FCHR  = 0x2000,
    FIFO  = 0x1000,
}

local ftype_name_map = {
    [STAT.FREG]  = 'file',
    [STAT.FDIR]  = 'directory',
    [STAT.FLNK]  = 'link',
    [STAT.FSOCK] = 'socket',
    [STAT.FCHR]  = 'char device',
    [STAT.FBLK]  = "block device",
    [STAT.FIFO]  = "named pipe",
}

local function mode_to_ftype(mode)
    local ftype = band(mode, STAT.FMT)
    return ftype_name_map[ftype] or 'other'
end

local function mode_to_perm(mode)
    local perm_bits = band(mode, tonumber(777, 8))
    local perm = new_tab(9, 0)
    local i = 9
    while i > 0 do
        local perm_bit = band(perm_bits, 7)
        perm[i] = (band(perm_bit, 1) > 0 and 'x' or '-')
        perm[i-1] = (band(perm_bit, 2) > 0 and 'w' or '-')
        perm[i-2] = (band(perm_bit, 4) > 0 and 'r' or '-')
        i = i - 3
        perm_bits = rshift(perm_bits, 3)
    end
    return concat(perm)
end

local function time_or_timespec(time, timespec)
    local t = tonumber(time)
    if not t and timespec then
        t = tonumber(timespec.tv_sec)
    end
    return t
end

local attr_handlers = {
    access = function(st) return time_or_timespec(st.st_atime, st.st_atimespec) end,
    blksize = function(st) return tonumber(st.st_blksize) end,
    blocks = function(st) return tonumber(st.st_blocks) end,
    change = function(st) return time_or_timespec(st.st_ctime, st.st_ctimespec) end,
    dev = function(st) return tonumber(st.st_dev) end,
    gid = function(st) return tonumber(st.st_gid) end,
    ino = function(st) return tonumber(st.st_ino) end,
    mode = function(st) return mode_to_ftype(st.st_mode) end,
    modification = function(st) return time_or_timespec(st.st_mtime, st.st_mtimespec) end,
    nlink = function(st) return tonumber(st.st_nlink) end,
    permissions = function(st) return mode_to_perm(st.st_mode) end,
    rdev = function(st) return tonumber(st.st_rdev) end,
    size = function(st) return tonumber(st.st_size) end,
    uid = function(st) return tonumber(st.st_uid) end,
}

-- Add target field for symlinkattributes, which is the absolute path of linked target
local get_link_target_path
if OS == 'Windows' then
    function get_link_target_path()
        return nil
    end
else
    ffi.cdef('unsigned long readlink(const char *path, char *buf, size_t bufsize);')
    function get_link_target_path(link_path)
        local size = MAXPATH
        while true do
            local buf = ffi.new('char[?]', size)
            local read = lib.readlink(link_path, buf, size)
            if read == -1 then
                return nil, errno()
            end
            if read < size then
                return ffi_str(buf)
            end
            size = size * 2
        end
    end
end

local mt = {
    __index = function(self, attr_name)
        local func = attr_handlers[attr_name]
        return func and func(self)
    end
}
local stat_type = ffi.metatype('stat', mt)

local function attributes(filepath, attr, follow_symlink)
    local buf = ffi.new(stat_type)
    local func = follow_symlink and stat_func or lstat_func
    if func(filepath, buf) == -1 then
        return nil, errno()
    end

    local atype = type(attr)
    if atype == 'string' then
        local value
        if attr == 'target' and not follow_symlink then
            value = get_link_target_path(filepath)
        else
            value = buf[attr]
        end
        if value == nil then
            error("invalid attribute name '" .. attr .. "'")
        end
        return value
    else
        local tab = (atype == 'table') and attr or {}
        for k, _ in pairs(attr_handlers) do
            tab[k] = buf[k]
        end
        if not follow_symlink then
            tab.target = get_link_target_path(filepath)
        end
        return tab
    end
end

function _M.attributes(filepath, attr)
    return attributes(filepath, attr, true)
end

function _M.symlinkattributes(filepath, attr)
    return attributes(filepath, attr, false)
end

return _M


text:
function r = makePixelMap(varargin)
% DESCRIPTION:
%       Function to generate a matrix populated with values of how far each
%       pixel in a grid is from the centre (given in pixel coordinates).
%       Both single and double pixel centres can be used by setting the
%       optional input parameter 'OriginSize'. For grids where the
%       dimension size and centre pixel size are not both odd or even, the
%       optional input parameter 'Shift' can be used to control the
%       location of the centerpoint.
%
%       Examples for a 2D pixel map:
%
%       Single pixel origin size for odd and even (with 'Shift' = [1 1] and
%       [0 0], respectively) grid sizes:
%
%       x x x       x x x x         x x x x
%       x 0 x       x x x x         x 0 x x
%       x x x       x x 0 x         x x x x
%                   x x x x         x x x x
%
%       Double pixel origin size for even and odd (with 'Shift' = [1 1] and
%       [0 0], respectively) grid sizes:
%
%       x x x x      x x x x x        x x x x x
%       x 0 0 x      x x x x x        x 0 0 x x
%       x 0 0 x      x x 0 0 x        x 0 0 x x
%       x x x x      x x 0 0 x        x x x x x
%                    x x x x x        x x x x x
%
%       By default a single pixel centre is used which is shifted towards
%       the final row and column.
%
% USAGE:
%       r = makePixelMap(Nx, Ny)
%       r = makePixelMap(Nx, Ny, varargin)
%       r = makePixelMap(Nx, Ny, Nz)
%       r = makePixelMap(Nx, Ny, Nz, varargin)
%
% INPUTS:
%       Nx, Ny, Nz      - size of Cartesian grid in pixels
%
% OPTIONAL INPUTS:
%       Optional 'string', value pairs that may be used to modify the
%       default computational settings.
%
%       'Shift'     - 2 element binary vector controlling the location of
%                     the centre pixel in the x (row) and y (column)
%                     directions for even grid sizes. A value of 0 will
%                     shift towards the first pixel, and 1 will shift
%                     towards the final pixel (default = [1 1])
%       'OriginSize' - parameter controlling whether a 'single' or
%                     'double' pixel is used as the centre (zero) position
%                     (default = 'single').
%
% OUTPUTS:
%       r           - pixel map
%
% ABOUT:
%       author      - Bradley Treeby
%       date        - 6th May 2009
%       last update - 19th July 2011
%
% This function is part of the k-Wave Toolbox (http://www.k-wave.org)
% Copyright (C) 2009-2014 Bradley Treeby and Ben Cox

% This file is part of k-Wave. k-Wave is free software: you can
% redistribute it and/or modify it under the terms of the GNU Lesser
% General Public License as published by the Free Software Foundation,
% either version 3 of the License, or (at your option) any later version.
%
% k-Wave is distributed in the hope that it will be useful, but WITHOUT ANY
% WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
% FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for
% more details.
%
% You should have received a copy of the GNU Lesser General Public License
% along with k-Wave. If not, see <http://www.gnu.org/licenses/>.

% UPDATES:
%       2009/06/19  - completely overhauled computation and added usage of
%                     a double centre point
%       2009/07/01  - added three-dimensional input options
%       2011/07/19  - re-ordered inputs

% define defaults
origin_size = 'single';
shift_def = 1;

% detect whether the inputs are for two or three dimensions
if nargin < 3 || ~isnumeric(varargin{3})
    map_dimension = 2;
    Nx = varargin{1};
    Ny = varargin{2};
    shift = [shift_def, shift_def];
else
    map_dimension = 3;
    Nx = varargin{1};
    Ny = varargin{2};
    Nz = varargin{3};
    shift = [shift_def, shift_def, shift_def];
end

% replace with user defined values if provided
if nargin > map_dimension
    if rem(nargin - map_dimension, 2)
        error('Optional inputs must be entered as param, value pairs');
    end
    for input_index = map_dimension + 1:2:length(varargin)
        switch varargin{input_index}
            case 'Shift'
                shift = varargin{input_index + 1};
            case 'OriginSize'
                origin_size = varargin{input_index + 1};
            otherwise
                error('Unknown optional input');
        end
    end
end

% catch input errors
if ~(strcmp(origin_size, 'single') || strcmp(origin_size, 'double'))
    error('Unknown setting for optional input Center');
end
if numel(shift) ~= map_dimension
    error(['Optional input Shift must have ' num2str(map_dimension) ' elements for ' num2str(map_dimension) ' dimensional input parameters']);
end

switch map_dimension
    case 2

        % create the maps for each dimension
        nx = createPixelDim(Nx, origin_size, shift(1));
        ny = createPixelDim(Ny, origin_size, shift(2));

        % create plaid grids
        [r_x, r_y] = ndgrid(nx, ny);

        % extract the pixel radius
        r = sqrt(r_x.^2 + r_y.^2);

    case 3

        % create the maps for each dimension
        nx = createPixelDim(Nx, origin_size, shift(1));
        ny = createPixelDim(Ny, origin_size, shift(2));
        nz = createPixelDim(Nz, origin_size, shift(3));

        % create plaid grids
        [r_x, r_y, r_z] = ndgrid(nx, ny, nz);

        % extract the pixel radius
        r = sqrt(r_x.^2 + r_y.^2 + r_z.^2);

end

function nx = createPixelDim(Nx, origin_size, shift)
% Nested function to create the pixel radius variable

% grid dimension has an even number of points
if rem(Nx, 2) == 0

    % pixel numbering has a single centre point
    if strcmp(origin_size, 'single')

        % centre point is shifted towards the final pixel
        if shift == 1
            nx = (-Nx/2:1:Nx/2-1).';

        % centre point is shifted towards the first pixel
        else
            nx = (-Nx/2+1:1:Nx/2).';
        end

    % pixel numbering has a double centre point
    else
        nx = [-Nx/2+1:1:0, 0:1:Nx/2-1].';
    end

% grid dimension has an odd number of points
else

    % pixel numbering has a single centre point
    if strcmp(origin_size, 'single')
        nx = (-(Nx-1)/2:1:(Nx-1)/2).';

    % pixel numbering has a double centre point
    else

        % centre point is shifted towards the final pixel
        if shift == 1
            nx = [-(Nx-1)/2:1:0, 0:1:(Nx-1)/2-1].';

        % centre point is shifted towards the first pixel
        else
            nx = [-(Nx-1)/2+1:1:0, 0:1:(Nx-1)/2].';
        end
    end
end

redpajama_set_name: RedPajamaGithub


text:
WD=$(dirname "$0")
WD=$(cd "$WD" || exit 1 ; pwd)

#######################################
# Presubmit script triggered by Prow. #
#######################################
# shellcheck disable=SC1090,SC1091
source "${WD}/proxy-common.inc"

echo 'Generate Wasm module files and run Wasm related test'
make check_wasm


text:
#ifndef _MAGICK_COMPARE_H
#define _MAGICK_COMPARE_H

#if defined(__cplusplus) || defined(c_plusplus)
extern "C" {
#endif /* defined(__cplusplus) || defined(c_plusplus) */

/*
  Pixel differencing algorithms.
*/
typedef enum
{
  UndefinedHighlightStyle,
  AssignHighlightStyle,
  ThresholdHighlightStyle,
  TintHighlightStyle,
  XorHighlightStyle
} HighlightStyle;

typedef struct _DifferenceImageOptions
{
  ChannelType              channel; /* Channel(s) to difference */
  HighlightStyle           highlight_style; /* Pixel annotation style */
  PixelPacket              highlight_color; /* Changed pixel highlight color */
} DifferenceImageOptions;

extern MagickExport void
  InitializeDifferenceImageOptions(DifferenceImageOptions *options,
                                   ExceptionInfo *exception);

extern MagickExport Image
  *DifferenceImage(const Image *reference_image,const Image *compare_image,
                   const DifferenceImageOptions *difference_options,
                   ExceptionInfo *exception);

/*
  Pixel error metrics.
*/
typedef enum
{
  UndefinedMetric,
  MeanAbsoluteErrorMetric,
  MeanSquaredErrorMetric,
  PeakAbsoluteErrorMetric,
  PeakSignalToNoiseRatioMetric,
  RootMeanSquaredErrorMetric
} MetricType;

/*
  Pixel difference statistics.
*/
typedef struct _DifferenceStatistics
{
  double
    red,
    green,
    blue,
    opacity,
    combined;
} DifferenceStatistics;

extern MagickExport void
  InitializeDifferenceStatistics(DifferenceStatistics *difference_statistics,
                                 ExceptionInfo *exception);

extern MagickExport MagickPassFail
  GetImageChannelDifference(const Image *reference_image,
                            const Image *compare_image,
                            const MetricType metric,
                            DifferenceStatistics *statistics,
                            ExceptionInfo *exception),
  GetImageChannelDistortion(const Image *reference_image,
                            const Image *compare_image,
                            const ChannelType channel,
                            const MetricType metric,
                            double *distortion,
                            ExceptionInfo *exception),
  GetImageDistortion(const Image *reference_image,
                     const Image *compare_image,
                     const MetricType metric,
                     double *distortion,
                     ExceptionInfo *exception);

extern MagickExport MagickBool
  IsImagesEqual(Image *,const Image *);

#if defined(__cplusplus) || defined(c_plusplus)
}
#endif /* defined(__cplusplus) || defined(c_plusplus) */

#endif /* _MAGICK_COMPARE_H */

/*
 * Local Variables:
 * mode: c
 * c-basic-offset: 2
 * fill-column: 78
 * End:
 */


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace AA_BIM_Vision_WPF_V1
{
    /// <summary>
    /// MainWindow.xaml 的互動邏輯
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            LoadXAMLMethod();
        }

        //private Button Button_Save;
        //private Button Button_Close;

        private DependencyObject rootObject;

        public void LoadXAMLMethod()
        {
            try
            {

                StreamReader mysr = new StreamReader(@"C:\ProgramData\BIM Vision\etag\AA_BIM_Vision_WPF_V1.xaml");
                MessageBox.Show(mysr.ToString());
                MessageBox.Show(mysr.BaseStream.ToString());
                rootObject = XamlReader.Load(mysr.BaseStream) as DependencyObject;
                MessageBox.Show(rootObject.ToString());

                //MyClass.SetMyProperty((Grid)this.FindName("TEST"), MyClass.GetMyProperty(LogicalTreeHelper.FindLogicalNode(rootObject, "TEST") as Grid));
                Button_Save = LogicalTreeHelper.FindLogicalNode(rootObject, "Button_Save") as Button;
                Button_Save.Click += new RoutedEventHandler(Button_Click_Save);
                Button_Close = LogicalTreeHelper.FindLogicalNode(rootObject, "Button_Close") as Button;
                Button_Close.Click += new RoutedEventHandler(Button_Click_Close);
                this.Content = rootObject;

            }
            catch (FileNotFoundException ex)
            {
                MessageBox.Show(ex.Message.ToString(), nameof(LoadXAMLMethod), MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        public void Button_Click_Save(object sender, RoutedEventArgs e)
        {
            try
            {
                // <Grid local:MyClass.MyProperty="TEST" Name="TEST">
                // MessageBox.Show(MyClass.GetMyProperty((Grid)this.FindName("TEST")), nameof(Button_Click_Save), MessageBoxButton.OK, MessageBoxImage.Information);
                MessageBox.Show(MyClass.GetMyProperty(LogicalTreeHelper.FindLogicalNode(rootObject, "TEST") as UIElement), nameof(Button_Click_Save), MessageBoxButton.OK, MessageBoxImage.Information);
                MessageBox.Show(MyClass.GetMyProperty(LogicalTreeHelper.FindLogicalNode(rootObject, "TEST2") as UIElement), nameof(Button_Click_Save), MessageBoxButton.OK, MessageBoxImage.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString(), nameof(Button_Click_Save), MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        public void Button_Click_Close(object sender, RoutedEventArgs e)
        {
            //MessageBox.Show("Hello World!", nameof(Button_Click));
            this.Hide();
        }
    }
}


text:
module Poise
  # Backported features from Chef to be able to use them with older versions.
  #
  # @since 2.3.0
  module Backports
    autoload :NOT_PASSED, 'poise/backports/not_passed'
  end

  autoload :NOT_PASSED, 'poise/backports/not_passed'
end


text:
from robot.errors import DataError
from robot.utils import (get_error_message, unic, is_java_method,
                         is_string, is_unicode)

from .arguments import JavaArgumentParser, PythonArgumentParser

def no_dynamic_method(*args):
    pass

class _DynamicMethod(object):
    _underscore_name = NotImplemented

    def __init__(self, lib):
        self.method = self._get_method(lib)

    def _get_method(self, lib):
        for name in self._underscore_name, self._camelCaseName:
            method = getattr(lib, name, None)
            if callable(method):
                return method
        return no_dynamic_method

    @property
    def _camelCaseName(self):
        tokens = self._underscore_name.split('_')
        return ''.join([tokens[0]] + [t.capitalize() for t in tokens[1:]])

    @property
    def name(self):
        return self.method.__name__

    def __call__(self, *args):
        try:
            return self._handle_return_value(self.method(*args))
        except:
            raise DataError("Calling dynamic method '%s' failed: %s"
                            % (self.method.__name__, get_error_message()))

    def _handle_return_value(self, value):
        raise NotImplementedError

    def _to_string(self, value):
        if not is_string(value):
            raise DataError('Return value must be string.')
        return value if is_unicode(value) else unic(value, 'UTF-8')

    def _to_list_of_strings(self, value):
        try:
            return [self._to_string(v) for v in value]
        except (TypeError, DataError):
            raise DataError('Return value must be list of strings.')

    def __nonzero__(self):
        return self.method is not no_dynamic_method

class GetKeywordNames(_DynamicMethod):
    _underscore_name = 'get_keyword_names'

    def _handle_return_value(self, value):
        names = self._to_list_of_strings(value or [])
        return list(name for name in self._remove_duplicates(names))

    def _remove_duplicates(self, names):
        seen = set()
        for name in names:
            if name not in seen:
                seen.add(name)
                yield name

class RunKeyword(_DynamicMethod):
    _underscore_name = 'run_keyword'

    @property
    def supports_kwargs(self):
        if is_java_method(self.method):
            return self._supports_java_kwargs(self.method)
        return self._supports_python_kwargs(self.method)

    def _supports_python_kwargs(self, method):
        spec = PythonArgumentParser().parse(method)
        return len(spec.positional) == 3

    def _supports_java_kwargs(self, method):
        func = self.method.im_func if hasattr(method, 'im_func') else method
        signatures = func.argslist[:func.nargs]
        spec = JavaArgumentParser().parse(signatures)
        return (self._java_single_signature_kwargs(spec) or
                self._java_multi_signature_kwargs(spec))

    def _java_single_signature_kwargs(self, spec):
        return len(spec.positional) == 1 and spec.varargs and spec.kwargs

    def _java_multi_signature_kwargs(self, spec):
        return len(spec.positional) == 3 and not (spec.varargs or spec.kwargs)

class GetKeywordDocumentation(_DynamicMethod):
    _underscore_name = 'get_keyword_documentation'

    def _handle_return_value(self, value):
        return self._to_string(value or '')

class GetKeywordArguments(_DynamicMethod):
    _underscore_name = 'get_keyword_arguments'

    def __init__(self, lib):
        _DynamicMethod.__init__(self, lib)
        self._supports_kwargs = RunKeyword(lib).supports_kwargs

    def _handle_return_value(self, value):
        if value is None:
            if self._supports_kwargs:
                return ['*varargs', '**kwargs']
            return ['*varargs']
        return self._to_list_of_strings(value)


text:
using System.Collections.Generic;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace Citrina
{
    public interface IDatabaseApi
    {
        /// <summary>
        /// Returns list of chairs on a specified faculty.
        /// </summary>
        Task<ApiRequest<DatabaseGetChairsResponse>> GetChairsApi(int? facultyId = null, int? offset = null, int? count = null);

        /// <summary>
        /// Returns a list of cities.
        /// </summary>
        Task<ApiRequest<DatabaseGetCitiesResponse>> GetCitiesApi(int? countryId = null, int? regionId = null, string q = null, bool? needAll = null, int? offset = null, int? count = null);

        /// <summary>
        /// Returns information about cities by their IDs.
        /// </summary>
        Task<ApiRequest<IEnumerable<BaseObject>>> GetCitiesByIdApi(IEnumerable<int> cityIds = null);

        /// <summary>
        /// Returns a list of countries.
        /// </summary>
        Task<ApiRequest<DatabaseGetCountriesResponse>> GetCountriesApi(bool? needAll = null, string code = null, int? offset = null, int? count = null);

        /// <summary>
        /// Returns information about countries by their IDs.
        /// </summary>
        Task<ApiRequest<IEnumerable<BaseCountry>>> GetCountriesByIdApi(IEnumerable<int> countryIds = null);

        /// <summary>
        /// Returns a list of faculties (i.e., university departments).
        /// </summary>
        Task<ApiRequest<DatabaseGetFacultiesResponse>> GetFacultiesApi(int? universityId = null, int? offset = null, int? count = null);

        /// <summary>
        /// Get metro stations by city.
        /// </summary>
        Task<ApiRequest<DatabaseGetMetroStationsResponse>> GetMetroStationsApi(int? cityId = null, int? offset = null, int? count = null, bool? extended = null);

        /// <summary>
        /// Get metro station by his id.
        /// </summary>
        Task<ApiRequest<IEnumerable<DatabaseStation>>> GetMetroStationsByIdApi(IEnumerable<int> stationIds = null);

        /// <summary>
        /// Returns a list of regions.
        /// </summary>
        Task<ApiRequest<DatabaseGetRegionsResponse>> GetRegionsApi(int? countryId = null, string q = null, int? offset = null, int? count = null);

        /// <summary>
        /// Returns a list of school classes specified for the country.
        /// </summary>
        Task<ApiRequest<IEnumerable<IEnumerable<string>>>> GetSchoolClassesApi(int? countryId = null);

        /// <summary>
        /// Returns a list of schools.
        /// </summary>
        Task<ApiRequest<DatabaseGetSchoolsResponse>> GetSchoolsApi(string q = null, int? cityId = null, int? offset = null, int? count = null);

        /// <summary>
        /// Returns a list of higher education institutions.
        /// </summary>
        Task<ApiRequest<DatabaseGetUniversitiesResponse>> GetUniversitiesApi(string q = null, int? countryId = null, int? cityId = null, int? offset = null, int? count = null);
    }
}


text:
# Plainion.Windows.Controls.Tree.NodeDropRequest

**Namespace:** Plainion.Windows.Controls.Tree

**Assembly:** Plainion.Windows

Send as parameter with the
*See:* P:Plainion.Windows.Controls.Tree.TreeEditor.DropCommand
to specify the requested DragDrop action.

## Constructors

### Constructor()

## Properties

### Plainion.Windows.Controls.Tree.INode DroppedNode

### Plainion.Windows.Controls.Tree.INode DropTarget

### Plainion.Windows.Interactivity.DragDrop.DropLocation Location


text:
namespace MassTransit.Middleware
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using Logging;
    using SagaStateMachine;

    /// <summary>
    /// Dispatches the ConsumeContext to the consumer method for the specified message type
    /// </summary>
    /// <typeparam name="TSaga">The consumer type</typeparam>
    /// <typeparam name="TMessage">The message type</typeparam>
    public class StateMachineSagaMessageFilter<TSaga, TMessage> :
        ISagaMessageFilter<TSaga, TMessage>
        where TSaga : class, ISaga, SagaStateMachineInstance
        where TMessage : class
    {
        readonly string _activityName;
        readonly Event<TMessage> _event;
        readonly SagaStateMachine<TSaga> _machine;

        public StateMachineSagaMessageFilter(SagaStateMachine<TSaga> machine, Event<TMessage> @event)
        {
            _machine = machine;
            _event = @event;

            _activityName = $"{_machine.Name} process";
        }

        void IProbeSite.Probe(ProbeContext context)
        {
            var scope = context.CreateScope("sagaStateMachine");
            scope.Set(new
            {
                Event = _event.Name,
                DataType = TypeCache<TMessage>.ShortName,
                InstanceType = TypeCache<TSaga>.ShortName
            });

            List<State<TSaga>> states = _machine.States.Cast<State<TSaga>>().Where(x => x.Events.Contains(_event)).ToList();
            if (states.Any())
                scope.Add("states", states.Select(x => x.Name).ToArray());

            _machine.Probe(context);
        }

        public async Task Send(SagaConsumeContext<TSaga, TMessage> context, IPipe<SagaConsumeContext<TSaga, TMessage>> next)
        {
            BehaviorContext<TSaga, TMessage> behaviorContext = new BehaviorContextProxy<TSaga, TMessage>(_machine, context, context, _event);

            StartedActivity? activity = LogContext.Current?.StartSagaStateMachineActivity(behaviorContext);
            try
            {
                if (activity != null && activity.Value.Activity.IsAllDataRequested)
                {
                    State<TSaga> beginState = await behaviorContext.StateMachine.Accessor.Get(behaviorContext).ConfigureAwait(false);
                    if (beginState != null)
                        activity?.SetTag(DiagnosticHeaders.BeginState, beginState.Name);
                }

                await _machine.RaiseEvent(behaviorContext).ConfigureAwait(false);

                if (await _machine.IsCompleted(behaviorContext).ConfigureAwait(false))
                    await context.SetCompleted().ConfigureAwait(false);
            }
            catch (UnhandledEventException ex)
            {
                State<TSaga> currentState = await _machine.Accessor.Get(behaviorContext).ConfigureAwait(false);

                var stateMachineException = new NotAcceptedStateMachineException(typeof(TSaga), typeof(TMessage),
                    context.CorrelationId ?? Guid.Empty, currentState.Name, ex);

                activity?.AddExceptionEvent(stateMachineException);

                throw stateMachineException;
            }
            catch (Exception exception)
            {
                activity?.AddExceptionEvent(exception);

                throw;
            }
            finally
            {
                if (activity != null)
                {
                    if (activity.Value.Activity.IsAllDataRequested)
                    {
                        State<TSaga> endState = await behaviorContext.StateMachine.Accessor.Get(behaviorContext).ConfigureAwait(false);
                        if (endState != null)
                            activity?.SetTag(DiagnosticHeaders.EndState, endState.Name);
                    }

                    activity.Value.Stop();
                }
            }
        }
    }
}


text:
<merge xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/FrameLayout1">

    <TextView
        android:id="@+id/question_text_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="24dp"
        android:layout_gravity="center_horizontal"/>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_gravity="center_horizontal|center_vertical"
        style="?android:attr/buttonBarStyle">

        <Button
            android:id="@+id/true_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/true_button"
            style="?android:attr/buttonBarButtonStyle"/>

        <Button
            android:id="@+id/false_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/false_button"
            style="?android:attr/buttonBarButtonStyle"/>

    </LinearLayout>

    <Button
        android:id="@+id/cheat_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|center"
        android:text="@string/cheat_button"
        style="?android:attr/buttonBarButtonStyle"/>

    <ImageButton
        android:id="@+id/previous_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|start"
        android:src="@drawable/ic_chevron_left_black_48dp"
        android:contentDescription="@string/previous_button"
        style="?android:attr/buttonBarStyle"/>

    <ImageButton
        android:id="@+id/next_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:src="@drawable/ic_chevron_right_black_48dp"
        android:contentDescription="@string/next_button"
        style="?android:attr/buttonBarStyle"/>
</merge>


text:
package org.apache.camel.management.mbean;

import java.util.concurrent.TimeUnit;

import org.apache.camel.CamelContext;
import org.apache.camel.Route;
import org.apache.camel.api.management.ManagedResource;
import org.apache.camel.api.management.mbean.ManagedSuspendableRouteMBean;

@ManagedResource(description = "Managed Suspendable Route")
public class ManagedSuspendableRoute extends ManagedRoute implements ManagedSuspendableRouteMBean {

    public ManagedSuspendableRoute(CamelContext context, Route route) {
        super(context, route);
    }

    public void suspend() throws Exception {
        if (!context.getStatus().isStarted()) {
            throw new IllegalArgumentException("CamelContext is not started");
        }
        context.getRouteController().suspendRoute(getRouteId());
    }

    public void suspend(long timeout) throws Exception {
        if (!context.getStatus().isStarted()) {
            throw new IllegalArgumentException("CamelContext is not started");
        }
        context.getRouteController().suspendRoute(getRouteId(), timeout, TimeUnit.SECONDS);
    }

    public void resume() throws Exception {
        if (!context.getStatus().isStarted()) {
            throw new IllegalArgumentException("CamelContext is not started");
        }
        context.getRouteController().resumeRoute(getRouteId());
    }

}


text:
using osu.Framework.Bindables;

namespace osu.Game.Rulesets.Mods
{
    public interface IHasSeed
    {
        Bindable<int?> Seed { get; }
    }
}


text:
#ifndef __MAIN_H
#define __MAIN_H

#define Lvl1_Det_Pin GPIO_PIN_13
#define Lvl1_Det_GPIO_Port GPIOC
#define Lvl2_Det_Pin GPIO_PIN_14
#define Lvl2_Det_GPIO_Port GPIOC
#define S_Meter_Pin GPIO_PIN_0
#define S_Meter_GPIO_Port GPIOA
#define Fwd_Pwr_Pin GPIO_PIN_1
#define Fwd_Pwr_GPIO_Port GPIOA
#define Rev_Pwr_Pin GPIO_PIN_2
#define Rev_Pwr_GPIO_Port GPIOA
#define IF_Meas_Pin GPIO_PIN_3
#define IF_Meas_GPIO_Port GPIOA
#define OLED_DATA_Pin GPIO_PIN_4
#define OLED_DATA_GPIO_Port GPIOA
#define OLED_CLK_Pin GPIO_PIN_5
#define OLED_CLK_GPIO_Port GPIOA
#define OLED_E_Pin GPIO_PIN_6
#define OLED_E_GPIO_Port GPIOA
#define LPF_17_Pin GPIO_PIN_12
#define LPF_17_GPIO_Port GPIOB
#define LPF_20_Pin GPIO_PIN_13
#define LPF_20_GPIO_Port GPIOB
#define LPF_30_Pin GPIO_PIN_14
#define LPF_30_GPIO_Port GPIOB
#define LPF_40_Pin GPIO_PIN_15
#define LPF_40_GPIO_Port GPIOB
#define Freq_Counter_Pin GPIO_PIN_8
#define Freq_Counter_GPIO_Port GPIOA
#define Atten_Out_Pin GPIO_PIN_9
#define Atten_Out_GPIO_Port GPIOA
#define Enc_Left_Pin GPIO_PIN_10
#define Enc_Left_GPIO_Port GPIOA
#define Enc_Right_Pin GPIO_PIN_11
#define Enc_Right_GPIO_Port GPIOA
#define Enc_Button_Pin GPIO_PIN_12
#define Enc_Button_GPIO_Port GPIOA
#define TXRX_Switch_Pin GPIO_PIN_6
#define TXRX_Switch_GPIO_Port GPIOF
#define CW_Relay_Pin GPIO_PIN_9
#define CW_Relay_GPIO_Port GPIOB
#define Sideband_Relay_Pin GPIO_PIN_8
#define Sideband_Relay_GPIO_Port GPIOB
#define Band_Up_Pin GPIO_PIN_3
#define Band_Up_GPIO_Port GPIOB
#define Band_Down_Pin GPIO_PIN_4
#define Band_Down_GPIO_Port GPIOB
#define CW_Key_Pin GPIO_PIN_0
#define CW_Key_GPIO_Port GPIOF
#define PTT_In_Pin GPIO_PIN_1
#define PTT_In_GPIO_Port GPIOF

void _Error_Handler(char *, int);

#define Error_Handler() _Error_Handler(__FILE__, __LINE__)

/**
  * @}
  */

/**
  * @}
*/

#endif


text:
<?php
include('../../../xeditor/ckeditor_php5.php');
?>

Content

Descriptions about your information.

              How To Use

                <?php
				$path = get_dirname($_SERVER['PHP_SELF']);
				$CKEditor = new CKEditor();
				$initialValue = 'How to use';
				$code = $CKEditor->editor("how", $initialValue);
				?>

              Technical Data

                <?php
				$path = get_dirname($_SERVER['PHP_SELF']);
				$CKEditor = new CKEditor();
				$initialValue = 'Technical Data';
				$code = $CKEditor->editor("technical", $initialValue);
				?>


text:
require 'spec_helper'

describe AwesomeZanox::Publisher do
  let(:client) { AwesomeZanox::Client.new('802B8BF4AE99EBE00F41', 'fa4c0c2020Aa4c+ab9Ea0ec8d39E06/df2c5aa44') }

  before do
    savon.mock!
  end

  after do
    savon.unmock!
  end

  it '#get_profiles' do
    message = client.auth_message('publisherservice', 'getprofile', 'some_date', 'some_nonce')
    savon.expects(:get_profile).with(message: message).returns(fixture('get_profile.xml'))

    response = client.publisher.get_profile({}, 'some_date', 'some_nonce')
    expect(response[:get_profile_response][:profile_item][:first_name]).to eq('Maksim')
  end

  it '#get_program' do
    savon.expects(:get_program).with(message: client.message(program_id: 9337)).returns(fixture('get_program.xml'))

    response = client.publisher.get_program(program_id: 9337)
    expect(response[:get_program_response][:program_item][:name]).to eq('Fluege DE')
  end

  it '#get_program_applications' do
    message = client.auth_message('publisherservice', 'getprogramapplications', 'some_date', 'some_nonce')
    savon.expects(:get_program_applications).with(message: message).returns(fixture('get_program_applications.xml'))

    response = client.publisher.get_program_applications({}, 'some_date', 'some_nonce')
    expect(response[:get_program_applications_response][:program_application_items][:program_application_item][0][:program]).to eq('ABC')
  end

  it '#get_admedia' do
    savon.expects(:get_admedia).with(message: client.message).returns(fixture('get_admedia.xml'))

    response = client.publisher.get_admedia
    expect(response[:get_admedia_response][:admedium_items][:admedium_item][0][:name]).to eq('Generic_DE_120x600')
  end
end


text:
"""
IPv6-related utilities and helper functions.
"""
import os

import netaddr
from oslo_log import log

from neutron.common import constants
from neutron.i18n import _LI

LOG = log.getLogger(__name__)
_IS_IPV6_ENABLED = None

def get_ipv6_addr_by_EUI64(prefix, mac):
    # Check if the prefix is IPv4 address
    isIPv4 = netaddr.valid_ipv4(prefix)
    if isIPv4:
        msg = _("Unable to generate IP address by EUI64 for IPv4 prefix")
        raise TypeError(msg)
    try:
        eui64 = int(netaddr.EUI(mac).eui64())
        prefix = netaddr.IPNetwork(prefix)
        return netaddr.IPAddress(prefix.first + eui64 ^ (1 << 57))
    except (ValueError, netaddr.AddrFormatError):
        raise TypeError(_('Bad prefix or mac format for generating IPv6 '
                          'address by EUI-64: %(prefix)s, %(mac)s:')
                        % {'prefix': prefix, 'mac': mac})
    except TypeError:
        raise TypeError(_('Bad prefix type for generate IPv6 address by '
                          'EUI-64: %s') % prefix)

def is_enabled():
    global _IS_IPV6_ENABLED

    if _IS_IPV6_ENABLED is None:
        disabled_ipv6_path = "/proc/sys/net/ipv6/conf/default/disable_ipv6"
        if os.path.exists(disabled_ipv6_path):
            with open(disabled_ipv6_path, 'r') as f:
                disabled = f.read().strip()
            _IS_IPV6_ENABLED = disabled == "0"
        else:
            _IS_IPV6_ENABLED = False
        if not _IS_IPV6_ENABLED:
            LOG.info(_LI("IPv6 is not enabled on this system."))
    return _IS_IPV6_ENABLED

def is_auto_address_subnet(subnet):
    """Check if subnet is an auto address subnet."""
    modes = [constants.IPV6_SLAAC, constants.DHCPV6_STATELESS]
    return (subnet['ipv6_address_mode'] in modes
            or subnet['ipv6_ra_mode'] in modes)

def is_eui64_address(ip_address):
    """Check if ip address is EUI64."""
    ip = netaddr.IPAddress(ip_address)
    # '0xfffe' addition is used to build EUI-64 from MAC (RFC4291)
    # Look for it in the middle of the EUI-64 part of address
    return ip.version == 6 and not ((ip & 0xffff000000) ^ 0xfffe000000)

def is_ipv6_pd_enabled(subnet):
    """Returns True if the subnetpool_id of the given subnet is equal to
       constants.IPV6_PD_POOL_ID
    """
    return subnet.get('subnetpool_id') == constants.IPV6_PD_POOL_ID


text:
import time
import os
import json
from packaging import version

k8s_resource_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)),
                               "resources/k8s_ymls/")
k8s_rancher_version = str(os.environ.get("RANCHER_K8S_VERSION").split("-")[0][1:])
k8s_rancher_version = version.parse(k8s_rancher_version)
k8s_rancher_version = version.parse(f"{str(k8s_rancher_version.major)}.{str(k8s_rancher_version.minor)}")
k8s_fixed_version = version.parse("1.21")

# Global expectedimagesdict declared to store the images for a specific
# k8s Version
expectedimagesdict = {}

def create_and_validate(
    cloud_provider, rke_client, kubectl, rke_template, nodes,
    base_namespace="ns", network_validation=None, dns_validation=None,
        teardown=False, remove_nodes=False, etcd_private_ip=False):

    create_rke_cluster(rke_client, kubectl, nodes, rke_template)
    network_validation, dns_validation = validate_rke_cluster(
        rke_client, kubectl, nodes, base_ns=base_namespace,
        network_validation=network_validation, dns_validation=dns_validation,
        teardown=teardown, etcd_private_ip=etcd_private_ip)

    if remove_nodes:
        delete_nodes(cloud_provider, nodes)

    return network_validation, dns_validation

def delete_nodes(cloud_provider, nodes):
    for node in nodes:
        cloud_provider.delete_node(node)

def create_rke_cluster(
        rke_client, kubectl, nodes, rke_template, **rke_template_kwargs):
    """
    Creates a cluster and returns the rke config as a python dictionary
    """

    # create rke cluster yml
    config_yml, nodes = rke_client.build_rke_template(
        rke_template, nodes, **rke_template_kwargs)

    # run rke up
    result = rke_client.up(config_yml)

    # validate k8s reachable
    kubectl.kube_config_path = rke_client.kube_config_path()

    return rke_client.convert_to_dict(config_yml)

def validate_rke_cluster(rke_client, kubectl, nodes, base_ns='one',
                         network_validation=None, dns_validation=None,
                         teardown=False, etcd_private_ip=False):
    """
    General rke up test validation, runs validations methods for:
    - node roles validation
    - intercommuincation per pod
    - dns service discovery validation
    If teardown is true, removes any resources created for validation
    """

    validation_node_roles(nodes, kubectl.get_nodes(), etcd_private_ip)
    if network_validation is None:
        network_validation = PodIntercommunicationValidation(kubectl, base_ns)
        network_validation.setup()
    if dns_validation is None:
        dns_validation = DNSServiceDiscoveryValidation(kubectl, base_ns)
        dns_validation.setup()

    network_validation.validate()
    dns_validation.validate()

    if teardown:
        network_validation.teardown()
        dns_validation.teardown()

    return network_validation, dns_validation

def match_nodes(nodes, k8s_nodes):
    """
    Builds a list of tuples, where:
    nodes_to_k8s_nodes[0][0] is the node object matched to
    nodes_to_k8s_nodes[0][1] is the k8s info for the same node
    """
    k8s_node_names = []
    for k8s_node in k8s_nodes['items']:
        k8s_node_names.append(
            k8s_node['metadata']['labels']['kubernetes.io/hostname'])

    nodes_to_k8s_nodes = []
    for node in nodes:
        for k8s_node in k8s_nodes['items']:
            hostname = k8s_node['metadata']['labels']['kubernetes.io/hostname']
            if hostname in node.node_name:
                nodes_to_k8s_nodes.append((node, k8s_node))
                break
        else:
            raise Exception(
                "Did not find provisioned node's '{0}' corresponding nodes "
                "resourse in cluster: {1}".format(
                    node.node_name, k8s_node_names))
    return nodes_to_k8s_nodes

def assert_containers_exist_for_roles(roles, containers):
    # All nodes will have these containers:
    expect_containers = ['kubelet', 'kube-proxy']

    # Add extra containers depending on roles present
    if 'controlplane' in roles:
        expect_containers.extend(
            ['kube-scheduler', 'kube-controller-manager', 'kube-apiserver'])
    else:
        expect_containers.extend(['nginx-proxy'])
    if 'etcd' in roles:
        expect_containers.extend(['etcd'])

    missing_containers = expect_containers[:]
    for container in containers:
        if container in expect_containers:
            missing_containers.remove(container)
    assert len(missing_containers) == 0, \
        "Missing expected containers for role '{0}': {1}".format(
            roles, missing_containers)

def wait_for_etcd_cluster_health(node, etcd_private_ip=False):
    result = ''
    endpoints = "127.0.0.1"
    if etcd_private_ip:
        endpoints = node.private_ip_address
    if k8s_rancher_version <= k8s_fixed_version:
        etcd_tls_cmd = (
                'ETCDCTL_API=2 etcdctl --endpoints "https://' + endpoints + ':2379" '
                 ' --ca-file /etc/kubernetes/ssl/kube-ca.pem --cert-file '
                 ' $ETCDCTL_CERT --key-file '
                 ' $ETCDCTL_KEY cluster-health'
        )
    else:
        etcd_tls_cmd = (
            'ETCDCTL_API=3 etcdctl endpoint health --cluster'
        )

    print(etcd_tls_cmd)
    start_time = time.time()
    while start_time - time.time() < 120:
        result = node.docker_exec('etcd', "sh -c '" + etcd_tls_cmd + "'")
        print("**RESULT**")
        print(result)
        if k8s_rancher_version <= k8s_fixed_version:
            if 'cluster is healthy' in result:
                break
        else:
            if 'is healthy' in result:
                break
        time.sleep(5)
    return result

def verify_metrics_server_addon_images(k8sversion, kubectl,
                                       namespace, selector):

    metricserver = get_component_version(k8sversion,
                                         "rancher/metrics-server")
    # Sleep to allow the metrics server component to get to running state
    time.sleep(10)
    verify_component_status_with_kubectl(kubectl, namespace, selector,
                                         metricserver)

def verify_ingress_addon_images(k8sversion, kubectl, namespace,
                                selector1, selector2):

    ingressdefaultbackend = \
        get_component_version(k8sversion,
                              "rancher/nginx-ingress-controller-defaultbackend"
                              )
    nginxingresscontoller =\
        get_component_version(k8sversion,
                              "rancher/nginx-ingress-controller")
    # Sleep to allow the ingress addon components to get to running state
    time.sleep(5)
    verify_component_status_with_kubectl(kubectl, namespace, selector1,
                                         nginxingresscontoller)
    verify_component_status_with_kubectl(kubectl, namespace, selector2,
                                         ingressdefaultbackend)

def verify_dns_addon_images(k8sversion, kubectl, namespace,
                            selector):

    coredns = get_component_version(k8sversion,
                                    "rancher/coredns-coredns")
    # Sleep to allow the dns addon component to get to running state
    time.sleep(5)

    verify_component_status_with_kubectl(kubectl, namespace, selector, coredns)

def verify_networking_addon_images(k8sversion, kubectl,
                                   namespace, selector):

    flannel = get_component_version(k8sversion,
                                    "rancher/coreos-flannel")

    calico = get_component_version(k8sversion,
                                   "rancher/calico-node")
    # Sleep to allow the network addon component to get to running state
    time.sleep(5)
    verify_component_status_with_kubectl(kubectl, namespace, selector, calico,
                                         flannel)

def verify_component_status_with_kubectl(kubectl, namespace, selector, *args):
    # Method to verify addon status and images

    command = "get pod --namespace " + namespace + " -l " + selector

    res = kubectl.execute_kubectl_cmd(command, json_out=True)
    result = json.loads(res)
    timeout = 180
    start = time.time()
    # Check if the pod is running
    for pod in result["items"]:
        podstatus = pod["status"]["phase"]
        podname = pod["metadata"]["name"]
        print("Pod name is " + podname)
        podreloadcommand = "get pod " + podname + " --namespace " + namespace
        while (podstatus != "Running"):
            if time.time() - start > timeout:
                raise AssertionError("Timed out waiting to reach running state")
            time.sleep(.5)
            podresult = kubectl.execute_kubectl_cmd(podreloadcommand,
                                                    json_out=True)
            podresult = json.loads(podresult)
            podname = podresult["metadata"]["name"]
            print("Pod name is " + podname)
            podstatus = podresult["status"]["phase"]
            print("Pod status is " + podstatus)
        assert True

    # Verify the component images in the pods
    testresult = kubectl.execute_kubectl_cmd(command, json_out=True)
    updatedresult = json.loads(testresult)
    for pod in updatedresult["items"]:
        print("Required Resource Image: ")
        print(args[0])
        podstatus = pod["status"]["phase"]
        if(podstatus == "Running"):
           for i in range(0, len(args)):
               print(pod["status"]["containerStatuses"][i]["image"])
               assert pod["status"]["containerStatuses"][i]["image"] == args[i]

def get_system_images(rke_client, k8s_version):

    # Method to obtain the system images for a k8s version  from rke cli

    command = ("rke config --system-images --version " + k8s_version)
    print(command)
    rke_system_images_dict = rke_client.run_command(command)
    result = rke_system_images_dict.split("\n")
    # Removing the first item which is not required
    result.pop(0)
    print(result)
    return result

def get_component_version(k8s_version, componentname):
    # Method to obtain the image version for a specific component

    systemimageslist = expectedimagesdict[k8s_version]["rkesystemimages"]
    print(systemimageslist)
    for item in systemimageslist:
        itemlist = item.split(":")
        if componentname == itemlist[0]:
           print(componentname)
           componentversion = item
    print("VERSION IS " + componentversion)
    return componentversion

def build_expectedimages_dict(k8s_version, rke_client):
    # Build the expected image list from rke system images list

    if k8s_version in expectedimagesdict.keys():
        return expectedimagesdict[k8s_version]
    else:
        expectedimagesdict[k8s_version] = {}
        result = get_system_images(rke_client, k8s_version)
        for item in result:
            itemlist = item.split(":")
            if "rancher/hyperkube" == itemlist[0]:
                expectedimagesdict[k8s_version]["kube-proxy"] = item
                expectedimagesdict[k8s_version]["kube-scheduler"] = item
                expectedimagesdict[k8s_version]["kube-controller-manager"] \
                    = item
                expectedimagesdict[k8s_version]["kube-apiserver"] = item
                expectedimagesdict[k8s_version]["kubelet"] = item
            if "rancher/coreos-etc[k8s_version]" == itemlist[0]:
                expectedimagesdict[k8s_version]["etcd"] = item
            if "rancher/rke-tools" == itemlist[0]:
                expectedimagesdict[k8s_version]["service-sidekick"] = item

        expectedimagesdict[k8s_version]["rkesystemimages"] = result
        return expectedimagesdict[k8s_version]

def validation_node_roles(nodes, k8s_nodes, etcd_private_ip=False):
    """
    Validates each node's labels for match its roles
    Validates each node's running containers match its role
    Validates etcd etcdctl cluster-health command
    Validates worker nodes nginx-proxy conf file for controlplane ips
    """

    role_matcher = {
        'worker': 'node-role.kubernetes.io/worker',
        'etcd': 'node-role.kubernetes.io/etcd',
        'controlplane': 'node-role.kubernetes.io/controlplane'}

    controlplane_ips = []
    etcd_members = []
    for node in nodes:
        if 'controlplane' in node.roles:
            controlplane_ips.append(node.node_address)
        if 'etcd' in node.roles:
            etcd_members.append(node.node_address)

    nodes_to_k8s_nodes = match_nodes(nodes, k8s_nodes)
    for node, k8s_node in nodes_to_k8s_nodes:
        containers = list(node.docker_ps().keys())
        assert_containers_exist_for_roles(node.roles, containers)
        k8s_node_labels = list(k8s_node['metadata']['labels'].keys())
        for role in node.roles:
            assert role_matcher[role] in k8s_node_labels, \
                "Expected label '{0}' not in labels: {1}".format(
                    role_matcher[role], k8s_node_labels)

            # nodes with controlplane roles do not have nginx-proxy
            if (role == 'worker' or role == 'etcd') and \
                    ('controlplane' not in node.roles):
                result = node.docker_exec(
                    'nginx-proxy', 'cat /etc/nginx/nginx.conf')
                for ip in controlplane_ips:
                    assert 'server {0}:6443'.format(ip) in result, (
                        "Expected to find all controlplane node addresses {0}"
                        "in nginx.conf: {1}".format(controlplane_ips, result))
            if role == 'etcd':
                if len(node.roles) == 1:
                    for taint in k8s_node['spec']['taints']:
                        if taint['key'] == 'node-role.kubernetes.io/etcd':
                            assert taint['effect'] == 'NoExecute', (
                                "{0} etcd-only node's taint is not 'NoExecute'"
                                ": {1}".format(node.node_name, taint['effect'])
                            )
                            # found, do not complete for loop
                            # or else an assertion will be raised
                            break
                    else:
                        assert False, \
                            "Expected to find taint for etcd-only node"
                # check etcd membership and cluster health
                result = wait_for_etcd_cluster_health(node, etcd_private_ip)
                if k8s_rancher_version <= k8s_fixed_version:
                    for member in etcd_members:
                        expect = "got healthy result from https://{}".format(member)
                        assert expect in result, result
                    assert 'cluster is healthy' in result, result
                else:
                    for member in etcd_members:
                        expect = "https://{}:2379 is healthy: successfully committed proposal".format(member)
                        assert expect in result, result
                    assert 'is healthy' in result, result

class PodIntercommunicationValidation(object):
    def __init__(self, kubectl, base_namespace):
        self.kubectl = kubectl
        self.yml_file = (
            k8s_resource_dir + 'daemonset_pods_per_node.yml')
        self.ns_out = 'daemonset-out-{}'.format(base_namespace)
        self.ns_in = 'daemonset-in-{}'.format(base_namespace)
        self.selector = 'name=daemonset-test1'

    def setup(self):
        self.kubectl.create_ns(self.ns_out)
        result = self.kubectl.create_resourse_from_yml(
            self.yml_file, namespace=self.ns_out)

        self.kubectl.create_ns(self.ns_in)
        result = self.kubectl.create_resourse_from_yml(
            self.yml_file, namespace=self.ns_in)

    def validate(self):
        """
        Gets pod name, pod ip, host ip, and containers
        For each pod, use kubectl exec to ping all other pod ips
        Asserts that each ping is successful
        Tears down daemonset
        """
        # get number of expected pods
        worker_nodes = self.kubectl.get_resource(
            'nodes', selector='node-role.kubernetes.io/worker=true')
        master_nodes = self.kubectl.get_resource(
            'nodes', selector='node-role.kubernetes.io/controlplane=true')
        node_names = [n['metadata']['name'] for n in worker_nodes['items']]
        expected_number_pods = len(worker_nodes['items'])
        """
        for master_node in master_nodes['items']:
            if master_node['metadata']['name'] not in node_names:
                expected_number_pods += 1
        """
        # get pods on each node/namespaces to test intercommunication
        # with pods on different nodes
        pods_to_ping = self.kubectl.wait_for_pods(
            selector=self.selector, namespace=self.ns_in,
            number_of_pods=expected_number_pods)
        pods_from_which_ping = self.kubectl.wait_for_pods(
            selector=self.selector, namespace=self.ns_out,
            number_of_pods=expected_number_pods)

        # verify daemonset pods are on all worker nodes
        assert len(pods_to_ping['items']) == expected_number_pods, (
            "DaemonSet number of pods '{0}', does not match number of worker "
            "nodes '{1}'".format(
                len(pods_to_ping['items']), expected_number_pods))
        assert len(pods_from_which_ping['items']) == expected_number_pods, (
            "DaemonSet number of pods '{0}', does not match number of worker "
            "nodes '{1}'".format(
                len(pods_from_which_ping['items']), expected_number_pods))

        pod_ips_to_ping = []
        for pod in pods_to_ping['items']:
            pod_ips_to_ping.append(pod['status']['podIP'])

        pod_names_to_ping_from = []
        for pod in pods_from_which_ping['items']:
            pod_names_to_ping_from.append(pod['metadata']['name'])

        # From each pod of daemonset in namespace ns_out, ping all pods
        # in from second daemonset in ns_in
        expect_result = \
            '1 packets transmitted, 1 received, 0% packet loss'
        for pod_name in pod_names_to_ping_from:
            for pod_ip in pod_ips_to_ping:
                cmd = 'ping -c 1 {0}'.format(pod_ip)
                for _ in range(10):
                    result = self.kubectl.exec_cmd(pod_name, cmd, self.ns_out)
                    assert expect_result in result, (
                        "Could not ping pod with ip {0} from pod {1}:\n"
                        "stdout: {2}\n".format(
                            pod_ip, pod_name, result))

    def teardown(self):
        """
        Deletes a daemonset of pods and namespace
        """
        result = self.kubectl.delete_resourse_from_yml(
            self.yml_file, namespace=self.ns_out)
        result = self.kubectl.delete_resourse_from_yml(
            self.yml_file, namespace=self.ns_in)
        self.kubectl.delete_resourse('namespace', self.ns_out)
        self.kubectl.delete_resourse('namespace', self.ns_in)

class DNSServiceDiscoveryValidation(object):
    def __init__(self, kubectl, base_namespace):
        namespace_one = 'nsone-{}'.format(base_namespace)
        namespace_two = 'nstwo-{}'.format(base_namespace)
        self.namespace = namespace_one
        self.services = {
            'k8test1': {
                'namespace': namespace_one,
                'selector': 'k8s-app=k8test1-service',
                'yml_file': k8s_resource_dir + 'service_k8test1.yml',
            },
            'k8test2': {
                'namespace': namespace_two,
                'selector': 'k8s-app=k8test2-service',
                'yml_file': k8s_resource_dir + 'service_k8test2.yml',
            }
        }
        self.pod_selector = 'k8s-app=pod-test-util'
        self.kubectl = kubectl

    def setup(self):

        for service_name, service_info in self.services.items():
            # create service
            result = self.kubectl.create_ns(service_info['namespace'])

            result = self.kubectl.create_resourse_from_yml(
                service_info['yml_file'], namespace=service_info['namespace'])

        result = self.kubectl.create_resourse_from_yml(
            k8s_resource_dir + 'single_pod.yml',
            namespace=self.namespace)

    def validate(self):
        # wait for exec pod to be ready before validating
        pods = self.kubectl.wait_for_pods(
            selector=self.pod_selector, namespace=self.namespace)
        exec_pod_name = pods['items'][0]['metadata']['name']

        # Get Cluster IP and pod names per service
        dns_records = {}
        for service_name, service_info in self.services.items():
            # map expected IP to dns service name
            dns = "{0}.{1}.svc.cluster.local".format(
                service_name, service_info['namespace'])
            svc = self.kubectl.get_resource(
                'svc', name=service_name, namespace=service_info['namespace'])
            service_pods = self.kubectl.wait_for_pods(
                selector=service_info['selector'],
                namespace=service_info['namespace'], number_of_pods=2)
            svc_cluster_ip = svc["spec"]["clusterIP"]
            dns_records[dns] = {
                'ip': svc_cluster_ip,
                'pods': [p['metadata']['name'] for p in service_pods['items']]
            }

        for dns_record, dns_info in dns_records.items():
            # Check dns resolution
            expected_ip = dns_info['ip']
            cmd = 'dig {0} +short'.format(dns_record)
            result = self.kubectl.exec_cmd(exec_pod_name, cmd, self.namespace)
            assert expected_ip in result, (
                "Unable to test DNS resolution for service {0}: {1}".format(
                    dns_record, result.stderr))

            # Check Cluster IP reaches pods in service
            pods_names = dns_info['pods']
            cmd = 'curl "http://{0}/name.html"'.format(dns_record)
            result = self.kubectl.exec_cmd(exec_pod_name, cmd, self.namespace)
            print(result)
            print(pods_names)
            assert result.rstrip() in pods_names, (
                "Service ClusterIP does not reach pods {0}".format(
                    dns_record))

    def teardown(self):
        self.kubectl.delete_resourse(
            'pod', 'pod-test-util', namespace=self.namespace)

        for service_name, service_info in self.services.items():
            self.kubectl.delete_resourse_from_yml(
                service_info['yml_file'], namespace=service_info['namespace'])
            self.kubectl.delete_resourse(
                'namespace', service_info['namespace'])

def validate_k8s_service_images(nodes, k8s_version, rke_client, kubectl):
    """
    expectedimages dictionary will be built in this method
    This verifies that the nodes have the correct image version
    This does not validate containers per role,
    assert_containers_exist_for_roles method does that
    """
    expectedimagesdict = build_expectedimages_dict(k8s_version, rke_client)
    print(expectedimagesdict)

    for node in nodes:
        containers = node.docker_ps()
        allcontainers = node.docker_ps(includeall=True)
        print("Container Dictionary ")
        print(containers)
        print("All containers dictionary")
        print(allcontainers)
        sidekickservice = "service-sidekick"
        for key in expectedimagesdict.keys():
            servicename = key
            if servicename in containers:
                print("Service name")
                print(servicename)
                print(expectedimagesdict[servicename])
                print(containers[servicename])
                assert expectedimagesdict[servicename] == \
                   containers[servicename], (
                   "K8s service '{0}' does not match config version "
                   "{1}, found {2} on node {3}".format(
                   servicename, expectedimagesdict[servicename],
                   containers[servicename], node.node_name))
        if sidekickservice in expectedimagesdict.keys():
            if sidekickservice in allcontainers:
                print("sidekick-service in allcontainers")
                print(sidekickservice)
                print(expectedimagesdict[sidekickservice])
                print(allcontainers[sidekickservice])
                assert expectedimagesdict[sidekickservice] == \
                    allcontainers[sidekickservice], (
                    "K8s service '{0}' does not match config version "
                    "{1}, found {2} on node {3}".format(
                    sidekickservice, expectedimagesdict[sidekickservice],
                    allcontainers[sidekickservice], node.node_name))

    verify_ingress_addon_images(k8s_version, kubectl,
                                "ingress-nginx", "app=ingress-nginx",
                                "app=default-http-backend")
    verify_networking_addon_images(k8s_version, kubectl,
                                   "kube-system", "k8s-app=canal")
    verify_metrics_server_addon_images(k8s_version, kubectl,
                                      "kube-system", "k8s-app=metrics-server")
    verify_dns_addon_images(k8s_version, kubectl,
                            "kube-system", "k8s-app=kube-dns")

def validate_remove_cluster(nodes):
    """
    Removes all k8s services containers on each node:
    ['kubelet', 'kube-proxy', 'kube-scheduler', 'kube-controller-manager',
     'kube-apiserver', 'nginx-proxy']
    Removes files from these directories:
    ['/etc/kubernetes/ssl', '/var/lib/etcd'
     '/etc/cni', '/opt/cni', '/var/run/calico']
    """
    k8s_services = [
        'kubelet', 'kube-proxy', 'kube-scheduler', 'kube-controller-manager',
        'kube-apiserver', 'nginx-proxy'
    ]
    rke_cleaned_directories = [
        '/etc/kubernetes/ssl', '/var/lib/etcd' '/etc/cni', '/opt/cni',
        '/var/run/calico'
    ]
    for node in nodes:
        containers = node.docker_ps()
        for service in k8s_services:
            assert service not in list(containers.keys()), (
                "Found kubernetes service '{0}' still running on node '{1}'"
                .format(service, node.node_name))

        for directory in rke_cleaned_directories:
            result = node.execute_command('ls ' + directory)
            assert result[0] == '', (
                "Found a non-empty directory '{0}' after remove on node '{1}'"
                .format(directory, node.node_name))

def validate_dashboard(kubectl):
    # Start dashboard
    # Validated it is reachable
    pass


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

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
Uses of Class liquibase.snapshot.CachedRow (Liquibase Core 3.5.3 API)
</TITLE>

<META NAME="date" CONTENT="2016-10-13">

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

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Class
liquibase.snapshot.CachedRow

Packages that use CachedRow

liquibase.snapshot

liquibase.snapshot.jvm

Uses of CachedRow in liquibase.snapshot

Methods in liquibase.snapshot that return types with arguments of type CachedRow

 List<CachedRow>
JdbcDatabaseSnapshot.CachingDatabaseMetaData.getColumns(String catalogName,
           String schemaName,
           String tableName,
           String columnName)

          Return the columns for the given catalog, schema, table, and column.

 List<CachedRow>
JdbcDatabaseSnapshot.CachingDatabaseMetaData.getForeignKeys(String catalogName,
               String schemaName,
               String tableName,
               String fkName)

 List<CachedRow>
JdbcDatabaseSnapshot.CachingDatabaseMetaData.getIndexInfo(String catalogName,
             String schemaName,
             String tableName,
             String indexName)

 List<CachedRow>
JdbcDatabaseSnapshot.CachingDatabaseMetaData.getPrimaryKeys(String catalogName,
               String schemaName,
               String table)

 List<CachedRow>
JdbcDatabaseSnapshot.CachingDatabaseMetaData.getTables(String catalogName,
          String schemaName,
          String table)

 List<CachedRow>
JdbcDatabaseSnapshot.CachingDatabaseMetaData.getUniqueConstraints(String catalogName,
                     String schemaName,
                     String tableName)

 List<CachedRow>
JdbcDatabaseSnapshot.CachingDatabaseMetaData.getViews(String catalogName,
         String schemaName,
         String view)

Uses of CachedRow in liquibase.snapshot.jvm

Methods in liquibase.snapshot.jvm that return types with arguments of type CachedRow

protected  List<CachedRow>
UniqueConstraintSnapshotGenerator.listConstraints(Table table,
                DatabaseSnapshot snapshot,
                Schema schema)

Methods in liquibase.snapshot.jvm with parameters of type CachedRow

protected  Column
ColumnSnapshotGenerator.readColumn(CachedRow columnMetadataResultSet,
           Relation table,
           Database database)

protected  DataType
ColumnSnapshotGenerator.readDataType(CachedRow columnMetadataResultSet,
             Column column,
             Database database)

protected  Object
ColumnSnapshotGenerator.readDefaultValue(CachedRow columnMetadataResultSet,
                 Column columnInfo,
                 Database database)

protected  Object
H2ColumnSnapshotGenerator.readDefaultValue(CachedRow columnMetadataResultSet,
                 Column columnInfo,
                 Database database)

protected  Table
TableSnapshotGenerator.readTable(CachedRow tableMetadataResultSet,
          Database database)

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Copyright © 2016 Liquibase.org. All rights reserved.


text:
package msci.mg.agents;

import msci.mg.Choice;
import msci.mg.ChoiceMemory;
import msci.mg.Strategy;
import msci.mg.StrategyManager;

public class BasicNetworkedAgent extends AbstractNetworkedAgent {
    public BasicNetworkedAgent(StrategyManager strategyManager, ChoiceMemory choiceMemory) {
        super(strategyManager, choiceMemory);
    }

    @Override
    public void prepare() {
        Strategy chosenStrategy;

        if (prediction == null) {
            chosenStrategy = strategyManager.getRandomStrategy();
        } else {
            chosenStrategy = strategyManager.getHighestScoringStrategy();
        }

        prediction = chosenStrategy.predictMinorityChoice(memory.fetch());
    }

    @Override
    public void choose() {
        Agent newBestFriend = neighbourhood.getMostSuccessfulPredictor();

        if (!(newBestFriend instanceof NetworkedAgent)) {
            this.choice = this.prediction;
            this.bestFriend = this;
        } else {
            NetworkedAgent networkedNewBestFriend = (NetworkedAgent) newBestFriend;
            this.choice = networkedNewBestFriend.getPrediction();
            this.bestFriend = newBestFriend;
        }
    }

    @Override
    public void update(Choice correctChoice) {
        super.update(correctChoice);

        if (correctChoice == prediction) {
            incrementCorrectPredictionCount();
        }

        strategyManager.incrementScores(memory.fetch(), correctChoice);
        memory.add(correctChoice);
    }
}


text:
/// <reference path="../../../Northwind/Product/ProductDialog.ts" />

namespace sharp.Serene.BasicSamples {

    @Serenity.Decorators.registerClass()
    @Serenity.Decorators.maximizable()
    export class CloneableEntityDialog extends Northwind.ProductDialog {
        protected updateInterface() {

            // by default cloneButton is hidden in base UpdateInterface method
            super.updateInterface();

            // here we show it if it is edit mode (not new)
            this.cloneButton.toggle(this.isEditMode());
        }

        /**
         * Overriding this method is optional to customize cloned entity
         */
        protected getCloningEntity() {
            var clone = super.getCloningEntity();

            // add (Clone) suffix if it's not already added
            var suffix = ' (Clone)';
            if (!Q.endsWith(clone.ProductName || '', suffix)) {
                clone.ProductName = (clone.ProductName || '') + suffix;
            }

            // it's better to clear image for this sample
            // otherwise we would have to create a temporary copy of it
            // and upload
            clone.ProductImage = null;

            // let's clear fields not logical to be cloned
            clone.UnitsInStock = 0;
            clone.UnitsOnOrder = 0;
            return clone;
        }
    }
}