text:
'use strict';

const models = require('./index');

/**
 * @class
 * Initializes a new instance of the RoleAssignment class.
 * @constructor
 * Role Assignments
 *
 * @member {string} [id] The role assignment ID.
 *
 * @member {string} [name] The role assignment name.
 *
 * @member {string} [type] The role assignment type.
 *
 * @member {object} [properties] Role assignment properties.
 *
 * @member {string} [properties.scope] The role assignment scope.
 *
 * @member {string} [properties.roleDefinitionId] The role definition ID.
 *
 * @member {string} [properties.principalId] The principal ID.
 *
 */
class RoleAssignment {
  constructor() {
  }

  /**
   * Defines the metadata of RoleAssignment
   *
   * @returns {object} metadata of RoleAssignment
   *
   */
  mapper() {
    return {
      required: false,
      serializedName: 'RoleAssignment',
      type: {
        name: 'Composite',
        className: 'RoleAssignment',
        modelProperties: {
          id: {
            required: false,
            serializedName: 'id',
            type: {
              name: 'String'
            }
          },
          name: {
            required: false,
            serializedName: 'name',
            type: {
              name: 'String'
            }
          },
          type: {
            required: false,
            serializedName: 'type',
            type: {
              name: 'String'
            }
          },
          properties: {
            required: false,
            serializedName: 'properties',
            type: {
              name: 'Composite',
              className: 'RoleAssignmentPropertiesWithScope'
            }
          }
        }
      }
    };
  }
}

module.exports = RoleAssignment;


text:
using HomeCinema.Data.Configurations;
using HomeCinema.Entities;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
using System.Data.Entity.Validation;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HomeCinema.Data
{
    public class HomeCinemaContext : DbContext
    {
        public HomeCinemaContext()
            : base("HomeCinema")
        {
            Database.SetInitializer<HomeCinemaContext>(null);
        }

        #region Entity Sets
        public IDbSet<User> UserSet { get; set; }
        public IDbSet<Role> RoleSet { get; set; }
        public IDbSet<UserRole> UserRoleSet { get; set; }
        public IDbSet<Customer> CustomerSet { get; set; }
        public IDbSet<Movie> MovieSet { get; set; }
        public IDbSet<Genre> GenreSet { get; set; }
        public IDbSet<Stock> StockSet { get; set; }
        public IDbSet<Rental> RentalSet { get; set; }
        public IDbSet<Error> ErrorSet { get; set; }
        #endregion

        public virtual void Commit()
        {
            base.SaveChanges();
        }
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();

            modelBuilder.Configurations.Add(new UserConfiguration());
            modelBuilder.Configurations.Add(new UserRoleConfiguration());
            modelBuilder.Configurations.Add(new RoleConfiguration());
            modelBuilder.Configurations.Add(new CustomerConfiguration());
            modelBuilder.Configurations.Add(new MovieConfiguration());
            modelBuilder.Configurations.Add(new GenreConfiguration());
            modelBuilder.Configurations.Add(new StockConfiguration());
            modelBuilder.Configurations.Add(new RentalConfiguration());
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
import fs from 'fs'
import { promisify } from 'util'

const readFileAsync = promisify(fs.readFile)
const writeFileAsync = promisify(fs.writeFile)

export default async function ensureFileContent(
  fileName: string,
  currentFileContent: ?string,
  newFileContent: string,
) {
  // If the current file content is not provided, get it
  if (currentFileContent == null) currentFileContent = (await readFileAsync(fileName)).toString()

  if (currentFileContent != newFileContent) {
    console.log('✍  written:  ' + fileName)
    await writeFileAsync(fileName, newFileContent, 'utf8')
  } else {
    console.log('📎  skipped:  ' + fileName)
  }
}


text:
var $ = jQuery;

var username=$( "a:contains('Profile')" ).attr("href").replace("/users/","").replace("/","");
var forum=false;
if (window.location.pathname.includes("/discuss/topic/")){
    forum=true;
}

var profile=true;

function httpGetAsync(a,b){var c=new XMLHttpRequest;c.onreadystatechange=function(){4==c.readyState&&200==c.status&&b(c.responseText)},c.open("GET",a,!0),c.send(null)}

if (forum || profile){
function loadJSON(a,b,c){var d=new XMLHttpRequest;d.onreadystatechange=function(){d.readyState===XMLHttpRequest.DONE&&(200===d.status?b&&b(JSON.parse(d.responseText)):c&&c(d))},d.open("GET",a,!0),d.send()}

function showUsers(users) {
    for (i in users){
	    $("a.username[href='/users/"+users[i].name+"/']").html(users[i].name+" (online)")
        if ($( ".header-text" ).find("h2").html()==users[i].name){
            $( ".header-text" ).find("h2").html(users[i].name+" (online)");
        }

    }
}

loadJSON('https://isonline.herokuapp.com/listAllOnline',
         function(data) { showUsers(data) },
         function(xhr) { alert(xhr); }
);
}

httpGetAsync("https://isonline.herokuapp.com/logConnected/"+username,function(){console.log("You are now marked as online")})

console.log("isOnline2.0 Has now been loaded and edited the webpage");
console.log("PS tell Herohamp that no one ever reads these things so they don't have to be formal... unless your activly bugfixing.");


text:
var M2OSelect=NFView.extend({
    _name: "m2o_select",
    className: "modal nf-modal",
    events: {
        "click .m2o-select": "select",
        "click .m2o-cancel": "cancel"
    },

    render: function() {
        var opts={
            model: this.options.model,
            condition: this.options.condition,
            view_xml: this.options.view_xml,
            show_search: true,
            no_click: true
        };
        var view_cls=get_view_cls("list_view");
        var view=new view_cls({options:opts});
        this.list_view=view;
        var content="

";
        this.data.content=content;
        NFView.prototype.render.call(this);
    },

    select: function() {
        log("m2o_select",this);
        var ids=this.list_view.get_selected_ids();
        log("selected ids",ids);
        if (ids.length==0) {
            alert("No items selected.");
            return;
        }
        $(".modal").modal("hide");
        this.trigger("items_selected",ids);
    },

    cancel: function() {
        log("m2o_cancel",this);
        $(".modal").modal("hide");
    }
});

M2OSelect.register();


text:
// You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this.
// If you use this binding you'll need to call 4 functions: ImGui_ImplXXXX_Init(), ImGui_ImplXXXX_NewFrame(), ImGui::Render() and ImGui_ImplXXXX_Shutdown().
// If you are new to ImGui, see examples/README.txt and documentation at the top of imgui.cpp.
// https://github.com/ocornut/imgui

#include "imgui/imgui.h"
#include "imgui_impl_vr.h"
#include "imgui/imgui_internal.h"

// SDL,GLEW
#include <SDL.h>
#include <SDL_syswm.h>
#include <openvr.h>
#include <GL/glew.h>
#include <glm/gtx/intersect.hpp>
#include <glm/gtx/transform.hpp>

// Data
static vr::IVRSystem*		g_HMD;
static vr::IVRScreenshots*	g_pScreenShots;
static vr::IVROverlay*		g_pOverlay;

static double       g_Time = 0.0f;
static GLuint       g_FontTexture = 0;
static int          g_ShaderHandle = 0, g_VertHandle = 0, g_FragHandle = 0;
static int          g_AttribLocationTex = 0, g_AttribLocationProjMtx = 0;
static int          g_AttribLocationPosition = 0, g_AttribLocationUV = 0, g_AttribLocationColor = 0;
static unsigned int g_VboHandle = 0, g_VaoHandle = 0, g_ElementsHandle = 0;

static glm::mat4	g_Mgui = glm::scale(glm::vec3(1.0f)); //GUI controller pose
static glm::mat4	g_MguiScale = glm::scale(glm::vec3(1.0f)); //GUI 3d modeling matrix
static glm::mat4	g_MguiRotation[4] = {glm::scale(glm::vec3(1.0f)), glm::scale(glm::vec3(1.0f)), glm::scale(glm::vec3(1.0f)), glm::scale(glm::vec3(1.0f))}; //GUI 3d rotation matrix
static glm::mat4	g_Mmouse = glm::scale(glm::vec3(1.0f)); // Mouse controller pose

const int			g_MaxTextures = 4;
static GLuint		g_GuiTexture[g_MaxTextures] = {0,0,0,0};
static int			g_TexWidth = 0;
static int			g_TexHeight = 0;
static GLuint		g_GuiFBO = 0;
static int			g_LastViewport[4] = {0,0,0,0};
static bool			g_IsHidden = false;
static bool			g_Pinned = false;

static ImVec2		g_AxisPos[2] = {ImVec2(0.0f, 0.0f), ImVec2(0.0f, 0.0f)};
static ImVec2		g_AxisClickedPos[2] = {ImVec2(0.0f, 0.0f), ImVec2(0.0f, 0.0f)};
static int			g_ActiveTexture = -1;

static char* InputTextBuf = 0;
static size_t InputTextBufSize = 0;

static ImGuiContext* g_Context[g_MaxTextures];

ImVec2 ImGui_Impl_VR_GetAxisPos(int i)
{
	return g_AxisPos[i];
}

ImVec2 ImGui_Impl_VR_GetAxisDragDelta(int i)
{
	return ImVec2(g_AxisPos[i].x-g_AxisClickedPos[i].x, g_AxisPos[i].y-g_AxisClickedPos[i].y);  //where is operator- ?
}

ImVec2 ImGui_Impl_VR_GetTextureSize()
{
   return ImVec2((float)g_TexWidth, (float)g_TexHeight);
}

void ImGui_Impl_VR_SetPinned(bool pinned)
{
	g_Pinned = pinned;
}

bool ImGui_Impl_VR_IsHidden()
{
	return g_IsHidden;
}

glm::mat4 ImGui_Impl_VR_GetGuiPose()
{
	return g_Mgui;
}

glm::mat4 ImGui_Impl_VR_GetGuiScale()
{
	return g_MguiScale;
}

 void ImGui_Impl_VR_SetGuiScale(float s)
{
	g_MguiScale = glm::scale(glm::vec3(s));
}

int  ImGui_Impl_VR_GetGuiTexture(int i)
{
	return g_GuiTexture[i];
}

void ImGui_Impl_VR_SetGuiRotation(int i, glm::mat4& R)
{
	if(i<0 || i>=4)
	{
		return;
	}
	g_MguiRotation[i] = R;
}

glm::mat4 ImGui_Impl_VR_GetGuiRotation(int i)
{
	return g_MguiRotation[i];
}

void ImGui_Impl_VR_TriggerHapticPulse(vr::TrackedDeviceIndex_t device)
{
	const int left_controller = g_HMD->GetTrackedDeviceIndexForControllerRole(vr::TrackedControllerRole_LeftHand);
	const uint32_t axis = 0; //there is currently only one actuator
	g_HMD->TriggerHapticPulse(left_controller, axis, 500);
}

void ImGui_Impl_VR_GrabScreenshot()
{
	vr::ScreenshotHandle_t handle;
	g_pScreenShots->RequestScreenshot( &handle, vr::VRScreenshotType_Stereo, "preview_ss", "vr_ss" );
}

void ImGui_Impl_VR_ShowKeyboard()
{
	g_pOverlay->ShowKeyboard( vr::k_EGamepadTextInputModeNormal, vr::k_EGamepadTextInputLineModeSingleLine, "Sample Keyboard", 1024, "", false, 0 );
}

void ImGui_Impl_VR_HideKeyboard()
{
	g_pOverlay->HideKeyboard();
}

// This is the main rendering function that you have to implement and provide to ImGui (via setting up 'RenderDrawListsFn' in the ImGuiIO structure)
// If text or lines are blurry when integrating ImGui in your engine:
// - in your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f)
void ImGui_Impl_VR_RenderDrawLists(ImDrawData* draw_data)
{
	// Backup GL state
	GLint last_program; glGetIntegerv(GL_CURRENT_PROGRAM, &last_program);
	GLint last_texture; glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture);
	GLint last_array_buffer; glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &last_array_buffer);
	GLint last_element_array_buffer; glGetIntegerv(GL_ELEMENT_ARRAY_BUFFER_BINDING, &last_element_array_buffer);
	GLint last_vertex_array; glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &last_vertex_array);
	GLint last_blend_src; glGetIntegerv(GL_BLEND_SRC, &last_blend_src);
	GLint last_blend_dst; glGetIntegerv(GL_BLEND_DST, &last_blend_dst);
	GLint last_blend_equation_rgb; glGetIntegerv(GL_BLEND_EQUATION_RGB, &last_blend_equation_rgb);
	GLint last_blend_equation_alpha; glGetIntegerv(GL_BLEND_EQUATION_ALPHA, &last_blend_equation_alpha);
    GLint last_viewport[4]; glGetIntegerv(GL_VIEWPORT, last_viewport);
	GLboolean last_enable_blend = glIsEnabled(GL_BLEND);
	GLboolean last_enable_cull_face = glIsEnabled(GL_CULL_FACE);
	GLboolean last_enable_depth_test = glIsEnabled(GL_DEPTH_TEST);
	GLboolean last_enable_scissor_test = glIsEnabled(GL_SCISSOR_TEST);

	// Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled
	glEnable(GL_BLEND);
	glBlendEquation(GL_FUNC_ADD);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	glDisable(GL_CULL_FACE);
	glDisable(GL_DEPTH_TEST);
	glEnable(GL_SCISSOR_TEST);
	glActiveTexture(GL_TEXTURE0);

	// Handle cases of screen coordinates != from framebuffer coordinates (e.g. retina displays)
	ImGuiIO& io = ImGui::GetIO();
    int fb_width = (int)(io.DisplaySize.x * io.DisplayFramebufferScale.x);
    int fb_height = (int)(io.DisplaySize.y * io.DisplayFramebufferScale.y);
	draw_data->ScaleClipRects(io.DisplayFramebufferScale);

	// Setup orthographic projection matrix
    glViewport(0, 0, (GLsizei)fb_width, (GLsizei)fb_height);
	const float ortho_projection[4][4] =
	{
		{ 2.0f/io.DisplaySize.x, 0.0f,                   0.0f, 0.0f },
		{ 0.0f,                  2.0f/-io.DisplaySize.y, 0.0f, 0.0f },
		{ 0.0f,                  0.0f,                  -1.0f, 0.0f },
		{-1.0f,                  1.0f,                   0.0f, 1.0f },
	};
	glUseProgram(g_ShaderHandle);
	glUniform1i(g_AttribLocationTex, 0);
	glUniformMatrix4fv(g_AttribLocationProjMtx, 1, GL_FALSE, &ortho_projection[0][0]);
	glBindVertexArray(g_VaoHandle);

	for (int n = 0; n < draw_data->CmdListsCount; n++)
	{
		const ImDrawList* cmd_list = draw_data->CmdLists[n];
		const ImDrawIdx* idx_buffer_offset = 0;

		glBindBuffer(GL_ARRAY_BUFFER, g_VboHandle);
		glBufferData(GL_ARRAY_BUFFER, (GLsizeiptr)cmd_list->VtxBuffer.size() * sizeof(ImDrawVert), (GLvoid*)&cmd_list->VtxBuffer.front(), GL_STREAM_DRAW);

		glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, g_ElementsHandle);
		glBufferData(GL_ELEMENT_ARRAY_BUFFER, (GLsizeiptr)cmd_list->IdxBuffer.size() * sizeof(ImDrawIdx), (GLvoid*)&cmd_list->IdxBuffer.front(), GL_STREAM_DRAW);

		for (const ImDrawCmd* pcmd = cmd_list->CmdBuffer.begin(); pcmd != cmd_list->CmdBuffer.end(); pcmd++)
		{
			if (pcmd->UserCallback)
			{
				pcmd->UserCallback(cmd_list, pcmd);
			}
			else
			{
				glBindTexture(GL_TEXTURE_2D, (GLuint)(intptr_t)pcmd->TextureId);
				glScissor((int)pcmd->ClipRect.x, (int)(fb_height - pcmd->ClipRect.w), (int)(pcmd->ClipRect.z - pcmd->ClipRect.x), (int)(pcmd->ClipRect.w - pcmd->ClipRect.y));
				glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer_offset);
			}
			idx_buffer_offset += pcmd->ElemCount;
		}
	}

	// Restore modified GL state
	glUseProgram(last_program);
	glBindTexture(GL_TEXTURE_2D, last_texture);
	glBindBuffer(GL_ARRAY_BUFFER, last_array_buffer);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, last_element_array_buffer);
	glBindVertexArray(last_vertex_array);
	glBlendEquationSeparate(last_blend_equation_rgb, last_blend_equation_alpha);
	glBlendFunc(last_blend_src, last_blend_dst);
	if (last_enable_blend) glEnable(GL_BLEND); else glDisable(GL_BLEND);
	if (last_enable_cull_face) glEnable(GL_CULL_FACE); else glDisable(GL_CULL_FACE);
	if (last_enable_depth_test) glEnable(GL_DEPTH_TEST); else glDisable(GL_DEPTH_TEST);
	if (last_enable_scissor_test) glEnable(GL_SCISSOR_TEST); else glDisable(GL_SCISSOR_TEST);
    glViewport(last_viewport[0], last_viewport[1], (GLsizei)last_viewport[2], (GLsizei)last_viewport[3]);
}

static const char* ImGui_Impl_VR_GetClipboardText()
{
	//return SDL_GetClipboardText(); //any openvr equivalent here?
	return 0;
}

static void ImGui_Impl_VR_SetClipboardText(const char* text)
{
	//SDL_SetClipboardText(text);
}

#include <stdio.h>

float last_axis = 0.0f;
bool axis_dragging = false;

void ImGui_Impl_VR_ProcessEvent(vr::VREvent_t* event)
{
	if(g_ActiveTexture != -1)
	{
		ImGui::SetCurrentContext(g_Context[g_ActiveTexture]);
	}

	const int left_controller = g_HMD->GetTrackedDeviceIndexForControllerRole(vr::TrackedControllerRole_LeftHand);
	const int right_controller = g_HMD->GetTrackedDeviceIndexForControllerRole(vr::TrackedControllerRole_RightHand);
	ImGuiIO& io = ImGui::GetIO();

	if(event->trackedDeviceIndex == left_controller) //right controller is mouse
	{
		const vr::VREvent_Controller_t controller = event->data.controller;
		if(controller.button == vr::k_EButton_Axis0)
		{

			vr::VRControllerState_t state;
			if( g_HMD->GetControllerState( left_controller, &state ) )
			{
				if(event->eventType == vr::VREvent_ButtonTouch)
				{
					g_AxisPos[0] = ImVec2(state.rAxis[0].x, state.rAxis[0].y);
					g_AxisClickedPos[0] = g_AxisPos[0];
				}
				else if(event->eventType == vr::VREvent_ButtonUntouch)
				{
					g_AxisPos[0] = ImVec2(0.0f, 0.0f);
					g_AxisClickedPos[0] = g_AxisPos[0];
				}

			}
		}
	}

	if(event->trackedDeviceIndex == right_controller) //right controller is mouse
	{
		const vr::VREvent_Controller_t controller = event->data.controller;
		if(controller.button == vr::k_EButton_SteamVR_Trigger)
		{
			if(event->eventType == vr::VREvent_ButtonPress)
			{
				io.MouseDown[0] = true;
			}

			if(event->eventType == vr::VREvent_ButtonUnpress)
			{
				io.MouseDown[0] = false;
			}
		}

		if(controller.button == vr::k_EButton_Axis0)
		{

			vr::VRControllerState_t state;
			if( g_HMD->GetControllerState( right_controller, &state ) )
			{

				if(event->eventType == vr::VREvent_ButtonTouch)
				{
					g_AxisPos[1] = ImVec2(state.rAxis[0].x, state.rAxis[0].y);
					g_AxisClickedPos[1] = g_AxisPos[1];
					axis_dragging = true;
					last_axis = state.rAxis[0].y;
				}
				else if(event->eventType == vr::VREvent_ButtonUntouch)
				{
					axis_dragging = false;
					g_AxisPos[1] = ImVec2(0.0f, 0.0f);
					g_AxisClickedPos[1] = g_AxisPos[1];
				}

			}
		}

		if(controller.button == vr::k_EButton_ApplicationMenu)
		{
			if(event->eventType == vr::VREvent_ButtonPress)
			{
				g_IsHidden = !g_IsHidden;
			}
		}
	}

	if(event->eventType == vr::VREvent_KeyboardCharInput)
	{
		for(int i=0; i<8; i++)
		{
			//io.AddInputCharacter((unsigned short)event->data.keyboard.cNewInput[i]); //no worky. Why?
		}
	}

	if((event->eventType == vr::VREvent_KeyboardDone) && (InputTextBuf != 0) && (InputTextBufSize > 0))
	{
		g_pOverlay->GetKeyboardText(InputTextBuf, InputTextBufSize);
		for(unsigned int i=0; i<InputTextBufSize; i++)
		{
			io.AddInputCharacter((unsigned short)InputTextBuf[i]);
		}
		InputTextBuf = 0;
		InputTextBufSize = 0;
	}

	if(event->eventType == vr::VREvent_KeyboardClosed)
	{

	}

}

void ImGui_Impl_VR_ProcessController(vr::TrackedDeviceIndex_t device, vr::VRControllerState_t* state, glm::mat4& M)
{
	if(g_ActiveTexture >= 0 && g_ActiveTexture < 4)
	{
		ImGui::SetCurrentContext(g_Context[g_ActiveTexture]);
	}

	const int left_controller = g_HMD->GetTrackedDeviceIndexForControllerRole(vr::TrackedControllerRole_LeftHand);
	const int right_controller = g_HMD->GetTrackedDeviceIndexForControllerRole(vr::TrackedControllerRole_RightHand);

	if(device == left_controller)
	{
		if(g_Pinned == false)
		{
			g_Mgui = M;
		}
		g_AxisPos[0] = ImVec2(state->rAxis[0].x, state->rAxis[0].y);
	}

	if(device == right_controller)
	{
		g_Mmouse = M;

		if(state->ulButtonTouched & ButtonMaskFromId(vr::k_EButton_SteamVR_Touchpad))
		{
			float new_axis = state->rAxis[0].y;
			if(axis_dragging == true)
			{

				if(g_ActiveTexture >= 0 && g_ActiveTexture < 4)
				{
					ImGuiIO& io = ImGui::GetIO();
					io.MouseWheel += new_axis - last_axis;
				}
			}
			last_axis = new_axis;
			g_AxisPos[1] = ImVec2(state->rAxis[0].x, state->rAxis[0].y);
		}
	}
}

void ImGui_Impl_VR_Poll3dMouse()
{
	//HACK: use ray/tri intersection tests
	const glm::vec3 p0(1.0f, 1.0f, 0.0f);
	const glm::vec3 p1(1.0f, -1.0f, 0.0f);
	const glm::vec3 p2(-1.0f, 1.0f, 0.0f);
	const glm::vec3 p3(-1.0f, -1.0f, 0.0f);

	for(int i=0; i<g_MaxTextures; i++)
	{
		ImGui::SetCurrentContext(g_Context[i]);

		const glm::mat4 M = glm::inverse(g_Mgui*g_MguiScale*g_MguiRotation[i])*g_Mmouse;
		const glm::vec3 start = glm::vec3(M * glm::vec4( 0, 0, -0.02f, 1 ));
		const glm::vec3 end = glm::vec3(M * glm::vec4( 0, 0, -39.f, 1 ));
		const glm::vec3 dir = end-start;

		glm::vec3 b, pt;
		bool intersect = glm::intersectRayTriangle(start, dir, p0, p2, p1, b);
		if(intersect == true)
		{
			pt = start + b.z*dir;
		}
		else if(intersect == false)
		{
			intersect = glm::intersectRayTriangle(start, dir, p3, p1, p2, b);
			if(intersect == true)
			{
				pt = start + b.z*dir;
			}
		}

		if(intersect==true)
		{
			ImGuiIO& io = ImGui::GetIO();
			io.MousePos = ImVec2(g_TexWidth*(0.5f*pt.x + 0.5f), g_TexHeight - g_TexHeight*(0.5f*pt.y + 0.5f));
			g_ActiveTexture = i;
		}
	}
}

void ImGui_Impl_VR_CreateFontsTexture()
{
	// Build texture atlas
    ImGuiIO& io = ImGui::GetIO();
	unsigned char* pixels;
	int width, height;
	io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);   // Load as RGBA 32-bits for OpenGL3 demo because it is more likely to be compatible with user's existing shader.

    // Upload texture to graphics system
    GLint last_texture;
    glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture);
	glGenTextures(1, &g_FontTexture);
	glBindTexture(GL_TEXTURE_2D, g_FontTexture);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels);

	// Store our identifier
	io.Fonts->TexID = (void *)(intptr_t)g_FontTexture;

    // Restore state
    glBindTexture(GL_TEXTURE_2D, last_texture);
}

bool ImGui_Impl_VR_CreateDeviceObjects()
{
	// Backup GL state
	GLint last_texture, last_array_buffer, last_vertex_array;
	glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture);
	glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &last_array_buffer);
	glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &last_vertex_array);

	const GLchar *vertex_shader =
		"#version 330\n"
		"uniform mat4 ProjMtx;\n"
		"in vec2 Position;\n"
		"in vec2 UV;\n"
		"in vec4 Color;\n"
		"out vec2 Frag_UV;\n"
		"out vec4 Frag_Color;\n"
		"void main()\n"
		"{\n"
		"	Frag_UV = UV;\n"
		"	Frag_Color = Color;\n"
		"	gl_Position = ProjMtx * vec4(Position.xy,0,1);\n"
		"}\n";

	const GLchar* fragment_shader =
		"#version 330\n"
		"uniform sampler2D Texture;\n"
		"in vec2 Frag_UV;\n"
		"in vec4 Frag_Color;\n"
		"out vec4 Out_Color;\n"
		"void main()\n"
		"{\n"
		"	Out_Color = Frag_Color * texture( Texture, Frag_UV.st);\n"
		"}\n";

	g_ShaderHandle = glCreateProgram();
	g_VertHandle = glCreateShader(GL_VERTEX_SHADER);
	g_FragHandle = glCreateShader(GL_FRAGMENT_SHADER);
	glShaderSource(g_VertHandle, 1, &vertex_shader, 0);
	glShaderSource(g_FragHandle, 1, &fragment_shader, 0);
	glCompileShader(g_VertHandle);
	glCompileShader(g_FragHandle);
	glAttachShader(g_ShaderHandle, g_VertHandle);
	glAttachShader(g_ShaderHandle, g_FragHandle);
	glLinkProgram(g_ShaderHandle);

	g_AttribLocationTex = glGetUniformLocation(g_ShaderHandle, "Texture");
	g_AttribLocationProjMtx = glGetUniformLocation(g_ShaderHandle, "ProjMtx");
	g_AttribLocationPosition = glGetAttribLocation(g_ShaderHandle, "Position");
	g_AttribLocationUV = glGetAttribLocation(g_ShaderHandle, "UV");
	g_AttribLocationColor = glGetAttribLocation(g_ShaderHandle, "Color");

	glGenBuffers(1, &g_VboHandle);
	glGenBuffers(1, &g_ElementsHandle);

	glGenVertexArrays(1, &g_VaoHandle);
	glBindVertexArray(g_VaoHandle);
	glBindBuffer(GL_ARRAY_BUFFER, g_VboHandle);
	glEnableVertexAttribArray(g_AttribLocationPosition);
	glEnableVertexAttribArray(g_AttribLocationUV);
	glEnableVertexAttribArray(g_AttribLocationColor);

#define OFFSETOF(TYPE, ELEMENT) ((size_t)&(((TYPE *)0)->ELEMENT))
	glVertexAttribPointer(g_AttribLocationPosition, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)OFFSETOF(ImDrawVert, pos));
	glVertexAttribPointer(g_AttribLocationUV, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)OFFSETOF(ImDrawVert, uv));
	glVertexAttribPointer(g_AttribLocationColor, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(ImDrawVert), (GLvoid*)OFFSETOF(ImDrawVert, col));
#undef OFFSETOF

	ImGui_Impl_VR_CreateFontsTexture();

	glGenTextures(g_MaxTextures, g_GuiTexture);
	glActiveTexture(GL_TEXTURE0);
	for(int i=0; i<g_MaxTextures; i++)
	{
		glBindTexture(GL_TEXTURE_2D, g_GuiTexture[i]);
		glTexStorage2D(GL_TEXTURE_2D, 1, GL_RGBA8, g_TexWidth, g_TexHeight);
		glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
		glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
		glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
		glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	}

	glGenFramebuffers(1, &g_GuiFBO);
	glBindFramebuffer(GL_FRAMEBUFFER, g_GuiFBO);
	for(int i=0; i<g_MaxTextures; i++)
	{
		glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0+i, g_GuiTexture[i], 0);
	}
	glBindFramebuffer(GL_FRAMEBUFFER, 0);

	// Restore modified GL state
	glBindTexture(GL_TEXTURE_2D, last_texture);
	glBindBuffer(GL_ARRAY_BUFFER, last_array_buffer);
	glBindVertexArray(last_vertex_array);

	return true;
}

void    ImGui_Impl_VR_InvalidateDeviceObjects()
{
    if (g_VaoHandle) glDeleteVertexArrays(1, &g_VaoHandle);
    if (g_VboHandle) glDeleteBuffers(1, &g_VboHandle);
    if (g_ElementsHandle) glDeleteBuffers(1, &g_ElementsHandle);
    g_VaoHandle = g_VboHandle = g_ElementsHandle = 0;

    glDetachShader(g_ShaderHandle, g_VertHandle);
    glDeleteShader(g_VertHandle);
    g_VertHandle = 0;

    glDetachShader(g_ShaderHandle, g_FragHandle);
    glDeleteShader(g_FragHandle);
    g_FragHandle = 0;

    glDeleteProgram(g_ShaderHandle);
    g_ShaderHandle = 0;

    if (g_FontTexture)
    {
        glDeleteTextures(1, &g_FontTexture);
        ImGui::GetIO().Fonts->TexID = 0;
        g_FontTexture = 0;
    }

	if(g_GuiTexture)
	{
		glDeleteTextures(g_MaxTextures, g_GuiTexture);
	}

	//TODO delete g_GuiFBO
}

bool ImGui_Impl_VR_Init(vr::IVRSystem* hmd, int w, int h)
{
	g_HMD = hmd;
	g_TexWidth = w;
	g_TexHeight = h;

	vr::EVRInitError eError = vr::VRInitError_None;
	g_pScreenShots = ( vr::IVRScreenshots * )vr::VR_GetGenericInterface( vr::IVRScreenshots_Version, &eError );
	g_pOverlay = ( vr::IVROverlay * )vr::VR_GetGenericInterface( vr::IVROverlay_Version, &eError );

	const ImColor title_colors[g_MaxTextures] = {ImColor(1.0f, 0.0f, 0.0f, 1.0f), ImColor(0.0f, 1.0f, 0.0f, 1.0f), ImColor(0.0f, 0.0f, 1.0f, 1.0f), ImColor(1.0f, 0.0f, 1.0f, 1.0f)};
	const ImColor title_active_colors[g_MaxTextures] = {ImColor(0.7f, 0.0f, 0.0f, 1.0f), ImColor(0.0f, 0.7f, 0.0f, 1.0f), ImColor(0.0f, 0.0f, 0.7f, 1.0f), ImColor(0.7f, 0.0f, 0.7f, 1.0f)};

	for(int i=0; i<g_MaxTextures; i++)
	{
		if(i==0)
		{
			g_Context[0] = ImGui::GetCurrentContext();
		}
		else
		{
			g_Context[i] = ImGui::CreateContext();
			ImGui::SetCurrentContext(g_Context[i]);
		}

		ImGuiStyle& style = ImGui::GetStyle();
		style.Colors[ImGuiCol_TitleBg] = title_colors[i];
		style.Colors[ImGuiCol_TitleBgActive] = title_active_colors[i];

		ImGuiIO& io = ImGui::GetIO();
		io.KeyMap[ImGuiKey_Tab] = SDLK_TAB;                     // Keyboard mapping. ImGui will use those indices to peek into the io.KeyDown[] array.
		io.KeyMap[ImGuiKey_LeftArrow] = SDL_SCANCODE_LEFT;
		io.KeyMap[ImGuiKey_RightArrow] = SDL_SCANCODE_RIGHT;
		io.KeyMap[ImGuiKey_UpArrow] = SDL_SCANCODE_UP;
		io.KeyMap[ImGuiKey_DownArrow] = SDL_SCANCODE_DOWN;
		io.KeyMap[ImGuiKey_PageUp] = SDL_SCANCODE_PAGEUP;
		io.KeyMap[ImGuiKey_PageDown] = SDL_SCANCODE_PAGEDOWN;
		io.KeyMap[ImGuiKey_Home] = SDL_SCANCODE_HOME;
		io.KeyMap[ImGuiKey_End] = SDL_SCANCODE_END;
		io.KeyMap[ImGuiKey_Delete] = SDLK_DELETE;
		io.KeyMap[ImGuiKey_Backspace] = SDLK_BACKSPACE;
		io.KeyMap[ImGuiKey_Enter] = SDLK_RETURN;
		io.KeyMap[ImGuiKey_Escape] = SDLK_ESCAPE;
		io.KeyMap[ImGuiKey_A] = SDLK_a;
		io.KeyMap[ImGuiKey_C] = SDLK_c;
		io.KeyMap[ImGuiKey_V] = SDLK_v;
		io.KeyMap[ImGuiKey_X] = SDLK_x;
		io.KeyMap[ImGuiKey_Y] = SDLK_y;
		io.KeyMap[ImGuiKey_Z] = SDLK_z;

		io.RenderDrawListsFn = ImGui_Impl_VR_RenderDrawLists;   // Alternatively you can set this to NULL and call ImGui::GetDrawData() after ImGui::Render() to get the same ImDrawData pointer.
		io.SetClipboardTextFn = ImGui_Impl_VR_SetClipboardText;
		io.GetClipboardTextFn = ImGui_Impl_VR_GetClipboardText;

		io.MouseDrawCursor = true; // let imgui draw the cursor in the HMD
		io.MouseDoubleClickTime = 0.50f;        // Time for a double-click, in seconds.
		io.MouseDoubleClickMaxDist = 8.0f;
		g_Context[i]->MouseCursorData[0].Size = ImVec2(10.0f, 10.0f);
	}

	return true;
}

void ImGui_Impl_VR_Shutdown()
{
    ImGui_Impl_VR_InvalidateDeviceObjects();
	ImGui::Shutdown();
}

void ImGui_Impl_VR_NewFrame(int i)
{
	ImGui::SetCurrentContext(g_Context[i]);
	ImGuiIO& io = ImGui::GetIO();
	if (!g_FontTexture)
	{
		ImGui_Impl_VR_CreateDeviceObjects();
      //HACK this fixes the square block mouse cursor bug
      for (int i = 0; i < g_MaxTextures; i++)
      {
         for (int c = 0; c < ImGuiMouseCursor_Count_; c++)
         {
            g_Context[i]->MouseCursorData[c] = g_Context[0]->MouseCursorData[c];
         }
      }
	}
	else
	{
		io.Fonts->TexID = (void *)(intptr_t)g_FontTexture; //TODO: still getting a square block mouse cursor
	}

	// Setup display size (every frame to accommodate for window resizing)
	io.DisplaySize = ImVec2((float)g_TexWidth, (float)g_TexHeight);
	io.DisplayFramebufferScale = ImVec2(1.0f, 1.0f);

	// Setup time step
	Uint32	time = SDL_GetTicks();
	double current_time = time / 1000.0;
	io.DeltaTime = g_Time > 0.0 ? (float)(current_time - g_Time) : (float)(1.0f / 60.0f);
	g_Time = current_time;

	//setup for render-to-texture
	glEnable(GL_BLEND);
	glDisable(GL_DEPTH_TEST);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

	glGetIntegerv(GL_VIEWPORT, g_LastViewport);
	glViewport(0, 0, g_TexWidth, g_TexHeight);

	glBindFramebuffer(GL_FRAMEBUFFER, g_GuiFBO);

	glDrawBuffer(GL_COLOR_ATTACHMENT0+i);
	float clearcolor[4] = {0.0f, 0.0f, 0.0f, 0.0f};
	glClearBufferfv(GL_COLOR, 0, clearcolor);

	// Start the frame
	ImGui::NewFrame();

}

void PulseIfItemHovered()
{
	static bool anyItemHoveredLastFrame = false;
	static bool anyWindowHoveredLastFrame = false;

	bool anyItemHoveredThisFrame = ImGui::IsAnyItemHovered();
	bool anyWindowHoveredThisFrame = ImGui::IsMouseHoveringAnyWindow();

	if((anyItemHoveredLastFrame != anyItemHoveredThisFrame) || (anyWindowHoveredLastFrame != anyWindowHoveredThisFrame))
	{
		ImGui_Impl_VR_TriggerHapticPulse(1);
	}
	anyItemHoveredLastFrame = anyItemHoveredThisFrame;
	anyWindowHoveredLastFrame = anyWindowHoveredThisFrame;
}

void  ImGui_Impl_VR_Render(int i)
{
		ImGui::SetCurrentContext(g_Context[i]);

		if(g_ActiveTexture == i)
		{
			PulseIfItemHovered(); // haptic pulse if window or item is hovered
		}

		ImGui::Render();

		static bool WantTextInputLastFrame[g_MaxTextures] = {false, false, false, false};
		ImGuiIO& io = ImGui::GetIO();
		if((io.WantTextInput == true)&&(WantTextInputLastFrame[i] == false)&&(InputTextBufSize != 0) && (InputTextBuf != 0))
		{
			g_pOverlay->ShowKeyboard( vr::k_EGamepadTextInputModeNormal, vr::k_EGamepadTextInputLineModeSingleLine, "Virtual Keyboard", InputTextBufSize, InputTextBuf, false, 0 );
		}
		WantTextInputLastFrame[i] = io.WantTextInput;

	glBindFramebuffer(GL_FRAMEBUFFER, 0);
	glDrawBuffer(GL_BACK);
	glEnable(GL_DEPTH_TEST);
	glViewport(g_LastViewport[0], g_LastViewport[1], g_LastViewport[2], g_LastViewport[3]);
}

bool ImGui_Impl_VR_InputText(const char* label, char* buf, size_t buf_size, ImGuiInputTextFlags flags, ImGuiTextEditCallback callback, void* user_data)
{
	bool retval = ImGui::InputText(label, buf, buf_size, flags, callback, user_data);

	if(ImGui::IsItemActive() == true)
	{
		InputTextBuf = buf;
		InputTextBufSize = buf_size;
	}

	if(retval==true)
	{
		printf("");
	}
	return retval;
}


text:
package bio.terra.service.snapshot.exception;

import bio.terra.common.exception.BadRequestException;
import java.util.List;

public class SnapshotExportException extends BadRequestException {
  public SnapshotExportException(String message, List<String> causes) {
    super(message, causes);
  }
}


text:
export interface Properties {
    getTotalLength(): number;
    getPointAtLength(pos: number): Point;
    getTangentAtLength(pos: number): Point;
    getPropertiesAtLength(pos: number): PointProperties;
}
export interface PartProperties {
    start: Point;
    end: Point;
    length: number;
    getPointAtLength(pos: number): Point;
    getTangentAtLength(pos: number): Point;
    getPropertiesAtLength(pos: number): PointProperties;
}
export interface Point {
    x: number;
    y: number;
}
export declare type PointArray = [number, number];
export interface PointProperties {
    x: number;
    y: number;
    tangentX: number;
    tangentY: number;
}
export declare type pathOrders = "a" | "c" | "h" | "l" | "m" | "q" | "s" | "t" | "v" | "z";


text:
require 'spec_helper'

module Argus
  describe NavData do
    Given(:state_bits) { 0xcf8a0c94 }
    Given(:seq_num) { 173064 }
    Given(:vision_flag) { 0 }
    Given(:raw_header) { Bytes.make_header(state_bits, seq_num, vision_flag) }
    Given(:raw_nav_bytes) { Bytes.make_nav_data(raw_header) }

    When(:nav_data) { NavData.new(raw_nav_bytes) }

    Then { nav_data.sequence_number == 173064 }
    Then { nav_data.vision_flag == 0 }
    Then { nav_data.raw == raw_nav_bytes }

    describe "sequence number" do
      Given(:seq_num) { 1234 }
      Then { nav_data.sequence_number == 1234 }
    end

    describe "vision flag" do
      Given(:vision_flag) { 1 }
      Then { nav_data.vision_flag == 1 }
    end

    describe "state queries" do

      def bit(n)
        0x00000001 << n
      end

      # Matcher for handling the mask testing for the state mask.
      #
      # Usage:
      #    bit(5).should be_the_mask_for(:method [, off_value, on_value])
      #
      # If off_value and on_value are not given, then false/true will
      # be assumed.
      #
      matcher :be_the_mask_for do |method, off_result=false, on_result=true|
        match do |mask|
          @msg = "OK"
          try_alternative(method, 0, off_result) &&
            try_alternative(method, mask, on_result)
        end

        failure_message_for_should do |mask|
          @msg
        end

        # Try one of the alternatives. Sending method to the navdata
        # constructed with mask should return teh expected value.
        def try_alternative(method, mask, expected)
          raw = Bytes.make_nav_data(Bytes.make_header(mask, 1, 0))
          nav_data = NavData.new(raw)
          result = nav_data.send(method)
          return true if result == expected
          @msg = "expected mask of 0x#{'%08x' % mask} with #{method}\n" +
            "to return: #{expected.inspect}\n" +
            "got:       #{result.inspect}"
          false
        end
      end

      Then { bit(0).should be_the_mask_for(:flying?) }
      Then { bit(1).should be_the_mask_for(:video_enabled?) }
      Then { bit(2).should be_the_mask_for(:vision_enabled?) }
      Then { bit(3).should be_the_mask_for(:control_algorithm, :euler, :angular_speed) }

      Then { bit(4).should be_the_mask_for(:altitude_control_algorithm_active?) }
      Then { bit(5).should be_the_mask_for(:start_button_pressed?) }
      Then { bit(6).should be_the_mask_for(:control_command_ack?) }
      Then { bit(7).should be_the_mask_for(:camera_ready?) }

      Then { bit(8).should be_the_mask_for(:travelling_enabled?) }
      Then { bit(9).should be_the_mask_for(:usb_ready?) }
      Then { bit(10).should be_the_mask_for(:mode, :all, :demo) }
      Then { bit(11).should be_the_mask_for(:bootstrap?) }

      Then { bit(12).should be_the_mask_for(:moter_problem?) }
      Then { bit(13).should be_the_mask_for(:communication_lost?) }
      Then { bit(14).should be_the_mask_for(:software_fault?) }
      Then { bit(15).should be_the_mask_for(:low_battery?) }

      Then { bit(16).should be_the_mask_for(:emergency_landing_requested?) }
      Then { bit(17).should be_the_mask_for(:timer_elapsed?) }
      Then { bit(18).should be_the_mask_for(:magnometer_needs_calibration?) }
      Then { bit(19).should be_the_mask_for(:angles_out_of_range?) }

      Then { bit(20).should be_the_mask_for(:too_much_wind?) }
      Then { bit(21).should be_the_mask_for(:ultrasonic_sensor_deaf?) }
      Then { bit(22).should be_the_mask_for(:cutout_detected?) }
      Then { bit(23).should be_the_mask_for(:pic_version_number_ok?) }

      Then { bit(24).should be_the_mask_for(:at_codec_thread_on?) }
      Then { bit(25).should be_the_mask_for(:navdata_thread_on?) }
      Then { bit(26).should be_the_mask_for(:video_thread_on?) }
      Then { bit(27).should be_the_mask_for(:acquisition_thread_on?) }

      Then { bit(28).should be_the_mask_for(:control_watchdog_delayed?) }
      Then { bit(29).should be_the_mask_for(:adc_watchdog_delayed?) }
      Then { bit(30).should be_the_mask_for(:com_watchdog_problem?) }
      Then { bit(31).should be_the_mask_for(:emergency_landing?) }
    end

    describe "state mask" do
      context "all zeros" do
        Given(:state_bits) { 0 }
        Then { nav_data.state_mask == state_bits }
      end

      context "non-zero" do
        Given(:state_bits) { 12345 }
        Then { nav_data.state_mask == state_bits }
      end
    end

    describe "#options" do
      Then { nav_data.options.size == 1 }
      Then { nav_data.options.first.is_a?(NavOptionChecksum) }
    end
  end

  describe "multiple options" do
    context "with good data" do
      Given(:raw_header) { Bytes.make_header(0, 0, 0) }
      Given(:raw_nav_bytes) {
        Bytes.make_nav_data(raw_header, Bytes.make_demo_data)
      }
      When(:nav_data) { NavData.new(raw_nav_bytes) }
      Then { nav_data.options.size == 2 }
      Then { nav_data.options[0].is_a?(NavOptionDemo) }
      Then { nav_data.options[1].is_a?(NavOptionChecksum) }
    end

    context "with short data" do
      Given(:raw_nav_bytes) {
        Bytes.make_header(0, 0, 0).pack("C*") +
        [4321, 100, 0].pack("vvV")
      }
      When(:nav_data) { NavData.new(raw_nav_bytes) }
      Then { nav_data.options.size == 1 }
      Then { nav_data.options[0].is_a?(NavOptionUnknown) }
    end
  end

end


text:
//
//  CoreTabsView.m
//  CoreTabsVC
//
//  Created by 冯成林 on 15/3/19.
//  Copyright (c) 2015年 冯成林. All rights reserved.
//

#import "CorePagesView.h"
#import "CorePagesBarView.h"

@interface CorePagesView ()<UIScrollViewDelegate>
{
    CorePagesViewConfig  *_config;
}

@property (strong, nonatomic) IBOutlet CorePagesBarView *pagesBarView;
@property (nonatomic,assign) CGFloat width;

/**
 *  性能优化字典
 */
@property (nonatomic,strong) NSMutableDictionary *indexDict;

/**
 *  本视图所属的控制器
 */
@property (nonatomic,weak) UIViewController *ownerVC;

/**
 *  分页模型数组
 */
@property (nonatomic,strong) NSArray *pageModels;

/**
 *  最大的页码
 */
@property (nonatomic,assign) NSUInteger maxPage;

@property (strong, nonatomic) IBOutlet NSLayoutConstraint *pagesBarViewHConstraint;

@property (nonatomic,assign) CGFloat barH;

@property (nonatomic,assign) CGRect originalFrame;

/**
 *  记录offset的字典
 */
@property (nonatomic,strong) NSMutableDictionary *offsetDict;

/**
 *  记录insets的字典
 */
@property (nonatomic,strong) NSMutableDictionary *insetsDict;

/**
 *  记录出现过的view
 */
@property (nonatomic,strong) NSMutableArray *calViewsM;

/**
 *  页码
 */
@property (nonatomic,assign) NSUInteger page;

/**
 *  减速前的页码
 */
@property (nonatomic,assign) NSUInteger deceleratingPage;

/**
 *  上一次scrollView在didScroll中计算页码所使用的宽度
 */
@property (nonatomic,assign) CGFloat lastCalWidth;

@property (nonatomic,strong) CorePagesViewConfig *config;

@end

@implementation CorePagesView

/**
 *  快速实例化对象
 *
 *  @param ownerVC    本视图所属的控制器
 *  @param pageModels 模型数组
 *  @param config     配置
 *
 *  @return 实例
 */
+(instancetype)viewWithOwnerVC:(UIViewController *)ownerVC pageModels:(NSArray *)pageModels config:(CorePagesViewConfig *)config{

    CorePagesView *pagesView=[[NSBundle mainBundle] loadNibNamed:NSStringFromClass(self) owner:nil options:nil].firstObject;

    dispatch_async(dispatch_get_main_queue(), ^{
        //记录所属控制器
        pagesView.ownerVC=ownerVC;

        //模型数组
        pagesView.pageModels=pageModels;

        //设置配置
        pagesView.config = config;

    });

    return pagesView;
}

-(void)awakeFromNib{

    [super awakeFromNib];

    self.scrollView.pagingEnabled=YES;
    self.scrollView.bounces = NO;

    //注册屏幕旋转
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deviceRotate) name:UIDeviceOrientationDidChangeNotification object:nil];

    //设置scrollView的代理
    self.scrollView.delegate=self;

    //隐藏水平滚动条
    self.scrollView.showsHorizontalScrollIndicator=NO;

    //高度修复
    _pagesBarViewHConstraint.constant =self.config.barViewH;

    //初始化
    self.lastCalWidth=self.width;

    //事件处理
    [self event];

    //设置值
    _scrollView.contentInset =UIEdgeInsetsMake(self.config.barViewH, 0, 0, 0);
    _scrollView.contentOffset = CGPointMake(0, -self.config.barViewH);
    self.pagesBarView.config = self.config;

}

-(void)dealloc{
    //移除通知
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

/**
 *  事件处理
 */
-(void)event{
     __weak typeof(self) weakSelf=self;
    self.pagesBarView.btnActionBlock=^(CorePagesBarBtn *btn,NSUInteger page){
        [weakSelf jumpToPage:page];
    };
}

/**
 *  注册屏幕旋转
 */
-(void)deviceRotate{

    self.pagesBarView.page=self.page;
    [self scrollViewActionWithPage:self.page];
    [self adjustContentSize];
}

-(void)setPageModels:(NSArray *)pageModels{

    _pageModels=pageModels;

    //模型检查
    BOOL res=[CorePageModel modelCheck:pageModels];

    if(!res){

        NSLog(@"您传的pageModels数组格式不正确,请检查!");

        return;
    }

    //数据传递
    self.pagesBarView.pageModels=pageModels;

    //调整contentSize
    [self adjustContentSize];

    //性能优化:最开始只加第一个
    [self handleForPage:0];
}

/**
 *  调整contentSize
 */
-(void)adjustContentSize{
    CGFloat width=self.width;
    CGFloat num=self.pageModels.count;
    if(num<=0) num=1;
    self.scrollView.contentSize=CGSizeMake(width * num, 0);
}

-(void)handleForPage:(NSUInteger)page{

    dispatch_async(dispatch_get_main_queue(), ^{
        CorePageModel *pageModel=_pageModels[page];

        //判断页面是否已经添加
        if(_indexDict!=nil && [_indexDict.allKeys containsObject:@(page)]){
            return;
        }

        //添加子控制器
        [self.ownerVC addChildViewController:pageModel.pageVC];

        //添加视图
        UIView *subView=pageModel.pageVC.view;
        subView.tag=100;

        [self.scrollView addSubview:subView];

        if(subView != nil){

            //字典记录
            [self.indexDict setObject:subView forKey:@(page)];
        }

        [self setNeedsLayout];
    });
}

-(void)layoutSubviews{

    [super layoutSubviews];

    self.originalFrame=self.bounds;

    NSArray *subViews=self.scrollView.subviews;

    CGRect frame=_originalFrame;

    NSUInteger index=0;

    for (NSInteger i=0; i<subViews.count; i++) {

        UIView *subView=subViews[i];

        //非我们的子控件不需要处理
        if([subView isKindOfClass:[UIImageView class]]) continue;

        index=[self findIndex:subView];

        if([subView isKindOfClass:[UIScrollView class]]){
            UIScrollView *scrollView=(UIScrollView *)subView;

            if(![self.calViewsM containsObject:@(index)]){
                //处理insets
                UIEdgeInsets insets=scrollView.contentInset;
                insets.top+=self.barH;
                scrollView.contentInset=insets;

                //处理offset
                CGPoint offset=scrollView.contentOffset;
                offset.y+=-self.barH;
                scrollView.contentOffset=offset;

                //记录subView
                [self.calViewsM addObject:@(index)];
            }

        }else{
            self.scrollView.contentInset=UIEdgeInsetsMake(self.config.barViewH, 0, 0, 0);

            frame.size.height=_originalFrame.size.height - self.config.barViewH;
        }

        frame.origin.x= frame.size.width * index;

        subView.frame=frame;
    }
}

-(NSUInteger)findIndex:(UIView *)subView{

    if(_pageModels==nil || _pageModels.count==0) return 0;

    for (CorePageModel *pageModel in _pageModels) {

        if(pageModel.pageVC.view != subView) continue;

        return [_pageModels indexOfObject:pageModel];
    }

    return 0;
}

-(CGFloat)width{
    return self.bounds.size.width;
}

-(CGFloat)barH{
    return _pagesBarViewHConstraint.constant;
}

-(void)setPage:(NSUInteger)page{

    if(_page==page) return;

    if(page>=self.maxPage) page=self.maxPage;

    if(page <=0) page=0;

    _page=page;

    //页码传递
    self.pagesBarView.page=page;

    if(self.scrollView.isDragging) return;

    //页码处理并加载视图
    [self pageHandle:YES];

    //处理视图生命周期
    [self handleViewLife:YES];
}

/**
 *  页码改变,scrollView做出响应
 */
-(void)scrollViewActionWithPage:(NSUInteger)page{

    CGFloat x =self.width * page;

    CGPoint offset=CGPointMake(x, -self.config.barViewH);

    [UIView animateWithDuration:self.config.animDuration animations:^{
        [self.scrollView setContentOffset:offset animated:NO];
    }];
}

/**
 *  scrollView代理方法区
 */
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{

    CGFloat offsetX=scrollView.contentOffset.x;

    CGFloat width=self.width;

    if(_lastCalWidth != width && _lastCalWidth!=600){

        _lastCalWidth=width;
        return;
    }

    //获取页面
    NSInteger page=(offsetX / width) + .5f;

    self.page=page;

    [self handleForPage:self.page];

    _lastCalWidth=width;
}

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    if(self.scrollView.isDragging) return;
    self.deceleratingPage=self.page;

    //滑动换页的相应delegate
    if ([self.delegate respondsToSelector:@selector(didJumpToPage:)]) {
        [self.delegate didJumpToPage:_page];
    }
}

/**
 *  处理视图生命周期
 */
-(void)handleViewLife:(BOOL)isTopBtnClick{

    //尝试遍历
    [_indexDict enumerateKeysAndObjectsUsingBlock:^(NSNumber *key, UIView *subView, BOOL *stop) {

        if(![key isEqualToNumber:@(_page)]){

            if(isTopBtnClick){
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.4f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    if(!self.scrollView.isDragging){
                        [subView removeFromSuperview];
                    }
                });
            }else{
                if(!self.scrollView.isDragging){
                    [subView removeFromSuperview];
                }
            }

            [_indexDict removeObjectForKey:key];
//            NSLog(@"index=%@的视图被移除",key);

        }else{
//            NSLog(@"index=%@的视图被保留",key);
        }
    }];
}

-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    //页码处理并加载视图
    [self pageHandle:NO];
}

/**
 *  页码处理并加载视图
 */
-(void)pageHandle:(BOOL)topBtnClick{

    if(_pageModels==nil ||_pageModels.count==0) return;

    //取出下一个页面的页码
    NSUInteger prePage=_page-1;
    NSUInteger nowPager=_page;
    NSUInteger nextPage=_page+1;

    if(nextPage >= self.maxPage) nextPage=self.maxPage;
    if(prePage>=self.maxPage-1)prePage=_maxPage-1;

    //取出对应的模型
    if(topBtnClick){
        [self handleForPage:nowPager];
        if ([self.delegate respondsToSelector:@selector(didJumpToPage:)]) {
            [self.delegate didJumpToPage:nowPager];
        }
    }else{
        [self handleForPage:prePage];
        [self handleForPage:nextPage];
    }

}

/**
 *  懒加载
 */
-(NSMutableDictionary *)indexDict{
    if(_indexDict==nil){
        _indexDict=[NSMutableDictionary dictionary];
    }

    return _indexDict;
}

-(NSMutableDictionary *)offsetDict{

    if(_offsetDict==nil){

        _offsetDict=[NSMutableDictionary dictionary];
    }

    return _offsetDict;
}

-(NSMutableDictionary *)insetsDict{

    if(_insetsDict==nil){

        _insetsDict=[NSMutableDictionary dictionary];
    }

    return _insetsDict;
}

-(NSMutableArray *)calViewsM{

    if(_calViewsM==nil){
        _calViewsM=[NSMutableArray array];
    }

    return _calViewsM;
}

-(NSUInteger)maxPage{

    if(_maxPage<=0 && _pageModels!=nil){
        _maxPage=_pageModels.count - 1;
    }

    return _maxPage;
}

-(CorePagesViewConfig *)config{

    if(_config == nil){

        _config = [[CorePagesViewConfig alloc] init];
    }

    return _config;
}

-(void)setConfig:(CorePagesViewConfig *)config{

    _config = config;

    self.pagesBarViewHConstraint.constant = config.barViewH;
    self.pagesBarView.config = config;
}

-(void)setDeceleratingPage:(NSUInteger)deceleratingPage{

    if(_deceleratingPage == deceleratingPage) return;

    _deceleratingPage = deceleratingPage;

    //处理视图生命周期
    [self handleViewLife:NO];
}

/** 中转到指定页码 */
-(void)jumpToPage:(NSUInteger)jumpPage{
    self.page = jumpPage;
    [self scrollViewActionWithPage:self.page];
}

@end


text:
namespace media {

// Static declaration for dictionary keys that we expect to be used inside
// different |MediaLogRecord|s. We declare them here so if they change, its
// only in one spot.
const char MediaLog::kEventKey[] = "event";

MediaLog::MediaLog() : MediaLog(new ParentLogRecord(this)) {}

MediaLog::MediaLog(scoped_refptr<ParentLogRecord> parent_log_record)
    : parent_log_record_(std::move(parent_log_record)) {}

MediaLog::~MediaLog() {
  // If we are the underlying log, then somebody should have called
  // InvalidateLog before now.  Otherwise, there could be concurrent calls into
  // this after we're destroyed.  Note that calling it here isn't really much
  // better, since there could be concurrent calls into the now destroyed
  // derived class.
  //
  // However, we can't DCHECK on it, since lots of folks create a base Medialog
  // implementation temporarily.  So, the best we can do is invalidate the log.
  // We could get around this if we introduce a new NullMediaLog that handles
  // log invalidation, so we could dcheck here.  However, that seems like a lot
  // of boilerplate.
  InvalidateLog();
}

// Default *Locked implementations
void MediaLog::AddLogRecordLocked(std::unique_ptr<MediaLogRecord> event) {}

std::string MediaLog::GetErrorMessageLocked() {
  return "";
}

// Default implementation.
void MediaLog::Stop() {}

void MediaLog::AddMessage(MediaLogMessageLevel level, std::string message) {
  std::unique_ptr<MediaLogRecord> record(
      CreateRecord(MediaLogRecord::Type::kMessage));
  if (!base::IsStringUTF8AllowingNoncharacters(message))
    message = "WARNING: system message could not be rendered!";
  record->params.Set(MediaLogMessageLevelToString(level), std::move(message));
  AddLogRecord(std::move(record));
}

void MediaLog::OnWebMediaPlayerDestroyedLocked() {}
void MediaLog::OnWebMediaPlayerDestroyed() {
  AddEvent<MediaLogEvent::kWebMediaPlayerDestroyed>();
  base::AutoLock auto_lock(parent_log_record_->lock);
  // Forward to the parent log's implementation.
  if (parent_log_record_->media_log)
    parent_log_record_->media_log->OnWebMediaPlayerDestroyedLocked();
}

std::string MediaLog::GetErrorMessage() {
  base::AutoLock auto_lock(parent_log_record_->lock);
  // Forward to the parent log's implementation.
  if (parent_log_record_->media_log)
    return parent_log_record_->media_log->GetErrorMessageLocked();

  return "";
}

std::unique_ptr<MediaLog> MediaLog::Clone() {
  // Protected ctor, so we can't use std::make_unique.
  return base::WrapUnique(new MediaLog(parent_log_record_));
}

void MediaLog::AddLogRecord(std::unique_ptr<MediaLogRecord> record) {
  base::AutoLock auto_lock(parent_log_record_->lock);
  // Forward to the parent log's implementation.
  if (parent_log_record_->media_log)
    parent_log_record_->media_log->AddLogRecordLocked(std::move(record));
}

std::unique_ptr<MediaLogRecord> MediaLog::CreateRecord(
    MediaLogRecord::Type type) {
  auto record = std::make_unique<MediaLogRecord>();
  // Record IDs are populated by event handlers before they are sent to various
  // log viewers, such as the media-internals page, or devtools.
  record->id = 0;
  record->type = type;
  record->time = base::TimeTicks::Now();
  return record;
}

void MediaLog::InvalidateLog() {
  base::AutoLock auto_lock(parent_log_record_->lock);
  // Do nothing if this log didn't create the record, i.e.
  // it's not the parent log. The parent log should invalidate itself.
  if (parent_log_record_->media_log == this)
    parent_log_record_->media_log = nullptr;
  // Keep |parent_log_record_| around, since the lock must keep working.
}

MediaLog::ParentLogRecord::ParentLogRecord(MediaLog* log) : media_log(log) {}
MediaLog::ParentLogRecord::~ParentLogRecord() = default;

LogHelper::LogHelper(MediaLogMessageLevel level, MediaLog* media_log)
    : level_(level), media_log_(media_log) {
  DCHECK(media_log_);
}

LogHelper::LogHelper(MediaLogMessageLevel level,
                     const std::unique_ptr<MediaLog>& media_log)
    : LogHelper(level, media_log.get()) {}

LogHelper::~LogHelper() {
  media_log_->AddMessage(level_, stream_.str());
}

}  //namespace media


text:
package org.apache.hadoop.hbase.mapreduce;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.CellUtil;
import org.apache.hadoop.hbase.HBaseTestingUtility;
import org.apache.hadoop.hbase.testclassification.LargeTests;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.Table;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.util.LauncherSecurityManager;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.util.GenericOptionsParser;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.categories.Category;

/**
 * Basic test for the CopyTable M/R tool
 */
@Category(LargeTests.class)
public class TestCopyTable {
  private static final HBaseTestingUtility TEST_UTIL = new HBaseTestingUtility();
  private static final byte[] ROW1 = Bytes.toBytes("row1");
  private static final byte[] ROW2 = Bytes.toBytes("row2");
  private static final String FAMILY_A_STRING = "a";
  private static final String FAMILY_B_STRING = "b";
  private static final byte[] FAMILY_A = Bytes.toBytes(FAMILY_A_STRING);
  private static final byte[] FAMILY_B = Bytes.toBytes(FAMILY_B_STRING);
  private static final byte[] QUALIFIER = Bytes.toBytes("q");

  @BeforeClass
  public static void beforeClass() throws Exception {
    TEST_UTIL.startMiniCluster(3);
    TEST_UTIL.startMiniMapReduceCluster();
  }

  @AfterClass
  public static void afterClass() throws Exception {
    TEST_UTIL.shutdownMiniMapReduceCluster();
    TEST_UTIL.shutdownMiniCluster();
  }

  private void doCopyTableTest(boolean bulkload) throws Exception {
    final TableName TABLENAME1 = TableName.valueOf("testCopyTable1");
    final TableName TABLENAME2 = TableName.valueOf("testCopyTable2");
    final byte[] FAMILY = Bytes.toBytes("family");
    final byte[] COLUMN1 = Bytes.toBytes("c1");

    Table t1 = TEST_UTIL.createTable(TABLENAME1, FAMILY);
    Table t2 = TEST_UTIL.createTable(TABLENAME2, FAMILY);

    // put rows into the first table
    for (int i = 0; i < 10; i++) {
      Put p = new Put(Bytes.toBytes("row" + i));
      p.add(FAMILY, COLUMN1, COLUMN1);
      t1.put(p);
    }

    CopyTable copy = new CopyTable(TEST_UTIL.getConfiguration());

    int code;
    if (bulkload) {
      code = copy.run(new String[] { "--new.name=" + TABLENAME2.getNameAsString(),
          "--bulkload", TABLENAME1.getNameAsString() });
    } else {
      code = copy.run(new String[] { "--new.name=" + TABLENAME2.getNameAsString(),
          TABLENAME1.getNameAsString() });
    }
    assertEquals("copy job failed", 0, code);

    // verify the data was copied into table 2
    for (int i = 0; i < 10; i++) {
      Get g = new Get(Bytes.toBytes("row" + i));
      Result r = t2.get(g);
      assertEquals(1, r.size());
      assertTrue(CellUtil.matchingQualifier(r.rawCells()[0], COLUMN1));
    }

    t1.close();
    t2.close();
    TEST_UTIL.deleteTable(TABLENAME1);
    TEST_UTIL.deleteTable(TABLENAME2);
  }

  /**
   * Simple end-to-end test
   * @throws Exception
   */
  @Test
  public void testCopyTable() throws Exception {
    doCopyTableTest(false);
  }

  /**
   * Simple end-to-end test with bulkload.
   */
  @Test
  public void testCopyTableWithBulkload() throws Exception {
    doCopyTableTest(true);
  }

  @Test
  public void testStartStopRow() throws Exception {
    final TableName TABLENAME1 = TableName.valueOf("testStartStopRow1");
    final TableName TABLENAME2 = TableName.valueOf("testStartStopRow2");
    final byte[] FAMILY = Bytes.toBytes("family");
    final byte[] COLUMN1 = Bytes.toBytes("c1");
    final byte[] ROW0 = Bytes.toBytes("row0");
    final byte[] ROW1 = Bytes.toBytes("row1");
    final byte[] ROW2 = Bytes.toBytes("row2");

    Table t1 = TEST_UTIL.createTable(TABLENAME1, FAMILY);
    Table t2 = TEST_UTIL.createTable(TABLENAME2, FAMILY);

    // put rows into the first table
    Put p = new Put(ROW0);
    p.add(FAMILY, COLUMN1, COLUMN1);
    t1.put(p);
    p = new Put(ROW1);
    p.add(FAMILY, COLUMN1, COLUMN1);
    t1.put(p);
    p = new Put(ROW2);
    p.add(FAMILY, COLUMN1, COLUMN1);
    t1.put(p);

    CopyTable copy = new CopyTable(TEST_UTIL.getConfiguration());
    assertEquals(
      0,
      copy.run(new String[] { "--new.name=" + TABLENAME2, "--startrow=row1",
          "--stoprow=row2", TABLENAME1.getNameAsString() }));

    // verify the data was copied into table 2
    // row1 exist, row0, row2 do not exist
    Get g = new Get(ROW1);
    Result r = t2.get(g);
    assertEquals(1, r.size());
    assertTrue(CellUtil.matchingQualifier(r.rawCells()[0], COLUMN1));

    g = new Get(ROW0);
    r = t2.get(g);
    assertEquals(0, r.size());

    g = new Get(ROW2);
    r = t2.get(g);
    assertEquals(0, r.size());

    t1.close();
    t2.close();
    TEST_UTIL.deleteTable(TABLENAME1);
    TEST_UTIL.deleteTable(TABLENAME2);
  }

  /**
   * Test copy of table from sourceTable to targetTable all rows from family a
   */
  @Test
  public void testRenameFamily() throws Exception {
    String sourceTable = "sourceTable";
    String targetTable = "targetTable";

    byte[][] families = { FAMILY_A, FAMILY_B };

    Table t = TEST_UTIL.createTable(Bytes.toBytes(sourceTable), families);
    Table t2 = TEST_UTIL.createTable(Bytes.toBytes(targetTable), families);
    Put p = new Put(ROW1);
    p.add(FAMILY_A, QUALIFIER,  Bytes.toBytes("Data11"));
    p.add(FAMILY_B, QUALIFIER,  Bytes.toBytes("Data12"));
    p.add(FAMILY_A, QUALIFIER,  Bytes.toBytes("Data13"));
    t.put(p);
    p = new Put(ROW2);
    p.add(FAMILY_B, QUALIFIER, Bytes.toBytes("Dat21"));
    p.add(FAMILY_A, QUALIFIER, Bytes.toBytes("Data22"));
    p.add(FAMILY_B, QUALIFIER, Bytes.toBytes("Data23"));
    t.put(p);

    long currentTime = System.currentTimeMillis();
    String[] args = new String[] { "--new.name=" + targetTable, "--families=a:b", "--all.cells",
        "--starttime=" + (currentTime - 100000), "--endtime=" + (currentTime + 100000),
        "--versions=1", sourceTable };
    assertNull(t2.get(new Get(ROW1)).getRow());

    assertTrue(runCopy(args));

    assertNotNull(t2.get(new Get(ROW1)).getRow());
    Result res = t2.get(new Get(ROW1));
    byte[] b1 = res.getValue(FAMILY_B, QUALIFIER);
    assertEquals("Data13", new String(b1));
    assertNotNull(t2.get(new Get(ROW2)).getRow());
    res = t2.get(new Get(ROW2));
    b1 = res.getValue(FAMILY_A, QUALIFIER);
    // Data from the family of B is not copied
    assertNull(b1);

  }

  /**
   * Test main method of CopyTable.
   */
  @Test
  public void testMainMethod() throws Exception {
    String[] emptyArgs = { "-h" };
    PrintStream oldWriter = System.err;
    ByteArrayOutputStream data = new ByteArrayOutputStream();
    PrintStream writer = new PrintStream(data);
    System.setErr(writer);
    SecurityManager SECURITY_MANAGER = System.getSecurityManager();
    LauncherSecurityManager newSecurityManager= new LauncherSecurityManager();
    System.setSecurityManager(newSecurityManager);
    try {
      CopyTable.main(emptyArgs);
      fail("should be exit");
    } catch (SecurityException e) {
      assertEquals(1, newSecurityManager.getExitCode());
    } finally {
      System.setErr(oldWriter);
      System.setSecurityManager(SECURITY_MANAGER);
    }
    assertTrue(data.toString().contains("rs.class"));
    // should print usage information
    assertTrue(data.toString().contains("Usage:"));
  }

  private boolean runCopy(String[] args) throws IOException, InterruptedException,
      ClassNotFoundException {
    GenericOptionsParser opts = new GenericOptionsParser(
        new Configuration(TEST_UTIL.getConfiguration()), args);
    Configuration configuration = opts.getConfiguration();
    args = opts.getRemainingArgs();
    Job job = new CopyTable(configuration).createSubmittableJob(args);
    job.waitForCompletion(false);
    return job.isSuccessful();
  }
}


text:
#include "os/os_misc.h"
#include "util/u_format_s3tc.h"
#include "vl/vl_decoder.h"
#include "vl/vl_video_buffer.h"
#include "genhw/genhw.h" /* for GEN6_REG_TIMESTAMP */
#include "intel_winsys.h"

#include "ilo_context.h"
#include "ilo_format.h"
#include "ilo_resource.h"
#include "ilo_transfer.h" /* for ILO_TRANSFER_MAP_BUFFER_ALIGNMENT */
#include "ilo_public.h"
#include "ilo_screen.h"

int ilo_debug;

static const struct debug_named_value ilo_debug_flags[] = {
   { "3d",        ILO_DEBUG_3D,       "Dump 3D commands and states" },
   { "vs",        ILO_DEBUG_VS,       "Dump vertex shaders" },
   { "gs",        ILO_DEBUG_GS,       "Dump geometry shaders" },
   { "fs",        ILO_DEBUG_FS,       "Dump fragment shaders" },
   { "cs",        ILO_DEBUG_CS,       "Dump compute shaders" },
   { "draw",      ILO_DEBUG_DRAW,     "Show draw information" },
   { "flush",     ILO_DEBUG_FLUSH,    "Show batch buffer flushes" },
   { "nohw",      ILO_DEBUG_NOHW,     "Do not send commands to HW" },
   { "nocache",   ILO_DEBUG_NOCACHE,  "Always invalidate HW caches" },
   { "nohiz",     ILO_DEBUG_NOHIZ,    "Disable HiZ" },
   DEBUG_NAMED_VALUE_END
};

static float
ilo_get_paramf(struct pipe_screen *screen, enum pipe_capf param)
{
   switch (param) {
   case PIPE_CAPF_MAX_LINE_WIDTH:
      /* in U3.7, defined in 3DSTATE_SF */
      return 7.0f;
   case PIPE_CAPF_MAX_LINE_WIDTH_AA:
      /* line width minus one, which is reserved for AA region */
      return 6.0f;
   case PIPE_CAPF_MAX_POINT_WIDTH:
      /* in U8.3, defined in 3DSTATE_SF */
      return 255.0f;
   case PIPE_CAPF_MAX_POINT_WIDTH_AA:
      /* same as point width, as we ignore rasterizer->point_smooth */
      return 255.0f;
   case PIPE_CAPF_MAX_TEXTURE_ANISOTROPY:
      /* [2.0, 16.0], defined in SAMPLER_STATE */
      return 16.0f;
   case PIPE_CAPF_MAX_TEXTURE_LOD_BIAS:
      /* [-16.0, 16.0), defined in SAMPLER_STATE */
      return 15.0f;
   case PIPE_CAPF_GUARD_BAND_LEFT:
   case PIPE_CAPF_GUARD_BAND_TOP:
   case PIPE_CAPF_GUARD_BAND_RIGHT:
   case PIPE_CAPF_GUARD_BAND_BOTTOM:
      /* what are these for? */
      return 0.0f;

   default:
      return 0.0f;
   }
}

static int
ilo_get_shader_param(struct pipe_screen *screen, unsigned shader,
                     enum pipe_shader_cap param)
{
   switch (shader) {
   case PIPE_SHADER_FRAGMENT:
   case PIPE_SHADER_VERTEX:
   case PIPE_SHADER_GEOMETRY:
      break;
   default:
      return 0;
   }

   switch (param) {
   /* the limits are copied from the classic driver */
   case PIPE_SHADER_CAP_MAX_INSTRUCTIONS:
      return (shader == PIPE_SHADER_FRAGMENT) ? 1024 : 16384;
   case PIPE_SHADER_CAP_MAX_ALU_INSTRUCTIONS:
      return (shader == PIPE_SHADER_FRAGMENT) ? 1024 : 0;
   case PIPE_SHADER_CAP_MAX_TEX_INSTRUCTIONS:
      return (shader == PIPE_SHADER_FRAGMENT) ? 1024 : 0;
   case PIPE_SHADER_CAP_MAX_TEX_INDIRECTIONS:
      return (shader == PIPE_SHADER_FRAGMENT) ? 1024 : 0;
   case PIPE_SHADER_CAP_MAX_CONTROL_FLOW_DEPTH:
      return UINT_MAX;
   case PIPE_SHADER_CAP_MAX_INPUTS:
      /* this is limited by how many attributes SF can remap */
      return 16;
   case PIPE_SHADER_CAP_MAX_CONST_BUFFER_SIZE:
      return 1024 * sizeof(float[4]);
   case PIPE_SHADER_CAP_MAX_CONST_BUFFERS:
      return ILO_MAX_CONST_BUFFERS;
   case PIPE_SHADER_CAP_MAX_TEMPS:
      return 256;
   case PIPE_SHADER_CAP_MAX_PREDS:
      return 0;
   case PIPE_SHADER_CAP_TGSI_CONT_SUPPORTED:
      return 1;
   case PIPE_SHADER_CAP_INDIRECT_INPUT_ADDR:
      return 0;
   case PIPE_SHADER_CAP_INDIRECT_OUTPUT_ADDR:
      return 0;
   case PIPE_SHADER_CAP_INDIRECT_TEMP_ADDR:
      return (shader == PIPE_SHADER_FRAGMENT) ? 0 : 1;
   case PIPE_SHADER_CAP_INDIRECT_CONST_ADDR:
      return 1;
   case PIPE_SHADER_CAP_SUBROUTINES:
      return 0;
   case PIPE_SHADER_CAP_INTEGERS:
      return 1;
   case PIPE_SHADER_CAP_MAX_TEXTURE_SAMPLERS:
      return ILO_MAX_SAMPLERS;
   case PIPE_SHADER_CAP_MAX_SAMPLER_VIEWS:
      return ILO_MAX_SAMPLER_VIEWS;
   case PIPE_SHADER_CAP_PREFERRED_IR:
      return PIPE_SHADER_IR_TGSI;
   case PIPE_SHADER_CAP_TGSI_SQRT_SUPPORTED:
      return 1;

   default:
      return 0;
   }
}

static int
ilo_get_video_param(struct pipe_screen *screen,
                    enum pipe_video_profile profile,
                    enum pipe_video_entrypoint entrypoint,
                    enum pipe_video_cap param)
{
   switch (param) {
   case PIPE_VIDEO_CAP_SUPPORTED:
      return vl_profile_supported(screen, profile, entrypoint);
   case PIPE_VIDEO_CAP_NPOT_TEXTURES:
      return 1;
   case PIPE_VIDEO_CAP_MAX_WIDTH:
   case PIPE_VIDEO_CAP_MAX_HEIGHT:
      return vl_video_buffer_max_size(screen);
   case PIPE_VIDEO_CAP_PREFERED_FORMAT:
      return PIPE_FORMAT_NV12;
   case PIPE_VIDEO_CAP_PREFERS_INTERLACED:
      return 1;
   case PIPE_VIDEO_CAP_SUPPORTS_PROGRESSIVE:
      return 1;
   case PIPE_VIDEO_CAP_SUPPORTS_INTERLACED:
      return 0;
   case PIPE_VIDEO_CAP_MAX_LEVEL:
      return vl_level_supported(screen, profile);
   default:
      return 0;
   }
}

static int
ilo_get_compute_param(struct pipe_screen *screen,
                      enum pipe_compute_cap param,
                      void *ret)
{
   union {
      const char *ir_target;
      uint64_t grid_dimension;
      uint64_t max_grid_size[3];
      uint64_t max_block_size[3];
      uint64_t max_threads_per_block;
      uint64_t max_global_size;
      uint64_t max_local_size;
      uint64_t max_private_size;
      uint64_t max_input_size;
      uint64_t max_mem_alloc_size;
   } val;
   const void *ptr;
   int size;

   /* XXX some randomly chosen values */
   switch (param) {
   case PIPE_COMPUTE_CAP_IR_TARGET:
      val.ir_target = "ilog";

      ptr = val.ir_target;
      size = strlen(val.ir_target) + 1;
      break;
   case PIPE_COMPUTE_CAP_GRID_DIMENSION:
      val.grid_dimension = Elements(val.max_grid_size);

      ptr = &val.grid_dimension;
      size = sizeof(val.grid_dimension);
      break;
   case PIPE_COMPUTE_CAP_MAX_GRID_SIZE:
      val.max_grid_size[0] = 65535;
      val.max_grid_size[1] = 65535;
      val.max_grid_size[2] = 1;

      ptr = &val.max_grid_size;
      size = sizeof(val.max_grid_size);
      break;
   case PIPE_COMPUTE_CAP_MAX_BLOCK_SIZE:
      val.max_block_size[0] = 512;
      val.max_block_size[1] = 512;
      val.max_block_size[2] = 512;

      ptr = &val.max_block_size;
      size = sizeof(val.max_block_size);
      break;

   case PIPE_COMPUTE_CAP_MAX_THREADS_PER_BLOCK:
      val.max_threads_per_block = 512;

      ptr = &val.max_threads_per_block;
      size = sizeof(val.max_threads_per_block);
      break;
   case PIPE_COMPUTE_CAP_MAX_GLOBAL_SIZE:
      val.max_global_size = 4;

      ptr = &val.max_global_size;
      size = sizeof(val.max_global_size);
      break;
   case PIPE_COMPUTE_CAP_MAX_LOCAL_SIZE:
      val.max_local_size = 64 * 1024;

      ptr = &val.max_local_size;
      size = sizeof(val.max_local_size);
      break;
   case PIPE_COMPUTE_CAP_MAX_PRIVATE_SIZE:
      val.max_private_size = 32768;

      ptr = &val.max_private_size;
      size = sizeof(val.max_private_size);
      break;
   case PIPE_COMPUTE_CAP_MAX_INPUT_SIZE:
      val.max_input_size = 256;

      ptr = &val.max_input_size;
      size = sizeof(val.max_input_size);
      break;
   case PIPE_COMPUTE_CAP_MAX_MEM_ALLOC_SIZE:
      val.max_mem_alloc_size = 128 * 1024 * 1024;

      ptr = &val.max_mem_alloc_size;
      size = sizeof(val.max_mem_alloc_size);
      break;
   default:
      ptr = NULL;
      size = 0;
      break;
   }

   if (ret)
      memcpy(ret, ptr, size);

   return size;
}

static int
ilo_get_param(struct pipe_screen *screen, enum pipe_cap param)
{
   struct ilo_screen *is = ilo_screen(screen);

   switch (param) {
   case PIPE_CAP_NPOT_TEXTURES:
   case PIPE_CAP_TWO_SIDED_STENCIL:
      return true;
   case PIPE_CAP_MAX_DUAL_SOURCE_RENDER_TARGETS:
      return 0; /* TODO */
   case PIPE_CAP_ANISOTROPIC_FILTER:
   case PIPE_CAP_POINT_SPRITE:
      return true;
   case PIPE_CAP_MAX_RENDER_TARGETS:
      return ILO_MAX_DRAW_BUFFERS;
   case PIPE_CAP_OCCLUSION_QUERY:
   case PIPE_CAP_QUERY_TIME_ELAPSED:
   case PIPE_CAP_TEXTURE_SHADOW_MAP:
   case PIPE_CAP_TEXTURE_SWIZZLE: /* must be supported for shadow map */
      return true;
   case PIPE_CAP_MAX_TEXTURE_2D_LEVELS:
      /*
       * As defined in SURFACE_STATE, we have
       *
       *           Max WxHxD for 2D and CUBE     Max WxHxD for 3D
       *  GEN6           8192x8192x512            2048x2048x2048
       *  GEN7         16384x16384x2048           2048x2048x2048
       */
      return (is->dev.gen >= ILO_GEN(7)) ? 15 : 14;
   case PIPE_CAP_MAX_TEXTURE_3D_LEVELS:
      return 12;
   case PIPE_CAP_MAX_TEXTURE_CUBE_LEVELS:
      return (is->dev.gen >= ILO_GEN(7)) ? 15 : 14;
   case PIPE_CAP_TEXTURE_MIRROR_CLAMP:
      return false;
   case PIPE_CAP_BLEND_EQUATION_SEPARATE:
   case PIPE_CAP_SM3:
      return true;
   case PIPE_CAP_MAX_STREAM_OUTPUT_BUFFERS:
      if (is->dev.gen >= ILO_GEN(7) && !is->dev.has_gen7_sol_reset)
         return 0;
      return ILO_MAX_SO_BUFFERS;
   case PIPE_CAP_PRIMITIVE_RESTART:
      return true;
   case PIPE_CAP_INDEP_BLEND_ENABLE:
   case PIPE_CAP_INDEP_BLEND_FUNC:
      return true;
   case PIPE_CAP_MAX_TEXTURE_ARRAY_LAYERS:
      return (is->dev.gen >= ILO_GEN(7)) ? 2048 : 512;
   case PIPE_CAP_TGSI_FS_COORD_ORIGIN_UPPER_LEFT:
   case PIPE_CAP_TGSI_FS_COORD_ORIGIN_LOWER_LEFT:
   case PIPE_CAP_TGSI_FS_COORD_PIXEL_CENTER_HALF_INTEGER:
   case PIPE_CAP_TGSI_FS_COORD_PIXEL_CENTER_INTEGER:
   case PIPE_CAP_DEPTH_CLIP_DISABLE:
      return true;
   case PIPE_CAP_SHADER_STENCIL_EXPORT:
      return false;
   case PIPE_CAP_TGSI_INSTANCEID:
   case PIPE_CAP_VERTEX_ELEMENT_INSTANCE_DIVISOR:
      return true;
   case PIPE_CAP_FRAGMENT_COLOR_CLAMPED:
      return false;
   case PIPE_CAP_MIXED_COLORBUFFER_FORMATS:
      return true;
   case PIPE_CAP_SEAMLESS_CUBE_MAP:
   case PIPE_CAP_SEAMLESS_CUBE_MAP_PER_TEXTURE:
      return true;
   case PIPE_CAP_MIN_TEXTURE_GATHER_OFFSET:
   case PIPE_CAP_MIN_TEXEL_OFFSET:
      return -8;
   case PIPE_CAP_MAX_TEXTURE_GATHER_OFFSET:
   case PIPE_CAP_MAX_TEXEL_OFFSET:
      return 7;
   case PIPE_CAP_CONDITIONAL_RENDER:
   case PIPE_CAP_TEXTURE_BARRIER:
      return true;
   case PIPE_CAP_MAX_STREAM_OUTPUT_SEPARATE_COMPONENTS:
      return ILO_MAX_SO_BINDINGS / ILO_MAX_SO_BUFFERS;
   case PIPE_CAP_MAX_STREAM_OUTPUT_INTERLEAVED_COMPONENTS:
      return ILO_MAX_SO_BINDINGS;
   case PIPE_CAP_STREAM_OUTPUT_PAUSE_RESUME:
      if (is->dev.gen >= ILO_GEN(7))
         return is->dev.has_gen7_sol_reset;
      else
         return false; /* TODO */
   case PIPE_CAP_TGSI_CAN_COMPACT_CONSTANTS:
      return false;
   case PIPE_CAP_VERTEX_COLOR_UNCLAMPED:
      return true;
   case PIPE_CAP_VERTEX_COLOR_CLAMPED:
      return false;
   case PIPE_CAP_GLSL_FEATURE_LEVEL:
      return 140;
   case PIPE_CAP_QUADS_FOLLOW_PROVOKING_VERTEX_CONVENTION:
   case PIPE_CAP_USER_VERTEX_BUFFERS:
      return false;
   case PIPE_CAP_VERTEX_BUFFER_OFFSET_4BYTE_ALIGNED_ONLY:
   case PIPE_CAP_VERTEX_BUFFER_STRIDE_4BYTE_ALIGNED_ONLY:
   case PIPE_CAP_VERTEX_ELEMENT_SRC_OFFSET_4BYTE_ALIGNED_ONLY:
      return false;
   case PIPE_CAP_COMPUTE:
      return false; /* TODO */
   case PIPE_CAP_USER_INDEX_BUFFERS:
   case PIPE_CAP_USER_CONSTANT_BUFFERS:
      return true;
   case PIPE_CAP_CONSTANT_BUFFER_OFFSET_ALIGNMENT:
      /* imposed by OWord (Dual) Block Read */
      return 16;
   case PIPE_CAP_START_INSTANCE:
      return true;
   case PIPE_CAP_QUERY_TIMESTAMP:
      return is->dev.has_timestamp;
   case PIPE_CAP_TEXTURE_MULTISAMPLE:
      return false; /* TODO */
   case PIPE_CAP_MIN_MAP_BUFFER_ALIGNMENT:
      return ILO_TRANSFER_MAP_BUFFER_ALIGNMENT;
   case PIPE_CAP_CUBE_MAP_ARRAY:
   case PIPE_CAP_TEXTURE_BUFFER_OBJECTS:
      return true;
   case PIPE_CAP_TEXTURE_BUFFER_OFFSET_ALIGNMENT:
      return 1;
   case PIPE_CAP_TGSI_TEXCOORD:
      return false;
   case PIPE_CAP_PREFER_BLIT_BASED_TEXTURE_TRANSFER:
   case PIPE_CAP_QUERY_PIPELINE_STATISTICS:
      return true;
   case PIPE_CAP_TEXTURE_BORDER_COLOR_QUIRK:
      return 0;
   case PIPE_CAP_MAX_TEXTURE_BUFFER_SIZE:
      /* a GEN6_SURFTYPE_BUFFER can have up to 2^27 elements */
      return 1 << 27;
   case PIPE_CAP_MAX_VIEWPORTS:
      return ILO_MAX_VIEWPORTS;
   case PIPE_CAP_ENDIANNESS:
      return PIPE_ENDIAN_LITTLE;
   case PIPE_CAP_MIXED_FRAMEBUFFER_SIZES:
      return true;
   case PIPE_CAP_TGSI_VS_LAYER_VIEWPORT:
   case PIPE_CAP_MAX_GEOMETRY_OUTPUT_VERTICES:
   case PIPE_CAP_MAX_GEOMETRY_TOTAL_OUTPUT_COMPONENTS:
   case PIPE_CAP_MAX_TEXTURE_GATHER_COMPONENTS:
   case PIPE_CAP_TEXTURE_GATHER_SM5:
      return 0;
   case PIPE_CAP_BUFFER_MAP_PERSISTENT_COHERENT:
      return true;
   case PIPE_CAP_FAKE_SW_MSAA:
   case PIPE_CAP_TEXTURE_QUERY_LOD:
   case PIPE_CAP_SAMPLE_SHADING:
   case PIPE_CAP_TEXTURE_GATHER_OFFSETS:
   case PIPE_CAP_TGSI_VS_WINDOW_SPACE_POSITION:
   case PIPE_CAP_MAX_VERTEX_STREAMS:
   case PIPE_CAP_DRAW_INDIRECT:
   case PIPE_CAP_TGSI_FS_FINE_DERIVATIVE:
   case PIPE_CAP_CONDITIONAL_RENDER_INVERTED:
      return 0;

   case PIPE_CAP_VENDOR_ID:
      return 0x8086;
   case PIPE_CAP_DEVICE_ID:
      return is->dev.devid;
   case PIPE_CAP_ACCELERATED:
      return true;
   case PIPE_CAP_VIDEO_MEMORY: {
      /* Once a batch uses more than 75% of the maximum mappable size, we
       * assume that there's some fragmentation, and we start doing extra
       * flushing, etc.  That's the big cliff apps will care about.
       */
      const uint64_t gpu_memory = is->dev.aperture_total * 3 / 4;
      uint64_t system_memory;

      if (!os_get_total_physical_memory(&system_memory))
         return 0;

      return (int) (MIN2(gpu_memory, system_memory) >> 20);
   }
   case PIPE_CAP_UMA:
      return true;

   default:
      return 0;
   }
}

static const char *
ilo_get_vendor(struct pipe_screen *screen)
{
   return "LunarG, Inc.";
}

static const char *
ilo_get_name(struct pipe_screen *screen)
{
   struct ilo_screen *is = ilo_screen(screen);
   const char *chipset = NULL;

   if (gen_is_vlv(is->dev.devid)) {
      chipset = "Intel(R) Bay Trail";
   }
   else if (gen_is_hsw(is->dev.devid)) {
      if (gen_is_desktop(is->dev.devid))
         chipset = "Intel(R) Haswell Desktop";
      else if (gen_is_mobile(is->dev.devid))
         chipset = "Intel(R) Haswell Mobile";
      else if (gen_is_server(is->dev.devid))
         chipset = "Intel(R) Haswell Server";
   }
   else if (gen_is_ivb(is->dev.devid)) {
      if (gen_is_desktop(is->dev.devid))
         chipset = "Intel(R) Ivybridge Desktop";
      else if (gen_is_mobile(is->dev.devid))
         chipset = "Intel(R) Ivybridge Mobile";
      else if (gen_is_server(is->dev.devid))
         chipset = "Intel(R) Ivybridge Server";
   }
   else if (gen_is_snb(is->dev.devid)) {
      if (gen_is_desktop(is->dev.devid))
         chipset = "Intel(R) Sandybridge Desktop";
      else if (gen_is_mobile(is->dev.devid))
         chipset = "Intel(R) Sandybridge Mobile";
      else if (gen_is_server(is->dev.devid))
         chipset = "Intel(R) Sandybridge Server";
   }

   if (!chipset)
      chipset = "Unknown Intel Chipset";

   return chipset;
}

static uint64_t
ilo_get_timestamp(struct pipe_screen *screen)
{
   struct ilo_screen *is = ilo_screen(screen);
   union {
      uint64_t val;
      uint32_t dw[2];
   } timestamp;

   intel_winsys_read_reg(is->winsys, GEN6_REG_TIMESTAMP, &timestamp.val);

   /*
    * From the Ivy Bridge PRM, volume 1 part 3, page 107:
    *
    *     "Note: This timestamp register reflects the value of the PCU TSC.
    *      The PCU TSC counts 10ns increments; this timestamp reflects bits
    *      38:3 of the TSC (i.e. 80ns granularity, rolling over every 1.5
    *      hours)."
    *
    * However, it seems dw[0] is garbage and dw[1] contains the lower 32 bits
    * of the timestamp.  We will have to live with a timestamp that rolls over
    * every ~343 seconds.
    *
    * See also brw_get_timestamp().
    */
   return (uint64_t) timestamp.dw[1] * 80;
}

static void
ilo_fence_reference(struct pipe_screen *screen,
                    struct pipe_fence_handle **p,
                    struct pipe_fence_handle *f)
{
   struct ilo_fence *fence = ilo_fence(f);
   struct ilo_fence *old;

   if (likely(p)) {
      old = ilo_fence(*p);
      *p = f;
   }
   else {
      old = NULL;
   }

   STATIC_ASSERT(&((struct ilo_fence *) NULL)->reference == NULL);
   if (pipe_reference(&old->reference, &fence->reference)) {
      if (old->bo)
         intel_bo_unreference(old->bo);
      FREE(old);
   }
}

static boolean
ilo_fence_signalled(struct pipe_screen *screen,
                    struct pipe_fence_handle *f)
{
   struct ilo_fence *fence = ilo_fence(f);

   /* mark signalled if the bo is idle */
   if (fence->bo && !intel_bo_is_busy(fence->bo)) {
      intel_bo_unreference(fence->bo);
      fence->bo = NULL;
   }

   return (fence->bo == NULL);
}

static boolean
ilo_fence_finish(struct pipe_screen *screen,
                 struct pipe_fence_handle *f,
                 uint64_t timeout)
{
   struct ilo_fence *fence = ilo_fence(f);
   const int64_t wait_timeout = (timeout > INT64_MAX) ? -1 : timeout;

   /* already signalled */
   if (!fence->bo)
      return true;

   /* wait and see if it returns error */
   if (intel_bo_wait(fence->bo, wait_timeout))
      return false;

   /* mark signalled */
   intel_bo_unreference(fence->bo);
   fence->bo = NULL;

   return true;
}

/**
 * Create a fence for \p bo.  When \p bo is not NULL, it must be submitted
 * before waited on or checked.
 */
struct ilo_fence *
ilo_fence_create(struct pipe_screen *screen, struct intel_bo *bo)
{
   struct ilo_fence *fence;

   fence = CALLOC_STRUCT(ilo_fence);
   if (!fence)
      return NULL;

   pipe_reference_init(&fence->reference, 1);

   if (bo)
      intel_bo_reference(bo);
   fence->bo = bo;

   return fence;
}

static void
ilo_screen_destroy(struct pipe_screen *screen)
{
   struct ilo_screen *is = ilo_screen(screen);

   /* as it seems, winsys is owned by the screen */
   intel_winsys_destroy(is->winsys);

   FREE(is);
}

static bool
init_dev(struct ilo_dev_info *dev, const struct intel_winsys_info *info)
{
   dev->devid = info->devid;
   dev->aperture_total = info->aperture_total;
   dev->aperture_mappable = info->aperture_mappable;
   dev->max_batch_size = info->max_batch_size;
   dev->has_llc = info->has_llc;
   dev->has_address_swizzling = info->has_address_swizzling;
   dev->has_logical_context = info->has_logical_context;
   dev->has_ppgtt = info->has_ppgtt;
   dev->has_timestamp = info->has_timestamp;
   dev->has_gen7_sol_reset = info->has_gen7_sol_reset;

   if (!dev->has_logical_context) {
      ilo_err("missing hardware logical context support\n");
      return false;
   }

   /*
    * PIPE_CONTROL and MI_* use PPGTT writes on GEN7+ and privileged GGTT
    * writes on GEN6.
    *
    * From the Sandy Bridge PRM, volume 1 part 3, page 101:
    *
    *     "[DevSNB] When Per-Process GTT Enable is set, it is assumed that all
    *      code is in a secure environment, independent of address space.
    *      Under this condition, this bit only specifies the address space
    *      (GGTT or PPGTT). All commands are executed "as-is""
    *
    * We need PPGTT to be enabled on GEN6 too.
    */
   if (!dev->has_ppgtt) {
      /* experiments show that it does not really matter... */
      ilo_warn("PPGTT disabled\n");
   }

   /*
    * From the Sandy Bridge PRM, volume 4 part 2, page 18:
    *
    *     "[DevSNB]: The GT1 product's URB provides 32KB of storage, arranged
    *      as 1024 256-bit rows. The GT2 product's URB provides 64KB of
    *      storage, arranged as 2048 256-bit rows. A row corresponds in size
    *      to an EU GRF register. Read/write access to the URB is generally
    *      supported on a row-granular basis."
    *
    * From the Ivy Bridge PRM, volume 4 part 2, page 17:
    *
    *     "URB Size    URB Rows    URB Rows when SLM Enabled
    *      128k        4096        2048
    *      256k        8096        4096"
    */

   if (gen_is_hsw(info->devid)) {
      dev->gen = ILO_GEN(7.5);
      dev->gt = gen_get_hsw_gt(info->devid);
      dev->urb_size = ((dev->gt == 3) ? 512 :
                       (dev->gt == 2) ? 256 : 128) * 1024;
   }
   else if (gen_is_ivb(info->devid) || gen_is_vlv(info->devid)) {
      dev->gen = ILO_GEN(7);
      dev->gt = (gen_is_ivb(info->devid)) ? gen_get_ivb_gt(info->devid) : 1;
      dev->urb_size = ((dev->gt == 2) ? 256 : 128) * 1024;
   }
   else if (gen_is_snb(info->devid)) {
      dev->gen = ILO_GEN(6);
      dev->gt = gen_get_snb_gt(info->devid);
      dev->urb_size = ((dev->gt == 2) ? 64 : 32) * 1024;
   }
   else {
      ilo_err("unknown GPU generation\n");
      return false;
   }

   return true;
}

struct pipe_screen *
ilo_screen_create(struct intel_winsys *ws)
{
   struct ilo_screen *is;
   const struct intel_winsys_info *info;

   ilo_debug = debug_get_flags_option("ILO_DEBUG", ilo_debug_flags, 0);

   is = CALLOC_STRUCT(ilo_screen);
   if (!is)
      return NULL;

   is->winsys = ws;

   info = intel_winsys_get_info(is->winsys);
   if (!init_dev(&is->dev, info)) {
      FREE(is);
      return NULL;
   }

   util_format_s3tc_init();

   is->base.destroy = ilo_screen_destroy;
   is->base.get_name = ilo_get_name;
   is->base.get_vendor = ilo_get_vendor;
   is->base.get_param = ilo_get_param;
   is->base.get_paramf = ilo_get_paramf;
   is->base.get_shader_param = ilo_get_shader_param;
   is->base.get_video_param = ilo_get_video_param;
   is->base.get_compute_param = ilo_get_compute_param;

   is->base.get_timestamp = ilo_get_timestamp;

   is->base.flush_frontbuffer = NULL;

   is->base.fence_reference = ilo_fence_reference;
   is->base.fence_signalled = ilo_fence_signalled;
   is->base.fence_finish = ilo_fence_finish;

   is->base.get_driver_query_info = NULL;

   ilo_init_format_functions(is);
   ilo_init_context_functions(is);
   ilo_init_resource_functions(is);

   return &is->base;
}


text:
module Fulcrum
  class Photo < MediaResource
    def default_content_type
      'image/jpeg'
    end

    def large(id, &blk)
      download_version(id, 'large', &blk)
    end

    def thumbnail(id, &blk)
      download_version(id, 'thumbnail', &blk)
    end
  end
end


text:
package pl.otwartapw.opw.ws.obwodowa.bean;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.io.Serializable;
import java.util.List;
import pl.otwartapw.opw.ws.obwodowa.entity.OpwObwodowaKomisja;
import pl.otwartapw.opw.ws.obwodowa.entity.OpwUser;
import pl.otwartapw.opw.ws.obwodowa.entity.OpwWynik;

/**
 * Provides access to wynik.
 *
 * @author Adam Kowalewski
 */
@Stateless
public class WynikBean extends AbstractOpwFacade<OpwWynik> implements Serializable {

    private static final Logger logger = LoggerFactory.getLogger(WynikBean.class);

    @PersistenceContext(unitName = PU_OPW)
    private EntityManager em;

    public WynikBean() {
        super(OpwWynik.class);
    }

    @Override
    protected EntityManager getEntityManager() {
        return em;
    }

    /**
     * Increments positive rating by 1.
     *
     * @param wynikId ID of Wynik to increment.
     * @return current counter.
     * @author Adam Kowalewski
     * @version 2015.05.02
     */
    public int ratePositive(int wynikId) {
        OpwWynik wynik = find(wynikId);
        int counter = wynik.getRatedPositiv();
        counter++;
        wynik.setRatedPositiv(counter);
        edit(wynik);
        logger.trace("rated pos wynik {} counter {}", wynikId, counter);
        return counter;
    }

    /**
     * Increments negative rating by 1.
     *
     * @param wynikId ID of Wynik to increment.
     * @return current counter.
     * @author Adam Kowalewski
     * @version 2015.05.02
     */
    public int rateNegative(int wynikId) {
        OpwWynik wynik = find(wynikId);
        int counter = wynik.getRatedNegativ();
        counter++;
        wynik.setRatedNegativ(counter);
        edit(wynik);
        logger.trace("rated neg wynik {} counter {}", wynikId, counter);
        return counter;
    }

    public List<OpwWynik> find(OpwObwodowaKomisja obwodowa) {
        Query q = em.createQuery("SELECT o FROM OpwWynik o WHERE o.opwObwodowaKomisjaId = :obwodowa");
        q.setParameter("obwodowa", obwodowa);
        List<OpwWynik> result = q.getResultList();
        logger.trace("For Obwodowa {} returned {} Wynik records.", obwodowa.getPkwId(), result.size());
        return result;
    }

    /**
     * Returns the number of Wynik uploaded for given Komisja Obwodowa.
     *
     * @param obwodowa Komisja Obwodowa to use.
     * @return number of Wynik in database matching given criteria.
     * @author Adam Kowalewski
     * @version 2015.05.01
     */
    public int countWynik(OpwObwodowaKomisja obwodowa) {
        Query q = em.createQuery("SELECT o FROM OpwWynik o WHERE o.opwObwodowaKomisjaId = :obwodowa");
        q.setParameter("obwodowa", obwodowa);
        int result = q.getResultList().size();
        logger.trace("For Obwodowa {} counted {} Wynik records.", obwodowa.getPkwId(), result);
        return result;
    }

    /**
     * Returns the number of Wynik uploaded by user for Komisja Obwodowa.
     *
     * @param obwodowa Komisja Obwodowa to use.
     * @param user uploader.
     * @return number of Wynik in database matching given criteria.
     * @author Adam Kowalewski
     * @version 2015.05.01
     */
    public int countWynik(OpwObwodowaKomisja obwodowa, OpwUser user) {
        Query q = em.createQuery("SELECT o FROM OpwWynik o WHERE o.opwObwodowaKomisjaId = :obwodowa AND o.opwUserId = :user");
        q.setParameter("obwodowa", obwodowa);
        q.setParameter("user", user);
        int result = q.getResultList().size();
        logger.trace("For Obwodowa {} and user {} counted {} Wynik records.", obwodowa.getPkwId(), user.getEmail(), result);
        return result;
    }

    public List<OpwWynik> fetchCurrentElectionResults() {

        List<OpwWynik> wynikList = findAll();

        for (OpwWynik wynik : wynikList) {

            if (!wynik.getActive()
                    && wynik.getRatedPositiv() < wynik.getRatedNegativ()) {
                wynikList.remove(wynik);
            }
        }

        return wynikList;
    }

}