text:
using namespace boost;
using namespace foundation;

//
// Configuration of the memory allocation subsystem.
//

// This is the global enable/disable switch that conditions everything else.
#undef ENABLE_MEMORY_TRACKING

// Define this symbol to enable report of memory allocations.
#define LOG_MEMORY_ALLOCATIONS

// Define this symbol to enable report of memory allocation failures.
#define LOG_MEMORY_ALLOCATION_FAILURES

// Define this symbol to enable report of memory deallocations.
#undef LOG_MEMORY_DEALLOCATIONS

// Define this symbol to dump a (part of) the callstack when a block of memory is allocated.
#define DUMP_CALLSTACK_ON_ALLOCATION

// Define this symbol to force a call to std::fflush() after every write to the log file.
#define FLUSH_AFTER_WRITE

namespace
{
    // Name of the log file. It will be created in the current working directory.
    const char* MemoryLogFileName = "memory.log";

    // Shave off that many levels from the top of the stack when dumping it to the log file.
    const std::size_t NumberOfCallStackLevelsToSkip = 3;

    // Minimum alignment boundary of all memory allocations, in bytes.
    const std::size_t MemoryAlignment = 16;
}

//
// Memory tracker implementation.
//

#ifdef ENABLE_MEMORY_TRACKING

namespace
{
    // This mutex is used to serialize access to all static members of this file.
    recursive_mutex g_mutex;

    // Indicate whether memory tracking is currently enabled.
    bool g_tracking_enabled = false;

    // Statistics.
    std::uint64_t g_allocation_count = 0;           // total number of memory allocations
    std::uint64_t g_allocated_bytes = 0;            // number of bytes currently allocated
    std::uint64_t g_peak_allocated_bytes = 0;       // peak number of bytes ever allocated
    std::uint64_t g_total_allocated_bytes = 0;      // total number of bytes ever allocated
    std::uint64_t g_largest_allocation_bytes = 0;   // size in bytes of the largest allocation

    // File to which memory operations and leaks are logged.
    std::FILE* g_log_file = 0;

    typedef std::pair<const void*, std::size_t> MemoryBlock;
    typedef std::vector<MemoryBlock> MemoryBlockVector;
    typedef std::map<const void*, std::size_t> MemoryBlockMap;

    // Memory blocks currently allocated.
    MemoryBlockMap g_allocated_mem_blocks;

#ifdef DUMP_CALLSTACK_ON_ALLOCATION

    class StackWalkerOutputToFile
      : public StackWalker
    {
      public:
        StackWalkerOutputToFile()
          : m_file(nullptr)
          , m_level(0)
          , m_skip(false)
        {
        }

        void reset(std::FILE* file)
        {
            m_file = file;
            m_level = 0;
            m_skip = false;
        }

      private:
        std::FILE*  m_file;
        std::size_t m_level;
        bool        m_skip;

        void OnOutput(LPCSTR szText) override
        {
            ++m_level;

            if (m_level <= NumberOfCallStackLevelsToSkip)
                return;

            if (m_skip)
                return;

            if (m_file == nullptr)
                StackWalker::OnOutput(szText);
            else std::fprintf(m_file, "    %s", szText);

            static const char* MainFunctionSuffix = ": main\n";
            const std::size_t main_function_suffix_length = strlen(MainFunctionSuffix);
            const std::size_t text_length = strlen(szText);

            // Don't report stack frames below main().
            if (text_length >= main_function_suffix_length &&
                strcmp(szText + text_length - main_function_suffix_length, MainFunctionSuffix) == 0)
            {
                m_skip = true;
                return;
            }
        }

        void OnDbgHelpErr(LPCSTR szFuncName, DWORD gle, DWORD64 addr) override
        {
            // Eat all error messages.
        }
    };

    StackWalkerOutputToFile g_stack_walker;

#endif

    std::string get_timestamp_string()
    {
        std::time_t t;
        std::time(&t);

        const std::tm* local_time = localtime(&t);

        std::stringstream sstr;
        sstr << std::setfill('0');

        sstr << std::setw(2) << local_time->tm_hour << ':';
        sstr << std::setw(2) << local_time->tm_min << ':';
        sstr << std::setw(2) << local_time->tm_sec;

        return sstr.str();
    }

    void log_allocation_to_file(const void* unaligned_ptr, const void* aligned_ptr, const std::size_t size)
    {
        assert(!g_tracking_enabled);

        std::fprintf(
            g_log_file,
            "[%s] Allocated %s at %s (unaligned: %s)\n",
            get_timestamp_string().c_str(),
            pretty_size(size).c_str(),
            to_string(aligned_ptr).c_str(),
            to_string(unaligned_ptr).c_str());

#ifdef DUMP_CALLSTACK_ON_ALLOCATION
        std::fprintf(g_log_file, "  Call stack:\n");

        g_stack_walker.reset(g_log_file);
        g_stack_walker.ShowCallstack();

        std::fprintf(g_log_file, "\n");
#endif

#ifdef FLUSH_AFTER_WRITE
        std::fflush(g_log_file);
#endif
    }

    void log_allocation_failure_to_file(const std::size_t size)
    {
        assert(!g_tracking_enabled);

        std::fprintf(
            g_log_file,
            "[%s] FAILED to allocate %s\n",
            get_timestamp_string().c_str(),
            pretty_size(size).c_str());

#ifdef FLUSH_AFTER_WRITE
        std::fflush(g_log_file);
#endif
    }

    void log_deallocation_to_file(const void* unaligned_ptr, const void* aligned_ptr, const std::size_t size)
    {
        assert(!g_tracking_enabled);

        std::fprintf(
            g_log_file,
            "[%s] Deallocating %s at %s (unaligned: %s)...\n",
            get_timestamp_string().c_str(),
            pretty_size(size).c_str(),
            to_string(aligned_ptr).c_str(),
            to_string(unaligned_ptr).c_str());

#ifdef DUMP_CALLSTACK_ON_ALLOCATION
        std::fprintf(g_log_file, "\n");
#endif

#ifdef FLUSH_AFTER_WRITE
        std::fflush(g_log_file);
#endif
    }

    std::uint64_t compute_leaked_memory_size()
    {
        std::uint64_t total_size = 0;

        for (const_each<MemoryBlockMap> i = g_allocated_mem_blocks; i; ++i)
            total_size += static_cast<std::uint64_t>(i->second);

        return total_size;
    }

    struct SortByDecreasingSize
    {
        bool operator()(const MemoryBlock& lhs, const MemoryBlock& rhs) const
        {
            return lhs.second > rhs.second;
        }
    };

    void report_allocation_statistics()
    {
        assert(!g_tracking_enabled);

        std::fprintf(
            g_log_file,
            "\n"
            "Statistics:\n"
            "\n"
            "  Allocations:            %s\n"
            "  Total allocated:        %s (%s byte%s)\n"
            "  Peak allocated:         %s (%s byte%s)\n"
            "  Largest allocation:     %s (%s byte%s)\n"
            "\n",
            pretty_uint(g_allocation_count).c_str(),
            pretty_size(g_total_allocated_bytes).c_str(),
            pretty_uint(g_total_allocated_bytes).c_str(),
            g_total_allocated_bytes > 1 ? "s" : "",
            pretty_size(g_peak_allocated_bytes).c_str(),
            pretty_uint(g_peak_allocated_bytes).c_str(),
            g_peak_allocated_bytes > 1 ? "s" : "",
            pretty_size(g_largest_allocation_bytes).c_str(),
            pretty_uint(g_largest_allocation_bytes).c_str(),
            g_largest_allocation_bytes > 1 ? "s" : "");
    }

    void report_memory_leaks()
    {
        assert(!g_tracking_enabled);

        if (g_allocated_mem_blocks.empty())
        {
            std::fprintf(g_log_file, "No memory leak detected.\n");
        }
        else
        {
            const std::size_t leak_count = g_allocated_mem_blocks.size();
            const std::uint64_t leak_bytes = compute_leaked_memory_size();

            std::fprintf(
                g_log_file,
                "Detected %s potential memory leak%s (%s in total):\n\n",
                pretty_uint(leak_count).c_str(),
                leak_count > 1 ? "s" : "",
                pretty_size(leak_bytes).c_str());

            MemoryBlockVector sorted_blocks;
            sorted_blocks.reserve(g_allocated_mem_blocks.size());

            for (const_each<MemoryBlockMap> i = g_allocated_mem_blocks; i; ++i)
                sorted_blocks.push_back(*i);

            std::sort(sorted_blocks.begin(), sorted_blocks.end(), SortByDecreasingSize());

            for (const_each<MemoryBlockVector> i = sorted_blocks; i; ++i)
            {
                std::fprintf(
                    g_log_file,
                    "  %s at %s\n",
                    pretty_size(i->second).c_str(),
                    to_string(i->first).c_str());
            }
        }
    }
}

//
// Public entry points.
//

void log_allocation(const void* unaligned_ptr, const void* aligned_ptr, const std::size_t size)
{
    if (!g_tracking_enabled)
        return;

    recursive_mutex::scoped_lock lock(g_mutex);

    g_tracking_enabled = false;

    ++g_allocation_count;
    g_allocated_bytes += size;
    g_peak_allocated_bytes = std::max(g_peak_allocated_bytes, g_allocated_bytes);
    g_total_allocated_bytes += size;
    g_largest_allocation_bytes = std::max<std::uint64_t>(g_largest_allocation_bytes, size);

    g_allocated_mem_blocks[aligned_ptr] = size;

#ifdef LOG_MEMORY_ALLOCATIONS
    log_allocation_to_file(unaligned_ptr, aligned_ptr, size);
#endif

    g_tracking_enabled = true;
}

void log_allocation_failure(const std::size_t size)
{
#ifdef LOG_MEMORY_ALLOCATION_FAILURES
    if (!g_tracking_enabled)
        return;

    recursive_mutex::scoped_lock lock(g_mutex);

    g_tracking_enabled = false;

    log_allocation_failure_to_file(size);

    g_tracking_enabled = true;
#endif
}

void log_deallocation(const void* unaligned_ptr, const void* aligned_ptr)
{
    if (!g_tracking_enabled)
        return;

    recursive_mutex::scoped_lock lock(g_mutex);

    g_tracking_enabled = false;

    const MemoryBlockMap::iterator i = g_allocated_mem_blocks.find(aligned_ptr);

    if (i != g_allocated_mem_blocks.end())
    {
        assert(g_allocated_bytes >= i->second);
        g_allocated_bytes -= i->second;

#ifdef LOG_MEMORY_DEALLOCATIONS
        log_deallocation_to_file(unaligned_ptr, aligned_ptr, i->second);
#endif

        g_allocated_mem_blocks.erase(i);
    }

    g_tracking_enabled = true;
}

void start_memory_tracking()
{
    recursive_mutex::scoped_lock lock(g_mutex);

    if (g_tracking_enabled)
        return;

    g_tracking_enabled = false;

    atexit(stop_memory_tracking);

    g_log_file = fopen(MemoryLogFileName, "wt");

    if (g_log_file)
    {
#ifdef DUMP_CALLSTACK_ON_ALLOCATION
        g_stack_walker.LoadModules();
#endif

        g_tracking_enabled = true;
    }
}

void stop_memory_tracking()
{
    recursive_mutex::scoped_lock lock(g_mutex);

    if (!g_tracking_enabled)
        return;

    g_tracking_enabled = false;

    if (g_log_file)
    {
        report_allocation_statistics();
        report_memory_leaks();

        fclose(g_log_file);
    }
}

#else

void log_allocation(const void* unaligned_ptr, const void* aligned_ptr, const std::size_t size) {}
void log_allocation_failure(const std::size_t size) {}
void log_deallocation(const void* unaligned_ptr, const void* aligned_ptr) {}
void start_memory_tracking() {}
void stop_memory_tracking() {}

#endif

//
// Override all variants of the new and delete operators.
//

namespace
{
    void* new_impl(std::size_t size)
    {
        if (size < 1)
            size = 1;

        void* ptr = aligned_malloc(size, MemoryAlignment);

        if (!ptr)
            throw std::bad_alloc();

        return ptr;
    }

    void delete_impl(void* ptr)
    {
        if (!ptr)
            return;

        aligned_free(ptr);
    }
}

_Ret_notnull_ _Post_writable_byte_size_(size)
void* operator new(std::size_t size)
  throw(std::bad_alloc)
{
    return new_impl(size);
}

_Ret_notnull_ _Post_writable_byte_size_(size)
void* operator new[](std::size_t size)
  throw(std::bad_alloc)
{
    return new_impl(size);
}

_Ret_maybenull_ _Post_writable_byte_size_(size)
void* operator new(std::size_t size, const std::nothrow_t&)
  throw()
{
    return new_impl(size);
}

_Ret_maybenull_ _Post_writable_byte_size_(size)
void* operator new[](std::size_t size, const std::nothrow_t&)
  throw()
{
    return new_impl(size);
}

void operator delete(void* ptr)
{
    delete_impl(ptr);
}

void operator delete[](void* ptr)
{
    delete_impl(ptr);
}

void operator delete(void* ptr, const std::nothrow_t&)
{
    delete_impl(ptr);
}

void operator delete[](void* ptr, const std::nothrow_t&)
{
    delete_impl(ptr);
}

#else

void log_allocation(const void* unaligned_ptr, const void* aligned_ptr, const std::size_t size) {}
void log_allocation_failure(const std::size_t size) {}
void log_deallocation(const void* unaligned_ptr, const void* aligned_ptr) {}
void start_memory_tracking() {}
void stop_memory_tracking() {}

#endif  // _WIN32


text:
use std::rc::Rc;
use std::{slice, ptr};

use {gl, tex};
use core::{self as d, factory as f, texture as t, buffer, mapping};
use core::memory::{self, Bind, SHADER_RESOURCE, UNORDERED_ACCESS, Typed};
use core::format::ChannelType;
use core::handle::{self, Producer};
use core::target::{Layer, Level};

use command::{CommandBuffer, COLOR_DEFAULT};
use {Resources as R, Share, OutputMerger};
use {Buffer, BufferElement, FatSampler, NewTexture,
     PipelineState, ResourceView, TargetView, Fence};

pub fn role_to_target(role: buffer::Role) -> gl::types::GLenum {
    match role {
        buffer::Role::Vertex   => gl::ARRAY_BUFFER,
        buffer::Role::Index    => gl::ELEMENT_ARRAY_BUFFER,
        buffer::Role::Constant => gl::UNIFORM_BUFFER,
        buffer::Role::Staging  => gl::ARRAY_BUFFER,
    }
}

fn access_to_map_bits(access: memory::Access) -> gl::types::GLenum {
    let mut r = 0;
    if access.contains(memory::READ) { r |= gl::MAP_READ_BIT; }
    if access.contains(memory::WRITE) { r |= gl::MAP_WRITE_BIT; }
    r
}

fn access_to_gl(access: memory::Access) -> gl::types::GLenum {
    match access {
        memory::RW => gl::READ_WRITE,
        memory::READ => gl::READ_ONLY,
        memory::WRITE => gl::WRITE_ONLY,
        _ => unreachable!(),
    }
}

pub fn update_sub_buffer(gl: &gl::Gl, buffer: Buffer, address: *const u8,
                         size: usize, offset: usize, role: buffer::Role) {
    let target = role_to_target(role);
    unsafe {
        gl.BindBuffer(target, buffer);
        gl.BufferSubData(target,
            offset as gl::types::GLintptr,
            size as gl::types::GLsizeiptr,
            address as *const gl::types::GLvoid
        );
    }
}

/// GL resource factory.
pub struct Factory {
    share: Rc<Share>,
    frame_handles: handle::Manager<R>,
}

impl Clone for Factory {
    fn clone(&self) -> Factory {
        Factory::new(self.share.clone())
    }
}

impl Factory {
    /// Create a new `Factory`.
    pub fn new(share: Rc<Share>) -> Factory {
        Factory {
            share: share,
            frame_handles: handle::Manager::new(),
        }
    }

    pub fn create_command_buffer(&mut self) -> CommandBuffer {
        CommandBuffer::new(self.create_fbo_internal())
    }

    fn create_fbo_internal(&mut self) -> gl::types::GLuint {
        let gl = &self.share.context;
        let mut name = 0 as ::FrameBuffer;
        unsafe {
            gl.GenFramebuffers(1, &mut name);
        }
        info!("\tCreated frame buffer {}", name);
        name
    }

    fn create_buffer_internal(&mut self) -> Buffer {
        let gl = &self.share.context;
        let mut name = 0 as Buffer;
        unsafe { gl.GenBuffers(1, &mut name); }
        info!("\tCreated buffer {}", name);
        name
    }

    fn init_buffer(&mut self,
                   buffer: Buffer,
                   info: &buffer::Info,
                   data_opt: Option<&[u8]>) -> Option<MappingGate> {
        use core::memory::Usage::*;

        let gl = &self.share.context;
        let target = role_to_target(info.role);
        let mut data_ptr = if let Some(data) = data_opt {
            debug_assert!(data.len() == info.size);
            data.as_ptr() as *const gl::types::GLvoid
        } else {
            0 as *const gl::types::GLvoid
        };

        if self.share.private_caps.buffer_storage_supported {
            let usage = match info.usage {
                Data => 0,
                // TODO: we could use mapping instead of glBufferSubData
                Dynamic => gl::DYNAMIC_STORAGE_BIT,
                Upload => access_to_map_bits(memory::WRITE) | gl::MAP_PERSISTENT_BIT,
                Download => access_to_map_bits(memory::READ) | gl::MAP_PERSISTENT_BIT,
            };
            let size = if info.size == 0 {
                // we are not allowed to pass size=0 into `glBufferStorage`
                data_ptr = 0 as *const _;
                1
            } else {
                info.size as gl::types::GLsizeiptr
            };
            unsafe {
                gl.BindBuffer(target, buffer);
                gl.BufferStorage(target,
                    size,
                    data_ptr,
                    usage
                );
            }
        }
        else {
            let usage = match info.usage {
                Data => gl::STATIC_DRAW,
                Dynamic => gl::DYNAMIC_DRAW,
                Upload => gl::STREAM_DRAW,
                Download => gl::STREAM_READ,
            };
            unsafe {
                gl.BindBuffer(target, buffer);
                gl.BufferData(target,
                    info.size as gl::types::GLsizeiptr,
                    data_ptr,
                    usage
                );
            }
        }
        if let Err(err) = self.share.check() {
            panic!("Error {:?} creating buffer: {:?}", err, info)
        }

        let mapping_access = match info.usage {
            Data | Dynamic => None,
            Upload => Some(memory::WRITE),
            Download => Some(memory::READ),
        };

        mapping_access.map(|access| {
            let (kind, ptr) = if self.share.private_caps.buffer_storage_supported {
                let mut gl_access = access_to_map_bits(access) |
                                    gl::MAP_PERSISTENT_BIT;
                if access.contains(memory::WRITE) {
                    gl_access |= gl::MAP_FLUSH_EXPLICIT_BIT;
                }
                let size = info.size as isize;
                let ptr = unsafe {
                    gl.BindBuffer(target, buffer);
                    gl.MapBufferRange(target, 0, size, gl_access)
                } as *mut ::std::os::raw::c_void;
                (MappingKind::Persistent(mapping::Status::clean()), ptr)
            } else {
                (MappingKind::Temporary, ptr::null_mut())
            };
            if let Err(err) = self.share.check() {
                panic!("Error {:?} mapping buffer: {:?}, with access: {:?}",
                       err, info, access)
            }

            MappingGate {
                kind: kind,
                pointer: ptr,
            }
        })
    }

    fn create_program_raw(&mut self, shader_set: &d::ShaderSet<R>)
                          -> Result<(gl::types::GLuint, d::shade::ProgramInfo), d::shade::CreateProgramError> {
        use shade::create_program;
        let frame_handles = &mut self.frame_handles;
        let mut shaders = [0; 5];
        let usage = shader_set.get_usage();
        let shader_slice = match shader_set {
            &d::ShaderSet::Simple(ref vs, ref ps) => {
                shaders[0] = *vs.reference(frame_handles);
                shaders[1] = *ps.reference(frame_handles);
                &shaders[..2]
            },
            &d::ShaderSet::Geometry(ref vs, ref gs, ref ps) => {
                shaders[0] = *vs.reference(frame_handles);
                shaders[1] = *gs.reference(frame_handles);
                shaders[2] = *ps.reference(frame_handles);
                &shaders[..3]
            },
            &d::ShaderSet::Tessellated(ref vs, ref hs, ref ds, ref ps) => {
                shaders[0] = *vs.reference(frame_handles);
                shaders[1] = *hs.reference(frame_handles);
                shaders[2] = *ds.reference(frame_handles);
                shaders[3] = *ps.reference(frame_handles);
                &shaders[..4]
            },
        };
        let result = create_program(&self.share.context, &self.share.capabilities,
                                    &self.share.private_caps, shader_slice, usage);
        if let Err(err) = self.share.check() {
            panic!("Error {:?} creating program: {:?}", err, shader_set)
        }
        result
    }

    fn view_texture_as_target(&mut self, htex: &handle::RawTexture<R>, level: Level, layer: Option<Layer>)
                              -> Result<TargetView, f::TargetViewError> {
        match (self.frame_handles.ref_texture(htex), layer) {
            (&NewTexture::Surface(_), Some(_)) => Err(f::TargetViewError::Unsupported),
            (&NewTexture::Surface(_), None) if level != 0 => Err(f::TargetViewError::Unsupported),
            (&NewTexture::Surface(s), None) => Ok(TargetView::Surface(s)),
            (&NewTexture::Texture(t), Some(l)) => Ok(TargetView::TextureLayer(t, level, l)),
            (&NewTexture::Texture(t), None) => Ok(TargetView::Texture(t, level)),
        }
    }
}

#[derive(Debug, PartialEq, Eq, Hash)]
pub enum MappingKind {
    Persistent(mapping::Status<R>),
    Temporary,
}

#[derive(Debug, Eq, Hash, PartialEq)]
#[allow(missing_copy_implementations)]
pub struct MappingGate {
    pub kind: MappingKind,
    pub pointer: *mut ::std::os::raw::c_void,
}

unsafe impl Send for MappingGate {}
unsafe impl Sync for MappingGate {}

impl mapping::Gate<R> for MappingGate {
    unsafe fn set<T>(&self, index: usize, val: T) {
        *(self.pointer as *mut T).offset(index as isize) = val;
    }

    unsafe fn slice<'a, 'b, T>(&'a self, len: usize) -> &'b [T] {
        slice::from_raw_parts(self.pointer as *const T, len)
    }

    unsafe fn mut_slice<'a, 'b, T>(&'a self, len: usize) -> &'b mut [T] {
        slice::from_raw_parts_mut(self.pointer as *mut T, len)
    }
}

pub fn temporary_ensure_mapped(pointer: &mut *mut ::std::os::raw::c_void,
                               target: gl::types::GLenum,
                               buffer: Buffer,
                               access: memory::Access,
                               gl: &gl::Gl) {
    if pointer.is_null() {
        unsafe {
            gl.BindBuffer(target, buffer);
            *pointer = gl.MapBuffer(target, access_to_gl(access))
                as *mut ::std::os::raw::c_void;
        }
    }
}

pub fn temporary_ensure_unmapped(pointer: &mut *mut ::std::os::raw::c_void,
                                 target: gl::types::GLenum,
                                 buffer: Buffer,
                                 gl: &gl::Gl) {
    if !pointer.is_null() {
        unsafe {
            gl.BindBuffer(target, buffer);
            gl.UnmapBuffer(target);
        }

        *pointer = ptr::null_mut();
    }
}

impl f::Factory<R> for Factory {
    fn get_capabilities(&self) -> &d::Capabilities {
        &self.share.capabilities
    }

    fn create_buffer_raw(&mut self, info: buffer::Info) -> Result<handle::RawBuffer<R>, buffer::CreationError> {
        if !self.share.capabilities.constant_buffer_supported && info.role == buffer::Role::Constant {
            error!("Constant buffers are not supported by this GL version");
            return Err(buffer::CreationError::Other);
        }
        let name = self.create_buffer_internal();
        let mapping = self.init_buffer(name, &info, None);
        Ok(self.share.handles.borrow_mut().make_buffer(name, info, mapping))
    }

    fn create_buffer_immutable_raw(&mut self, data: &[u8], stride: usize, role: buffer::Role, bind: Bind)
                               -> Result<handle::RawBuffer<R>, buffer::CreationError> {
        let name = self.create_buffer_internal();
        let info = buffer::Info {
            role: role,
            usage: memory::Usage::Data,
            bind: bind,
            size: data.len(),
            stride: stride,
        };
        let mapping = self.init_buffer(name, &info, Some(data));
        Ok(self.share.handles.borrow_mut().make_buffer(name, info, mapping))
    }

    fn create_shader(&mut self, stage: d::shade::Stage, code: &[u8])
                     -> Result<handle::Shader<R>, d::shade::CreateShaderError> {
        ::shade::create_shader(&self.share.context, stage, code)
                .map(|sh| self.share.handles.borrow_mut().make_shader(sh))
    }

    fn create_program(&mut self, shader_set: &d::ShaderSet<R>)
                      -> Result<handle::Program<R>, d::shade::CreateProgramError> {
        self.create_program_raw(shader_set)
            .map(|(name, info)| self.share.handles.borrow_mut().make_program(name, info))
    }

    fn create_pipeline_state_raw(&mut self, program: &handle::Program<R>, desc: &d::pso::Descriptor)
                                 -> Result<handle::RawPipelineState<R>, d::pso::CreationError> {
        use core::state as s;
        let caps = &self.share.capabilities;
        match desc.primitive {
            d::Primitive::PatchList(num) if num == 0 || (num as usize) > caps.max_patch_size =>
                return Err(d::pso::CreationError),
            _ => ()
        }
        let mut output = OutputMerger {
            draw_mask: 0,
            stencil: match desc.depth_stencil {
                Some((_, t)) if t.front.is_some() || t.back.is_some() => Some(s::Stencil {
                    front: t.front.unwrap_or_default(),
                    back: t.back.unwrap_or_default(),
                }),
                _ => None,
            },
            depth: desc.depth_stencil.and_then(|(_, t)| t.depth),
            colors: [COLOR_DEFAULT; d::MAX_COLOR_TARGETS],
        };
        for i in 0 .. d::MAX_COLOR_TARGETS {
            if let Some((_, ref bi)) = desc.color_targets[i] {
                output.draw_mask |= 1<<i;
                output.colors[i].mask = bi.mask;
                if bi.color.is_some() || bi.alpha.is_some() {
                    output.colors[i].blend = Some(s::Blend {
                        color: bi.color.unwrap_or_default(),
                        alpha: bi.alpha.unwrap_or_default(),
                    });
                }
            }
        }
        let mut inputs = [None; d::MAX_VERTEX_ATTRIBUTES];
        for i in 0 .. d::MAX_VERTEX_ATTRIBUTES {
            inputs[i] = desc.attributes[i].map(|at| BufferElement {
                desc: desc.vertex_buffers[at.0 as usize].unwrap(),
                elem: at.1,
            });
        }
        let pso = PipelineState {
            program: *self.frame_handles.ref_program(program),
            primitive: desc.primitive,
            input: inputs,
            scissor: desc.scissor,
            rasterizer: desc.rasterizer,
            output: output,
        };
        Ok(self.share.handles.borrow_mut().make_pso(pso, program))
    }

    fn create_texture_raw(&mut self, desc: t::Info, hint: Option<ChannelType>, data_opt: Option<&[&[u8]]>)
                          -> Result<handle::RawTexture<R>, t::CreationError> {
        use core::texture::CreationError;
        let caps = &self.share.private_caps;
        if desc.levels == 0 {
            return Err(CreationError::Size(0))
        }
        let dim = desc.kind.get_dimensions();
        let max_size = self.share.capabilities.max_texture_size;
        if dim.0 as usize > max_size {
            return Err(CreationError::Size(dim.0));
        }
        if dim.1 as usize > max_size {
            return Err(CreationError::Size(dim.1));
        }
        let cty = hint.unwrap_or(ChannelType::Uint); //careful here
        let gl = &self.share.context;
        let object = if desc.bind.intersects(SHADER_RESOURCE | UNORDERED_ACCESS) || data_opt.is_some() {
            let name = if caps.immutable_storage_supported {
                try!(tex::make_with_storage(gl, &desc, cty))
            } else {
                try!(tex::make_without_storage(gl, &desc, cty))
            };
            if let Some(data) = data_opt {
                try!(tex::init_texture_data(gl, name, desc, cty, data));
            }
            NewTexture::Texture(name)
        }else {
            let name = try!(tex::make_surface(gl, &desc, cty));
            NewTexture::Surface(name)
        };
        if let Err(err) = self.share.check() {
            panic!("Error {:?} creating texture: {:?}, hint: {:?}", err, desc, hint)
        }
        Ok(self.share.handles.borrow_mut().make_texture(object, desc))
    }

    fn view_buffer_as_shader_resource_raw(&mut self, hbuf: &handle::RawBuffer<R>)
                                      -> Result<handle::RawShaderResourceView<R>, f::ResourceViewError> {
        let gl = &self.share.context;
        let mut name = 0 as gl::types::GLuint;
        let buf_name = *self.frame_handles.ref_buffer(hbuf);
        let format = gl::R8; //TODO: get from the buffer handle
        unsafe {
            gl.GenTextures(1, &mut name);
            gl.BindTexture(gl::TEXTURE_BUFFER, name);
            gl.TexBuffer(gl::TEXTURE_BUFFER, format, buf_name);
        }
        let view = ResourceView::new_buffer(name);
        if let Err(err) = self.share.check() {
            panic!("Error {:?} creating buffer SRV: {:?}", err, hbuf.get_info())
        }
        Ok(self.share.handles.borrow_mut().make_buffer_srv(view, hbuf))
    }

    fn view_buffer_as_unordered_access_raw(&mut self, _hbuf: &handle::RawBuffer<R>)
                                       -> Result<handle::RawUnorderedAccessView<R>, f::ResourceViewError> {
        Err(f::ResourceViewError::Unsupported) //TODO
    }

    fn view_texture_as_shader_resource_raw(&mut self, htex: &handle::RawTexture<R>, _desc: t::ResourceDesc)
                                       -> Result<handle::RawShaderResourceView<R>, f::ResourceViewError> {
        match self.frame_handles.ref_texture(htex) {
            &NewTexture::Surface(_) => Err(f::ResourceViewError::NoBindFlag),
            &NewTexture::Texture(t) => {
                //TODO: use the view descriptor
                let view = ResourceView::new_texture(t, htex.get_info().kind);
                Ok(self.share.handles.borrow_mut().make_texture_srv(view, htex))
            },
        }
    }

    fn view_texture_as_unordered_access_raw(&mut self, _htex: &handle::RawTexture<R>)
                                        -> Result<handle::RawUnorderedAccessView<R>, f::ResourceViewError> {
        Err(f::ResourceViewError::Unsupported) //TODO
    }

    fn view_texture_as_render_target_raw(&mut self, htex: &handle::RawTexture<R>, desc: t::RenderDesc)
                                         -> Result<handle::RawRenderTargetView<R>, f::TargetViewError> {
        self.view_texture_as_target(htex, desc.level, desc.layer)
            .map(|view| {
                let dim = htex.get_info().kind.get_level_dimensions(desc.level);
                self.share.handles.borrow_mut().make_rtv(view, htex, dim)
            })
    }

    fn view_texture_as_depth_stencil_raw(&mut self, htex: &handle::RawTexture<R>, desc: t::DepthStencilDesc)
                                         -> Result<handle::RawDepthStencilView<R>, f::TargetViewError> {
        self.view_texture_as_target(htex, desc.level, desc.layer)
            .map(|view| {
                let dim = htex.get_info().kind.get_level_dimensions(0);
                self.share.handles.borrow_mut().make_dsv(view, htex, dim)
            })
    }

    fn create_sampler(&mut self, info: t::SamplerInfo) -> handle::Sampler<R> {
        let name = if self.share.private_caps.sampler_objects_supported {
            tex::make_sampler(&self.share.context, &info)
        } else {
            0
        };
        let sam = FatSampler {
            object: name,
            info: info.clone(),
        };
        if let Err(err) = self.share.check() {
            panic!("Error {:?} creating sampler: {:?}", err, info)
        }
        self.share.handles.borrow_mut().make_sampler(sam, info)
    }

    fn read_mapping<'a, 'b, T>(&'a mut self, buf: &'b handle::Buffer<R, T>)
                               -> Result<mapping::Reader<'b, R, T>,
                                         mapping::Error>
        where T: Copy
    {
        let gl = &self.share.context;
        let handles = &mut self.frame_handles;
        unsafe {
            mapping::read(buf.raw(), |mapping| match mapping.kind {
                MappingKind::Persistent(ref mut status) =>
                    status.cpu_access(|fence| wait_fence(&handles.ref_fence(&fence), gl)),
                MappingKind::Temporary =>
                    temporary_ensure_mapped(&mut mapping.pointer,
                                            role_to_target(buf.get_info().role),
                                            *buf.raw().resource(),
                                            memory::READ,
                                            gl),
            })
        }
    }

    fn write_mapping<'a, 'b, T>(&'a mut self, buf: &'b handle::Buffer<R, T>)
                                -> Result<mapping::Writer<'b, R, T>,
                                          mapping::Error>
        where T: Copy
    {
        let gl = &self.share.context;
        let handles = &mut self.frame_handles;
        unsafe {
            mapping::write(buf.raw(), |mapping| match mapping.kind {
                MappingKind::Persistent(ref mut status) =>
                    status.cpu_write_access(|fence| wait_fence(&handles.ref_fence(&fence), gl)),
                MappingKind::Temporary =>
                    temporary_ensure_mapped(&mut mapping.pointer,
                                            role_to_target(buf.get_info().role),
                                            *buf.raw().resource(),
                                            memory::WRITE,
                                            gl),
            })
        }
    }
}

pub fn wait_fence(fence: &Fence, gl: &gl::Gl) {
    let timeout = 1_000_000_000_000;
    // TODO: use the return value of this call
    // TODO:
    // This can be called by multiple objects wanting to ensure they have exclusive
    // access to a resource. How much does this call costs ? The status of the fence
    // could be cached to avoid calling this more than once (in core or in the backend ?).
    unsafe {
        gl.ClientWaitSync(fence.0, gl::SYNC_FLUSH_COMMANDS_BIT, timeout);
    }
}

redpajama_set_name: RedPajamaGithub


text:
namespace MobileApp.Android.UI.Controls
{
    using global::Android.Content;
    using global::Android.Provider;
    using global::Android.Support.V4.View;
    using global::Android.Views;
    using global::Android.Widget;

    public class SettingsActionProvider : ActionProvider
    {
        #region Static Fields

        private static readonly Intent sSettingsIntent = new Intent(Settings.ActionSettings);

        #endregion

        #region Fields

        private readonly Context mContext;

        #endregion

        #region Constructors and Destructors

        public SettingsActionProvider(Context context)
            : base(context)
        {
            this.mContext = context;
        }

        #endregion

        #region Public Methods and Operators

        public override View OnCreateActionView()
        {
            LayoutInflater layoutInflater = LayoutInflater.From(this.mContext);
            View view = layoutInflater.Inflate(Resource.Layout.settings_action_provider, null);
            var button = view.FindViewById<ImageButton>(Resource.Id.button);
            // Attach a click listener for launching the system settings.
            button.Click += delegate { this.mContext.StartActivity(sSettingsIntent); };
            return view;
        }

        public override bool OnPerformDefaultAction()
        {
            // This is called if the host menu item placed in the overflow menu of the
            // action bar is clicked and the host activity did not handle the click.
            this.mContext.StartActivity(sSettingsIntent);
            return true;
        }

        #endregion
    }
}


text:
#include "ExpandConvLayer.h"
#include "paddle/utils/Logging.h"
#include "paddle/utils/Stat.h"

namespace paddle {

REGISTER_LAYER(exconv, ExpandConvLayer);

bool ExpandConvLayer::init(const LayerMap &layerMap,
                           const ParameterMap &parameterMap) {
  /* Initialize the basic convolutional parent class */
  ExpandConvBaseLayer::init(layerMap, parameterMap);
  return true;
}

void ExpandConvLayer::forward(PassType passType) {
  Layer::forward(passType);

  /* malloc memory for the output_ if necessary */
  int batchSize = inputLayers_[0]->getOutputValue()->getHeight();
  resetOutput(batchSize, getOutputSize());

  MatrixPtr image = nullptr;
  MatrixPtr outV = getOutputValue();
  for (size_t i = 0; i < inputLayers_.size(); ++i) {
    LayerPtr prevLayer = getPrev(i);
    image = prevLayer->getOutputValue();
    for (size_t off = 0; off < image->getHeight(); off++) {
      REGISTER_TIMER_INFO("expandFwdOnce", getName().c_str());
      expandFwdOnce(image, outV, i, off);
    }
  }
  /* add the bias-vector */
  if (biases_.get()) {
    if (sharedBiases_) {
      addSharedBias();
    } else {
      addUnsharedBias();
    }
  }

  /* activation */
  forwardActivation();
}

void ExpandConvLayer::backward(const UpdateCallback &callback) {
  backwardActivation();

  MatrixPtr outGrad = getOutputGrad();
  if (biases_ && biases_->getWGrad()) {
    bpropBiases(outGrad);
    /* Increasing the number of gradient */
    biases_->getParameterPtr()->incUpdate(callback);
  }

  for (size_t i = 0; i < inputLayers_.size(); ++i) {
    /* First, calculate the input layers error */
    if (getPrev(i)->getOutputGrad()) {
      bpropActs(outGrad, getPrev(i)->getOutputGrad(), i);
    }
    if (weights_[i]->getWGrad()) {
      /* Then, calculate the W-gradient for the current layer */
      bpropWeights(getPrev(i)->getOutputValue(), outGrad, i);
      /* Increasing the number of gradient */
      weights_[i]->getParameterPtr()->incUpdate(callback);
    }
  }
}

}  // namespace paddle


text:
<!DOCTYPE html>
<html>
<head lang="en">
  <meta charset="UTF-8">
  <title></title>
  <script type="text/javascript" src="language-detect_localstorage.js"></script>
</head>
<body>

</body>
</html>


text:
<!doctype html>

    <link rel="stylesheet" href="../static/css/bootstrap-combined.min-2.0.4.css"/>

JavaScript Projects


text:
<?php

/**
 * Do not write your custom settings into this file
 */
return array(
    'di' => array(
        'definition' => array(
            'compiler' => array(
                __DIR__ . '/../data/di/definition.php',
            ),
        ),
        'instance' => array(
            'alias' => array(
               'WebinoImageThumb' => 'WebinoImageThumb\WebinoImageThumb',
           ),
        ),
    ),
);


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <androidx.appcompat.widget.AppCompatTextView
        android:id="@+id/mTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="30dp"
        android:text="@string/app_name"
        android:textColor="#000000"
        android:textSize="25sp" />

    <com.uber.okbuck.example.CustomView
        android:id="@+id/mTextView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="30dp"
        android:text="@string/test_string"
        android:textColor="@color/button_material_light" />
</LinearLayout>


text:
<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE chapter [
<!ENTITY % slc_entities SYSTEM "../common/entities.ent">
%slc_entities;
]>

<chapter xml:id="doc-85c61ed5-7f9f-427e-8b93-2202e0d8e945"
         xmlns="http://docbook.org/ns/docbook"
         xmlns:xi="http://www.w3.org/2001/XInclude"
         xmlns:xlink="http://www.w3.org/1999/xlink" version="5.0">

    <title>Portal Administration</title>

    <para> The &PRODUCTABBR; Portal is the web interface you initially sign in to when accessing
        other &PRODUCTABBR; applications and features. </para>
    <para>
       Review the Welcome information for vital information to ensure you protect private data.
    </para>
    <para>Any applications that you have access to are listed under My Applications on the right of
        the Portal. This includes the &COMPANYABBR; Dashboards application and any environment
        specific applications to which your administrator has given you access. </para>
   <para>
        <figure>
            <title>Example Portal</title>
            <mediaobject>
                <imageobject role="html">
                    <imagedata fileref="images/portal-admin_welcome.png" scalefit="1"
                    />
                </imageobject>
                <imageobject role="fo">
                    <imagedata fileref="../common/images/portal-admin_welcome.png"
                        width="7in" scalefit="1"/>
                </imageobject>
            </mediaobject>
        </figure>
    </para>
    <para> Clicking on your name displays a menu. To log out of the &PRODUCTABBR; Portal, select the
            <emphasis>Logout</emphasis> link to end your session. If you experience a problem report
        the problem to your administrator by clicking on the <emphasis>Report a problem
            link</emphasis>. </para>
    <para>
        These instructions describe the default &PRODUCTABBR; Portal. It is possible that the Portal for your organization
        has been customized and differs from what has been displayed and described here. If your Portal has been customized and you have questions relating to using
        your Portal, your administrator is likely the best source of information.
    </para>

</chapter>


text:
package org.food.safety.trace.dto;

import lombok.Setter;
import lombok.ToString;

import javax.persistence.MappedSuperclass;
import javax.persistence.Transient;

/**
 * Created by tom on 2017/8/28.
 */
@Setter
@ToString
@MappedSuperclass
public class GestView extends BusinessView {
    public static final String TARGET_NAME="Gest";

    public SelectItemView gestSexSelectItem;
    @Transient
    public SelectItemView getGestSexSelectItem() {
        return gestSexSelectItem;
    }

    public SelectItemView gestStyleSelectItem;
    @Transient
    public SelectItemView getGestStyleSelectItem() {
        return gestStyleSelectItem;
    }

    public SelectItemView statusSelectItem;
    @Transient
    public SelectItemView getStatusSelectItem() {
        return statusSelectItem;
    }

    public SelectItemView isVipSelectItem;
    @Transient
    public SelectItemView getIsVipSelectItem() {
        return isVipSelectItem;
    }

}


text:
/*
 *  generate test data for navdata structures
 */

#include <stdio.h>
#include <navdata_common.h>

#define assert_size(name) printf("self.assertSize(options.%s, %lu)\n", #name, sizeof(name))
#define _assert_size(name) printf("self.assertSize(options._%s, %lu)\n", #name, sizeof(name))
#define assert_option_size(name) printf("self.assertOptionSize(\'%s\', %lu)\n", #name, sizeof(name))

int main(int argc, char** argv)
{
    assert_size(uint8_t);
    assert_size(uint16_t);
    assert_size(uint32_t);
    assert_size(int16_t);
    assert_size(bool_t);
    assert_size(char);
    assert_size(float32_t);

    putchar('\n');

    _assert_size(vector31_t);
    _assert_size(vector21_t);
    _assert_size(velocities_t);
    _assert_size(screen_point_t);
    _assert_size(matrix33_t);

    putchar('\n');

    assert_option_size(navdata_t);

    putchar('\n')

    assert_option_size(navdata_demo_t);
    assert_option_size(navdata_time_t);
    assert_option_size(navdata_raw_measures_t);
    assert_option_size(navdata_pressure_raw_t);
    assert_option_size(navdata_magneto_t);
    assert_option_size(navdata_wind_speed_t);
    assert_option_size(navdata_kalman_pressure_t);
    assert_option_size(navdata_zimmu_3000_t);
    assert_option_size(navdata_phys_measures_t);
    assert_option_size(navdata_gyros_offsets_t);
    assert_option_size(navdata_references_t);
    assert_option_size(navdata_trims_t);
    assert_option_size(navdata_rc_references_t);
    assert_option_size(navdata_pwm_t);
    assert_option_size(navdata_altitude_t);
    assert_option_size(navdata_vision_raw_t);
    assert_option_size(navdata_vision_t);
    assert_option_size(navdata_vision_perf_t);
    assert_option_size(navdata_trackers_send_t);
    assert_option_size(navdata_vision_detect_t);
    assert_option_size(navdata_vision_of_t);
    assert_option_size(navdata_watchdog_t);
    assert_option_size(navdata_adc_data_frame_t);
    assert_option_size(navdata_video_stream_t);
    assert_option_size(navdata_hdvideo_stream_t);
    assert_option_size(navdata_games_t);
    assert_option_size(navdata_wifi_t);
    assert_option_size(navdata_cks_t);

    return 0;
}


text:
angular.module('os.biospecimen.models.specimenkit', ['os.common.models'])
  .factory('SpecimenKit', function(osModel, $http) {

    var SpecimenKit = osModel('specimen-kits');

    SpecimenKit.list = function(opts) {
      var defOpts = {includeStats: true};
      return SpecimenKit.query(angular.extend(defOpts, opts || {}));
    }

    SpecimenKit.prototype.generateReport = function() {
      return $http.get(SpecimenKit.url() + this.$id() + "/report").then(
        function(resp) {
          return resp.data;
        }
      );
    }

    return SpecimenKit;
});


text:
export const configurations = {
    "small": {channelName: "small", mediaQuery: "only screen"},
    "small-only": {channelName: "small-only", mediaQuery: "only screen and (max-width: 39.9375em)"},
    "medium": {channelName: "medium", mediaQuery: "only screen and (min-width:40em)"},
    "medium-only": {channelName: "medium-only", mediaQuery: "only screen and (min-width:40em) and (max-width:63.9375em)"},
    "large": {channelName: "large", mediaQuery: "only screen and (min-width:64em)"},
    "large-only": {channelName: "large-only", mediaQuery: "only screen and (min-width:64em) and (max-width:89.9375em)"},
    "xlarge": {channelName: "xlarge", mediaQuery: "only screen and (min-width:90em)"},
    "xlarge-only": {channelName: "xlarge-only", mediaQuery: "only screen and (min-width:90em) and (max-width:119.9375em)"},
    "xxlarge": {channelName: "xxlarge", mediaQuery: "only screen and (min-width:120em)"}
};


text:
from setuptools import setup, find_packages

setup(
    name='git-tree',
    description='List contents of git in a tree-like format',
    author='Kazufumi Onuma',
    author_email='k.o.system2@gmail.com',
    license='MIT License',
    url='https://github.com/kosystem/gitTree',
    version='0.1',
    packages=find_packages(),
    entry_points={
        'console_scripts': [
            'git-tree=gitTree.gitTree:main',
            ],
        }
    )


text:
<?php
namespace Scalr\Upgrade\Updates;

use Scalr\Upgrade\SequenceInterface;
use Scalr\Upgrade\AbstractUpdate;

class Update20141119142404 extends AbstractUpdate implements SequenceInterface
{

    protected $uuid = 'f8a06c72-f0e4-4408-9885-9cbafb59814d';

    protected $depends = [];

    protected $description = 'Adding server_termination_errors table';

    protected $ignoreChanges = true;

    protected $dbservice = 'adodb';

    /**
     * {@inheritdoc}
     * @see Scalr\Upgrade.SequenceInterface::getNumberStages()
     */
    public function getNumberStages()
    {
        return 1;
    }

    protected function isApplied1($stage)
    {
        return $this->hasTable('server_termination_errors');
    }

    protected function validateBefore1($stage)
    {
        return $this->hasTable('servers');
    }

    protected function run1($stage)
    {
        if (!$this->hasTable('server_termination_errors')) {
            $this->console->out('Executing create table server_termination_errors statement...');

            $this->db->Execute("
                CREATE TABLE IF NOT EXISTS `server_termination_errors`(
                    `server_id` VARCHAR(36) NOT NULL COMMENT 'servers.server_id ref',
                    `retry_after` DATETIME NOT NULL COMMENT 'After what time it should be revalidated',
                    `attempts` INT UNSIGNED NOT NULL DEFAULT '1' COMMENT 'The number of unsuccessful attempts',
                    `last_error` TEXT COMMENT 'Error message',
                    PRIMARY KEY (`server_id`),
                    INDEX `idx_retry_after` (`retry_after` ASC)
                ) ENGINE=InnoDB
                COMMENT='Server termination process errors'
            ");
        }
    }
}


text:
import javax.jms.*;
import javax.naming.InitialContext;

public class MyReceiver {
    public static void main(String[] args) {
        try{
            //1) Create and start connection
            InitialContext ctx=new InitialContext();
            QueueConnectionFactory f=(QueueConnectionFactory)ctx.lookup("myQueueConnectionFactory");
            QueueConnection con=f.createQueueConnection();
            con.start();
            //2) create Queue session
            QueueSession ses=con.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
            //3) get the Queue object
            Queue t=(Queue)ctx.lookup("myQueue");
            //4)create QueueReceiver
            QueueReceiver receiver=ses.createReceiver(t);

            //5) create listener object
            MyListener listener=new MyListener();

            //6) register the listener object with receiver
            receiver.setMessageListener(listener);

            System.out.println("Receiver1 is ready, waiting for messages...");
            System.out.println("press Ctrl+c to shutdown...");
            while(true){
                Thread.sleep(1000);
            }
        }catch(Exception e){System.out.println(e);}
    }

}


text:
"""Functionality that should be in the standard library. Like
builtins, but Boltons.

Otherwise known as, "everyone's util.py," but cleaned up and
tested.

Contains over 160 BSD-licensed utility types and functions that can be
used as a package or independently. `Extensively documented on Read
the Docs <http://boltons.readthedocs.org>`_.
"""

from setuptools import setup

__author__ = 'Mahmoud Hashemi'
__version__ = '15.0.3dev'
__contact__ = 'mahmoudrhashemi@gmail.com'
__url__ = 'https://github.com/mahmoud/boltons'
__license__ = 'BSD'

setup(name='boltons',
      version=__version__,
      description="When they're not builtins, they're boltons.",
      long_description=__doc__,
      author=__author__,
      author_email=__contact__,
      url=__url__,
      packages=['boltons'],
      include_package_data=True,
      zip_safe=False,
      license=__license__,
      platforms='any',
      classifiers=[
          'Intended Audience :: Developers',
          'Topic :: Software Development :: Libraries',
          'Programming Language :: Python :: 2.6',
          'Programming Language :: Python :: 2.7',
          'Programming Language :: Python :: 3.4', ]
      )


text:
<Record>
<Term>Keratopathy</Term>
<SemanticType>Disease or Syndrome</SemanticType>
<ParentTerm>Non-Neoplastic Corneal Disorder</ParentTerm>
<ClassificationPath>Findings_and_Disorders_Kind/Disease, Disorder or Finding/Disease or Disorder/Non-Neoplastic Disorder/Non-Neoplastic Disorder by Site/Non-Neoplastic Eye Disorder/Non-Neoplastic Corneal Disorder/Keratopathy</ClassificationPath>
<BroaderTerm>Non-Neoplastic Disorder by Site</BroaderTerm>
<BroaderTerm>Non-Neoplastic Disorder</BroaderTerm>
<BroaderTerm>Disease or Disorder</BroaderTerm>
<BroaderTerm>Non-Neoplastic Corneal Disorder</BroaderTerm>
<BroaderTerm>Non-Neoplastic Eye Disorder</BroaderTerm>
<BroaderTerm>Keratopathy</BroaderTerm>
<BroaderTerm>Disease, Disorder or Finding</BroaderTerm>
<BroaderTerm>Findings_and_Disorders_Kind</BroaderTerm>
<ChildTerm>Bullous Keratopathy</ChildTerm>
<Synonym>Keratopathy</Synonym>
<Source>NCI Thesaurus</Source>
</Record>


text:
<?php

namespace Balance\Form;

/**
 * Exceção de Formulários
 */
class FormException extends \Exception
{
}


text:
var validator = require("validator")
  , FilterPrototype = validator.Filter.prototype
  , ValidatorPrototype = validator.Validator.prototype
  , externalFilter = new validator.Filter()
  , externalValidator = new validator.Validator()
  , object = require("object-additions").object
  , async = require("async")
  , utils = require("./utils");

function Field(property, label) {
  var stack = []
    , isArray = false
    , fieldLabel = label || property;

  this.name = property;
  this.__required = false;
  this.__trimmed = false;

  this.add = function(func) {
    stack.push(func);
    return this;
  };

  this.array = function() {
    isArray = true;
    return this;
  };

  this.run = function (source, form, options, cb) {
    var self = this
      , errors = []
      , value = utils.getProp(property, form) || utils.getProp(property, source);

    if (options.autoTrim && !self.__trimmed) {
      self.__trimmed = true;
      stack.unshift(function (value) {
        if (object.isString(value)) {
          return FilterPrototype.trim.apply(externalFilter.sanitize(value));
        }
        return value;
      });
    }

    function runStack(foo, cb) {

      async.eachSeries(stack, function(proc, cb) {

        if (proc.length == 3) {
          // run the async validator/filter
          return proc(foo, source, function(err, result) {
            if (err) {
              errors.push(err.message.replace("%s", fieldLabel));
              return cb(null);
            }

            // filters return values
            if (result != null) {
              foo = result
            }

            cb(null);

          });
        }

        // run the sync validator/filter
        var result = proc(foo, source);
        if (result.valid) return cb(null);
        if (result.error) {
          // If this field is not required and it doesn't have a value, ignore error.
          if (!utils.hasValue(value) && !self.__required) return cb(null);

          errors.push(result.error.replace("%s", fieldLabel));
          return cb(null);
        }
        foo = result;
        cb(null);

      }, function(err) {
        cb(null, foo);
      });
    }

    if (isArray) {
      if (!utils.hasValue(value)) value = [];
      if (!Array.isArray(value)) value = [value];
      async.mapSeries(value, runStack, function(err, value) {
        utils.setProp(property, form, value);
        cb(null, errors);
      });

    } else {
      if (Array.isArray(value)) value = value[0];
      runStack(value, function(err, value) {
        utils.setProp(property, form, value);
        cb(null, errors);
      });
    }
  };
}

// ARRAY METHODS

Field.prototype.array = function () {
  return this.array();
};

Field.prototype.arrLength = function (from, to) {
  return this.add(function (arr) {
    if (value.length < from) {
      return { error: message || e.message || "%s is too short" };
    }
    if (value.length > to) {
      return { error: message || e.message || "%s is too long" };
    }
    return { valid: true };
  });
}

// HYBRID METHODS

Field.prototype.custom = function(func, message) {

  // custom function is async
  if (func.length == 3) {
    return this.add(function(value, source, cb) {
      func(value, source, function(err, result) {
        if (err) return cb(new Error(message || err.message || "%s is invalid"));

        // functions that return values are filters
        if (result != null) return cb(null, result);

        // value passed validator
        cb(null, null);
      });
    });
  }

  // custom function is sync
  return this.add(function (value, source) {

    try {
      var result = func(value, source);
    } catch (e) {
      return { error: message || e.message || "%s is invalid" };
    }
    // Functions that return values are filters.
    if (result != null) return result;

    // value passed validator
    return { valid: true };

  });
};

// FILTER METHODS

Object.keys(FilterPrototype).forEach(function (name) {
  if (name.match(/^ifNull$/)) return;

  Field.prototype[name] = function () {
    var args = arguments;
    return this.add(function (value) {
      var a = FilterPrototype[name].apply(externalFilter.sanitize(value), args);
      return a;
    });
  };
});

Field.prototype.ifNull = function (replacement) {
  return this.add(function (value) {
    if (object.isUndefined(value) || null === value || '' === value) {
      return replacement;
    }
    return value;
  });
};

Field.prototype.toUpper = Field.prototype.toUpperCase = function () {
  return this.add(function (value) {
    return value.toString().toUpperCase();
  });
};

Field.prototype.toLower = Field.prototype.toLowerCase = function () {
  return this.add(function (value) {
    return value.toString().toLowerCase();
  });
};

Field.prototype.truncate = function (length) {
  return this.add(function (value) {
    value = value.toString();
    if (value.length <= length) {
      return value;
    }

    if (length <= 3) return "...";

    if (value.length > length - 3) {
      return value.substr(0,length - 3) + "...";
    }

    return value;
  });
};

Field.prototype.customFilter = function (func) {
  return this.add(func);
};

// VALIDATE METHODS

var MESSAGES = {
  isDate: "%s is not a date",
  isUrl: "%s is not a URL",
  isIP: "%s is not an IP address",
  isAlpha: "%s contains non-letter characters",
  isAlphanumeric: "%s contains non alpha-numeric characters",
  isNumeric: "%s is not numeric",
  isLowercase: "%s contains uppercase letters",
  isUppercase: "%s contains lowercase letters",
  isInt: "%s is not an integer",
  notEmpty: "%s has no value or is only whitespace"
};

Object.keys(ValidatorPrototype).forEach(function (name) {
  if (name.match(/^(contains|notContains|equals|check|validate|assert|error|len|isNumeric|isDecimal|isEmail|isFloat|regex|notRegex|is|not|notNull|isNull)$/)) {
    return;
  }

  Field.prototype[name] = function (message) {
    var args = arguments;
    message = message || MESSAGES[name];

    return this.add(function(value) {
      try {
        ValidatorPrototype[name].apply(externalValidator.check(value, message), args);
      } catch (e) {
        return { error: e.message || e.toString() };
      }
      return { valid: true };
    });
  };
});

Field.prototype.contains = function (test, message) {
  return this.add(function(value) {
    try {
      ValidatorPrototype.contains.call(externalValidator.check(value, message), test);
    } catch (e) {
      return { error: message || "%s does not contain required characters" };
    }
    return { valid: true };
  });
};

Field.prototype.notContains = function (test, message) {
  return this.add(function (value) {
    try {
      ValidatorPrototype.notContains.call(externalValidator.check(value, message), test);
    } catch (e) {
      return { error: message || "%s contains invalid characters" };
    }
    return { valid: true };
  });
};

Field.prototype.equals = function (other, message) {
  if (object.isString(other) && other.match(/^field::/)) {
    this.__required = true;
  }

  return this.add(function (value, source) {
    // If other is a field token (field::fieldname), grab the value of fieldname
    // and use that as the OTHER value.
    var test = other;
    if (object.isString(other) && other.match(/^field::/)) {
      test = utils.getProp(other.replace(/^field::/, ""), source);
    }
    if (value != test) {
      return { error: message || "%s does not equal " + String(test) };
    }
    return { valid: true };
  });
};

// node-validator's numeric validator seems unintuitive. All numeric values should be valid, not just int.
Field.prototype.isNumeric = function (message) {
  return this.add(function (value) {
    if (object.isNumber(value) || (object.isString(value) && value.match(/^[-+]?[0-9]*\.?[0-9]+$/))) {
    } else {
      return { error: message || "%s is not a number" };
    }
    return { valid: true };
  });
};

// node-validator's decimal/float validator incorrectly thinks Ints are valid.
Field.prototype.isFloat = Field.prototype.isDecimal = function (message) {
  return this.add(function (value) {
    if ((object.isNumber(value) && value % 1 == 0) || (object.isString(value) && value.match(/^[-+]?[0-9]*\.[0-9]+$/))) {
    } else {
      return { error: message || "%s is not a decimal" };
    }
    return { valid: true };
  });
};

// super simple email validation
Field.prototype.isEmail = function (message) {
  return this.add(function (value) {
    if (typeof value != 'string' || !(/^[\-0-9a-zA-Z\.\+_]+@[\-0-9a-zA-Z\.\+_]+\.[a-zA-Z]{2,4}$/).test(value)) {
      return { error: message || "%s is not an email address" };
    }
    return { valid: true };
  });
};

Field.prototype.isString = function (message) {
  return this.add(function (value) {
    if (!object.isString(value)) {
      return { error: message || "%s is not a string" };
    }
    return { valid: true };
  });
};

Field.prototype.regex = Field.prototype.is = function (pattern, modifiers, message) {
  // regex(/pattern/)
  // regex(/pattern/, "message")
  // regex("pattern")
  // regex("pattern", "modifiers")
  // regex("pattern", "message")
  // regex("pattern", "modifiers", "message")

  if (pattern instanceof RegExp) {
    if (object.isString(modifiers) && modifiers.match(/^[gimy]+$/)) {
      throw new Error("Invalid arguments: `modifiers` can only be passed in if `pattern` is a string.");
    }

    message = modifiers;
    modifiers = undefined;

  } else if (object.isString(pattern)) {
    if (arguments.length == 2 && !modifiers.match(/^[gimy]+$/)) {
      // 2nd arg doesn't look like modifier flags, it's the message (might also be undefined)
      message = modifiers;
      modifiers = undefined;
    }
    pattern = new RegExp(pattern, modifiers);
  }

  return this.add(function (value) {
    if (pattern.test(value) === false) {
      return { error: message || "%s has invalid characters" };
    }
    return { valid: true };
  });
};

Field.prototype.notRegex = Field.prototype.not = function(pattern, modifiers, message) {
  // notRegex(/pattern/)
  // notRegex(/pattern/, "message")
  // notRegex("pattern")
  // notRegex("pattern", "modifiers")
  // notRegex("pattern", "message")
  // notRegex("pattern", "modifiers", "message")

  if (pattern instanceof RegExp) {
    if (object.isString(modifiers) && modifiers.match(/^[gimy]+$/)) {
      throw new Error("Invalid arguments: `modifiers` can only be passed in if `pattern` is a string.");
    }

    message = modifiers;
    modifiers = undefined;

  } else if (object.isString(pattern)) {
    if (arguments.length == 2 && !modifiers.match(/^[gimy]+$/)) {
      // 2nd arg doesn't look like modifier flags, it's the message (might also be undefined)
      message = modifiers;
      modifiers = undefined;
    }
    pattern = new RegExp(pattern, modifiers);
  }

  return this.add(function(value) {
    if (pattern.test(value) === true) {
      return { error: message || "%s has invalid characters" };
    }
    return { valid: true };
  });
};

Field.prototype.required = function (placeholderValue, message) {
  this.__required = true;
  return this.add(function (value) {
    if (!utils.hasValue(value) || value == placeholderValue) {
      return { error: message || "%s is required" };
    }
    return { valid: true };
  });
};

Field.prototype.minLength = function (length, message) {
  return this.add(function(value) {
    if (value.toString().length < length) {
      return { error: message || "%s is too short" };
    }
    return { valid: true };
  });
};

Field.prototype.maxLength = function (length, message) {
  return this.add(function(value) {
    if (value.toString().length > length) {
      return { error: message || "%s is too long" };
    }
    return { valid: true };
  });
};

Field.prototype.customValidator = function(func, message) {
  return this.add(function(value, source) {
    try {
      func(value, source);
    } catch (e) {
      return { error: message || e.message || "%s is invalid" };
    }
    return { valid: true };
  });
};

module.exports = Field;


text:
import { createRouter } from '@stencil/router'

export const SettingsRouter = createRouter()


text:
.employee-example h1 {
    background-color: purple
}


text:
'''
Pseudocode:
import math
import random
set varriables
startFrogNum
frogNum

loops for the sim:
for i in range(startFrogNum):
    set a new list for every froge, l=[]
    for i in range(5):
        frogLuck=random.randint(1,4)
        l.append(frogLuck)
        assign each number(1-4) to a direction
        north= l.count(1)
        south= "      "
        east= "       "
        west= "       "
        measure distances of each direction

calculate survival rate

print('blahblahblahbalh', frogNumn 'blahblahblahblah', frogPercent, '%.)
print(little froggie guys)

'''

import random
startFrogNum=1000                             #set varriables
frogSuv=0

for i in range(1000):                         #loop for main sim
    lifeLine=[]
    for i in range(5):                        #loop for each frog
        frogLuck=random.randint(1,4)
        lifeLine.append(frogLuck)
        north= lifeLine.count(1)              #counting the distance taveled
        south= lifeLine.count(2)
        east= lifeLine.count(3)
        west= lifeLine.count(4)
        if north >= 3:                        #evaluating the distance traveled
            frogSuv+=1
        if south >= 3:
            frogSuv+=1
        if east >= 3:
            frogSuv+=1
        if west >= 3:
            frogSuv+=1
suvRate=frogSuv/10
print('Of the  1000 frogs simulated, there were', frogSuv, 'frogs that survived.','\n','This represents a survival rate of', suvRate,'%.')
print('     @..@           <O)','\n','    (--)           /))','\n','   (>__<)         ==#==','\n',   '   ^^~~^^')


text:
'''
The MIT License (MIT)

Copyright (c) 2017 Sean UN Wood

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

@author: Sean UN Wood
'''

import logging
from collections import namedtuple
import ast
import argparse
try:
    import configparser  # Python 3.x
except ImportError:
    import ConfigParser as configparser # Python 2.x

from gccNMF.defs import DEFAULT_AUDIO_FILE, DEFAULT_CONFIG_FILE
from gccNMF.realtime.gccNMFPretraining import getDictionariesW

INT_OPTIONS = ['numTDOAs', 'numTDOAHistory', 'numSpectrogramHistory', 'numChannels',
               'windowSize', 'hopSize', 'blockSize', 'dictionarySize', 'numHUpdates',
               'localizationWindowSize']
FLOAT_OPTIONS = ['gccPHATNLAlpha', 'microphoneSeparationInMetres']
BOOL_OPTIONS = ['gccPHATNLEnabled', 'localizationEnabled']
STRING_OPTIONS = ['dictionaryType', 'audioPath']

def getDefaultConfig():
    configParser = configparser.ConfigParser(allow_no_value=True)
    configParser.optionxform = str
    config = {}
    config['TDOA'] = {'numTDOAs': '64',
                      'numTDOAHistory': '128',
                      'numSpectrogramHistory': '128',
                      'gccPHATNLAlpha': '2.0',
                      'gccPHATNLEnabled': 'False',
                      'microphoneSeparationInMetres': '0.1',
                      'targetTDOAEpsilon': '5.0',
                      'targetTDOABeta': '2.0',
                      'targetTDOANoiseFloor': '0.0',
                      'localizationEnabled': 'True',
                      'localizationWindowSize': '6'}

    config['Audio'] = {'numChannels': '2',
                       'sampleRate': '16000',
                       'deviceIndex': 'None'}

    config['STFT'] = {'windowSize': '1024',
                      'hopSize': '512',
                      'blockSize': '512'}

    config['NMF'] = {'dictionarySize': '64',
                     'dictionarySizes': '[64, 128, 256, 512, 1024]',
                     'dictionaryType': 'Pretrained',
                     'numHUpdates': '0'}
    try:
        for key, value in config.items():
            configParser[key] = value
    except:
        for sectionKey, sectionValue in config.items():
            configParser.add_section(sectionKey)
            for key, value in sectionValue.items():
                configParser.set(sectionKey, key, value)
    return configParser

def getDictFromConfig(config):
    logging.info('GCCNMFConfig: loading configuration params...')
    dictionary = {}
    for section in config.sections():
        logging.info(section)
        dictionary[section] = {}
        for option in config.options(section):
            if option in INT_OPTIONS:
                dictionary[option] = config.getint(section, option)
            elif option in FLOAT_OPTIONS:
                dictionary[option] = config.getfloat(section, option)
            elif option in BOOL_OPTIONS:
                dictionary[option] = config.getboolean(section, option)
            elif option in STRING_OPTIONS:
                dictionary[option] = config.get(section, option)
            else:
                dictionary[option] = ast.literal_eval( config.get(section, option) )
            logging.info('    %s: %s' % (option, str(dictionary[option])) )
    return dictionary

def getGCCNMFConfig(configPath):
    raise ValueError('configPath is None')

def getGCCNMFConfigParams(audioPath=DEFAULT_AUDIO_FILE, configPath=DEFAULT_CONFIG_FILE):
    try:
        config = getGCCNMFConfig(configPath)
    except:
        config = getDefaultConfig()

    parametersDict = getDictFromConfig(config)
    parametersDict['audioPath'] = audioPath
    parametersDict['numFreq'] = parametersDict['windowSize'] // 2 + 1
    parametersDict['windowsPerBlock'] = parametersDict['blockSize'] // parametersDict['hopSize']
    parametersDict['dictionariesW'] = getDictionariesW(parametersDict['windowSize'], parametersDict['dictionarySizes'], ordered=True)

    params = namedtuple('ParamsDict', parametersDict.keys())(**parametersDict)
    return params

def parseArguments():
    parser = argparse.ArgumentParser(description='Real-time GCC-NMF Speech Enhancement')
    parser.add_argument('-i','--input', help='input wav file path', default=DEFAULT_AUDIO_FILE, required=False)
    parser.add_argument('-c','--config', help='config file path', default=DEFAULT_CONFIG_FILE, required=False)
    parser.add_argument('--no-gui', help='no user interface mode', action='store_true')
    return parser.parse_args()


text:
	{{ travelreimbursementdetail.sno }} {{ travelreimbursementdetail.clientlocation }} {{ travelreimbursementdetail.jobno }} {{ travelreimbursementdetail.fromdate }} {{ travelreimbursementdetail.todate }} {{ travelreimbursementdetail.noofdays }} {{ travelreimbursementdetail.conveyance }} {{ travelreimbursementdetail.foodallowance }} {{ travelreimbursementdetail.otherexpenses }} {{ travelreimbursementdetail.totalamount }}

			Posted on

			by


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference
// Implementation, v2.2.11
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2016.11.17 at 11:49:24 AM EET
//

package ee.ria.dhx.server.types.ee.riik.schemas.dhl;

import java.math.BigInteger;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAnyElement;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.datatype.XMLGregorianCalendar;

/**
 *

 * Java class for anonymous complex type.
 *
 *

 * The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType>
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <all>
 *         <element ref="{http://www.riik.ee/schemas/dhl}saaja"/>
 *         <element name="saadud" type="{http://www.w3.org/2001/XMLSchema}dateTime"/>
 *         <element name="meetod">
 *           <simpleType>
 *             <restriction base="{http://www.w3.org/2001/XMLSchema}string">
 *               <enumeration value="epost"/>
 *               <enumeration value="xtee"/>
 *             </restriction>
 *           </simpleType>
 *         </element>
 *         <element name="edastatud" type="{http://www.w3.org/2001/XMLSchema}dateTime" minOccurs="0"/>
 *         <element name="loetud" type="{http://www.w3.org/2001/XMLSchema}dateTime" minOccurs="0"/>
 *         <element ref="{http://www.riik.ee/schemas/dhl}fault" minOccurs="0"/>
 *         <element name="staatus">
 *           <simpleType>
 *             <restriction base="{http://www.w3.org/2001/XMLSchema}string">
 *               <enumeration value="saatmisel"/>
 *               <enumeration value="saadetud"/>
 *               <enumeration value="katkestatud"/>
 *             </restriction>
 *           </simpleType>
 *         </element>
 *         <element name="vastuvotja_staatus_id" type="{http://www.w3.org/2001/XMLSchema}integer" minOccurs="0"/>
 *         <element name="metaxml" minOccurs="0">
 *           <complexType>
 *             <complexContent>
 *               <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *                 <sequence>
 *                   <any minOccurs="0"/>
 *                 </sequence>
 *               </restriction>
 *             </complexContent>
 *           </complexType>
 *         </element>
 *       </all>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {

})
@XmlRootElement(name = "edastus")
public class Edastus {

  @XmlElement(required = true, namespace = "")
  protected AadressType saaja;
  @XmlElement(namespace = "", required = true)
  @XmlSchemaType(name = "dateTime")
  protected XMLGregorianCalendar saadud;
  @XmlElement(namespace = "", required = true)
  protected String meetod;
  @XmlElement(namespace = "")
  @XmlSchemaType(name = "dateTime")
  protected XMLGregorianCalendar edastatud;
  @XmlElement(namespace = "")
  @XmlSchemaType(name = "dateTime")
  protected XMLGregorianCalendar loetud;
  protected Fault fault;
  @XmlElement(namespace = "", required = true)
  protected String staatus;
  @XmlElement(name = "vastuvotja_staatus_id", namespace = "")
  protected BigInteger vastuvotjaStaatusId;
  @XmlElement(namespace = "")
  protected Edastus.Metaxml metaxml;

  /**
   * Gets the value of the saaja property.
   *
   * @return possible object is {@link AadressType }
   *
   */
  public AadressType getSaaja() {
    return saaja;
  }

  /**
   * Sets the value of the saaja property.
   *
   * @param value allowed object is {@link AadressType }
   *
   */
  public void setSaaja(AadressType value) {
    this.saaja = value;
  }

  /**
   * Gets the value of the saadud property.
   *
   * @return possible object is {@link XMLGregorianCalendar }
   *
   */
  public XMLGregorianCalendar getSaadud() {
    return saadud;
  }

  /**
   * Sets the value of the saadud property.
   *
   * @param value allowed object is {@link XMLGregorianCalendar }
   *
   */
  public void setSaadud(XMLGregorianCalendar value) {
    this.saadud = value;
  }

  /**
   * Gets the value of the meetod property.
   *
   * @return possible object is {@link String }
   *
   */
  public String getMeetod() {
    return meetod;
  }

  /**
   * Sets the value of the meetod property.
   *
   * @param value allowed object is {@link String }
   *
   */
  public void setMeetod(String value) {
    this.meetod = value;
  }

  /**
   * Gets the value of the edastatud property.
   *
   * @return possible object is {@link XMLGregorianCalendar }
   *
   */
  public XMLGregorianCalendar getEdastatud() {
    return edastatud;
  }

  /**
   * Sets the value of the edastatud property.
   *
   * @param value allowed object is {@link XMLGregorianCalendar }
   *
   */
  public void setEdastatud(XMLGregorianCalendar value) {
    this.edastatud = value;
  }

  /**
   * Gets the value of the loetud property.
   *
   * @return possible object is {@link XMLGregorianCalendar }
   *
   */
  public XMLGregorianCalendar getLoetud() {
    return loetud;
  }

  /**
   * Sets the value of the loetud property.
   *
   * @param value allowed object is {@link XMLGregorianCalendar }
   *
   */
  public void setLoetud(XMLGregorianCalendar value) {
    this.loetud = value;
  }

  /**
   * Gets the value of the fault property.
   *
   * @return possible object is {@link Fault }
   *
   */
  public Fault getFault() {
    return fault;
  }

  /**
   * Sets the value of the fault property.
   *
   * @param value allowed object is {@link Fault }
   *
   */
  public void setFault(Fault value) {
    this.fault = value;
  }

  /**
   * Gets the value of the staatus property.
   *
   * @return possible object is {@link String }
   *
   */
  public String getStaatus() {
    return staatus;
  }

  /**
   * Sets the value of the staatus property.
   *
   * @param value allowed object is {@link String }
   *
   */
  public void setStaatus(String value) {
    this.staatus = value;
  }

  /**
   * Gets the value of the vastuvotjaStaatusId property.
   *
   * @return possible object is {@link BigInteger }
   *
   */
  public BigInteger getVastuvotjaStaatusId() {
    return vastuvotjaStaatusId;
  }

  /**
   * Sets the value of the vastuvotjaStaatusId property.
   *
   * @param value allowed object is {@link BigInteger }
   *
   */
  public void setVastuvotjaStaatusId(BigInteger value) {
    this.vastuvotjaStaatusId = value;
  }

  /**
   * Gets the value of the metaxml property.
   *
   * @return possible object is {@link Edastus.Metaxml }
   *
   */
  public Edastus.Metaxml getMetaxml() {
    return metaxml;
  }

  /**
   * Sets the value of the metaxml property.
   *
   * @param value allowed object is {@link Edastus.Metaxml }
   *
   */
  public void setMetaxml(Edastus.Metaxml value) {
    this.metaxml = value;
  }

  /**
   *

   * Java class for anonymous complex type.
   *
   *

   * The following schema fragment specifies the expected content contained within this class.
   *
   *

     * <complexType>
     *   <complexContent>
     *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
     *       <sequence>
     *         <any minOccurs="0"/>
     *       </sequence>
     *     </restriction>
     *   </complexContent>
     * </complexType>
     *

   *
   *
   */
  @XmlAccessorType(XmlAccessType.FIELD)
  @XmlType(name = "", propOrder = {
      "any"
  })
  public static class Metaxml {

    @XmlAnyElement(lax = true)
    protected Object any;

    /**
     * Gets the value of the any property.
     *
     * @return possible object is {@link Object }
     *
     */
    public Object getAny() {
      return any;
    }

    /**
     * Sets the value of the any property.
     *
     * @param value allowed object is {@link Object }
     *
     */
    public void setAny(Object value) {
      this.any = value;
    }

  }

}


text:
<title>Flot Preset</title><link href="img/favicon.png" rel="shortcut icon" type="image/x-icon"><link type="text/css" rel="stylesheet" href="../../lib/css/themes/jquery-ui/default/jquery-ui.min.css">
loading...


text:
$def with (games, players, gamePage, playerPage, gamePages, playerPages, tab, isLoggedIn)

$if isLoggedIn:
  $var logout: True
  $var link1:  Back to Levels
$else:
  $var link1:  Login

$if tab == 'game':
  $ gameActiveClass = ' active'
$else:
  $ gameActiveClass = ''

$if tab == 'player':
  $ playerActiveClass = ' active'
$else:
  $ playerActiveClass = ''

Leaderboard

    Game Based
    Player Based

          Rank
          Player
          Score
          Badge

        $if len(games) > 0:
          $ i = 1
          $for leader in games:
            $if leader["badge"] == "Ruby":
              $ cls = "diamond icon orange"
            $elif leader["badge"] == "Sapphire":
              $ cls = "diamond icon blue"
            $elif leader["badge"] == "Emerald":
              $ cls = "diamond icon green"
            $elif leader["badge"] == "Diamond":
              $ cls = "diamond icon grey"
            $elif leader["badge"] == "-":
              $ cls = ""

              $((gamePage-1)*20+i)
              $leader["username"]
              $leader["score"]
               $leader["badge"]

            $ i = i + 1
        $else:

            No player has won any game yet.

            $if gamePage >= 3:

            $if gamePage - 1 > 0:
              $(gamePage-1)

            $(gamePage)

            $if gamePages - gamePage > 1:
              $(gamePage+1)

            $if gamePages - gamePage > 2:

          Rank
          Player
          Total Score
          Total Wins

        $if len(players) > 0:
          $ i = 1
          $for maxLeader in players:
            $if maxLeader["wins"] >= 45:
              $ cls = "red10"
            $elif maxLeader["wins"] >= 40:
              $ cls = "red9"
            $elif maxLeader["wins"] >= 35:
              $ cls = "red8"
            $elif maxLeader["wins"] >= 30:
              $ cls = "red7"
            $elif maxLeader["wins"] >= 25:
              $ cls = "red6"
            $elif maxLeader["wins"] >= 20:
              $ cls = "red5"
            $elif maxLeader["wins"] >= 15:
              $ cls = "red4"
            $elif maxLeader["wins"] >= 10:
              $ cls = "red3"
            $elif maxLeader["wins"] >= 5:
              $ cls = "red2"
            $else:
              $ cls = "red1"

              $((playerPage-1)*20+i)
              $maxLeader["username"]
              $maxLeader["totalScore"]
               $maxLeader["wins"]

            $ i = i + 1
        $else:

              No player has won any game yet.

            $if playerPage >= 3:

            $if playerPage - 1 > 0:
              $(playerPage-1)

            $(playerPage)

            $if playerPages - playerPage >= 1:
              $(playerPage+1)

            $if playerPages - playerPage >= 2: