text:
namespace fixie
{
    template <typename output_type>
    size_t get_framebuffer_attachment_parameter(GLenum target, GLenum attachment, GLenum pname, output_type* output)
    {
        try
        {
            std::shared_ptr<context> ctx = get_current_context();
            if (!ctx->caps().supports_framebuffer_objects())
            {
                throw invalid_operation_error("framebuffers are not supported.");
            }

            std::shared_ptr<framebuffer> framebuffer = ctx->state().bound_framebuffer().lock();

            const fixie::framebuffer_attachment* framebuffer_attachment = nullptr;
            switch (attachment)
            {
            case GL_COLOR_ATTACHMENT0_OES:
                framebuffer_attachment = &framebuffer->color_attachment();
                break;

            case GL_DEPTH_ATTACHMENT_OES:
                framebuffer_attachment = &framebuffer->depth_attachment();
                break;

            case GL_STENCIL_ATTACHMENT_OES:
                framebuffer_attachment = &framebuffer->stencil_attachment();
                break;

            default:
                throw invalid_enum_error(format("invalid framebuffer attachment, %s.", get_gl_enum_name(attachment).c_str()));
            }

            switch (pname)
            {
            case GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE_OES:
                if (!framebuffer_attachment->is_bound())
                {
                    output[0] = static_cast<output_type>(GL_NONE_OES);
                }
                else if (framebuffer_attachment->is_texture())
                {
                    output[0] = static_cast<output_type>(GL_TEXTURE);
                }
                else if (framebuffer_attachment->is_renderbuffer())
                {
                    output[0] = static_cast<output_type>(GL_RENDERBUFFER_OES);
                }
                else
                {
                    UNREACHABLE();
                }
                return 1;

            case GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME_OES:
                if (!framebuffer_attachment->is_bound())
                {
                    output[0] = static_cast<output_type>(0);
                }
                if (framebuffer_attachment->is_texture())
                {
                    output[0] = static_cast<output_type>(ctx->textures().get_handle(framebuffer_attachment->texture()));
                }
                else if (framebuffer_attachment->is_renderbuffer())
                {
                    output[0] = static_cast<output_type>(ctx->renderbuffers().get_handle(framebuffer_attachment->renderbuffer()));
                }
                else
                {
                    UNREACHABLE();
                }
                return 1;

            case GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL_OES:
                if (framebuffer_attachment->is_texture())
                {
                    output[0] = static_cast<output_type>(framebuffer_attachment->texture_level());
                }
                else
                {
                    throw invalid_operation_error("GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL_OES is not a valid query when a texture is not bound.");
                }
                return 1;

            case GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE_OES:
                if (framebuffer_attachment->is_texture())
                {
                    throw invalid_operation_error("cube maps are not supported.");
                }
                else
                {
                    throw invalid_operation_error("GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE_OES is not a valid query when a texture is not bound.");
                }
                return 1;

            default:
                throw invalid_enum_error(format("invalid framebuffer attachment parameter name, %s.", get_gl_enum_name(pname).c_str()));
            }
        }
        catch (...)
        {
            return handle_entry_point_exception(0);
        }
    }

    template <typename output_type>
    size_t get_renderbuffer_parameter(GLenum target, GLenum pname, output_type* output)
    {
        try
        {
            std::shared_ptr<context> ctx = get_current_context();
            if (!ctx->caps().supports_framebuffer_objects())
            {
                throw invalid_operation_error("renderbuffers are not supported.");
            }

            std::shared_ptr<renderbuffer> renderbuffer;
            switch (target)
            {
            case GL_RENDERBUFFER_OES:
                renderbuffer = ctx->state().bound_renderbuffer().lock();
                break;

            default:
                throw invalid_enum_error(format("unknown renderbuffer target, %s.", get_gl_enum_name(target).c_str()));;
            }

            switch (pname)
            {
            case GL_RENDERBUFFER_WIDTH_OES:
                if (output != nullptr && renderbuffer != nullptr)
                {
                    output[0] = static_cast<output_type>(renderbuffer->width());
                }
                return 1;

            case GL_RENDERBUFFER_HEIGHT_OES:
                if (output != nullptr && renderbuffer != nullptr)
                {
                    output[0] = static_cast<output_type>(renderbuffer->height());
                }
                return 1;

            case GL_RENDERBUFFER_INTERNAL_FORMAT_OES:
                if (output != nullptr && renderbuffer != nullptr)
                {
                    output[0] = static_cast<output_type>(renderbuffer->internal_format());
                }
                return 1;

            case GL_RENDERBUFFER_RED_SIZE_OES:
                if (output != nullptr && renderbuffer != nullptr)
                {
                    output[0] = static_cast<output_type>(renderbuffer->red_size());
                }
                break;

            case GL_RENDERBUFFER_GREEN_SIZE_OES:
                if (output != nullptr && renderbuffer != nullptr)
                {
                    output[0] = static_cast<output_type>(renderbuffer->green_size());
                }
                return 1;

            case GL_RENDERBUFFER_BLUE_SIZE_OES:
                if (output != nullptr && renderbuffer != nullptr)
                {
                    output[0] = static_cast<output_type>(renderbuffer->blue_size());
                }
                return 1;

            case GL_RENDERBUFFER_ALPHA_SIZE_OES:
                if (output != nullptr && renderbuffer != nullptr)
                {
                    output[0] = static_cast<output_type>(renderbuffer->alpha_size());
                }
                return 1;

            case GL_RENDERBUFFER_DEPTH_SIZE_OES:
                if (output != nullptr && renderbuffer != nullptr)
                {
                    output[0] = static_cast<output_type>(renderbuffer->depth_size());
                }
                return 1;

            case GL_RENDERBUFFER_STENCIL_SIZE_OES:
                if (output != nullptr && renderbuffer != nullptr)
                {
                    output[0] = static_cast<output_type>(renderbuffer->stencil_size());
                }
                return 1;

            default:
                throw invalid_enum_error(format("invalid renderbuffer parameter name, %s.", get_gl_enum_name(pname).c_str()));
            }
        }
        catch (...)
        {
            return handle_entry_point_exception(0);
        }
    }
}

extern "C"
{

GLboolean FIXIE_APIENTRY glIsRenderbufferOES(GLuint renderbuffer)
{
    try
    {
        std::shared_ptr<fixie::context> ctx = fixie::get_current_context();

        if (!ctx->caps().supports_framebuffer_objects())
        {
            throw fixie::invalid_operation_error("renderbuffers are not supported.");
        }

        return ctx->renderbuffers().contains_handle(renderbuffer) ? GL_TRUE : GL_FALSE;
    }
    catch (...)
    {
        return fixie::handle_entry_point_exception(GL_FALSE);
    }
}

void FIXIE_APIENTRY glBindRenderbufferOES(GLenum target, GLuint renderbuffer)
{
    try
    {
        std::shared_ptr<fixie::context> ctx = fixie::get_current_context();

        if (!ctx->caps().supports_framebuffer_objects())
        {
            throw fixie::invalid_operation_error("renderbuffers are not supported.");
        }

        std::weak_ptr<fixie::renderbuffer> rb = ctx->renderbuffers().get_object(renderbuffer);

        switch (target)
        {
        case GL_RENDERBUFFER_OES:
            ctx->state().bind_renderbuffer(rb);
            break;

        default:
            throw fixie::invalid_enum_error(fixie::format("unknown renderbuffer binding target, %s.", fixie::get_gl_enum_name(target).c_str()));
        }
    }
    catch (...)
    {
        fixie::handle_entry_point_exception();
    }
}

void FIXIE_APIENTRY glDeleteRenderbuffersOES(GLsizei n, const GLuint* renderbuffers)
{
    try
    {
        std::shared_ptr<fixie::context> ctx = fixie::get_current_context();

        if (!ctx->caps().supports_framebuffer_objects())
        {
            throw fixie::invalid_operation_error("renderbuffers are not supported.");
        }

        if (n < 0)
        {
            throw fixie::invalid_value_error(fixie::format("invalid number of renderbuffers, at least 0 required, %i provided.", n));
        }

        fixie::for_each_n(0, n, [&](size_t i){ ctx->renderbuffers().erase_object(renderbuffers[i]); });
    }
    catch (...)
    {
        fixie::handle_entry_point_exception();
    }
}

void FIXIE_APIENTRY glGenRenderbuffersOES(GLsizei n, GLuint* renderbuffers)
{
    try
    {
        std::shared_ptr<fixie::context> ctx = fixie::get_current_context();

        if (!ctx->caps().supports_framebuffer_objects())
        {
            throw fixie::invalid_operation_error("renderbuffers are not supported.");
        }

        if (n < 0)
        {
            throw fixie::invalid_value_error(fixie::format("invalid number of renderbuffers, at least 0 required, %i provided.", n));
        }

        std::fill(renderbuffers, renderbuffers + n, 0);

        try
        {
            std::generate_n(renderbuffers, n, [&](){ return ctx->create_renderbuffer(); });
        }
        catch (...)
        {
            try
            {
                std::for_each(renderbuffers, renderbuffers + n, [&](GLuint rb){ ctx->renderbuffers().erase_object(rb); });
            }
            catch (...)
            {
                // error while deleting a renderbuffer, ignore it
            }

            throw;
        }
    }
    catch (...)
    {
        fixie::handle_entry_point_exception();
    }
}

void FIXIE_APIENTRY glRenderbufferStorageOES(GLenum target, GLenum internalformat, GLsizei width, GLsizei height)
{
    try
    {
        std::shared_ptr<fixie::context> ctx = fixie::get_current_context();

        if (!ctx->caps().supports_framebuffer_objects())
        {
            throw fixie::invalid_operation_error("renderbuffers are not supported.");
        }

        if (target != GL_RENDERBUFFER_OES)
        {
            throw fixie::invalid_enum_error(fixie::format("renderbuffer target must be GL_RENDERBUFFER_OES, %s provided.", fixie::get_gl_enum_name(target).c_str()));
        }

        std::set<GLenum> valid_internal_formats;
        valid_internal_formats.insert(GL_RGB565_OES);
        valid_internal_formats.insert(GL_RGBA4_OES);
        valid_internal_formats.insert(GL_RGB5_A1_OES);
        valid_internal_formats.insert(GL_DEPTH_COMPONENT16_OES);
        if (ctx->caps().supports_rgb8_rgba8())
        {
            valid_internal_formats.insert(GL_RGBA8_OES);
            valid_internal_formats.insert(GL_RGB8_OES);
        }
        if (ctx->caps().supports_depth24())
        {
            valid_internal_formats.insert(GL_DEPTH_COMPONENT24_OES);
        }
        if (ctx->caps().supports_depth32())
        {
            valid_internal_formats.insert(GL_DEPTH_COMPONENT32_OES);
        }
        if (ctx->caps().supports_stencil1())
        {
            valid_internal_formats.insert(GL_DEPTH_COMPONENT32_OES);
        }
        if (ctx->caps().supports_stencil4())
        {
            valid_internal_formats.insert(GL_STENCIL_INDEX4_OES);
        }
        if (ctx->caps().supports_stencil8())
        {
            valid_internal_formats.insert(GL_STENCIL_INDEX8_OES);
        }

        if (valid_internal_formats.find(internalformat) == valid_internal_formats.end())
        {
            throw fixie::invalid_value_error(fixie::format("invalid internal format, %s", fixie::get_gl_enum_name(internalformat).c_str()));
        }

        std::shared_ptr<fixie::renderbuffer> renderbuffer = ctx->state().bound_renderbuffer().lock();
        if (renderbuffer != nullptr)
        {
            renderbuffer->set_storage(target, internalformat, width, height);
        }
    }
    catch (...)
    {
        fixie::handle_entry_point_exception();
    }
}

void FIXIE_APIENTRY glGetRenderbufferParameterivOES(GLenum target, GLenum pname, GLint* params)
{
    fixie::get_renderbuffer_parameter(target, pname, params);
}

GLboolean FIXIE_APIENTRY glIsFramebufferOES(GLuint framebuffer)
{
    try
    {
        std::shared_ptr<fixie::context> ctx = fixie::get_current_context();

        if (!ctx->caps().supports_framebuffer_objects())
        {
            throw fixie::invalid_operation_error("framebuffers are not supported.");
        }

        return ctx->framebuffers().contains_handle(framebuffer) ? GL_TRUE : GL_FALSE;
    }
    catch (...)
    {
        return fixie::handle_entry_point_exception(GL_FALSE);
    }
}

void FIXIE_APIENTRY glBindFramebufferOES(GLenum target, GLuint framebuffer)
{
    try
    {
        std::shared_ptr<fixie::context> ctx = fixie::get_current_context();

        if (!ctx->caps().supports_framebuffer_objects())
        {
            throw fixie::invalid_operation_error("framebuffers are not supported.");
        }

        std::weak_ptr<fixie::framebuffer> fbo = ctx->framebuffers().get_object(framebuffer);

        // TODO: handle creating temporary framebuffers if fbo is null

        switch (target)
        {
        case GL_FRAMEBUFFER_OES:
            ctx->state().bind_framebuffer(fbo);
            break;

        default:
            throw fixie::invalid_enum_error(fixie::format("unknown framebuffer target, %s.", fixie::get_gl_enum_name(target).c_str()));
        }
    }
    catch (...)
    {
        fixie::handle_entry_point_exception();
    }
}

void FIXIE_APIENTRY glDeleteFramebuffersOES(GLsizei n, const GLuint* framebuffers)
{
    try
    {
        std::shared_ptr<fixie::context> ctx = fixie::get_current_context();

        if (!ctx->caps().supports_framebuffer_objects())
        {
            throw fixie::invalid_operation_error("framebuffers are not supported.");
        }

        if (n < 0)
        {
            throw fixie::invalid_value_error(fixie::format("invalid number of framebuffers, at least 0 required, %i provided.", n));
        }

        auto erase_func = [&](GLuint framebuffer)
        {
            std::shared_ptr<fixie::framebuffer> frammebuffer_object = ctx->framebuffers().get_object(framebuffer).lock();
            if (ctx->state().bound_framebuffer().lock() == frammebuffer_object)
            {
                ctx->state().bind_framebuffer(ctx->framebuffers().get_object(0));
            }

            ctx->framebuffers().erase_object(framebuffer);
        };

        std::for_each(framebuffers, framebuffers + n, erase_func);
    }
    catch (...)
    {
        fixie::handle_entry_point_exception();
    }
}

void FIXIE_APIENTRY glGenFramebuffersOES(GLsizei n, GLuint* framebuffers)
{
    try
    {
        std::shared_ptr<fixie::context> ctx = fixie::get_current_context();

        if (!ctx->caps().supports_framebuffer_objects())
        {
            throw fixie::invalid_operation_error("framebuffers are not supported.");
        }

        if (n < 0)
        {
            throw fixie::invalid_value_error(fixie::format("invalid number of framebuffers, at least 0 required, %i provided.", n));
        }

        std::fill(framebuffers, framebuffers + n, 0);

        try
        {
            std::generate_n(framebuffers, n, [&](){ return ctx->create_framebuffer(); });
        }
        catch (...)
        {
            try
            {
                std::for_each(framebuffers, framebuffers + n, [&](GLuint fbo){ ctx->framebuffers().erase_object(fbo); });
            }
            catch (...)
            {
                // error while deleting a framebuffer, ignore it
            }

            throw;
        }
    }
    catch (...)
    {
        fixie::handle_entry_point_exception();
    }
}

GLenum FIXIE_APIENTRY glCheckFramebufferStatusOES(GLenum target)
{
    try
    {
        std::shared_ptr<fixie::context> ctx = fixie::get_current_context();

        if (!ctx->caps().supports_framebuffer_objects())
        {
            throw fixie::invalid_operation_error("framebuffers are not supported.");
        }

        std::shared_ptr<fixie::framebuffer> framebuffer;

        switch (target)
        {
        case GL_FRAMEBUFFER_OES:
            framebuffer = ctx->state().bound_framebuffer().lock();
            break;

        default:
            throw fixie::invalid_enum_error(fixie::format("unknown framebuffer target, %s.", fixie::get_gl_enum_name(target).c_str()));
        }

        if (framebuffer == nullptr)
        {
            throw fixie::state_error("null framebuffer bound.");
        }

        return framebuffer->status();
    }
    catch (...)
    {
        return fixie::handle_entry_point_exception(0);
    }
}

void FIXIE_APIENTRY glFramebufferRenderbufferOES(GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer)
{
    try
    {
        std::shared_ptr<fixie::context> ctx = fixie::get_current_context();

        if (!ctx->caps().supports_framebuffer_objects())
        {
            throw fixie::invalid_operation_error("framebuffers are not supported.");
        }

        std::shared_ptr<fixie::framebuffer> framebuffer;
        switch (target)
        {
        case GL_FRAMEBUFFER_OES:
            framebuffer = ctx->state().bound_framebuffer().lock();
            break;

        default:
            throw fixie::invalid_enum_error(fixie::format("unknown framebuffer target, %s.", fixie::get_gl_enum_name(target).c_str()));
        }

        if (framebuffer == nullptr)
        {
            throw fixie::state_error("null framebuffer bound.");
        }

        std::weak_ptr<fixie::renderbuffer> rb;
        switch (renderbuffertarget)
        {
        case GL_RENDERBUFFER_OES:
            rb = ctx->renderbuffers().get_object(renderbuffer);
            break;

        default:
            throw fixie::invalid_enum_error(fixie::format("unknown renderbuffer target, %s.", fixie::get_gl_enum_name(renderbuffertarget).c_str()));
        }

        fixie::framebuffer_attachment attach(rb);
        switch (attachment)
        {
        case GL_COLOR_ATTACHMENT0_OES:
            framebuffer->set_color_attachment(attach);
            break;

        case GL_DEPTH_ATTACHMENT_OES:
            framebuffer->set_depth_attachment(attach);
            break;

        case GL_STENCIL_ATTACHMENT_OES:
            framebuffer->set_stencil_attachment(attach);
            break;

        default:
            throw fixie::invalid_enum_error(fixie::format("unknown framebuffer attachment, %s.", fixie::get_gl_enum_name(attachment).c_str()));
        }
    }
    catch (...)
    {
        fixie::handle_entry_point_exception();
    }
}

void FIXIE_APIENTRY glFramebufferTexture2DOES(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level)
{
    try
    {
        std::shared_ptr<fixie::context> ctx = fixie::get_current_context();

        if (!ctx->caps().supports_framebuffer_objects())
        {
            throw fixie::invalid_operation_error("framebuffers are not supported.");
        }

        std::shared_ptr<fixie::framebuffer> framebuffer;
        switch (target)
        {
        case GL_FRAMEBUFFER_OES:
            framebuffer = ctx->state().bound_framebuffer().lock();
            break;

        default:
            throw fixie::invalid_enum_error(fixie::format("unknown framebuffer target, %s.", fixie::get_gl_enum_name(target).c_str()));
        }

        if (framebuffer == nullptr)
        {
            throw fixie::state_error("null framebuffer bound.");
        }

        std::weak_ptr<fixie::texture> tex;
        switch (textarget)
        {
        case GL_TEXTURE_2D:
            tex = ctx->textures().get_object(texture);
            break;

        default:
            throw fixie::invalid_enum_error(fixie::format("unknown texture target, %s.", fixie::get_gl_enum_name(textarget).c_str()));
        }

        fixie::framebuffer_attachment attach(tex, level, 1);
        switch (attachment)
        {
        case GL_COLOR_ATTACHMENT0_OES:
            framebuffer->set_color_attachment(attach);
            break;

        case GL_DEPTH_ATTACHMENT_OES:
            framebuffer->set_depth_attachment(attach);
            break;

        case GL_STENCIL_ATTACHMENT_OES:
            framebuffer->set_stencil_attachment(attach);
            break;

        default:
            throw fixie::invalid_enum_error(fixie::format("unknown framebuffer attachment, %s.", fixie::get_gl_enum_name(attachment).c_str()));
        }
    }
    catch (...)
    {
        fixie::handle_entry_point_exception();
    }
}

void FIXIE_APIENTRY glGetFramebufferAttachmentParameterivOES(GLenum target, GLenum attachment, GLenum pname, GLint* params)
{
    fixie::get_framebuffer_attachment_parameter(target, attachment, pname, params);
}

void FIXIE_APIENTRY glGenerateMipmapOES(GLenum target)
{
    try
    {
        std::shared_ptr<fixie::context> ctx = fixie::get_current_context();

        std::shared_ptr<fixie::texture> tex;
        switch (target)
        {
        case GL_TEXTURE_2D:
            tex = ctx->state().bound_texture(ctx->state().active_texture_unit()).lock();
            break;

        default:
            throw fixie::invalid_enum_error(fixie::format("unknown texture target, %s.", fixie::get_gl_enum_name(target).c_str()));
        }

        if (tex != nullptr)
        {
            if (!fixie::is_power_of_two(tex->mip_level_width(0)) || !fixie::is_power_of_two(tex->mip_level_height(0)))
            {
                throw fixie::invalid_operation_error(fixie::format("texture zero level array must be have a power of two width and height, "
                                                                   "width and height are %i and %i.", tex->mip_level_width(0), tex->mip_level_height(0)));
            }

            if (tex->mip_level_compressed(0))
            {
                throw fixie::invalid_operation_error("texture zero level array cannot be compressed.");
            }

            tex->generate_mipmaps();
        }
    }
    catch (...)
    {
        fixie::handle_entry_point_exception();
    }
}

void FIXIE_APIENTRY glBindVertexArrayOES(GLuint array)
{
    try
    {
        std::shared_ptr<fixie::context> ctx = fixie::get_current_context();

        if (!ctx->caps().supports_vertex_array_objects())
        {
            throw fixie::invalid_operation_error("vertex array objects are not supported.");
        }

        std::weak_ptr<fixie::vertex_array> vao = ctx->vertex_arrays().get_object(array);
        if (vao.expired())
        {
            throw fixie::invalid_operation_error(fixie::format("vertex array %u is not valid.", array));
        }

        ctx->state().bind_vertex_array(vao);
    }
    catch (...)
    {
        fixie::handle_entry_point_exception();
    }
}

void FIXIE_APIENTRY glDeleteVertexArraysOES(GLsizei n, const GLuint *arrays)
{
    try
    {
        std::shared_ptr<fixie::context> ctx = fixie::get_current_context();

        if (!ctx->caps().supports_vertex_array_objects())
        {
            throw fixie::invalid_operation_error("vertex array objects are not supported.");
        }

        if (n < 0)
        {
            throw fixie::invalid_value_error(fixie::format("invalid number of textures, at least 0 required, %i provided.", n));
        }

        std::for_each(arrays, arrays + n, [&](GLuint array){ if (array) { ctx->vertex_arrays().erase_object(array); } });
    }
    catch (...)
    {
        fixie::handle_entry_point_exception();
    }
}

void FIXIE_APIENTRY glGenVertexArraysOES(GLsizei n, GLuint *arrays)
{
    try
    {
        std::shared_ptr<fixie::context> ctx = fixie::get_current_context();

        if (!ctx->caps().supports_vertex_array_objects())
        {
            throw fixie::invalid_operation_error("vertex array objects are not supported.");
        }

        if (n < 0)
        {
            throw fixie::invalid_value_error(fixie::format("invalid number of textures, at least 0 required, %i provided.", n));
        }

        std::fill(arrays, arrays + n, 0);

        try
        {
            std::generate_n(arrays, n, [&](){ return ctx->create_vertex_array(); });
        }
        catch(...)
        {
            try
            {
                std::for_each(arrays, arrays + n, [&](GLuint array){ if (array) { ctx->vertex_arrays().erase_object(array); } });
            }
            catch (...)
            {
                // error while deleting a vertex array, ignore it
            }

            throw;
        }
    }
    catch (...)
    {
        fixie::handle_entry_point_exception();
    }
}

GLboolean FIXIE_APIENTRY glIsVertexArrayOES(GLuint array)
{
    try
    {
        std::shared_ptr<fixie::context> ctx = fixie::get_current_context();

        if (!ctx->caps().supports_vertex_array_objects())
        {
            throw fixie::invalid_operation_error("vertex array objects are not supported.");
        }

        return ctx->vertex_arrays().contains_handle(array) ? GL_TRUE : GL_FALSE;
    }
    catch (...)
    {
        return fixie::handle_entry_point_exception(GL_FALSE);
    }
}

}


text:
/**
 * Chat.js
 *
 * @description :: TODO: You might write a short summary of how this model works and what it represents here.
 * @docs        :: http://sailsjs.org/documentation/concepts/models-and-orm/models
 */

module.exports = {

  attributes: {
    // Both fields are set to required
    user:{
      type:'string',
      required:true
    },
    message:{
      type:'string',
      required:true
    }
  }
};

redpajama_set_name: RedPajamaGithub


text:
package org.kuali.rice.kns.kim.role;

import org.apache.commons.lang.StringUtils;
import org.kuali.rice.core.api.exception.RiceIllegalArgumentException;
import org.kuali.rice.core.api.membership.MemberType;
import org.kuali.rice.core.api.util.jaxb.MapStringStringAdapter;
import org.kuali.rice.kim.api.role.Role;
import org.kuali.rice.kim.api.role.RoleMembership;
import org.kuali.rice.kim.framework.common.delegate.DelegationTypeService;
import org.kuali.rice.kim.framework.role.RoleTypeService;
import org.kuali.rice.kns.kim.type.DataDictionaryTypeServiceBase;

import javax.jws.WebParam;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @deprecated A krad integrated type service base class will be provided in the future.
 */
@Deprecated
public class RoleTypeServiceBase extends DataDictionaryTypeServiceBase implements RoleTypeService, DelegationTypeService {

	/**
	 * Performs a simple check that the qualifier on the role matches the qualification.
	 * Extra qualification attributes are ignored.
	 */
    @Override
	public boolean doesRoleQualifierMatchQualification(Map<String, String> qualification, Map<String, String> roleQualifier) {
		if (qualification == null) {
            throw new RiceIllegalArgumentException("qualification was null or blank");
        }

        if (roleQualifier == null) {
            throw new RiceIllegalArgumentException("roleQualifier was null or blank");
        }

        Map<String, String> translatedQualification = translateInputAttributes(qualification);
		validateRequiredAttributesAgainstReceived(translatedQualification);
		return performMatch(translatedQualification, roleQualifier);
	}

    @Override
	public List<RoleMembership> getMatchingRoleMemberships(Map<String, String> qualification,
            List<RoleMembership> roleMemberList) {
		if (qualification == null) {
            throw new RiceIllegalArgumentException("qualification was null or blank");
        }

        if (roleMemberList == null) {
            throw new RiceIllegalArgumentException("roleMemberList was null or blank");
        }

        Map<String, String> translatedQualification = translateInputAttributes(qualification);
		validateRequiredAttributesAgainstReceived(translatedQualification);
		List<RoleMembership> matchingMemberships = new ArrayList<RoleMembership>();
		for ( RoleMembership roleMembership : roleMemberList ) {
			if ( performMatch( translatedQualification, roleMembership.getQualifier() ) ) {
				matchingMemberships.add( roleMembership );
			}
		}
		return Collections.unmodifiableList(matchingMemberships);
	}

	/**
	 * Return an empty list since this method should not be called by the role service for this service type.
	 * Subclasses which are application role types should override this method.
	 *
	 */
    @Override
	public List<RoleMembership> getRoleMembersFromDerivedRole(String namespaceCode, String roleName, Map<String, String> qualification) {

        if (StringUtils.isBlank(namespaceCode)) {
            throw new RiceIllegalArgumentException("namespaceCode was null or blank");
        }

        if (StringUtils.isBlank(roleName)) {
            throw new RiceIllegalArgumentException("roleName was null or blank");
        }

        if (qualification == null) {
            throw new RiceIllegalArgumentException("qualification was null or blank");
        }

        validateRequiredAttributesAgainstReceived(qualification);
		if ( !isDerivedRoleType() ) {
			throw new UnsupportedOperationException( this.getClass().getName() + " is not an application role." );
		} else {
			throw new UnsupportedOperationException( this.getClass().getName() + " is an application role type but has not overridden this method." );
		}
	}

	/**
	 * This simple initial implementation just calls
	 * {@link #getRoleMembersFromApplicationRole(String, String, Map<String, String>)} and checks the results.
	 *
	 */
    @Override
	public boolean hasDerivedRole(String principalId, List<String> groupIds, String namespaceCode, String roleName, Map<String, String> qualification) {
	    if (StringUtils.isBlank(principalId)) {
            throw new RiceIllegalArgumentException("principalId was null or blank");
        }

        if (groupIds == null) {
            throw new RiceIllegalArgumentException("groupIds was null or blank");
        }

        if (StringUtils.isBlank(namespaceCode)) {
            throw new RiceIllegalArgumentException("namespaceCode was null or blank");
        }

        if (StringUtils.isBlank(roleName)) {
            throw new RiceIllegalArgumentException("roleName was null or blank");
        }

        if (qualification == null) {
            throw new RiceIllegalArgumentException("qualification was null or blank");
        }

        if ( !isDerivedRoleType() ) {
			throw new UnsupportedOperationException( this.getClass().getName() + " is not an application role." );
		}
		// if principal ID given, check if it is in the list generated from the getPrincipalIdsFromApplicationRole method
		if ( StringUtils.isNotBlank( principalId ) ) {
		    List<RoleMembership> members = getRoleMembersFromDerivedRole(namespaceCode, roleName, qualification);
		    for ( RoleMembership rm : members ) {
		    	if ( StringUtils.isBlank( rm.getMemberId() ) ) {
		    		continue;
		    	}
		        if ( MemberType.PRINCIPAL.equals(rm.getType()) ) {
		            if ( rm.getMemberId().equals( principalId ) ) {
		                return true;
		            }
		        } else { // groups
		            if ( groupIds != null
		                    && groupIds.contains(rm.getMemberId())) {
		                return true;
		            }
		        }
			}
		}
		return false;
	}

	/**
	 * Default to not being a derived role type.  Always returns false.
	 *
	 * @see org.kuali.rice.kim.framework.role.RoleTypeService#isDerivedRoleType()
	 */
    @Override
	public boolean isDerivedRoleType() {
		return false;
	}

	/**
	 * This base implementation simply returns the passed in Attributes.
	 *
	 * @see org.kuali.rice.kim.framework.role.RoleTypeService#convertQualificationForMemberRoles(String, String, String, String, Map<String, String>)
	 */
    @Override
	public Map<String, String> convertQualificationForMemberRoles(String namespaceCode, String roleName, String memberRoleNamespaceCode, String memberRoleName, Map<String, String> qualification) {
        if (StringUtils.isBlank(namespaceCode)) {
            throw new RiceIllegalArgumentException("namespaceCode was null or blank");
        }

        if (StringUtils.isBlank(roleName)) {
            throw new RiceIllegalArgumentException("roleName was null or blank");
        }

        if (StringUtils.isBlank(memberRoleNamespaceCode)) {
            throw new RiceIllegalArgumentException("memberRoleNamespaceCode was null or blank");
        }

        if (StringUtils.isBlank(memberRoleName)) {
            throw new RiceIllegalArgumentException("memberRoleName was null or blank");
        }

        if (qualification == null) {
            throw new RiceIllegalArgumentException("qualification was null");
        }

        return Collections.unmodifiableMap(new HashMap<String, String>(qualification));
	}

    @Override
    public Map<String, String> convertQualificationForMemberRolesAndMemberAttributes(
            @WebParam(name = "namespaceCode") String namespaceCode, @WebParam(name = "roleName") String roleName,
            @WebParam(name = "memberRoleNamespaceCode") String memberRoleNamespaceCode,
            @WebParam(name = "memberRoleName") String memberRoleName, @WebParam(name = "qualification") @XmlJavaTypeAdapter(
            value = MapStringStringAdapter.class) Map<String, String> qualification, @WebParam(name = "memberQualification") @XmlJavaTypeAdapter(
            value = MapStringStringAdapter.class) Map<String, String> memberQualification) throws RiceIllegalArgumentException {

        if (memberQualification == null) {
            throw new RiceIllegalArgumentException("memberQualification was null");
        }

        return convertQualificationForMemberRoles(namespaceCode, roleName, memberRoleNamespaceCode, memberRoleName, qualification);
    }

    /**
	 * Performs a simple check that the qualifier on the delegation matches the qualification.
	 * Extra qualification attributes are ignored.
	 *
	 */
    @Override
	public boolean doesDelegationQualifierMatchQualification(Map<String, String> qualification, Map<String, String> roleQualifier) {
		if (qualification == null) {
            throw new RiceIllegalArgumentException("qualification was null or blank");
        }

        if (roleQualifier == null) {
            throw new RiceIllegalArgumentException("roleQualifier was null or blank");
        }

        Map<String, String> translatedQualification = translateInputAttributes(qualification);
		validateRequiredAttributesAgainstReceived(translatedQualification);
		return performMatch(translatedQualification, roleQualifier);
	}

	/**
	 * Returns false as a default
	 *
	 * @see org.kuali.rice.kim.framework.role.RoleTypeService#dynamicRoleMembership(java.lang.String, java.lang.String)
	 */
    @Override
	public boolean dynamicRoleMembership(String namespaceCode, String roleName) {
		if (StringUtils.isBlank(namespaceCode)) {
            throw new RiceIllegalArgumentException("namespaceCode was null or blank");
        }

        if (StringUtils.isBlank(roleName)) {
            throw new RiceIllegalArgumentException("roleName was null or blank");
        }

        return false;
	}

    @Override
	public List<String> getQualifiersForExactMatch() {
		return Collections.emptyList();
	}

    /**
     * Base implementation: no sorting.  Just returns the input list.
     */
	@Override
	public List<RoleMembership> sortRoleMembers(List<RoleMembership> roleMembers)
			throws RiceIllegalArgumentException {
		return roleMembers;
	}

    @Override
    public boolean shouldValidateQualifiersForMemberType(MemberType memberType) {
        return false;
    }
}


text:
YUI.add('event-touch', function(Y) {

/**
 * Adds touch event facade normalization properties (touches, changedTouches, targetTouches etc.) to the DOM event facade
 *
 * @module event-touch
 */

var SCALE = "scale",
    ROTATION = "rotation",
    IDENTIFIER = "identifier";

/**
 * Adds touch event facade normalization properties to the DOM event facade
 *
 * @method _touch
 * @for DOMEventFacade
 * @private
 * @param ev {Event} the DOM event
 * @param currentTarget {HTMLElement} the element the listener was attached to
 * @param wrapper {Event.Custom} the custom event wrapper for this DOM event
 */
Y.DOMEventFacade.prototype._touch = function(e, currentTarget, wrapper) {

    var i,l, etCached, et,touchCache;

    Y.log("Calling facade._touch() with e = " + e);

    if (e.touches) {
        Y.log("Found e.touches. Replicating on facade");

        this.touches = [];
        touchCache = {};

        for (i = 0, l = e.touches.length; i < l; ++i) {
            et = e.touches[i];
            touchCache[Y.stamp(et)] = this.touches[i] = new Y.DOMEventFacade(et, currentTarget, wrapper);
        }
    }

    if (e.targetTouches) {
        Y.log("Found e.targetTouches. Replicating on facade");

        this.targetTouches = [];

        for (i = 0, l = e.targetTouches.length; i < l; ++i) {
            et = e.targetTouches[i];
            etCached = touchCache && touchCache[Y.stamp(et, true)];

            this.targetTouches[i] = etCached || new Y.DOMEventFacade(et, currentTarget, wrapper);

            if (etCached) { Y.log("Found native event in touches. Using same facade in targetTouches"); }
        }
    }

    if (e.changedTouches) {
        Y.log("Found e.changedTouches. Replicating on facade");

        this.changedTouches = [];

        for (i = 0, l = e.changedTouches.length; i < l; ++i) {
            et = e.changedTouches[i];
            etCached = touchCache && touchCache[Y.stamp(et, true)];

            this.changedTouches[i] = etCached || new Y.DOMEventFacade(et, currentTarget, wrapper);

            if (etCached) { Y.log("Found native event in touches. Using same facade in changedTouches"); }
        }
    }

    if (SCALE in e) {
        this[SCALE] = e[SCALE];
    }

    if (ROTATION in e) {
        this[ROTATION] = e[ROTATION];
    }

    if (IDENTIFIER in e) {
        this[IDENTIFIER] = e[IDENTIFIER];
    }
};

if (Y.Node.DOM_EVENTS) {
    Y.mix(Y.Node.DOM_EVENTS, {
        touchstart:1,
        touchmove:1,
        touchend:1,
        touchcancel:1,
        gesturestart:1,
        gesturechange:1,
        gestureend:1
    });
}

}, '3.3.0' ,{requires:['node-base']});


text:
  <select name="batch_action">
    <option value=""><?php echo __('Choose an action', array(), 'apostrophe') ?></option>
    <option value="batchDelete"><?php echo __('Delete', array(), 'a-admin') ?></option>  </select>
  <input type="hidden" name="_csrf_token" value="1912d35b7857bae5ef4155bd74aea733" />
	<?php echo jq_link_to_function(__('Go', null, 'apostrophe'), '$("#a-admin-batch-form").submit();', array('class' => 'a-btn', )) ?>


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

<title>Uses of Class math.doubleV.SGVec_3d</title>
<meta name="date" content="2021-01-31">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
math.doubleV.SGVec_3d

Packages that use SGVec_3d

Package
Description

IK.doubleIK

math.doubleV

Uses of SGVec_3d in IK.doubleIK

Methods in IK.doubleIK with parameters of type SGVec_3d

Modifier and Type
Method and Description

void
AbstractKusudama.addLimitCone(SGVec_3d newPoint,
            double radius,
            AbstractLimitCone previous,
            AbstractLimitCone next)

Add a LimitCone to the Kusudama.

void
AbstractKusudama.addLimitConeAtIndex(int insertAt,
                   SGVec_3d newPoint,
                   double radius)

Adds a LimitCone to the Kusudama.

double
SegmentedArmature.getManualMSD(SGVec_3d[] locTips,
            SGVec_3d[] locTargets,
            double[] weights)

double
SegmentedArmature.getManualMSD(SGVec_3d[] locTips,
            SGVec_3d[] locTargets,
            double[] weights)

void
AbstractBone.setPin_(SGVec_3d pin)

Uses of SGVec_3d in math.doubleV

Fields in math.doubleV declared as SGVec_3d

Modifier and Type
Field and Description

static SGVec_3d
RotationOrder.X

static SGVec_3d
RotationOrder.Y

static SGVec_3d
RotationOrder.Z

Methods in math.doubleV with type parameters of type SGVec_3d

Modifier and Type
Method and Description

<T extends SGVec_3d>
T
MRotation.applyInverseTo(T u)

Apply the inverse of the rotation to a vector.

<T extends SGVec_3d>
T
MRotation.applyTo(T u)

Apply the rotation to a vector.

<T extends SGVec_3d>
void
MRotation.setAxis(T newAxis)

modify this rotation to have the specified axis,
 without changing the angle.

Methods in math.doubleV that return SGVec_3d

Modifier and Type
Method and Description

SGVec_3d
SGVec_3d.copy()

SGVec_3d
RotationOrder.getA1()

Get the axis of the first rotation.

SGVec_3d
RotationOrder.getA2()

Get the axis of the second rotation.

SGVec_3d
RotationOrder.getA3()

Get the axis of the second rotation.

SGVec_3d
Rot.getAxis()

SGVec_3d
MRotation.getAxis()

Get the normalized axis of the rotation.

SGVec_3d
QCP.getTranslation()

Methods in math.doubleV with parameters of type SGVec_3d

Modifier and Type
Method and Description

static double
Vec3d.dot(SGVec_3d u,
   SGVec_3d v)

void
sgRayd.getHeading(SGVec_3d setTo)

sets the input vector equal to this sgRay's heading.

double
QCP.getRmsd(SGVec_3d[] fixed,
       SGVec_3d[] moved)

double
QCP.getRmsd(SGVec_3d[] fixed,
       SGVec_3d[] moved)

Rot[]
Rot.getSwingTwist(SGVec_3d axis)

Get the swing rotation and twist rotation for the specified axis.

void
sgRayd.pointWith(SGVec_3d heading)

double
sgRayd.scaledProjection(SGVec_3d input)

Returns the scalar projection of the input vector on this
 ray.

void
sgRayd.translateTipTo(SGVec_3d newLocation)

void
sgRayd.translateTo(SGVec_3d newLocation)

Constructors in math.doubleV with parameters of type SGVec_3d

Constructor and Description

SGVec_3d(SGVec_3d sgVec_3d)

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateEmailAddressesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('email_addresses', function (Blueprint $table) {
            $table->increments('id');
            $table->string('email');
            $table->integer('user_id')->unsigned();
            $table->foreign('user_id')
                  ->references('id')->on('users');
            $table->timestamps();
            $table->softDeletes();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('email_addresses');
    }
}


text:
//
//  IQGeometry+Distance.h
//  Geometry Extension
//
//  Created by Iftekhar Mac Pro on 8/25/13.
//  Copyright (c) 2013 Iftekhar. All rights reserved.
//

#import <Foundation/Foundation.h>
#import <CoreGraphics/CGGeometry.h>
/*
 A (x1, y1) and B (x2, y2) = sqrt( (x2−x1)2+(y2−y1)2)
 */
CGFloat IQPointGetDistance(CGPoint point1, CGPoint point2);


text:
.class public Lo/fY;
.super Ljava/lang/Object;

# interfaces
.implements Landroid/os/Parcelable$Creator;

# annotations
.annotation system Ldalvik/annotation/Signature;
    value = {
        "Ljava/lang/Object;Landroid/os/Parcelable$Creator<Lcom/google/android/gms/games/snapshot/SnapshotMetadataChangeEntity;>;"
    }
.end annotation

# direct methods
.method public constructor <init>()V
    .locals 0

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

.method public static ˊ(Lcom/google/android/gms/games/snapshot/SnapshotMetadataChangeEntity;Landroid/os/Parcel;I)V
    .locals 4

    invoke-static {p1}, Lo/ż;->ˊ(Landroid/os/Parcel;)I

    move-result v3

    invoke-virtual {p0}, Lcom/google/android/gms/games/snapshot/SnapshotMetadataChangeEntity;->ˊ()Ljava/lang/String;

    move-result-object v0

    const/4 v1, 0x1

    const/4 v2, 0x0

    invoke-static {p1, v1, v0, v2}, Lo/ż;->ˊ(Landroid/os/Parcel;ILjava/lang/String;Z)V

    invoke-virtual {p0}, Lcom/google/android/gms/games/snapshot/SnapshotMetadataChangeEntity;->ᐝ()I

    move-result v0

    const/16 v1, 0x3e8

    invoke-static {p1, v1, v0}, Lo/ż;->ˊ(Landroid/os/Parcel;II)V

    invoke-virtual {p0}, Lcom/google/android/gms/games/snapshot/SnapshotMetadataChangeEntity;->ˋ()Ljava/lang/Long;

    move-result-object v0

    const/4 v1, 0x2

    const/4 v2, 0x0

    invoke-static {p1, v1, v0, v2}, Lo/ż;->ˊ(Landroid/os/Parcel;ILjava/lang/Long;Z)V

    invoke-virtual {p0}, Lcom/google/android/gms/games/snapshot/SnapshotMetadataChangeEntity;->ʻ()Landroid/net/Uri;

    move-result-object v0

    const/4 v1, 0x4

    const/4 v2, 0x0

    invoke-static {p1, v1, v0, p2, v2}, Lo/ż;->ˊ(Landroid/os/Parcel;ILandroid/os/Parcelable;IZ)V

    invoke-virtual {p0}, Lcom/google/android/gms/games/snapshot/SnapshotMetadataChangeEntity;->ˎ()Lcom/google/android/gms/common/data/a;

    move-result-object v0

    const/4 v1, 0x5

    const/4 v2, 0x0

    invoke-static {p1, v1, v0, p2, v2}, Lo/ż;->ˊ(Landroid/os/Parcel;ILandroid/os/Parcelable;IZ)V

    invoke-static {p1, v3}, Lo/ż;->ˊ(Landroid/os/Parcel;I)V

    return-void
.end method

# virtual methods
.method public synthetic createFromParcel(Landroid/os/Parcel;)Ljava/lang/Object;
    .locals 1

    invoke-virtual {p0, p1}, Lo/fY;->ˊ(Landroid/os/Parcel;)Lcom/google/android/gms/games/snapshot/SnapshotMetadataChangeEntity;

    move-result-object v0

    return-object v0
.end method

.method public synthetic newArray(I)[Ljava/lang/Object;
    .locals 1

    invoke-virtual {p0, p1}, Lo/fY;->ˊ(I)[Lcom/google/android/gms/games/snapshot/SnapshotMetadataChangeEntity;

    move-result-object v0

    return-object v0
.end method

.method public ˊ(Landroid/os/Parcel;)Lcom/google/android/gms/games/snapshot/SnapshotMetadataChangeEntity;
    .locals 13

    invoke-static {p1}, Lo/Ŷ;->ˋ(Landroid/os/Parcel;)I

    move-result v6

    const/4 v7, 0x0

    const/4 v8, 0x0

    const/4 v9, 0x0

    const/4 v10, 0x0

    const/4 v11, 0x0

    :goto_0
    invoke-virtual {p1}, Landroid/os/Parcel;->dataPosition()I

    move-result v0

    if-ge v0, v6, :cond_0

    invoke-static {p1}, Lo/Ŷ;->ˊ(Landroid/os/Parcel;)I

    move-result v12

    invoke-static {v12}, Lo/Ŷ;->ˊ(I)I

    move-result v0

    sparse-switch v0, :sswitch_data_0

    goto :goto_1

    :sswitch_0
    invoke-static {p1, v12}, Lo/Ŷ;->ˌ(Landroid/os/Parcel;I)Ljava/lang/String;

    move-result-object v8

    goto :goto_2

    :sswitch_1
    invoke-static {p1, v12}, Lo/Ŷ;->'(Landroid/os/Parcel;I)I

    move-result v7

    goto :goto_2

    :sswitch_2
    invoke-static {p1, v12}, Lo/Ŷ;->ι(Landroid/os/Parcel;I)Ljava/lang/Long;

    move-result-object v9

    goto :goto_2

    :sswitch_3
    sget-object v0, Landroid/net/Uri;->CREATOR:Landroid/os/Parcelable$Creator;

    invoke-static {p1, v12, v0}, Lo/Ŷ;->ˊ(Landroid/os/Parcel;ILandroid/os/Parcelable$Creator;)Landroid/os/Parcelable;

    move-result-object v0

    check-cast v0, Landroid/net/Uri;

    move-object v11, v0

    goto :goto_2

    :sswitch_4
    sget-object v0, Lcom/google/android/gms/common/data/a;->CREATOR:Landroid/os/Parcelable$Creator;

    invoke-static {p1, v12, v0}, Lo/Ŷ;->ˊ(Landroid/os/Parcel;ILandroid/os/Parcelable$Creator;)Landroid/os/Parcelable;

    move-result-object v0

    check-cast v0, Lcom/google/android/gms/common/data/a;

    move-object v10, v0

    goto :goto_2

    :goto_1
    invoke-static {p1, v12}, Lo/Ŷ;->ˋ(Landroid/os/Parcel;I)V

    :goto_2
    goto/16 :goto_0

    :cond_0
    invoke-virtual {p1}, Landroid/os/Parcel;->dataPosition()I

    move-result v0

    if-eq v0, v6, :cond_1

    new-instance v0, Lo/Ŷ$if;

    new-instance v1, Ljava/lang/StringBuilder;

    invoke-direct {v1}, Ljava/lang/StringBuilder;-><init>()V

    const-string v2, "Overread allowed size end="

    invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v1

    invoke-virtual {v1, v6}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;

    move-result-object v1

    invoke-virtual {v1}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v1

    invoke-direct {v0, v1, p1}, Lo/Ŷ$if;-><init>(Ljava/lang/String;Landroid/os/Parcel;)V

    throw v0

    :cond_1
    new-instance v0, Lcom/google/android/gms/games/snapshot/SnapshotMetadataChangeEntity;

    move v1, v7

    move-object v2, v8

    move-object v3, v9

    move-object v4, v10

    move-object v5, v11

    invoke-direct/range {v0 .. v5}, Lcom/google/android/gms/games/snapshot/SnapshotMetadataChangeEntity;-><init>(ILjava/lang/String;Ljava/lang/Long;Lcom/google/android/gms/common/data/a;Landroid/net/Uri;)V

    move-object v12, v0

    return-object v12

    :sswitch_data_0
    .sparse-switch
        0x1 -> :sswitch_0
        0x2 -> :sswitch_2
        0x4 -> :sswitch_3
        0x5 -> :sswitch_4
        0x3e8 -> :sswitch_1
    .end sparse-switch
.end method

.method public ˊ(I)[Lcom/google/android/gms/games/snapshot/SnapshotMetadataChangeEntity;
    .locals 1

    new-array v0, p1, [Lcom/google/android/gms/games/snapshot/SnapshotMetadataChangeEntity;

    return-object v0
.end method


text:
import unittest

from draftjs_exporter.engines.string import DOMString

S = DOMString

class TestDOMString(unittest.TestCase):
    def test_create_tag(self):
        self.assertEqual(
            S.render_debug(S.create_tag("p", {"class": "intro"})),
            '

',
        )

    def test_create_tag_empty(self):
        self.assertEqual(S.render_debug(S.create_tag("p")), "

")

    def test_parse_html(self):
        self.assertEqual(
            S.render(S.parse_html("
Test text
")),
            "
Test text
",
        )

    def test_append_child(self):
        parent = S.create_tag("p")
        S.append_child(parent, S.create_tag("span", {}))
        self.assertEqual(S.render_debug(parent), "

")

    def test_append_child_identical_text(self):
        parent = S.create_tag("p")
        S.append_child(parent, S.parse_html("test"))
        S.append_child(parent, S.parse_html("test"))
        self.assertEqual(S.render_debug(parent), "
testtest
")

    def test_append_child_identical_elements(self):
        parent = S.create_tag("p")
        S.append_child(parent, S.create_tag("br"))
        S.append_child(parent, S.create_tag("br"))
        self.assertEqual(S.render_debug(parent), "

")

    def test_render_attrs_escaping(self):
        self.assertEqual(
            S.render_attrs(
                {"alt": "img's alt", "class": 'intro " text', "src": "src.png"}
            ),
            ' alt="img's alt" class="intro " text" src="src.png"',
        )

    def test_render_children(self):
        self.assertEqual(
            S.render_children(
                [
                    "single ' quote",
                    S.create_tag("p", {"class": "intro"}),
                    'double " quote',
                ]
            ),
            'single \' quote

double " quote',
        )

    def test_render(self):
        self.assertEqual(
            S.render_debug(S.create_tag("p", {"class": "intro"})),
            '

',
        )

    def test_render_debug(self):
        self.assertEqual(
            S.render_debug(S.create_tag("p", {"class": "intro"})),
            '

',
        )


text:
function qvals = q_get
% q_get --- get the values held in the queue

global GRAPH_MAGIC

if q_size == 0
    qvals = [];
    return
end

i = GRAPH_MAGIC.Q.first;
j = GRAPH_MAGIC.Q.last;

qvals = GRAPH_MAGIC.Q.array(i:j);


text:
/*                     __                                               *\
**     ________ ___   / /  ___      __ ____  Scala.js tools             **
**    / __/ __// _ | / /  / _ | __ / // __/  (c) 2014, LAMP/EPFL        **
**  __\ \/ /__/ __ |/ /__/ __ |/_// /_\ \    http://scala-js.org/       **
** /____/\___/_/ |_/____/_/ | |__/ /____/                               **
**                          |/____/                                     **
\*                                                                      */

package org.scalajs.core.tools.javascript

import org.scalajs.core.ir._
import Position._
import Transformers._
import org.scalajs.core.ir.Trees._
import Types._

import org.scalajs.core.tools.sem._
import CheckedBehavior.Unchecked

import org.scalajs.core.tools.javascript.{Trees => js}

import org.scalajs.core.tools.optimizer.{LinkedClass, LinkingUnit}

/** Defines methods to emit Scala.js classes to JavaScript code.
 *  The results are completely desugared.
 */
final class ScalaJSClassEmitter private (
    private[javascript] val semantics: Semantics,
    private[javascript] val outputMode: OutputMode,
    linkingUnit: LinkingUnit, // null if coming from a deprecated constructor
    globalInfo: LinkingUnit.GlobalInfo) {

  import ScalaJSClassEmitter._
  import JSDesugaring._

  def this(semantics: Semantics, outputMode: OutputMode,
      linkingUnit: LinkingUnit) = {
    this(semantics, outputMode, linkingUnit, linkingUnit.globalInfo)
  }

  @deprecated(
      "This constructor creates an emitter that cannot handle JS classes. " +
      "Use the constructor with a LinkingUnit instead.", "0.6.5")
  def this(semantics: Semantics, outputMode: OutputMode,
      globalInfo: LinkingUnit.GlobalInfo) =
    this(semantics, OutputMode.ECMAScript51Global, null, globalInfo)

  @deprecated(
      "This constructor creates an emitter that cannot handle JS classes. " +
      "Use the constructor with a LinkingUnit instead.", "0.6.2")
  def this(semantics: Semantics, globalInfo: LinkingUnit.GlobalInfo) =
    this(semantics, OutputMode.ECMAScript51Global, globalInfo)

  @deprecated(
      "This constructor creates an emitter that cannot handle JS classes. " +
      "Use the constructor with a LinkingUnit instead.", "0.6.1")
  def this(semantics: Semantics) =
    this(semantics, LinkingUnit.GlobalInfo.SafeApproximation)

  private[javascript] lazy val linkedClassByName: Map[String, LinkedClass] = {
    if (linkingUnit == null) {
      throw new IllegalArgumentException(
          "A class emitter created without a LinkingUnit cannot emit JS classes")
    }
    linkingUnit.classDefs.map(c => c.encodedName -> c).toMap
  }

  private implicit def implicitOutputMode: OutputMode = outputMode

  def genDeclareTypeData(tree: LinkedClass): js.Tree = {
    implicit val pos = tree.pos
    envFieldDef("d", tree.encodedName, js.Null(), mutable = true)
  }

  def genDeclareModule(tree: LinkedClass): js.Tree = {
    implicit val pos = tree.pos
    if (tree.kind.hasModuleAccessor)
      envFieldDef("n", tree.encodedName, js.Undefined(), mutable = true)
    else
      js.Skip()
  }

  /** Desugar a Scala.js class into ECMAScript 5 constructs
   *
   *  @param tree The IR tree to emit to raw JavaScript
   *  @param ancestors Encoded names of the ancestors of the class (not only
   *                   parents), including the class itself.
   */
  def genClassDef(tree: LinkedClass): js.Tree = {
    implicit val pos = tree.pos
    val kind = tree.kind

    var reverseParts: List[js.Tree] = Nil

    reverseParts ::= genStaticMembers(tree)
    if (kind.isAnyScalaJSDefinedClass && tree.hasInstances)
      reverseParts ::= genClass(tree)
    if (needInstanceTests(tree)) {
      reverseParts ::= genInstanceTests(tree)
      reverseParts ::= genArrayInstanceTests(tree)
    }
    if (tree.hasRuntimeTypeInfo)
      reverseParts ::= genTypeData(tree)
    if (kind.isClass && tree.hasInstances && tree.hasRuntimeTypeInfo)
      reverseParts ::= genSetTypeData(tree)
    if (kind.hasModuleAccessor)
      reverseParts ::= genModuleAccessor(tree)
    reverseParts ::= genClassExports(tree)

    js.Block(reverseParts.reverse)
  }

  def genStaticMembers(tree: LinkedClass): js.Tree = {
    val className = tree.name.name
    val staticMemberDefs =
      tree.staticMethods.map(m => genMethod(className, m.tree))
    js.Block(staticMemberDefs)(tree.pos)
  }

  def genClass(tree: LinkedClass): js.Tree = {
    val className = tree.name.name
    val typeFunctionDef = genConstructor(tree)
    val memberDefs =
      tree.memberMethods.map(m => genMethod(className, m.tree))

    val exportedDefs = genExportedMembers(tree)

    val allDefsBlock =
      js.Block(typeFunctionDef +: memberDefs :+ exportedDefs)(tree.pos)

    outputMode match {
      case OutputMode.ECMAScript51Global | OutputMode.ECMAScript51Isolated =>
        allDefsBlock

      case OutputMode.ECMAScript6 | OutputMode.ECMAScript6StrongMode =>
        val allDefs = allDefsBlock match {
          case js.Block(allDefs) => allDefs
          case js.Skip()         => Nil
          case oneDef            => List(oneDef)
        }
        genES6Class(tree, allDefs)
    }
  }

  /** Generates an ECMAScript 6 class for a linked class. */
  def genES6Class(tree: LinkedClass, members: List[js.Tree]): js.Tree = {
    require(outputMode == OutputMode.ECMAScript6 ||
        outputMode == OutputMode.ECMAScript6StrongMode)

    val className = tree.name.name
    val classIdent = encodeClassVar(className)(
        outputMode, tree.name.pos).asInstanceOf[js.VarRef].ident

    val parentVar = for (parentIdent <- tree.superClass) yield {
      implicit val pos = parentIdent.pos
      if (!tree.kind.isJSClass)
        encodeClassVar(parentIdent.name)
      else
        genRawJSClassConstructor(linkedClassByName(parentIdent.name))
    }

    js.ClassDef(Some(classIdent), parentVar, members)(tree.pos)
  }

  /** Generates an ECMAScript 6 class for a linked class containing only static
   *  methods.
   *
   *  This is used for classes that do not have instances, as well as
   *  non-classes, such as interfaces. These linked classes must not have a
   *  parent nor a constructor.
   *
   *  This method can only be used when emitting to Strong Mode. In ES6
   *  non-strong (as well as ES5 modes), static methods are emitted as
   *  top-level functions instead.
   */
  def genStaticsES6Class(tree: LinkedClass, members: List[js.Tree]): js.Tree = {
    require(outputMode == OutputMode.ECMAScript6StrongMode)

    val className = tree.name.name
    val classIdent = encodeClassVar(className)(
        outputMode, tree.name.pos).asInstanceOf[js.VarRef].ident

    js.ClassDef(Some(classIdent), None, members)(tree.pos)
  }

  /** Generates the JS constructor for a class. */
  def genConstructor(tree: LinkedClass): js.Tree = {
    assert(tree.kind.isAnyScalaJSDefinedClass)
    assert(tree.superClass.isDefined || tree.name.name == Definitions.ObjectClass,
        s"Class ${tree.name.name} is missing a parent class")

    outputMode match {
      case OutputMode.ECMAScript51Global | OutputMode.ECMAScript51Isolated =>
        genES5Constructor(tree)

      case OutputMode.ECMAScript6 | OutputMode.ECMAScript6StrongMode =>
        genES6Constructor(tree)
    }
  }

  /** Generates the JS constructor for a class, ES5 style. */
  private def genES5Constructor(tree: LinkedClass): js.Tree = {
    implicit val pos = tree.pos

    val className = tree.name.name
    val isJSClass = tree.kind.isJSClass

    def makeInheritableCtorDef(ctorToMimic: js.Tree) = {
      js.Block(
        js.DocComment("@constructor"),
        envFieldDef("h", className, js.Function(Nil, js.Skip())),
        js.Assign(envField("h", className).prototype, ctorToMimic.prototype)
      )
    }

    val ctorFun = if (!isJSClass) {
      val superCtorCall = tree.superClass.fold[js.Tree] {
        js.Skip()
      } { parentIdent =>
        js.Apply(
            js.DotSelect(encodeClassVar(parentIdent.name), js.Ident("call")),
            List(js.This()))
      }
      val fieldDefs = genFieldDefs(tree)
      js.Function(Nil, js.Block(superCtorCall :: fieldDefs))
    } else {
      genConstructorFunForJSClass(tree)
    }

    val typeVar = encodeClassVar(className)
    val docComment = js.DocComment("@constructor")
    val ctorDef = envFieldDef("c", className, ctorFun)

    val chainProto = tree.superClass.fold[js.Tree] {
      js.Skip()
    } { parentIdent =>
      val (inheritedCtorDef, inheritedCtorRef) = if (!isJSClass) {
        (js.Skip(), envField("h", parentIdent.name))
      } else {
        val superCtor = genRawJSClassConstructor(
            linkedClassByName(parentIdent.name))
        (makeInheritableCtorDef(superCtor), envField("h", className))
      }
      js.Block(
          inheritedCtorDef,
          js.Assign(typeVar.prototype, js.New(inheritedCtorRef, Nil)),
          genAddToPrototype(className, js.StringLiteral("constructor"), typeVar)
      )
    }

    val inheritableCtorDef =
      if (isJSClass) js.Skip()
      else makeInheritableCtorDef(typeVar)

    js.Block(docComment, ctorDef, chainProto, inheritableCtorDef)
  }

  /** Generates the JS constructor for a class, ES6 style. */
  private def genES6Constructor(tree: LinkedClass): js.Tree = {
    implicit val pos = tree.pos

    if (tree.kind.isJSClass) {
      val js.Function(params, body) = genConstructorFunForJSClass(tree)
      js.MethodDef(static = false, js.Ident("constructor"), params, body)
    } else {
      val fieldDefs = genFieldDefs(tree)
      if (fieldDefs.isEmpty && outputMode == OutputMode.ECMAScript6) {
        js.Skip()
      } else {
        val superCtorCall = tree.superClass.fold[js.Tree] {
          js.Skip()(tree.pos)
        } { parentIdent =>
          js.Apply(js.Super(), Nil)
        }
        val initClassData = outputMode match {
          case OutputMode.ECMAScript6StrongMode =>
            js.Assign(js.DotSelect(js.This(), js.Ident("$classData")),
                envField("d", tree.name.name))
          case _ =>
            js.Skip()
        }
        js.MethodDef(static = false, js.Ident("constructor"), Nil,
            js.Block(superCtorCall :: initClassData :: fieldDefs))
      }
    }
  }

  private def genConstructorFunForJSClass(tree: LinkedClass): js.Function = {
    implicit val pos = tree.pos

    require(tree.kind.isJSClass)

    tree.exportedMembers.map(_.tree) collectFirst {
      case MethodDef(false, StringLiteral("constructor"), params, _, body) =>
        desugarToFunction(this, tree.encodedName,
            params, body, isStat = true)
    } getOrElse {
      throw new IllegalArgumentException(
          s"${tree.encodedName} does not have an exported constructor")
    }
  }

  /** Generates the creation of fields for a class. */
  private def genFieldDefs(tree: LinkedClass): List[js.Tree] = {
    val tpe = ClassType(tree.encodedName)
    for {
      field @ FieldDef(name, ftpe, mutable) <- tree.fields
    } yield {
      implicit val pos = field.pos
      val selectField = (name: @unchecked) match {
        case name: Ident => Select(This()(tpe), name)(ftpe)
      }
      desugarTree(this, tree.encodedName,
          Assign(selectField, zeroOf(ftpe)), isStat = true)
    }
  }

  /** Generates a method. */
  def genMethod(className: String, method: MethodDef): js.Tree = {
    implicit val pos = method.pos

    val methodFun = desugarToFunction(this, className,
        method.args, method.body, method.resultType == NoType)

    outputMode match {
      case OutputMode.ECMAScript6StrongMode =>
        js.MethodDef(static = method.static, genPropertyName(method.name),
            methodFun.args, methodFun.body)

      case _ if method.static =>
        val Ident(methodName, origName) = method.name
        envFieldDef(
            "s", className + "__" + methodName, origName,
            methodFun)

      case OutputMode.ECMAScript51Global | OutputMode.ECMAScript51Isolated =>
        genAddToPrototype(className, method.name, methodFun)

      case OutputMode.ECMAScript6 =>
        js.MethodDef(static = false, genPropertyName(method.name),
            methodFun.args, methodFun.body)
    }
  }

  /** Generates a property. */
  def genProperty(className: String, property: PropertyDef): js.Tree = {
    outputMode match {
      case OutputMode.ECMAScript51Global | OutputMode.ECMAScript51Isolated =>
        genPropertyES5(className, property)
      case OutputMode.ECMAScript6 | OutputMode.ECMAScript6StrongMode =>
        genPropertyES6(className, property)
    }
  }

  private def genPropertyES5(className: String,
      property: PropertyDef): js.Tree = {
    implicit val pos = property.pos

    // defineProperty method
    val defProp =
      js.BracketSelect(js.VarRef(js.Ident("Object")),
          js.StringLiteral("defineProperty"))

    // class prototype
    val proto = encodeClassVar(className).prototype

    // property name
    val name = property.name match {
      case StringLiteral(value) =>
        js.StringLiteral(value)
      case id: Ident =>
        // We need to work around the closure compiler. Call propertyName to
        // get a string representation of the optimized name
        genCallHelper("propertyName",
            js.ObjectConstr(transformIdent(id) -> js.IntLiteral(0) :: Nil))
    }

    // Options passed to the defineProperty method
    val descriptor = js.ObjectConstr {
      // Basic config
      val base =
        js.StringLiteral("enumerable") -> js.BooleanLiteral(true) :: Nil

      // Optionally add getter
      val wget = {
        if (property.getterBody == EmptyTree) base
        else {
          val fun = desugarToFunction(this, className,
              Nil, property.getterBody, isStat = false)
          js.StringLiteral("get") -> fun :: base
        }
      }

      // Optionally add setter
      if (property.setterBody == EmptyTree) wget
      else {
        val fun = desugarToFunction(this, className,
            property.setterArg :: Nil, property.setterBody, isStat = true)
        js.StringLiteral("set") -> fun :: wget
      }
    }

    js.Apply(defProp, proto :: name :: descriptor :: Nil)
  }

  private def genPropertyES6(className: String,
      property: PropertyDef): js.Tree = {
    implicit val pos = property.pos

    val propName = genPropertyName(property.name)

    val getter = {
      if (property.getterBody == EmptyTree) js.Skip()
      else {
        val fun = desugarToFunction(this, className,
            Nil, property.getterBody, isStat = false)
        js.GetterDef(static = false, propName, fun.body)
      }
    }

    val setter = {
      if (property.setterBody == EmptyTree) js.Skip()
      else {
        val fun = desugarToFunction(this, className,
            property.setterArg :: Nil, property.setterBody, isStat = true)
        js.SetterDef(static = false, propName, fun.args.head, fun.body)
      }
    }

    js.Block(getter, setter)
  }

  /** Generate `classVar.prototype.name = value` */
  def genAddToPrototype(className: String, name: js.PropertyName,
      value: js.Tree)(implicit pos: Position): js.Tree = {
    val proto = encodeClassVar(className).prototype
    val select = name match {
      case name: js.Ident         => js.DotSelect(proto, name)
      case name: js.StringLiteral => js.BracketSelect(proto, name)
    }
    js.Assign(select, value)
  }

  /** Generate `classVar.prototype.name = value` */
  def genAddToPrototype(className: String, name: PropertyName,
      value: js.Tree)(implicit pos: Position): js.Tree = {
    genAddToPrototype(className, genPropertyName(name), value)
  }

  def genPropertyName(name: PropertyName): js.PropertyName = name match {
    case ident: Ident         => transformIdent(ident)
    case StringLiteral(value) => js.StringLiteral(value)(name.pos)
  }

  private[tools] def needInstanceTests(tree: LinkedClass): Boolean = {
    tree.hasInstanceTests || {
      tree.hasRuntimeTypeInfo &&
      ClassesWhoseDataReferToTheirInstanceTests.contains(tree.encodedName)
    }
  }

  def genInstanceTests(tree: LinkedClass): js.Tree = {
    import Definitions._
    import TreeDSL._

    implicit val pos = tree.pos

    if (tree.kind.isClass || tree.kind == ClassKind.Interface ||
        tree.name.name == Definitions.StringClass) {
      val className = tree.name.name
      val displayName = decodeClassName(className)

      val isAncestorOfString =
        AncestorsOfStringClass.contains(className)
      val isAncestorOfHijackedNumberClass =
        AncestorsOfHijackedNumberClasses.contains(className)
      val isAncestorOfBoxedBooleanClass =
        AncestorsOfBoxedBooleanClass.contains(className)

      val objParam = js.ParamDef(Ident("obj"), rest = false)
      val obj = objParam.ref

      val createIsStat = {
        envFieldDef("is", className,
          js.Function(List(objParam), js.Return(className match {
            case Definitions.ObjectClass =>
              js.BinaryOp(JSBinaryOp.!==, obj, js.Null())

            case Definitions.StringClass =>
              js.UnaryOp(JSUnaryOp.typeof, obj) === js.StringLiteral("string")

            case _ =>
              var test = (genIsScalaJSObject(obj) &&
                  (obj DOT "$classData" DOT "ancestors" DOT className))

              if (isAncestorOfString)
                test = test || (
                    js.UnaryOp(JSUnaryOp.typeof, obj) === js.StringLiteral("string"))
              if (isAncestorOfHijackedNumberClass)
                test = test || (
                    js.UnaryOp(JSUnaryOp.typeof, obj) === js.StringLiteral("number"))
              if (isAncestorOfBoxedBooleanClass)
                test = test || (
                    js.UnaryOp(JSUnaryOp.typeof, obj) === js.StringLiteral("boolean"))

              !(!test)
          })))
      }

      val createAsStat = if (semantics.asInstanceOfs == Unchecked) {
        js.Skip()
      } else {
        envFieldDef("as", className,
          js.Function(List(objParam), js.Return(className match {
            case Definitions.ObjectClass =>
              obj

            case _ =>
              js.If(js.Apply(envField("is", className), List(obj)) ||
                  (obj === js.Null()), {
                obj
              }, {
                genCallHelper("throwClassCastException",
                    obj, js.StringLiteral(displayName))
              })
        })))
      }

      js.Block(createIsStat, createAsStat)
    } else {
      js.Skip()
    }
  }

  def genArrayInstanceTests(tree: LinkedClass): js.Tree = {
    import Definitions._
    import TreeDSL._

    implicit val pos = tree.pos

    val className = tree.name.name
    val displayName = decodeClassName(className)

    val objParam = js.ParamDef(Ident("obj"), rest = false)
    val obj = objParam.ref

    val depthParam = js.ParamDef(Ident("depth"), rest = false)
    val depth = depthParam.ref

    val createIsArrayOfStat = {
      envFieldDef("isArrayOf", className,
        js.Function(List(objParam, depthParam), className match {
          case Definitions.ObjectClass =>
            val isStrongMode = outputMode == OutputMode.ECMAScript6StrongMode
            val dataVarDef = genLet(Ident("data"), mutable = false, {
              obj && (obj DOT "$classData")
            })
            val data = dataVarDef.ref
            js.Block(
              if (isStrongMode) js.Skip() else dataVarDef,
              js.If(!(if (isStrongMode) genIsScalaJSObject(obj) else data), {
                js.Return(js.BooleanLiteral(false))
              }, {
                val arrayDepthVarDef = genLet(Ident("arrayDepth"), mutable = false, {
                  (data DOT "arrayDepth") || js.IntLiteral(0)
                })
                val arrayDepth = arrayDepthVarDef.ref
                js.Block(
                  if (isStrongMode) dataVarDef else js.Skip(),
                  arrayDepthVarDef,
                  js.Return {
                    // Array[A] </: Array[Array[A]]
                    !js.BinaryOp(JSBinaryOp.<, arrayDepth, depth) && (
                      // Array[Array[A]] <: Array[Object]
                      js.BinaryOp(JSBinaryOp.>, arrayDepth, depth) ||
                      // Array[Int] </: Array[Object]
                      !js.BracketSelect(data DOT "arrayBase", js.StringLiteral("isPrimitive"))
                    )
                  })
              }))

          case _ =>
            js.Return(!(!(genIsScalaJSObject(obj) &&
                ((obj DOT "$classData" DOT "arrayDepth") === depth) &&
                (obj DOT "$classData" DOT "arrayBase" DOT "ancestors" DOT className))))
        }))
    }

    val createAsArrayOfStat = if (semantics.asInstanceOfs == Unchecked) {
      js.Skip()
    } else {
      envFieldDef("asArrayOf", className,
        js.Function(List(objParam, depthParam), js.Return {
          js.If(js.Apply(envField("isArrayOf", className), List(obj, depth)) ||
              (obj === js.Null()), {
            obj
          }, {
            genCallHelper("throwArrayCastException",
                obj, js.StringLiteral("L"+displayName+";"), depth)
          })
        }))
    }

    js.Block(createIsArrayOfStat, createAsArrayOfStat)
  }

  private def genIsScalaJSObject(obj: js.Tree)(implicit pos: Position): js.Tree = {
    import TreeDSL._
    outputMode match {
      case OutputMode.ECMAScript6StrongMode =>
        js.Apply(js.VarRef(js.Ident("$isScalaJSObject")), List(obj))
      case _ =>
        obj && (obj DOT "$classData")
    }
  }

  def genTypeData(tree: LinkedClass): js.Tree = {
    import Definitions._
    import TreeDSL._

    implicit val pos = tree.pos

    val classIdent = transformIdent(tree.name)
    val className = classIdent.name
    val kind = tree.kind

    val isObjectClass =
      className == ObjectClass
    val isHijackedBoxedClass =
      HijackedBoxedClasses.contains(className)
    val isAncestorOfHijackedClass =
      AncestorsOfHijackedClasses.contains(className)
    val isRawJSType =
      kind == ClassKind.RawJSType || kind.isJSClass

    val isRawJSTypeParam =
      if (isRawJSType) js.BooleanLiteral(true)
      else js.Undefined()

    val parentData = if (globalInfo.isParentDataAccessed) {
      tree.superClass.fold[js.Tree] {
        if (isObjectClass) js.Null()
        else js.Undefined()
      } { parent =>
        envField("d", parent.name)
      }
    } else {
      js.Undefined()
    }

    val ancestorsRecord = js.ObjectConstr(
        tree.ancestors.map(ancestor => (js.Ident(ancestor), js.IntLiteral(1))))

    val (isInstanceFun, isArrayOfFun) = {
      if (isObjectClass) {
        /* Object has special ScalaJS.is.O *and* ScalaJS.isArrayOf.O. */
        (envField("is", className), envField("isArrayOf", className))
      } else if (isHijackedBoxedClass) {
        /* Hijacked boxed classes have a special isInstanceOf test. */
        val xParam = js.ParamDef(Ident("x"), rest = false)
        (js.Function(List(xParam), js.Return {
          genIsInstanceOf(xParam.ref, ClassType(className))
        }), js.Undefined())
      } else if (isAncestorOfHijackedClass || className == StringClass) {
        /* java.lang.String and ancestors of hijacked classes have a normal
         * ScalaJS.is.pack_Class test but with a non-standard behavior. */
        (envField("is", className), js.Undefined())
      } else if (isRawJSType) {
        /* Raw JS types have an instanceof operator-based isInstanceOf test
         * dictated by their jsName. If there is no jsName, the test cannot
         * be performed and must throw.
         * JS classes have something similar, based on their constructor.
         */
        if (tree.jsName.isEmpty && kind != ClassKind.JSClass) {
          (envField("noIsInstance"), js.Undefined())
        } else {
          val jsCtor = genRawJSClassConstructor(tree)
          (js.Function(List(js.ParamDef(Ident("x"), rest = false)), js.Return {
            js.BinaryOp(JSBinaryOp.instanceof, js.VarRef(Ident("x")), jsCtor)
          }), js.Undefined())
        }
      } else {
        // For other classes, the isInstance function can be inferred.
        (js.Undefined(), js.Undefined())
      }
    }

    val allParams = List(
        js.ObjectConstr(List(classIdent -> js.IntLiteral(0))),
        js.BooleanLiteral(kind == ClassKind.Interface),
        js.StringLiteral(semantics.runtimeClassName(tree)),
        ancestorsRecord,
        isRawJSTypeParam,
        parentData,
        isInstanceFun,
        isArrayOfFun
    )

    val prunedParams = outputMode match {
      case OutputMode.ECMAScript6StrongMode =>
        allParams
      case _ =>
        allParams.reverse.dropWhile(_.isInstanceOf[js.Undefined]).reverse
    }

    val typeData = js.Apply(js.New(envField("TypeData"), Nil) DOT "initClass",
        prunedParams)

    outputMode match {
      case OutputMode.ECMAScript6StrongMode =>
        js.Assign(envField("d", className), typeData)
      case _ =>
        envFieldDef("d", className, typeData)
    }
  }

  def genSetTypeData(tree: LinkedClass): js.Tree = {
    import TreeDSL._

    implicit val pos = tree.pos

    assert(tree.kind.isClass)

    encodeClassVar(tree.name.name).prototype DOT "$classData" :=
      envField("d", tree.name.name)
  }

  def genModuleAccessor(tree: LinkedClass): js.Tree = {
    import TreeDSL._

    implicit val pos = tree.pos

    val classIdent = transformIdent(tree.name)
    val className = classIdent.name
    val tpe = ClassType(className)

    require(tree.kind.hasModuleAccessor,
        s"genModuleAccessor called with non-module class: $className")

    val createModuleInstanceField = outputMode match {
      case OutputMode.ECMAScript6StrongMode =>
        js.Skip()
      case _ =>
        envFieldDef("n", className, js.Undefined(), mutable = true)
    }

    val createAccessor = {
      val moduleInstanceVar = envField("n", className)

      val assignModule = {
        val jsNew = js.New(encodeClassVar(className), Nil)
        val instantiateModule =
          if (tree.kind == ClassKind.JSModuleClass) jsNew
          else js.Apply(jsNew DOT js.Ident("init___"), Nil)
        moduleInstanceVar := instantiateModule
      }

      val initBlock = semantics.moduleInit match {
        case CheckedBehavior.Unchecked =>
          js.If(!(moduleInstanceVar), assignModule, js.Skip())
        case CheckedBehavior.Compliant =>
          js.If(moduleInstanceVar === js.Undefined(),
            js.Block(
                moduleInstanceVar := js.Null(),
                assignModule
            ),
            js.Skip())
        case CheckedBehavior.Fatal =>
          js.If(moduleInstanceVar === js.Undefined(), {
            js.Block(
                moduleInstanceVar := js.Null(),
                assignModule
            )
          }, js.If(moduleInstanceVar === js.Null(), {
            // throw new UndefinedBehaviorError(
            //     "Initializer of $className called before completion of its" +
            //     "super constructor")
            val decodedName = Definitions.decodeClassName(className).stripSuffix("$")
            val msg = s"Initializer of $decodedName called before completion " +
              "of its super constructor"
            val obj = js.New(encodeClassVar("sjsr_UndefinedBehaviorError"), Nil)
            val ctor = obj DOT js.Ident("init___T")
            js.Throw(js.Apply(ctor, js.StringLiteral(msg) :: Nil))
          }, js.Skip()))
      }

      val body = js.Block(initBlock, js.Return(moduleInstanceVar))

      outputMode match {
        case OutputMode.ECMAScript6StrongMode =>
          js.MethodDef(static = true, js.Ident("__M"), Nil, body)
        case _ =>
          envFieldDef("m", className, js.Function(Nil, body))
      }
    }

    js.Block(createModuleInstanceField, createAccessor)
  }

  def genExportedMembers(tree: LinkedClass): js.Tree = {
    val exports = tree.exportedMembers map { member =>
      member.tree match {
        case MethodDef(false, StringLiteral("constructor"), _, _, _)
            if tree.kind.isJSClass =>
          js.Skip()(member.tree.pos)
        case m: MethodDef =>
          genMethod(tree.encodedName, m)
        case p: PropertyDef =>
          genProperty(tree.encodedName, p)
        case tree =>
          throw new AssertionError(
              "Illegal exportedMember " + tree.getClass.getName)
      }
    }

    js.Block(exports)(tree.pos)
  }

  def genClassExports(tree: LinkedClass): js.Tree = {
    val exports = tree.classExports collect {
      case e: ConstructorExportDef =>
        genConstructorExportDef(tree, e)
      case e: JSClassExportDef =>
        genJSClassExportDef(tree, e)
      case e: ModuleExportDef =>
        genModuleExportDef(tree, e)
    }

    js.Block(exports)(tree.pos)
  }

  def genConstructorExportDef(cd: LinkedClass,
      tree: ConstructorExportDef): js.Tree = {
    import TreeDSL._

    implicit val pos = tree.pos
    val classType = ClassType(cd.name.name)
    val ConstructorExportDef(fullName, args, body) = tree

    val baseCtor = envField("c", cd.name.name, cd.name.originalName)

    val thisIdent = js.Ident("$thiz")

    val js.Function(ctorParams, ctorBody) =
      desugarToFunction(this, cd.encodedName,
          Some(thisIdent), args, body, isStat = true)

    val exportedCtor = js.Function(ctorParams, js.Block(
      genLet(thisIdent, mutable = false, js.New(baseCtor, Nil)),
      ctorBody,
      js.Return(js.VarRef(thisIdent))
    ))

    outputMode match {
      case OutputMode.ECMAScript6StrongMode =>
        val (nsParts, name) = genStrongModeNamespaceInfo(fullName)
        js.Apply(js.VarRef(js.Ident("$exportCtor")), List(
            nsParts, name, exportedCtor, baseCtor DOT "prototype"))

      case _ =>
        val (createNamespace, expCtorVar) =
          genCreateNamespaceInExports(fullName)
        js.Block(
          createNamespace,
          js.DocComment("@constructor"),
          expCtorVar := exportedCtor,
          expCtorVar DOT "prototype" := baseCtor DOT "prototype"
        )
    }
  }

  def genJSClassExportDef(cd: LinkedClass, tree: JSClassExportDef): js.Tree = {
    import TreeDSL._

    implicit val pos = tree.pos

    val classVar = envField("c", cd.name.name)
    genClassOrModuleExportDef(cd, tree.fullName, classVar)
  }

  def genModuleExportDef(cd: LinkedClass, tree: ModuleExportDef): js.Tree = {
    import TreeDSL._

    implicit val pos = tree.pos

    val baseAccessor = outputMode match {
      case OutputMode.ECMAScript6StrongMode =>
        js.DotSelect(envField("c", cd.name.name), js.Ident("__M"))
      case _ =>
        envField("m", cd.name.name)
    }

    genClassOrModuleExportDef(cd, tree.fullName, baseAccessor)
  }

  private def genClassOrModuleExportDef(cd: LinkedClass, exportFullName: String,
      exportedValue: js.Tree)(implicit pos: Position): js.Tree = {
    import TreeDSL._

    outputMode match {
      case OutputMode.ECMAScript6StrongMode =>
        val (nsParts, name) = genStrongModeNamespaceInfo(exportFullName)
        js.Apply(js.VarRef(js.Ident("$export")), List(
            nsParts, name, exportedValue))

      case _ =>
        val (createNamespace, expAccessorVar) =
          genCreateNamespaceInExports(exportFullName)
        js.Block(
          createNamespace,
          expAccessorVar := exportedValue
        )
    }
  }

  // Helpers

  /** Gen JS code for assigning an rhs to a qualified name in the exports scope.
   *  For example, given the qualified name "foo.bar.Something", generates:
   *
   *  ScalaJS.e["foo"] = ScalaJS.e["foo"] || {};
   *  ScalaJS.e["foo"]["bar"] = ScalaJS.e["foo"]["bar"] || {};
   *
   *  Returns (statements, ScalaJS.e["foo"]["bar"]["Something"])
   */
  private def genCreateNamespaceInExports(qualName: String)(
      implicit pos: Position): (js.Tree, js.Tree) = {
    val parts = qualName.split("\\.")
    val statements = List.newBuilder[js.Tree]
    var namespace = envField("e")
    for (i <- 0 until parts.length-1) {
      namespace = js.BracketSelect(namespace, js.StringLiteral(parts(i)))
      statements +=
        js.Assign(namespace, js.BinaryOp(JSBinaryOp.||,
            namespace, js.ObjectConstr(Nil)))
    }
    val lhs = js.BracketSelect(namespace, js.StringLiteral(parts.last))
    (js.Block(statements.result()), lhs)
  }

  private def genStrongModeNamespaceInfo(qualName: String)(
      implicit pos: Position): (js.Tree, js.Tree) = {
    val parts = qualName.split("\\.").toList.map(js.StringLiteral(_))
    (js.ArrayConstr(parts.init), parts.last)
  }

}

object ScalaJSClassEmitter {
  private val ClassesWhoseDataReferToTheirInstanceTests = {
    Definitions.AncestorsOfHijackedClasses +
    Definitions.ObjectClass + Definitions.StringClass
  }
}


text:
package main

type hub struct {
	// Registered connections.
	connections map[*connection]bool

	// Inbound messages from the connections.
	broadcast chan []byte

	// Register requests from the connections.
	register chan *connection

	// Unregister requests from connections.
	unregister chan *connection
}

func newHub() *hub {
	return &hub{
		broadcast:   make(chan []byte),
		register:    make(chan *connection),
		unregister:  make(chan *connection),
		connections: make(map[*connection]bool),
	}
}

func (h *hub) run() {
	for {
		select {
		case c := <-h.register:
			h.connections[c] = true
		case c := <-h.unregister:
			if _, ok := h.connections[c]; ok {
				delete(h.connections, c)
				close(c.send)
			}
		//Global broadcasts
		case m := <-h.broadcast:
			for c := range h.connections {
				select {
				case c.send <- m:
				default:
					delete(h.connections, c)
					close(c.send)
				}
			}
		}
	}
}


text:
module.exports = patch;

var now = new Date();

var debug = require('debug')('snyk');
var Promise = require('es6-promise').Promise; // jshint ignore:line
var chalk = require('chalk');
var recursive = require('snyk-recursive-readdir');
var request = require('request');
var tempfile = require('tempfile');
var fs = require('then-fs');
var path = require('path');
var _ = require('lodash');
var applyPatch = require('./apply-patch');
var stripVersions = require('./strip-versions');
var getVulnSource = require('./get-vuln-source');
var dedupe = require('./dedupe-patches');
var writePatchFlag = require('./write-patch-flag');
var spinner = require('../spinner');
var errors = require('../error');

// note: cwd is optional and mostly used for testing
function patch(vulns, live, cwd) {
  var lbl = 'Applying patches...';

  // we also need to normalise the patches. specifically, using the __filename
  // as the identifier, we'll ensure the vuln.id is unique, so we don't have
  // multiple attempts to patch the same location (which leads to failed patch
  // due to "Reversed (or previously applied)").

  var noPatchRequired = {};
  if (vulns.length) {
    vulns = vulns.reduce(function (acc, curr) {
      var key = curr.id + ':' + curr.__filename;
      if (!noPatchRequired[key]) {
        noPatchRequired[key] = [];
        acc.push(curr);
      } else {
        noPatchRequired[key].push(curr);
      }
      return acc;
    }, []);
  }

  var errorList = [];
  return spinner(lbl).then(function () {
    // the target directory where our module name will live
    vulns.forEach(function (vuln) {
      vuln.source = getVulnSource(vuln, cwd, live);
    });

    var deduped = dedupe(vulns);
    debug('patching %s', deduped.packages.length);

    // find the patches, pull them down off the web, save them in a temp file
    // then apply each individual patch - but do it one at a time (via reduce)
    var promises = deduped.packages.reduce(function (acc, vuln) {
      return acc.then(function (res) {
        var patches = vuln.patches; // this is also deduped in `dedupe`

        if (patches === null) {
          debug('no patch available for ' + vuln.id);
          return false;
        }

        // the colon doesn't like Windows, ref: https://git.io/vw2iO
        var fileSafeId = vuln.id.replace(/:/g, '-');
        var flag = path.resolve(vuln.source, '.snyk-' + fileSafeId + '.flag');
        var oldFlag = path.resolve(vuln.source, '.snyk-' + vuln.id + '.flag');

        // get the patches on the local fs
        var promises = patches.urls.map(function (url) {
          return new Promise(function (resolve, reject) {
            var filename = tempfile('.' + fileSafeId + '.snyk-patch');
            request(url)
              .on('end', function () {
                resolve(filename);
              })
              .on('error', reject)
              .pipe(fs.createWriteStream(filename));
          }).then(function (patch) {
            // check whether there's a trace of us having patched before
            return fs.exists(flag).then(function (exists) {
              // if the file doesn't exist, look for the old style filename
              // in case and for backward compat
              return exists || fs.exists(oldFlag);
            }).then(function (exists) {
              if (!exists) {
                return patch;
              }

              // else revert the patch
              return new Promise(function (resolve, reject) {
                recursive(vuln.source, function (error, files) {
                  if (error) {
                    return reject(error);
                  }

                  resolve(Promise.all(files.filter(function (file) {
                    return file.slice(-5) === '.orig';
                  }).map(function (file) {
                    return fs.rename(file, path.dirname(file) + '/' +
                      path.basename(file).slice(0, -5));
                  })));
                });
              }).then(function () {
                return patch;
              });
            });
          }).then(function (patch) {
            if (patch === false) {
              debug('already patched %s', vuln.id);
              return vuln;
            }

            debug('applying patch file for %s: \n%s\n%s', vuln.id, url, patch);

            return applyPatch(patch, vuln, live).then(function () {
              return true;
            }, function (e) {
              errorList.push(e);
              return false;
            }).then(function (ok) {
              return ok ? vuln : false;
            });
          });
        });

        return Promise.all(promises).then(function (result) {
          res.push(result);
          return res; // this is what makes the waterfall reduce chain work
        });
      });
    }, Promise.resolve(deduped.removed));

    var promise = promises.then(function (res) {
      var patched = _.flatten(res).filter(Boolean);

      if (!live) {
        debug('[skipping - dry run]');
        return patched;
      }

      return Promise.all(patched.map(writePatchFlag.bind(null, now)));
    }).then(function (patched) {
      patched = patched.reduce(function (acc, curr) {
        var key = curr.id + ':' + curr.__filename;

        if (noPatchRequired[key]) {
          noPatchRequired[key].forEach(function (vuln) {
            acc.push(vuln);
          });
        }

        acc.push(curr);

        return acc;
      }, []);

      var config = {};

      // this reduce function will look to see if the patch actually resolves
      // more than one vulnerability, and if it does, it'll replicate the
      // patch rule against the *other* vuln.ids. This will happen when the user
      // runs the wizard and selects to apply a patch that fixes more than one
      // vuln.
      var mapped = patched.map(patchRule).reduce(function (acc, curr, i) {
        var vuln = patched[i];
        if (vuln.grouped && vuln.grouped.includes) {
          vuln.grouped.includes.forEach(function (id) {
            var rule = _.cloneDeep(curr);
            rule.vulnId = id;
            acc.push(rule);
          });
        }

        acc.push(curr);

        return acc;
      }, []);

      config.patch = mapped.reduce(function (acc, curr) {
        if (!acc[curr.vulnId]) {
          acc[curr.vulnId] = [];
        }

        var id = curr.vulnId;
        delete curr.vulnId;
        acc[id].push(curr);

        return acc;
      }, {});

      debug('patched', config);

      return config;
    });

    return promise;
  }).then(spinner.clear(lbl)).then(function (res) {
    if (errorList.length) {
      errorList.forEach(function (error) {
        console.log(chalk.red(errors.message(error)));
      });
    }

    return res;
  });
}

function patchRule(vuln) {
  var rule = {
    vulnId: vuln.id,
  };
  rule[stripVersions(vuln.from.slice(1)).join(' > ')] = {
    patched: now.toJSON(),
  };
  return rule;
}


text:
using Evolution.IRepository;
using Evolution.Domain.Entity.SystemSecurity;
using System.Threading.Tasks;

namespace Evolution.Domain.IRepository.SystemSecurity
{
    public interface IDbBackupRepository : IRepositoryBase<DbBackupEntity>
    {
        Task<int> Delete(string keyValue);
        Task<int> ExecuteDbBackup(DbBackupEntity dbBackupEntity);
    }
}


text:
local s = require('say')

s:set_namespace('nl')

s:set("assertion.same.positive", "Verwachtte objecten die vergelijkbaar zijn. Aangeboden:\n%s\nVerwachtte:\n%s")
s:set("assertion.same.negative", "Verwachtte objecten die niet vergelijkbaar zijn. Aangeboden:\n%s\nVerwachtte niet:\n%s")

s:set("assertion.equals.positive", "Verwachtte objecten die hetzelfde zijn. Aangeboden:\n%s\nVerwachtte:\n%s")
s:set("assertion.equals.negative", "Verwachtte objecten die niet hetzelfde zijn. Aangeboden:\n%s\nVerwachtte niet:\n%s")

s:set("assertion.unique.positive", "Verwachtte objecten die uniek zijn:\n%s")
s:set("assertion.unique.negative", "Verwachtte objecten die niet uniek zijn:\n%s")

s:set("assertion.error.positive", "Verwachtte een foutmelding.")
s:set("assertion.error.negative", "Verwachtte geen foutmelding.\n%s")

s:set("assertion.truthy.positive", "Verwachtte een 'warige' (thruthy) waarde, maar was:\n%s")
s:set("assertion.truthy.negative", "Verwachtte een niet 'warige' (thruthy) waarde, maar was:\n%s")

s:set("assertion.falsy.positive", "Verwachtte een 'onwarige' (falsy) waarde, maar was:\n%s")
s:set("assertion.falsy.negative", "Verwachtte een niet 'onwarige' (falsy) waarde, maar was:\n%s")

-- errors
s:set("assertion.internal.argtolittle", "de '%s' functie verwacht minimaal %s parameters, maar kreeg er: %s")
s:set("assertion.internal.badargtype", "de '%s' functie verwacht een %s als parameter, maar kreeg een: %s")


text:
(function ($, document, undefined) {

	var pluses = /\+/g;

	function raw(s) {
		return s;
	}

	function decoded(s) {
		return unRfc2068(decodeURIComponent(s.replace(pluses, ' ')));
	}

	function unRfc2068(_value) {
	    var value = _value;
		if (value.indexOf('"') === 0) {
			// This is a quoted cookie as according to RFC2068, unescape
			value = value.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, '\\');
		}
		return value;
	}

	var config = null;

	$.cookie = function (key, _value, _options) {
	    var value = _value;
	    var options = _options;
		// write
		if (value !== undefined) {
			options = $.extend({}, config.defaults, options);

			if (value === null) {
				options.expires = -1;
			}

			if (typeof options.expires === 'number') {
				var days = options.expires, t = options.expires = new Date();
				t.setDate(t.getDate() + days);
			}

			value = config.json ? JSON.stringify(value) : String(value);

			return (document.cookie = [
				encodeURIComponent(key), '=', config.raw ? value : encodeURIComponent(value),
				options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
				options.path    ? '; path=' + options.path : '',
				options.domain  ? '; domain=' + options.domain : '',
				options.secure  ? '; secure' : ''
			].join(''));
		}

		// read
		var decode = config.raw ? raw : decoded;
		var cookies = document.cookie.split('; ');
		var result = key ? null : {};
		for (var i = 0, l = cookies.length; i < l; i++) {
			var parts = cookies[i].split('=');
			var cookieName = decode(parts.shift());
			var cookie = decode(parts.join('='));

			if (key && key === cookieName) {
				result = fromJSON(cookie);
				break;
			}

			if (!key) {
				result[cookieName] = fromJSON(cookie);
			}
		}

		return result;
	};

	var config = $.cookie;
	config.defaults = {};

	$.removeCookie = function (key, options) {
		if ($.cookie(key) !== null) {
			$.cookie(key, null, options);
			return true;
		}
		return false;
	};

    function fromJSON(value) {
        return config.json ? JSON.parse(value) : value;
    }
})(jQuery, document);