text:
<?php $this->load->view("newTemp/head.php") ?>
<link href="<?php echo base_url('asserts') ?>/css/jquery.tagit.css" rel="stylesheet" type="text/css">

        <?php $this->load->view("newTemp/navhead.php") ?>

        <?php $this->load->view("newTemp/navside.php") ?>

                                    Inspection Form

                                        <a href="<?php echo base_url() . "index.php/CompanyManage/showHistory/" . $company_id ?>"  >

                            <form role="form" action="<?php echo base_url('index.php/CompanyManage/addHistoryWithFile') ?>" method="post" enctype="multipart/form-data" >

                                        <input type="hidden" name="company_id" value="<?= $company_id ?>">
                                        Objective

Customer Solution

1.1 Product and Application Advisor

Product Solution

2.1 Specialty Product Monitoring

2.2 Trend Prediction Analysis

2.3 Product Optimization & Customization

Service Solution

3.1 On-site Inspection

3.2 Machinery & System Optimization

3.3 Lube Maintenance Program

3.4 Problem Solving

3.5 Lube Technical Survey

Academic Solution

4.1 Training

                                        <input class="form-control" id="objective"  name="objective" >

                                            Visit Date
                                            <input type="text" class="form-control" name="vis_date" id="vis_date" />

                                            Appointment Date
                                            <input type="text" class="form-control " name="app_date" id="app_date" />

                                            <input type="checkbox" name="tentative" id="tentative"  />
                                            Tentative

                                        Tech Services
                                        <input class="form-control" id="team"  name="team" >

                                        Detail
                                        <textarea class="ckeditor form-control" rows="1" name="detail">
                                        </textarea>

                                        Problem Solutions
                                        <textarea class="ckeditor form-control" rows="1" name="pro_sol">
                                        </textarea>

                                        Service
                                        <textarea class="ckeditor form-control" rows="1" name="service">
                                        </textarea>

                                        Recommend Product
                                        <textarea class="ckeditor form-control" rows="1" name="rec_pro">
                                        </textarea>

                                        รูปภาพที่เกี่ยวข้อง

                                                <input  class="form-control" type='file' name='uploadedimages[]' multiple='true'  placeholder="Username">

                                    <button type="submit" class="btn btn-success">Save</button>

                            </form>

<?php $this->load->view("newTemp/script"); ?>
<?php $this->load->view("newTemp/footer"); ?>


text:
package imagedesc

import (
	"fmt"
	"image"
	_ "image/gif"
	_ "image/jpeg"
	_ "image/png"
	"mime"
	"net"
	"net/http"
	"time"
)

const (
	dial_timeo = time.Duration(3) * time.Second
	resp_timeo = time.Duration(5) * time.Second
	rw_timeo   = time.Duration(5) * time.Second
)

func dial_timeout(network, addr string) (net.Conn, error) {
	return net.DialTimeout(network, addr, dial_timeo)
}

func new_timeout_httpclient() *http.Client {
	return &http.Client{
		Transport: &http.Transport{Dial: dial_timeout, ResponseHeaderTimeout: resp_timeo},
	}
}

func NewTimeoutHttpClient(dial_timeo, resp_timeo time.Duration) *http.Client {
	return &http.Client{
		Transport: &http.Transport{
			ResponseHeaderTimeout: resp_timeo,
			Dial: func(network, addr string) (net.Conn, error) {
				return net.DialTimeout(network, addr, dial_timeo)
			},
		},
	}
}

func DetectImageType(uri string) (mediatype string, width, height int, filelength int64, err error) {
	resp, err := new_timeout_httpclient().Get(uri)
	if err != nil {
		return
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		err = fmt.Errorf("%v: %v", resp.StatusCode, http.StatusText(resp.StatusCode))
		return
	}
	filelength = resp.ContentLength
	if resp.ContentLength < 16 && resp.ContentLength >= 0 {
		fmt.Errorf("%v: %v", resp.ContentLength, "content-length insufficient info")
		return
	}
	ct := resp.Header.Get("Content-Type")
	mediatype, _, _ = mime.ParseMediaType(ct)

	ic, mediatype, err := image.DecodeConfig(resp.Body)
	width = ic.Width
	height = ic.Height
	return
}

redpajama_set_name: RedPajamaGithub


text:
import React from 'react';

const IconCircleText = ({label, style, center, className}) => {
  let cls = 'rh-icon-circle-text';

  if (style) {
    cls += '-' + style;
  }

  if (center) {
    cls += ' margin-center';
  }

  if (className) {
    cls += ' ' + className;
  }

  return (

    {label}

);
};

export default IconCircleText;


text:
/**
 * @file Renderer.cpp
 *
 * @author Jan Dušek <xdusek17@stud.fit.vutbr.cz>
 * @date 2013
 */

#include "Renderer.h"

#include "Camera.h"
#include "BaseSceneObject.h"
#include "Light.h"
#include "Logging.h"
#include "Exception.h"
#include "Scene.h"
#include "BoundingBoxDrawer.h"

#include <GL/glew.h>

#include <algorithm>
#include <cassert>

namespace gl {

ShadowMap::ShadowMap(size_t size, std::shared_ptr<ShaderProgram> shader)
	: m_size(size), m_shader(std::move(shader))
{
	glGenFramebuffers(1, &m_fbo);
	glBindFramebuffer(GL_FRAMEBUFFER, m_fbo);

	// create depth buffer texture
	glGenTextures(1, &m_tex);
	glBindTexture(GL_TEXTURE_2D, m_tex);
	glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, size, size, 0, GL_DEPTH_COMPONENT, GL_FLOAT, nullptr);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC, GL_LEQUAL);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_R_TO_TEXTURE);

	// use texture as depth buffer
	glFramebufferTexture(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, m_tex, 0);

	// do not draw color buffer
	glDrawBuffer(GL_NONE);

	if(glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
		throw Exception("glCheckFramebufferStatus returns error");

	glBindFramebuffer(GL_FRAMEBUFFER, 0);
}

ShadowMap::~ShadowMap() {
	glDeleteTextures(1, &m_tex);
	glDeleteFramebuffers(1, &m_fbo);
}

Renderer::Renderer() : m_shadowMappingActive(false), m_showBboxes(false),
	m_scene(nullptr), m_frameID(0) {

}

Renderer::~Renderer() { }

void Renderer::initialize() {
	m_bboxDrawer = std::unique_ptr<BoundingBoxDrawer>(
		new BoundingBoxDrawer(shaderManager()->getGlslProgram("simple"), &m_currentState)
	);

	glEnable(GL_DEPTH_TEST);
}

ShaderManager* Renderer::shaderManager() {
	static ShaderManager manager;
	return &manager;
}

void Renderer::setViewport(const Viewport& viewport) {
	glViewport(static_cast<int>(viewport.x), static_cast<int>(viewport.y),
		static_cast<size_t>(viewport.width), static_cast<size_t>(viewport.height));
	glDepthRange(viewport.znear, viewport.zfar);

	m_viewport = viewport;
}

void Renderer::drawSceneNodeBatches(SceneNode* node) {
	// view frustum culling
	if (m_camera->viewFrustum().boundingBoxIntersetion(node->boundingBox()) == Frustum::Intersection::None)
		return;

	if (m_showBboxes)
		m_bboxDrawer->drawLinedSingle(node->boundingBox());

	if (node->isLeaf()) {
		for (size_t i = 0; i < node->numObjects(); ++i) {
			if (m_showBboxes)
				m_bboxDrawer->drawLinedSingle(node->object(i)->boundingBox());
			drawBatch(m_batches.at(node->object(i)));
		}
	} else {
		drawSceneNodeBatches(node->leftChild());
		drawSceneNodeBatches(node->rightChild());
	}
}

void Renderer::drawSceneNodeGeometry(SceneNode* node) {
	if (node->isLeaf()) {
		for (size_t i = 0; i < node->numObjects(); ++i) {
			drawGeometry(*m_batches.at(node->object(i)).geometry);
		}
	} else {
		drawSceneNodeGeometry(node->leftChild());
		drawSceneNodeGeometry(node->rightChild());
	}
}

void Renderer::drawFrame() {
	m_frameID++;

	// optional shadow map pass
	if (m_shadowMappingActive) {
		drawShadowMap();
	}

	// draw normal forward pass

	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	drawSceneWithOcclussionCulling(m_scene->rootNode());
	//drawSceneNodeBatches(m_scene->rootNode());

	VertexArrayObject::unbind();
}

void Renderer::setCamera(Camera* camera) {
	camera->uniformBuffer()->bind(CAMERA_BINDING_POINT, GL_UNIFORM_BUFFER);
	m_camera = camera;
}

void Renderer::setLight(Light* light) {
	light->uniformBuffer()->bind(LIGHT_BINDING_POINT,  GL_UNIFORM_BUFFER);

	// create shadow map if we don't have one and new light is shadow source.
	if (!m_shadowMappingActive && light->isShadowSource()) {
		m_shadowMap = std::unique_ptr<ShadowMap>(
			new ShadowMap(SHADOW_MAP_SIZE, shaderManager()->getGlslProgram("shadowmap"))
		);

		m_shadowMappingActive = true;
	// release shadow map if light is no longer shadow source.
	} else if (m_shadowMappingActive && !light->isShadowSource()) {
		m_shadowMap = nullptr;
		m_shadowMappingActive = false;
	}
}

void Renderer::setScene(Scene* scene) {
	m_scene = scene;
}

void Renderer::registerSceneObject(ISceneObject* renderable) {
	assert(renderable->material() != nullptr && renderable->mesh() != nullptr);

	RenderBatch batch;
	batch.shader = renderable->material()->shader();
	batch.materialUbo = renderable->material()->uniformBuffer();
	batch.nodeUbo = renderable->uniformBuffer();

	auto mesh = renderable->mesh();
	if (!mesh->isValid()) {
		LOG(ERROR) << "Renderable with invalid mesh registered to renderer.";
		return;
	}

	// create OpenGL geometry i.e. vao, vbo etc.

	auto vbo = std::make_shared<Buffer>();
	vbo->loadData(mesh->vertexData().data(), mesh->vertexData().size());

	auto geom = new GeometryBatch();
	geom->vao().bind();
	geom->setPrimitiveType(mesh->primitiveType());
	geom->setVertices(vbo, mesh->vertexCount(), mesh->vertexLayout());
	if (mesh->isIndexed()) {
		auto ebo = std::make_shared<Buffer>();
		ebo->loadData(mesh->indices().data(), mesh->indices().size() * sizeof(uint32_t));
		geom->setIndices(ebo, GL_UNSIGNED_INT, mesh->indices().size());
	}
	VertexArrayObject::unbind();
	batch.geometry.reset(geom);

	m_batches.insert(std::make_pair(renderable, std::move(batch)));

	// group batches to minimize state changes
	/*std::sort(m_batches.begin(), m_batches.end(), [] (RenderBatch& b1, RenderBatch& b2) {
		if (b1.shader != b2.shader)
			return b1.shader < b2.shader;
		else if (b1.materialUbo != b2.materialUbo)
			return b1.materialUbo < b2.materialUbo;
		else
			return b1.nodeUbo < b2.nodeUbo;
	});*/
}

void Renderer::unregisterSceneObject(ISceneObject* renderable) {
	LOG(ERROR) << "Renderer::unregisterSceneNode not implemented.";
}

void Renderer::drawBatch(RenderBatch& batch) {
	if (batch.shader != m_currentState.shader) {
		batch.shader->use();
		m_currentState.shader = batch.shader;
	}

	if (batch.materialUbo != m_currentState.materialUbo) {
		batch.materialUbo->bind(MATERIAL_BINDING_POINT, GL_UNIFORM_BUFFER);
		m_currentState.materialUbo = batch.materialUbo;
	}

	if (batch.nodeUbo != m_currentState.nodeUbo) {
		batch.nodeUbo->bind(NODE_BINDING_POINT, GL_UNIFORM_BUFFER);
		m_currentState.nodeUbo = batch.nodeUbo;
	}

	// bind shadow map to texture unit
	if (m_shadowMappingActive) {
		glActiveTexture(GL_TEXTURE0 + SHADOW_MAP_BINDING_POINT);
		glBindTexture(GL_TEXTURE_2D, m_shadowMap->depthTexture());
	}

	drawGeometry(*batch.geometry);
}

void Renderer::drawGeometry(GeometryBatch& geom) {
	geom.vao().bind();
	if (geom.hasElements())
		glDrawElements(geom.drawMode(), geom.indexCount(), geom.elementsType(), nullptr);
	else
		glDrawArrays(geom.drawMode(), 0, geom.vertexCount());
}

void Renderer::drawShadowMap() {
	// bind fbo and set its viewport
	glBindFramebuffer(GL_FRAMEBUFFER, m_shadowMap->fbo());
	glViewport(0, 0, m_shadowMap->size(), m_shadowMap->size());

	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	m_shadowMap->shader()->use();
	m_currentState.shader = m_shadowMap->shader();

	// draw only geometry
	drawSceneNodeGeometry(m_scene->rootNode());
	VertexArrayObject::unbind();

	// unbound fbo and set viewport back
	glBindFramebuffer(GL_FRAMEBUFFER, 0);
	glViewport(static_cast<int>(m_viewport.x), static_cast<int>(m_viewport.y),
		static_cast<size_t>(m_viewport.width), static_cast<size_t>(m_viewport.height));
}

void Renderer::drawSceneWithOcclussionCulling(SceneNode* root) {
	traversalStack.push_back(root);
	while (!traversalStack.empty() || !queryQueue.empty()) {
		// process finished queries
		while (!queryQueue.empty() && (queryQueue.front()->query().isResultAvailable() || traversalStack.empty())) {
			// pop node from queue
			auto node = queryQueue.front();
			queryQueue.pop();

			// get query result (will wait to result if traversalStack is empty)
			int visible = GL_FALSE;
			node->query().getResult(&visible);
			if (visible) {
				pullUpVisibility(node);
				traverseNode(node);
			}
		}

		// hierarchical traversal
		if (!traversalStack.empty()) {
			// pop node from stack
			auto node = traversalStack.back();
			traversalStack.pop_back();

			// do frustum culling
			if (m_camera->viewFrustum().boundingBoxIntersetion(node->boundingBox()) != Frustum::Intersection::None) {
				// determine if node was previously visible
				bool wasVisible = node->isVisible() && (node->lastVisited() == m_frameID - 1);

				// update node visibility
				node->setVisibility(false);
				node->setLastVisited(m_frameID);

				// issue query for leafs and previously invisible
				if (node->isLeaf() || !wasVisible) {
					issueQuery(node);
				}

				// always traverse a node when it was visible
				if (wasVisible)
					traverseNode(node);
			}
		}
	}
}

void Renderer::pullUpVisibility(SceneNode* node) {
	while (node && !node->isVisible()) {
		node->setVisibility(true);
		node = node->parent();
	}
}

void Renderer::traverseNode(SceneNode* node) {
	if (m_showBboxes)
		m_bboxDrawer->drawLinedSingle(node->boundingBox());

	if (node->isLeaf()) {
		for (size_t i = 0; i < node->numObjects(); ++i) {
			drawBatch(m_batches.at(node->object(i)));
		}
	} else {
		auto left = node->leftChild();
		auto right = node->rightChild();

		// compute distance from camera position to children bboxes
		float distToLeft = left->boundingBox().distance(m_camera->position());
		float distToRight = right->boundingBox().distance(m_camera->position());

		// push children to stack ... farther child first
		if (distToLeft > distToRight) {
			traversalStack.push_back(left);
			traversalStack.push_back(right);
		} else {
			traversalStack.push_back(right);
			traversalStack.push_back(left);
		}
	}
}

void Renderer::issueQuery(SceneNode* node) {
	// disable writing to depth buffer and color buffer
	glDepthMask(GL_FALSE);
	glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);

	node->query().begin(GL_ANY_SAMPLES_PASSED);
	m_bboxDrawer->drawSingle(node->boundingBox());
	node->query().end(GL_ANY_SAMPLES_PASSED);

	// re enable writing to depth buffer and color buffer
	glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
	glDepthMask(GL_TRUE);

	// push to queue
	queryQueue.push(node);
}

}


text:
import Control.Applicative (liftA3)
import Control.Monad (replicateM)
import Control.Monad.Trans.State
import System.Random

data Die =
      DieOne
    | DieTwo
    | DieThree
    | DieFour
    | DieFive
    | DieSix
    deriving (Eq, Show)

intToDie :: Int -> Die
intToDie n =
    case n of
        1 -> DieOne
        2 -> DieTwo
        3 -> DieThree
        4 -> DieFour
        5 -> DieFive
        6 -> DieSix
        x -> error $ "intToDie got non 1-6 integer: " ++ show x

rollDieThreeTimes :: (Die, Die, Die)
rollDieThreeTimes = do
    let s = mkStdGen 0
        (d1, s1) = randomR (1, 6) s
        (d2, s2) = randomR (1, 6) s1
        (d3, _)  = randomR (1,6) s2
    (intToDie d1, intToDie d2, intToDie d3)

rollDie :: State StdGen Die
rollDie = state $ do
    (n, s) <- randomR (1, 6)
    return (intToDie n, s)

rollDie' :: State StdGen Die
rollDie' = intToDie <$> state (randomR (1,6))

rollDieThreeTimes' :: State StdGen (Die, Die, Die)
rollDieThreeTimes' = liftA3 (,,) rollDie rollDie rollDie

-- infiniteDie doesn't really work, it just repeats the first roll infinite times

infiniteDie :: State StdGen [Die]
infiniteDie = repeat <$> rollDie

-- nDie gives us what we want, rolls the die n times, with new state each time

nDie :: Int -> State StdGen [Die]
nDie n = replicateM n rollDie

rollsToGetTwenty :: StdGen -> Int
rollsToGetTwenty g = go 0 0 g
    where go :: Int -> Int -> StdGen -> Int
          go sum count gen
            | sum >= 20 = count
            | otherwise =
                let (die, nextGen) = randomR (1,6) gen
                in go (sum + die) (count + 1) nextGen

-- use randomIO to not have to make a StdGen each time:

rolls = (rollsToGetTwenty . mkStdGen) <$> randomIO

rollsToGetN :: Int -> StdGen -> Int
rollsToGetN n g = go 0 0 g
    where go :: Int -> Int -> StdGen -> Int
          go sum count gen
            | sum >= n = count
            | otherwise =
                let (die, nextGen) = randomR (1,6) gen
                in go (sum + die) (count + 1) nextGen

rolls' :: Int -> IO [Die]
rolls' n = evalState (nDie n) . mkStdGen <$> randomIO

rollsCountLogged :: Int -> StdGen -> (Int, [Die])
rollsCountLogged n g = go 0 0 g []
    where go :: Int -> Int -> StdGen -> [Die] -> (Int, [Die])
          go sum count gen ds
            | sum >= n = (count, ds)
            | otherwise =
                let (die, nextGen) = randomR (1,6) gen
                in go (sum + die) (count + 1) nextGen (ds ++ [intToDie die])


text:
Copyright 2015 The Luvit Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

--]]

local http = require('http')
local string = require('string')

local HOST = "127.0.0.1"
local PORT = process.env.PORT or 10080
local server = nil
local client = nil

local a = string.rep('a', 1024)
local data = string.rep(a, 1024)
local MB = data:len()

require('tap')(function(test)
  test('http-post-1mb', function(expect)
    server = http.createServer(function(request, response)
      p('server:onConnection')
      local postBuffer = ''
      assert(request.method == "POST")
      assert(request.url == "/foo")
      assert(request.headers.bar == "cats")
      request:on('data', function(chunk)
        postBuffer = postBuffer .. chunk
      end)
      request:on('end', expect(function()
        p('server:onEnd')
        assert(postBuffer == data)
        response:write(data)
        response:finish()
      end))
    end)

    server:listen(PORT, HOST, function()
      local headers = {
        {'bar', 'cats'},
        {'Content-Length', MB},
        {'Transfer-Encoding', 'chunked'}
      }
      local req = http.request({
        host = HOST,
        port = PORT,
        method = 'POST',
        path = "/foo",
        headers = headers
      }, function(response)
        assert(response.statusCode == 200)
        assert(response.httpVersion == '1.1')
        response:on('data', expect(function(data)
          assert(data:len() == MB)
          p('All data received')
        end))
        response:on('end', expect(function(data)
          p('Response ended')
          server:close()
        end))
      end)
      req:write(data)
      req:done()
    end)
  end)
end)


text:
namespace PIM.Service.Services
{
    using PIM.Database.Cruds;
    using PIM.Database.Infra;
    using PIM.Database.TO;
    using PIM.Service.Infra;
    using System;
    using System.Linq;

    public static class ColaboradorService
    {
        private static ColaboradorCrud _Crud;

        public static void Atualizar(ColaboradorTO entidadeTO)
        {
            _Crud = CrudService<ColaboradorCrud>.ObterInstancia();
            _Crud.Atualizar(entidadeTO);
        }

        public static void Criar(ColaboradorTO entidadeTO)
        {
            _Crud = CrudService<ColaboradorCrud>.ObterInstancia();
            _Crud.Cadastrar(entidadeTO);
        }

        public static ColaboradorTO Obter(int identificador)
        {
            _Crud = CrudService<ColaboradorCrud>.ObterInstancia();
            return _Crud.Obter(identificador);
        }

        public static RetornoTO Remover(int identificador)
        {
            _Crud = CrudService<ColaboradorCrud>.ObterInstancia();
            return _Crud.Remover(identificador);
        }

        public static ListaColaboradorTO Listar()
        {
            _Crud = CrudService<ColaboradorCrud>.ObterInstancia();
            return _Crud.Listar();
        }

        public static ListaColaboradorTO PesquisarPorNome(string nomeColaborador)
        {
            _Crud = CrudService<ColaboradorCrud>.ObterInstancia();
            ListaColaboradorTO retorno = new ListaColaboradorTO();

            try
            {
                retorno = _Crud.Listar();

                if (retorno.Valido)
                {
                    retorno.Lista = retorno.Lista.Where(x => x.Nome.Contains(nomeColaborador)).ToList();
                }
            }
            catch (Exception ex)
            {
                retorno.Valido = false;
                retorno.Mensagem = string.Format("Erro: {0}", ex.Message);
            }

            return retorno;
        }

        public static ListaColaboradorTO PesquisarPorFuncao(string funcao)
        {
            _Crud = CrudService<ColaboradorCrud>.ObterInstancia();
            ListaColaboradorTO retorno = new ListaColaboradorTO();

            try
            {
                retorno = _Crud.Listar();

                if (retorno.Valido)
                {
                    retorno.Lista = retorno.Lista.Where(x => x.Funcao.Contains(funcao)).ToList();
                }
            }
            catch (Exception ex)
            {
                retorno.Valido = false;
                retorno.Mensagem = string.Format("Erro: {0}", ex.Message);
            }

            return retorno;
        }

    }
}


text:
/*
 * $Id$
 */

/*

Copyright (c) 2000-2008 Board of Trustees of Leland Stanford Jr. University,
all rights reserved.

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

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

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

Except as contained in this notice, the name of Stanford University shall not
be used in advertising or otherwise to promote the sale, use or other dealings
in this Software without prior written authorization from Stanford University.

*/

package org.lockss.scheduler;

import java.util.*;

import org.lockss.config.*;
import org.lockss.util.*;

/** This scheduler assigns tasks to intervals preferentially based on their
 * finish time */
public class SortScheduler implements Scheduler {
  protected static Logger log = Logger.getLogger("Scheduler");

  static final String PREFIX = Configuration.PREFIX + "scheduler.";

  /** Maximum cumulative load, over time, that background tasks are allowed
   * to consume */
  public static final String PARAM_MAX_BACKGROUND_LOAD =
    PREFIX + "maxBackgroundLoad";
  public static final double DEFAULT_MAX_BACKGROUND_LOAD = 1.0;

  /** Fraction of CPU time that is assumed to be consumed by threads other
   * than StepThread */
  public static final String PARAM_OVERHEAD_LOAD = PREFIX + "overheadLoad";
  public static final double DEFAULT_OVERHEAD_LOAD = 0.2;

  // Vars that should not be reset between invocations
  final double maxBackgroundLoad;
  final double overheadLoad;

  // Vars that should be reset between invocations
  Collection<SchedulableTask> rawTasks;
  TaskData tdarr[];
  SchedInterval intervals[];
  int nIntervals;
  List ranges = new ArrayList();
  Set unscheduledTasks;
  boolean scheduleCreated;
  Deadline scheduledAt;

  private void resetVars() {
    rawTasks = null;
    tdarr = null;
    intervals = null;
    nIntervals = 0;
    ranges = new ArrayList();
    unscheduledTasks = null;
    scheduleCreated = false;
    scheduledAt = null;
  }

  /** Create a scheduler */
  public SortScheduler() {
    Configuration config = CurrentConfig.getCurrentConfig();
    maxBackgroundLoad = config.getPercentage(PARAM_MAX_BACKGROUND_LOAD,
					     DEFAULT_MAX_BACKGROUND_LOAD);
    overheadLoad = config.getPercentage(PARAM_OVERHEAD_LOAD,
					DEFAULT_OVERHEAD_LOAD);
  }

  /** Create a scheduler to schedule the collection of tasks */
  SortScheduler(Collection tasks) {
    this();
    rawTasks = tasks;
  }

  void setTasks(Collection tasks) {
    resetVars();
    rawTasks = tasks;
  }

  /** Store list of tasks to schedule, check validity, move times in the
   * past up to now. */
  private boolean initTasks() {
    unscheduledTasks = new HashSet(rawTasks);
    tdarr = new TaskData[rawTasks.size()];
    if (scheduledAt == null) {
      // can happen during testing
      scheduledAt = Deadline.in(0);
    }
    Deadline now = scheduledAt ;
    int tdix = 0;
    for (SchedulableTask rawTask : rawTasks) {
      if (!rawTask.isProperWindow()) {
	log.warning("Task has improper window: " + rawTask);
	throw new IllegalArgumentException("Task has improper window");
      }

      // make a TaskData whose start time is no earlier than now
      TaskData td;
      if (rawTask.getEarliestStart().before(now)) {
	td = new TaskData(rawTask, now);
      } else {
	td = new TaskData(rawTask);
      }
      // fail now if task can't finish
      if (td.getWSize() <= 0) {
	log.warning("initTasks: expired task: " + td);
	return false;
      }
      tdarr[tdix++] = td;
    }
    scheduleCreated = false;
    return true;
  }

  public boolean createSchedule(Collection tasks) {
    setTasks(tasks);
    return createSchedule();
  }

  public boolean createSchedule() {
    if (log.isDebug2())
      log.debug2("createSchedule: " + rawTasks.size() + " tasks");
    scheduledAt = Deadline.in(0);
    scheduleCreated = initIntervals() &&
      scheduleAll();
    return scheduleCreated;
  }

  public Collection<SchedulableTask> getTasks() {
    return rawTasks;
  }

  /** Set all the tasks in this scheduler as having been accepted */
  public void acceptTasks() {
    for (SchedulableTask task : rawTasks) {
      task.setAccepted(true);
    }
  }

  public Schedule getSchedule() {
    if (!scheduleCreated) {
      throw new IllegalStateException("Attempt to get nonexistent schedule");
    }
    List<Schedule.Event> events = new ArrayList();
    for (int xintr = 0; xintr < nIntervals; xintr++) {
      SchedInterval intrvl = intervals[xintr];
      intrvl.addEvents(events);
    }
    if (log.isDebug2()) {
      for (Schedule.Event event : events) {
	log.debug2("  " + event.toString());
      }
    }
    Schedule res = new Schedule(events, unscheduledTasks);
    res.setScheduler(this);
    return res;
  }

  // find all task boundaries and create intervals between them
  boolean initIntervals() {
    if (!initTasks()) {
      return false;
    }
    if (tdarr == null || tdarr.length == 0) {
      intervals = null;
      return true;
    }
    TreeMap bdTasks = new TreeMap();
    for (TaskData td : tdarr) {
      getBoundaryTasks(bdTasks, td.getWStart()).addStartingTask(td);
      getBoundaryTasks(bdTasks, td.getWEnd()).addEndingTask(td);
    }
    nIntervals = bdTasks.size() - 1;
    intervals = new SchedInterval[nIntervals];

    long cumBackTime = 0;		// cumulative background time
    Set<TaskData> cumBackTasks = new HashSet();
    Set<TaskData> cumForeTasks = new HashSet();
    boolean seenNewTask = false;
    int ix = 0;
    Iterator beIter = bdTasks.entrySet().iterator();
    Map.Entry lentry = (Map.Entry)beIter.next();
    Deadline lower = (Deadline)lentry.getKey();
    BoundaryTasks lbt = (BoundaryTasks)lentry.getValue();
    while (beIter.hasNext()) {
      Map.Entry uentry = (Map.Entry)beIter.next();
      Deadline upper = (Deadline)uentry.getKey();
      BoundaryTasks ubt = (BoundaryTasks)uentry.getValue();
      SchedInterval intrvl = new SchedInterval(lower, upper);
      intervals[ix++] = intrvl;
      if (!cumBackTasks.isEmpty()) {
	for (TaskData btd : cumBackTasks) {
	  BackgroundTask btask = (BackgroundTask)btd.task;
	  intrvl.loadFactor -= btask.getLoadFactor();
	  intrvl.backgroundTaskList.add(btd);
	}
      }
      if (lbt.startingTasks != null) {
	for (TaskData std : lbt.startingTasks) {
	  if (!std.isAccepted()) {
	    seenNewTask = true;
	  }
	  if (std.task.isBackgroundTask()) {
	    BackgroundTask btask = (BackgroundTask)std.task;
	    intrvl.loadFactor -= btask.getLoadFactor();
	    if (log.isDebug3())
	      log.debug3("reduced " + intrvl + " by " + btask.getLoadFactor());
	    intrvl.backgroundTaskList.add(std);
	    cumBackTasks.add(std);
	  } else {
	    cumForeTasks.add(std);
	  }
	}
      }
      intrvl.competingTaskList = new ArrayList(cumForeTasks);
      intrvl.seenNewTask = seenNewTask;
      if (intrvl.loadFactor < 0.0) {
	if (log.isDebug2())
	  log.debug2("initIntrTskList: loadFactor < 0: " + intrvl);
	return false;
      }

      if (ubt.endingTasks != null) {
	for (TaskData etd : ubt.endingTasks) {
	  if (etd.task.isBackgroundTask()) {
	    cumBackTasks.remove(etd);
	  } else {
	    intrvl.addEndingTask(etd);
	    cumForeTasks.remove(etd);
	  }
	}
      }
      intrvl.cumBackTime = cumBackTime;
      cumBackTime += intrvl.backgroundTime();

      lower = upper;
      lbt = ubt;
    }
    if (log.isDebug3()) {
      log.debug3(nIntervals + " intervals: " + arrayString(intervals));
    }
    return true;
  }

  BoundaryTasks getBoundaryTasks(TreeMap bdTasks, Deadline time) {
    BoundaryTasks bt = (BoundaryTasks)bdTasks.get(time);
    if (bt == null) {
      bt = new BoundaryTasks();
      bdTasks.put(time, bt);
    }
    return bt;
  }

  static class BoundaryTasks {
    List<TaskData> startingTasks;
    List<TaskData> endingTasks;

    void addStartingTask(TaskData td) {
      if (startingTasks == null) {
	startingTasks = new ArrayList();
      }
      startingTasks.add(td);
    }

    void addEndingTask(TaskData td) {
      if (endingTasks == null) {
	endingTasks = new ArrayList();
      }
      endingTasks.add(td);
    }
  }

  // Divide into groups of intervals with no overlapping tasks, schedule
  // each group
  boolean scheduleAll() {
    SchedInterval prev = null;
    int xfirst = -1;
    for (int ix = 0; ix < nIntervals; ix++) {
      SchedInterval intrvl = intervals[ix];
      if (prev == null) {
	if (intrvl.hasTasks()) {
	  xfirst = ix;
	  prev = intrvl;
	}
      } else {
	if ((!intrvl.hasTasks()) ||
	    CollectionUtil.isDisjoint(prev.competingTaskList,
				      intrvl.competingTaskList)) {
	  if (! scheduleIntervalRange(xfirst, ix - 1)) {
	    return false;
	  }
	  prev = null;
	  xfirst = -1;
	} else {
	  prev = intrvl;
	}
      }
    }
    if (prev != null) {
      if (!scheduleIntervalRange(xfirst, nIntervals - 1)) {
	return false;
      }
    }
    return true;
  }

  boolean scheduleIntervalRange(int first, int last) {
    IntervalRange rng = new IntervalRange(intervals, first, last);
    ranges.add(rng);
    return rng.scheduleIntervalRange();
  }

  /** Using the previously created intervals, find the earliest possible
   * time a background task could be scheduled.  This is only a hint; it
   * may not be possible to schedule the task then.
   * @param task a Background task specifying the duration, load factor and
   * earliest desired start time.
   * @return The BackgroundTask (the same one) with possibly updated start
   * and finish times when it might be schedulable. */
  public BackgroundTask scheduleHint(BackgroundTask task) {
    long start = task.getStart().getExpirationTime();
    long finish = task.getFinish().getExpirationTime();
    long duration = finish - start;
    double loadFactor = task.getLoadFactor();
    for (int xintr = 0; xintr < nIntervals; xintr++) {
      SchedInterval intrvl = intervals[xintr];
      if (intrvl.getEnd().getExpirationTime() <= start) {
	continue;
      }
      if (intrvl.getBegin().getExpirationTime() >= finish) {
	break;
      }
      if (intrvl.loadFactor < loadFactor) {
	// can't run at all during this interval, next possible start is
	// end of interval
	start = intrvl.getEnd().getExpirationTime();
	finish = start + duration;
      }
      double cumBackLoad = 0.0;
      if (intrvl.cumBackTime != 0) {
	cumBackLoad = ((double)intrvl.cumBackTime /
		       ((double)intrvl.getBegin().minus(scheduledAt)));
      }
      if (cumBackLoad >= maxBackgroundLoad) {
	// average background load too high, push start back until load
	// would be low enough
	start =
	  Math.max(start, (scheduledAt.getExpirationTime() +
			   (long)((intrvl.cumBackTime +
				   intrvl.backgroundTime()) /
				  maxBackgroundLoad)));
	finish = start + duration;
	if (log.isDebug2()) {
	  log.debug2("Hint, delaying from " + intrvl.getEnd().shortString() +
		     " to " + Deadline.at(start).shortString());
	}
      }
    }
    task.setInterval(Deadline.at(start), Deadline.at(finish));
    return task;
  }

  static protected String arrayString(Object[] a) {
    return StringUtil.separatedString(a, ", ");
  }
  static protected String arrayString(long[] a) {
    return StringUtil.separatedString(objArray(a), ", ");
  }

  static protected Object[] objArray(long[] a) {
    Object[] o = new Object[a.length];
    for (int ix = 0; ix < a.length; ix++) {
      o[ix] = new Long(a[ix]);
    }
    return o;
  }

  static protected Object[] objArray(int[] a) {
    Object[] o = new Object[a.length];
    for (int ix = 0; ix < a.length; ix++) {
      o[ix] = new Integer(a[ix]);
    }
    return o;
  }

  //********************* Nested classes *********************

  /** Struct to keep track of task time remaining to be scheduled.  (Need
      per task, and can't modify actual SchedulableTask. */
  static class TaskData {
    private static int nextSeq = 0;	 // See _endTimeComparator.

    SchedulableTask task;
    Interval window;
    long totalTime;
    long unschedTaskTime;		 // remaining unscheduled time
    int seq = nextSeq++;		 // See _endTimeComparator.

    TaskData(SchedulableTask t, Deadline earliestStart) {
      task = t;
      window = new Interval(earliestStart, t.getLatestFinish());
      reset();
    }

    TaskData(SchedulableTask t) {
      task = t;
      window = t.getWindow();
      reset();
    }

    /** Reset unschedTaskTime to totalTime */
    void reset() {
      this.totalTime = task.curEst();
      unschedTaskTime = totalTime;
      if (task.isDropped()) {
	unschedTaskTime = 0;
      }
    }

    /** Return (possibly modified) execution window */
    Interval getWindow() {
      return window;
    }

    /** Return (possibly modified) start of execution window */
    Deadline getWStart() {
      return (Deadline)window.getLB();
    }

    /** Return (possibly modified) end of execution window */
    Deadline getWEnd() {
      return (Deadline)window.getUB();
    }

    /** Return size of (possibly modified) execution window */
    long getWSize() {
      return getWEnd().minus(getWStart());
    }

    public boolean isAccepted() {
      return task.isAccepted();
    }

    public String toString() {
      return "[TD: t=" + task + "]";
    }

    public int hashCode() {
      return task.hashCode();
    }

    public boolean equals(Object o) {
      if (o instanceof TaskData) {
	TaskData td = (TaskData)o;
	return task.equals(td.task);
      }
      return false;
    }

    /** Comparator for ordering tasks by ending deadline */
    private static final Comparator _endTimeComparator =
      new Comparator() {
	public int compare(Object o1, Object o2) {
	  TaskData t1 = (TaskData)o1;
	  TaskData t2 = (TaskData)o2;
	  int res = t1.getWEnd().compareTo(t2.getWEnd());
	  if (res == 0) {
	    // If the end times are equal, sort by creation order.  A
	    // consistent (repeatable) sort order is useful so unit tests
	    // can predict which of several possible schedules will be
	    // created.
	    res = t1.seq - t2.seq;
	  }
	  return res;
	}};

    /** Return a comparator for ordering tasks by ending deadline */
    public static Comparator endTimeComparator() {
      return _endTimeComparator;
    }
  }

  /** Struct representing an interval in which tasks can be placed, during
   * which no task window boundaries occur. */
  class SchedInterval extends Interval {
    long duration;			// length of interval
    long unscheduledTime;		// available cpu time (adjusted for
					// load factor)
    long cumBackTime;			// cumulative scheduled background
					// time at the start of this
					// interval, for calculating
					// average background time
    List competingTaskList;
    List<TaskData> backgroundTaskList = new ArrayList();
    List endingTaskList;
    TaskData[] endingTasks;
    List<Schedule.Chunk> chunks;	// scheduled chunks (result)
    boolean seenNewTask = false;

    double loadFactor = 1.0;

    SchedInterval(Deadline begin, Deadline end) {
      super(begin, end);
      duration = end.minus(begin);
      if (duration < 0) {
	throw new RuntimeException("Illegal SchedInterval, "
				   + end + " before " + begin);
      }
    }

    Deadline getBegin() {
      return (Deadline)getLB();
    }

    Deadline getEnd() {
      return (Deadline)getUB();
    }

    long backgroundTime() {
      return (long)(duration * (1.0 - loadFactor));
    }

    /** Return true if any tasks are available to run during this interval */
    boolean hasTasks() {
      return !competingTaskList.isEmpty();
    }

    void addEndingTask(TaskData td) {
      if (endingTaskList == null) {
	endingTaskList = new ArrayList();
      }
      endingTaskList.add(td);
    }

    /** Add Schedule.Events for all background events and chunks in this
     * interval.  Starting background tasks first (because they must happen
     * at the beginning of the interval), then step chunks, then ending
     * background events * (because they must happen at the end of the
     * interval).
     * @param events the event list to add to.
     */
    void addEvents(List events) {
      addStartingBackgroundEvents(events);
      if (chunks != null) {
	for (Schedule.Chunk chunk : chunks) {
	  addChunk(events, chunk);
	}
      }
      addEndingBackgroundEvents(events);
    }

    void addStartingBackgroundEvents(List events) {
      for (TaskData td : backgroundTaskList) {
	BackgroundTask task = (BackgroundTask)td.task;
	// important to use td start, not task start, to ensure produce
	// start event for task whose start is in the past.
	if (td.getWStart().equals(getBegin())) {
	  Schedule.BackgroundEvent event =
	    new Schedule.BackgroundEvent(task, getBegin(),
					 Schedule.EventType.START);
	  events.add(event);
	  unscheduledTasks.remove(task);
	}
      }
    }

    void addEndingBackgroundEvents(List events) {
      for (TaskData td : backgroundTaskList) {
	BackgroundTask task = (BackgroundTask)td.task;
	if (task.getFinish().equals(getEnd())) {
	  Schedule.BackgroundEvent event =
	    new Schedule.BackgroundEvent(task, getEnd(),
					 Schedule.EventType.FINISH);
	  events.add(event);
	}
      }
    }

    /** Add intersecting tasks to interval until interval is full.
	@return true iff no ending tasks have remaining unscheduled time.
    */
    boolean scheduleInterval(TaskData tasks[]) {
      double foreLoad = Math.min(loadFactor, 1.0 - overheadLoad);
      unscheduledTime = (long)(duration * foreLoad);
      chunks = new ArrayList();
      long chunkOffset = 0;
      long chunkStart = getBegin().getExpirationTime();
      if (log.isDebug3()) log.debug3("Scheduling " + toString());
      int ntasks = tasks.length;
      for (int tix = 0;
	   tix < ntasks && unscheduledTime > 0;
	   tix++) {
	TaskData td = tasks[tix];
	StepTask stask = (StepTask)td.task;
	if (log.isDebug3())
	  log.debug3("examining task " + tix + "(" + stask.cookie +
		     "), unsched = " + td.unschedTaskTime);
	if (td.unschedTaskTime > 0 && !isDisjoint(td.getWindow())) {
	  long taskTime = Math.min(unscheduledTime, td.unschedTaskTime);
	  long taskDur = (long)(taskTime / foreLoad);
	  if (log.isDebug3())
	    log.debug3("add task " + tix + "(" + stask.cookie +
		       "), time = " + taskTime + ", duration = " + taskDur);

	  // these times may have past if creating a schedule with tasks
	  // starting immediately, so suppres unreasonable deadline
	  // warning.  All passed-in deadlines have been checked for sanity.
	  Deadline start =
	    Deadline.restoreDeadlineAt(chunkStart + chunkOffset);
	  // roundoff error may leave chunkStart + chunkOffset + taskDur
	  // short of the end of the interval.  The this task got all the
	  // remaining time in the intern, ensure it ends exactly at the
	  // end of the interval
	  Deadline stop =
	    (taskTime == unscheduledTime
	     ? getEnd()
	     : Deadline.restoreDeadlineAt(chunkStart + chunkOffset + taskDur));

	  Schedule.Chunk chunk =
	     new Schedule.Chunk(stask, start, stop, taskTime);
	  td.unschedTaskTime -= taskTime;
	  unscheduledTime -= taskTime;
	  if (td.unschedTaskTime <= 0) {
	    chunk.setTaskEnd();
	  }
	  chunks.add(chunk);
	  chunkOffset += taskDur;
	  unscheduledTasks.remove(stask);
	}
      }
      // if any tasks ending at this interval have unschedTaskTime, fail
      if (endingTasks != null) {
	for (TaskData etd : endingTasks) {
	  if (etd.unschedTaskTime > 0) {
	    if (!seenNewTask) {
	      // don't fail to generate a schedule because no longer time
	      // to satisfy already-accepted tasks
	      if (log.isDebug2()) {
		log.debug("No longer time to finish, proceeding: " + etd);
	      }
	    } else {
	      log.debug("No schedule found: " + etd);
	      return false;
	    }
	  }
	}
      }
      return true;
    }

    void addChunk(List<Schedule.Event> events, Schedule.Chunk chunk) {
      if (!events.isEmpty()) {
	Schedule.Event prevEvent = events.get(events.size() - 1);
	if (prevEvent instanceof Schedule.Chunk) {
	  Schedule.Chunk prevChunk = (Schedule.Chunk)prevEvent;
	  if (prevChunk.extend(chunk)) {
	    return;
	  }
	}
      }
      events.add(chunk);
    }

    public String toString() {
      StringBuffer sb = new StringBuffer();
      sb.append("[");
      sb.append(getBegin().shortString());
      sb.append("-");
      sb.append(getEnd().shortString());
      if (loadFactor != 1.0) {
	sb.append("*");
	sb.append(loadFactor);
      }
      sb.append(",");
      sb.append(unscheduledTime);
      sb.append("]");
      return sb.toString();
    }

  }

  // prototype for List.toArray() calls
  static final TaskData[] EMPTY_TASKDATA_ARRAY = new TaskData[0];

  /** A set of contiguous intervals over which the scheduling algorithm
   * runs.  (This exists in order to break divisible scheduling problems
   * into smaller, non-divisible pieces, to reduce combinatorics.  In this
   * version of the scheduler, which sorts but does no other combinatorics,
   * it helps only a little.) */
  static class IntervalRange {
    SortScheduler.SchedInterval intervals[]; // the entire set of intervals
    int first;				// index of first interval in the range
    int last;				// index of last interval in the range
    TaskData tasks[];			// tasks to schedule during this range
    int ntasks;				// number of tasks

    IntervalRange(SortScheduler.SchedInterval intervals[],
		  int first, int last) {
      this.intervals = intervals;
      this.first = first;
      this.last = last;
    }

    void initIntervalTasks() {
      Set taskset = new HashSet();
      for (int ix = first; ix <= last; ix++) {
	SortScheduler.SchedInterval intrvl = intervals[ix];
	taskset.addAll(intrvl.competingTaskList);
	if (intrvl.endingTaskList != null) {
	  intrvl.endingTasks =
	    (TaskData[])intrvl.endingTaskList.toArray(EMPTY_TASKDATA_ARRAY);
	}
      }
      ntasks = taskset.size();
      log.debug2(ntasks + " tasks");
      tasks = (TaskData[])taskset.toArray(EMPTY_TASKDATA_ARRAY);
      Arrays.sort(tasks, TaskData.endTimeComparator());
      if (log.isDebug3()) log.debug3("tasks: " + arrayString(tasks));
    }

    boolean scheduleIntervalRange() {
      log.debug2("sched " + first + " - " + last + " of " + intervals.length +
		" intervals");
      initIntervalTasks();

      for (int iix = first; iix <= last; iix++) {
	SortScheduler.SchedInterval intrvl = intervals[iix];
	if (!intrvl.scheduleInterval(tasks)) {
	  if (log.isDebug2()) {
	    log.debug2("schedIntrvlRng: can't schedule interval: " +
		       iix +"; " + intrvl);
	  }
	  return false;
	}
      }
      log.debug2("Schedule found");
      return true;
    }
  }

}


text:
using System;

namespace Orleans.Versions.Compatibility
{
    [Serializable]
    [GenerateSerializer]
    public class StrictVersionCompatible : CompatibilityStrategy
    {
        public static StrictVersionCompatible Singleton { get; } = new StrictVersionCompatible();
    }
}


text:
ENV["RAILS_ENV"] = "test"

require 'rubygems'
gemfile = File.expand_path('../../Gemfile', __FILE__)

ENV['BUNDLE_GEMFILE'] = gemfile
require 'bundler'
Bundler.setup

require 'rubygems'
require 'active_support'
require 'active_support/dependencies'
require 'active_record'
ActiveRecord::ActiveRecordError # work-around from https://rails.lighthouseapp.com/projects/8994/tickets/2577-when-using-activerecordassociations-outside-of-rails-a-nameerror-is-thrown
require 'minitest'
require 'minitest/autorun'
#require 'active_support/core_ext/logger'
require 'hobofields' if ENV['INCLUDE_HOBO']
require 'pry'
require "minitest/reporters"

junit_ouptut_dir = ENV["JUNIT_OUTPUT_DIR"].presence || "test/reports"

Minitest::Reporters.use!([
  Minitest::Reporters::ProgressReporter.new,
  Minitest::Reporters::JUnitReporter.new(junit_ouptut_dir)
])

require 'attr_default'

ActiveRecord::Base.time_zone_aware_attributes = true
Time.zone = 'Pacific Time (US & Canada)'

$LOAD_PATH.unshift File.expand_path("lib", File.dirname(__FILE__))

if defined?(Rails::Railtie)
  AttrDefault.initialize_railtie
  AttrDefault.initialize_active_record_extensions
end


text:
require 'spec_helper'

describe Yelp::Endpoint::PhoneSearch do
  include_context 'shared configuration'

  let(:api_keys) { real_api_keys }
  let(:phone) { '+14159083801' }
  let(:options) { { code: 'US', category: 'localflavor' } }
  let(:client) { Yelp::Client.new(api_keys) }

  describe '#phone_search' do
    subject(:results) {
      VCR.use_cassette('phone_search') do
        client.phone_search(phone, options)
      end
    }

    it { should be_a(BurstStruct::Burst) }
    it 'should get results' do
      expect(results.businesses.size).to be > 0
    end
  end

  describe 'errors' do
    it_behaves_like 'a request error' do
      let(:request) { client.phone_search(phone) }
    end
  end
end


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Lichenes Epiphylli Novi 13 (1890)

#### Original name
Heterothecium perpallidum var. monosporum Müll. Arg.

### Remarks
null


text:
package com.example.helloworld.resources;

import com.example.helloworld.core.Person;
import com.example.helloworld.db.PersonDAO;
import io.dropwizard.testing.junit5.DropwizardExtensionsSupport;
import io.dropwizard.testing.junit5.ResourceExtension;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;

import javax.ws.rs.client.Entity;
import javax.ws.rs.core.GenericType;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.Collections;
import java.util.List;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

/**
 * Unit tests for {@link PeopleResource}.
 */
@ExtendWith(DropwizardExtensionsSupport.class)
public class PeopleResourceTest {
    private static final PersonDAO PERSON_DAO = mock(PersonDAO.class);
    public static final ResourceExtension RESOURCES = ResourceExtension.builder()
            .addResource(new PeopleResource(PERSON_DAO))
            .build();
    private ArgumentCaptor<Person> personCaptor = ArgumentCaptor.forClass(Person.class);
    private Person person;

    @BeforeEach
    public void setUp() {
        person = new Person();
        person.setFullName("Full Name");
        person.setJobTitle("Job Title");
        person.setYearBorn(1995);
    }

    @AfterEach
    public void tearDown() {
        reset(PERSON_DAO);
    }

    @Test
    public void createPerson() {
        when(PERSON_DAO.create(any(Person.class))).thenReturn(person);
        final Response response = RESOURCES.target("/people")
                .request(MediaType.APPLICATION_JSON_TYPE)
                .post(Entity.entity(person, MediaType.APPLICATION_JSON_TYPE));

        assertThat(response.getStatusInfo()).isEqualTo(Response.Status.OK);
        verify(PERSON_DAO).create(personCaptor.capture());
        assertThat(personCaptor.getValue()).isEqualTo(person);
    }

    @Test
    public void createPersonFailureMinYearBorn() {
        person.setYearBorn(-1);

        final Response response = RESOURCES.target("/people")
                .request(MediaType.APPLICATION_JSON_TYPE)
                .post(Entity.entity(person, MediaType.APPLICATION_JSON_TYPE));

        assertThat(response.getStatusInfo()).isNotEqualTo(Response.Status.OK);
        assertThat(response.readEntity(String.class)).contains("yearBorn must be greater than or equal to 0");
    }

    @Test
    public void createPersonFailureMaxYearBorn() {
        person.setYearBorn(10000);

        final Response response = RESOURCES.target("/people")
                .request(MediaType.APPLICATION_JSON_TYPE)
                .post(Entity.entity(person, MediaType.APPLICATION_JSON_TYPE));

        assertThat(response.getStatusInfo()).isNotEqualTo(Response.Status.OK);
        assertThat(response.readEntity(String.class)).contains("yearBorn must be less than or equal to 9999");
    }

    @Test
    public void listPeople() throws Exception {
        final List<Person> people = Collections.singletonList(person);
        when(PERSON_DAO.findAll()).thenReturn(people);

        final List<Person> response = RESOURCES.target("/people")
            .request().get(new GenericType<List<Person>>() {
            });

        verify(PERSON_DAO).findAll();
        assertThat(response).containsAll(people);
    }
}


text:
/** @file
 *  @brief Internal APIs for Bluetooth Handsfree profile handling.
 */

/*
 * Copyright (c) 2015-2016 Intel Corporation
 *
 * SPDX-License-Identifier: Apache-2.0
 */

#define BT_HFP_MAX_MTU           140
#define BT_HF_CLIENT_MAX_PDU     BT_HFP_MAX_MTU

/* HFP AG Features */
#define BT_HFP_AG_FEATURE_3WAY_CALL     0x00000001 /* Three-way calling */
#define BT_HFP_AG_FEATURE_ECNR          0x00000002 /* EC and/or NR function */
#define BT_HFP_AG_FEATURE_VOICE_RECG    0x00000004 /* Voice recognition */
#define BT_HFP_AG_INBAND_RING_TONE      0x00000008 /* In-band ring capability */
#define BT_HFP_AG_VOICE_TAG             0x00000010 /* Attach no. to voice tag */
#define BT_HFP_AG_FEATURE_REJECT_CALL   0x00000020 /* Ability to reject call */
#define BT_HFP_AG_FEATURE_ECS           0x00000040 /* Enhanced call status */
#define BT_HFP_AG_FEATURE_ECC           0x00000080 /* Enhanced call control */
#define BT_HFP_AG_FEATURE_EXT_ERR       0x00000100 /* Extented error codes */
#define BT_HFP_AG_FEATURE_CODEC_NEG     0x00000200 /* Codec negotiation */
#define BT_HFP_AG_FEATURE_HF_IND        0x00000400 /* HF Indicators */
#define BT_HFP_AG_FEARTURE_ESCO_S4      0x00000800 /* eSCO S4 Settings */

/* HFP HF Features */
#define BT_HFP_HF_FEATURE_ECNR          0x00000001 /* EC and/or NR */
#define BT_HFP_HF_FEATURE_3WAY_CALL     0x00000002 /* Three-way calling */
#define BT_HFP_HF_FEATURE_CLI           0x00000004 /* CLI presentation */
#define BT_HFP_HF_FEATURE_VOICE_RECG    0x00000008 /* Voice recognition */
#define BT_HFP_HF_FEATURE_VOLUME        0x00000010 /* Remote volume control */
#define BT_HFP_HF_FEATURE_ECS           0x00000020 /* Enhanced call status */
#define BT_HFP_HF_FEATURE_ECC           0x00000040 /* Enhanced call control */
#define BT_HFP_HF_FEATURE_CODEC_NEG     0x00000080 /* CODEC Negotiation */
#define BT_HFP_HF_FEATURE_HF_IND        0x00000100 /* HF Indicators */
#define BT_HFP_HF_FEATURE_ESCO_S4       0x00000200 /* eSCO S4 Settings */

/* HFP HF Supported features */
#define BT_HFP_HF_SUPPORTED_FEATURES    (BT_HFP_HF_FEATURE_CLI | \
					 BT_HFP_HF_FEATURE_VOLUME)

#define HF_MAX_BUF_LEN                  BT_HF_CLIENT_MAX_PDU
#define HF_MAX_AG_INDICATORS            20

struct bt_hfp_hf {
	struct bt_rfcomm_dlc rfcomm_dlc;
	char hf_buffer[HF_MAX_BUF_LEN];
	struct at_client at;
	uint32_t hf_features;
	uint32_t ag_features;
	int8_t ind_table[HF_MAX_AG_INDICATORS];
};

enum hfp_hf_ag_indicators {
	HF_SERVICE_IND,
	HF_CALL_IND,
	HF_CALL_SETUP_IND,
	HF_CALL_HELD_IND,
	HF_SINGNAL_IND,
	HF_ROAM_IND,
	HF_BATTERY_IND
};


text:
start=$(date +%s)

# Get the date for a log file.
now=$(date +"%m_%d_%Y")
the_time=$(date +"%T")

# Add some space and the date to the log file.
printf "LAPTOP & DESKTOP SYNC/BACKUP."
cur_date=$(date +"%c")
echo " Backup Date: $cur_date"
printf "\n"

# These are hard coded into the router. They shouldn't change.
# But in case they do, they are defined below.
laptop='jason@192.168.1.7'
desktop='jason@192.168.1.6'
#750GB='/media/Linux-Data'
#1TB='/media/Data/Linux-Data'

# Decided to change how I run my backups.
# It will work like this, backuping the entire home directory (~/):

# Desktop = 240GB SSD, 1TB HDD
# Desktop -> local backup to HDD, external backup to 750GB laptop

# Laptop = 256GB SSD, 750GB HDD
# Laptop -> local backup to HDD, external backup to 1TB desktop

# First, completely backup the desktop's ~/ to the 1TB HDD
# | sed '0,/^$/d' -> just prints the summary out and nothing more.
rsync -azq --delete --exclude /.cache* ~/ \
/media/Data/Linux-Data/Desktop

# Next backup the Desktop to the laptop's 750GB HDD
rsync -azq --delete --exclude /.cache* ~/ \
$laptop:/media/Linux-Data/Desktop

# SSH into the laptop and run the LAPTOP sync script.
# It basically syncs from laptop to laptop HDD and then to
# the desktop's 1TB hard drive.
ssh -t $laptop '~/_Custom/Backup_Laptop.sh'
ssh -t $laptop '~/_Custom/Sync_LAPTOP.sh'

# Let's get the total time it took!
end=$(date +%s)
total=$((end-start))

# Print we done yo to ze screen.
printf "***********************************************************************************\n"
echo   "	FINISHED BACKUP. TOTAL TIME THIS TOOK: " $total "seconds"
printf "***********************************************************************************\n"


text:
var loopyApp = angular.module('loopyApp', []);
loopyApp.config(function($interpolateProvider) {
    $interpolateProvider.startSymbol('{[{');
    $interpolateProvider.endSymbol('}]}');
});

loopyApp.controller('LooperController', function ($scope) {
    $scope.startSeconds = 0;
    $scope.endSeconds = 0;
});

$('#audio_file').change(function() {
    var files = this.files;
    var file = URL.createObjectURL(files[0]);
    $('#audio_player').prop('src', file);
    $('#audio_player').get(0).loop = true;
    $('#audio_player').get(0).playbackRate = 2.0;
    $('#audio_player').get(0).play();
});


text:
"""Tests shutdown of the Kernel."""
from .utils import wait_for_selector, wait_for_xpath

def test_shutdown(notebook):
    notebook.edit_cell(content="print(21)")
    wait_for_xpath(notebook.browser, '//a[text()="Kernel"]', single=True).click()
    wait_for_selector(notebook.browser, '#shutdown_kernel', single=True).click()
    wait_for_selector(notebook.browser, '.btn.btn-default.btn-sm.btn-danger', single=True).click()

    #Wait until all shutdown modal elements disappear before trying to execute the cell
    wait_for_xpath(notebook.browser, "//div[contains(@class,'modal')]", obscures=True)
    notebook.execute_cell(0)

    assert not notebook.is_kernel_running()
    assert len(notebook.get_cell_output()) == 0


text:
namespace gfx {

std::vector<Font> GetFallbackFonts(const Font& font) {
  return std::vector<Font>();
}

bool GetFallbackFont(const Font& font,
                     const std::string& locale,
                     base::StringPiece16 text,
                     Font* result) {
  TRACE_EVENT0("fonts", "gfx::GetFallbackFont");

  if (text.empty())
    return false;

  sk_sp<SkTypeface> fallback_typeface =
      GetSkiaFallbackTypeface(font, locale, text);

  if (!fallback_typeface)
    return false;

  // Fallback needs to keep the exact SkTypeface, as re-matching the font using
  // family name and styling information loses access to the underlying platform
  // font handles and is not guaranteed to result in the correct typeface, see
  // https://crbug.com/1003829
  *result = Font(PlatformFont::CreateFromSkTypeface(
      std::move(fallback_typeface), font.GetFontSize(), absl::nullopt));
  return true;
}

}  // namespace gfx


text:
  <uib-accordion close-others="oneAtATime">
    <uib-accordion-group heading="Sort:">

          {{sort}}

    </uib-accordion-group>
    <uib-accordion-group heading="Time:">

          {{time}}

    </uib-accordion-group>
    <uib-accordion-group heading="Subreddits:" is-open="true">

          {{subReddit.data.display_name}}

    </uib-accordion-group>
  </uib-accordion>


text:
name "cloudify-rest-service"

ENV['CORE_TAG_NAME'] || raise('CORE_TAG_NAME environment variable not set')
default_version ENV['CORE_TAG_NAME']
# script_plugin_tag = '1.4'
dependency "python"
dependency "pip"
dependency "dbus"
dependency "dsl-parser"
dependency "rest-client"
dependency "plugins-common"
dependency "script-plugin"
dependency "cloudify-agent"

source git: "https://github.com/cloudify-cosmo/cloudify-manager"

build do
    command ["#{install_dir}/embedded/bin/pip",
             "install", "--build=#{project_dir}/#{name}", "./rest-service/"]
    command ["#{install_dir}/embedded/bin/pip",
             "install", "--build=#{project_dir}/#{name}/dev-requirements",
             "-r", "./rest-service/dev-requirements.txt"]
    command ["#{install_dir}/embedded/bin/pip",
             "install", "https://github.com/cloudify-cosmo/wagon/archive/master.zip"]
end

whitelist_file /.*/


text:
On Linux one might want to use the [GPaste](https://github.com/Keruspe/GPaste) clipboard manager. Using the `GOPASS_CLIPBOARD_COPY_CMD` and `GOPASS_CLIPBOARD_CLEAR_CMD` environment variables one can instruct gopass to use the GPaste client directly. This hides passwords when viewed in the manager and removes them by name after the timeout.

## Usage

### Helper scripts

Both environment variables expect a path to an executable or the name of an executable in the `PATH` environment variable. The executables receive the name of the password as the first argument and the password (copy) or its checksum (clear) in `STDIN`. To use the GPaste client one has to use helper scripts like this:

`~/.local/scripts/gopass_clipboard_copy_cmd.sh`
```sh
#!/bin/sh

# gpaste-client will use the password in /dev/stdin
gpaste-client add-password "$1"
```

`~/.local/scripts/gopass_clipboard_clear_cmd.sh`
```sh
#!/bin/sh

gpaste-client delete-password "$1"
```

Make sure both are executable: `chmod +x ~/.local/scripts/gopass_clipboard_{copy,clear}_cmd.sh`

### Setting the environment variables

#### Shell

You can set the environment variables in the `.profile` file of your shell, for example:

`~/.bash_profile`
```sh
# [...]
export GOPASS_CLIPBOARD_COPY_CMD="$HOME/.local/scripts/gopass_clipboard_copy_cmd.sh"
export GOPASS_CLIPBOARD_CLEAR_CMD="$HOME/.local/scripts/gopass_clipboard_clear_cmd.sh"
# [...]
```

#### Graphical environment

If you are using X11 you can set the above in `~/.xprofile`.

On Wayland one may use systemd user environment variables:

`~/.config/environment.d/gopass.conf`
```sh
GOPASS_CLIPBOARD_COPY_CMD="$HOME/.local/scripts/gopass_clipboard_copy_cmd.sh"
GOPASS_CLIPBOARD_CLEAR_CMD="$HOME/.local/scripts/gopass_clipboard_clear_cmd.sh"
```

A reboot might be required.


text:
Semigroups
*********

.. code-block:: python
    :caption: example_semigroup.py
    :name: example_semigroup-py

    from pymonet.semigroups import All, First, Map, Sum

    All(True).concat(All(False))  # All<False>
    All(True).concat(All(True))  # All<True>

    All(True) == All(True)  # True
    All(True) == All(False)  # False

    ingredient1 = Map({'score': Sum(1), 'won': All(True), 'captain': First('captain america')})
    ingredient2 = Map({'score': Sum(2), 'won': All(True), 'captain': First('iron man')})
    ingredient1.concat(ingredient2)  # Map<{'score': Sum(3), 'won': All(True), 'captain': First('captain america')}>

.. autoclass:: pymonet.semigroups.All
    :members: __init__, concat, fold

.. autoclass:: pymonet.semigroups.One
    :members: __init__, concat, fold

.. autoclass:: pymonet.semigroups.First
    :members: __init__, concat, fold

.. autoclass:: pymonet.semigroups.Last
    :members: __init__, concat, fold

.. autoclass:: pymonet.semigroups.Map
    :members: __init__, concat, fold

.. autoclass:: pymonet.semigroups.Max
    :members: __init__, concat, fold

.. autoclass:: pymonet.semigroups.Min
    :members: __init__, concat, fold


text:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [AutoWho].[DimWaitType](
	[DimWaitTypeID] [smallint] IDENTITY(30,1) NOT NULL,
	[wait_type] [nvarchar](60) NOT NULL,
	[wait_type_short] [nvarchar](60) NOT NULL,
	[latch_subtype] [nvarchar](100) NOT NULL,
	[TimeAdded] [datetime] NOT NULL,
 CONSTRAINT [PK_AutoWho_DimWaitType] PRIMARY KEY CLUSTERED
(
	[DimWaitTypeID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
SET ANSI_PADDING ON

GO
CREATE UNIQUE NONCLUSTERED INDEX [AK_allattributes] ON [AutoWho].[DimWaitType]
(
	[wait_type] ASC,
	[wait_type_short] ASC,
	[latch_subtype] ASC
)
INCLUDE ( 	[DimWaitTypeID],
	[TimeAdded]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
ALTER TABLE [AutoWho].[DimWaitType] ADD  CONSTRAINT [DF_AutoWho_DimWaitType_TimeAdded]  DEFAULT (getdate()) FOR [TimeAdded]
GO


text:
package it.unisa.dia.gas.jpbc.benchmark;

import java.util.ArrayList;
import java.util.List;

/**
 * Angelo De Caro (jpbclib@gmail.com)
 */
public class JPBCBenchmark implements Benchmark {
    protected static final String[] pairingBenchmarkNames = new String[]{
            "Pairing#pairing(in1, in2)",
            "Pairing#getPairingPreProcessingFromElement(in1)",
            "PairingPreProcessing#pairing(in2)",
    };

    protected static final String[] elementBenchmarkNames = new String[]{
            "Element#pow(BigInteger)",
            "Element#powZn(Element)",
            "Element#getElementPowPreProcessing()",
            "ElementPowPreProcessing#pow(BigInteger)",
            "ElementPowPreProcessing#powZn(Element)",
            "Element#mul(BigInteger)",
            "Element#setToRandom()"
    };

    protected static final String[] fieldNames = new String[]{
            "G1", "G2", "GT", "Zr"
    };

    private String[] curves;
    private double[][] pairingBenchmarks;
    private double[][][] elementBenchmarks;

    private List<Benchmark> benchmarks;

    public JPBCBenchmark(String[] curves) {
        this.curves = curves;
        this.pairingBenchmarks = new double[3 + (5 * 4)][curves.length];
        this.elementBenchmarks = new double[fieldNames.length][elementBenchmarkNames.length][curves.length];
    }

    public double[][] getPairingBenchmarks() {
        return pairingBenchmarks;
    }

    public double[][][] getElementBenchmarks() {
        return elementBenchmarks;
    }

    public String toHTML() {
        if (benchmarks != null && benchmarks.size() > 0)
            return toHTML(benchmarks.toArray(new JPBCBenchmark[benchmarks.size()]));

        StringBuilder buffer = new StringBuilder();

        buffer.append("
\n")
                .append("
\n")
                .append("                        Benchmark - Average Time (ms)	\n")
                .append("                        Pairing Type	\n")
                .append("
\n")
                .append("
\n")
                .append("                        	\n");
        for (String curve : curves) {
            curve = curve.substring(curve.lastIndexOf('/') + 1, curve.lastIndexOf('.'));

            buffer.append("                        ").append(curve).append("	\n");
        }
        buffer.append("
\n");

        for (int row = 0; row < pairingBenchmarkNames.length; row++) {
            buffer.append("
\n")
                    .append("                        ").append(pairingBenchmarkNames[row]).append("	\n");
            for (int col = 0; col < curves.length; col++) {
                buffer.append("                        ").append(pairingBenchmarks[row][col]).append("	\n");
            }
            buffer.append("
\n");
        }

        for (int fieldIndex = 0; fieldIndex < fieldNames.length; fieldIndex++) {
            buffer.append("
\n")
                    .append("                        \n")
                    .append("                            Element Pow (").append(fieldNames[fieldIndex]).append(")\n")
                    .append("                        	\n");
            for (int col = 0; col < curves.length; col++) {
                buffer.append("                        	\n");
            }
            buffer.append("
\n");

            for (int row = 0; row < elementBenchmarkNames.length; row++) {
                buffer.append("
\n")
                        .append("                        ")
                        .append(elementBenchmarkNames[row])
                        .append("	\n");
                for (int col = 0; col < curves.length; col++) {
                    buffer.append("                        ").append(elementBenchmarks[fieldIndex][row][col]).append("	\n");
                }
                buffer.append("
\n");
            }
        }

        buffer.append("
\n");

        return buffer.toString();
    }

    public String toHTML(Benchmark... benchmarks) {
        StringBuilder buffer = new StringBuilder();

        buffer.append("
\n")
                .append("
\n")
                .append("                        Benchmark - Average Time (ms)	\n")
                .append("                        Pairing Type	\n")
                .append("
\n")
                .append("
\n")
                .append("                        	\n");
        for (String curve : curves) {
            curve = curve.substring(curve.lastIndexOf('/') + 1, curve.lastIndexOf('.'));

            buffer.append("                        ").append(curve).append("	\n");
        }
        buffer.append("
\n");

        for (int row = 0; row < pairingBenchmarkNames.length; row++) {
            buffer.append("
\n")
                    .append("                        ").append(pairingBenchmarkNames[row]).append("	\n");
            for (int col = 0; col < curves.length; col++) {
                buffer.append("                        ").append(pairingBenchmarks[row][col]);

                if (benchmarks != null) {
                    buffer.append(" (");
                    for (int i = 0; i < benchmarks.length; i++) {
                        JPBCBenchmark benchmark = (JPBCBenchmark) benchmarks[i];
                        buffer.append(benchmark.getPairingBenchmarks()[row][col]);
                        if (i + 1 < benchmarks.length)
                            buffer.append(", ");
                    }
                    buffer.append(")");
                }

                buffer.append("	\n");
            }
            buffer.append("
\n");
        }

        for (int fieldIndex = 0; fieldIndex < fieldNames.length; fieldIndex++) {
            buffer.append("
\n")
                    .append("                        \n")
                    .append("                            Element Pow (").append(fieldNames[fieldIndex]).append(")\n")
                    .append("                        	\n");
            for (int col = 0; col < curves.length; col++) {
                buffer.append("                        	\n");
            }
            buffer.append("
\n");

            for (int row = 0; row < elementBenchmarkNames.length; row++) {
                buffer.append("
\n")
                        .append("                        ")
                        .append(elementBenchmarkNames[row])
                        .append("	\n");
                for (int col = 0; col < curves.length; col++) {
                    buffer.append("                        ").append(elementBenchmarks[fieldIndex][row][col]);

                    if (benchmarks != null) {
                        buffer.append(" (");
                        for (int i = 0; i < benchmarks.length; i++) {
                            JPBCBenchmark benchmark = (JPBCBenchmark) benchmarks[i];
                            buffer.append(benchmark.getElementBenchmarks()[fieldIndex][row][col]);
                            if (i + 1 < benchmarks.length)
                                buffer.append(", ");
                        }
                        buffer.append(")");
                    }

                    buffer.append("	\n");
                }
                buffer.append("
\n");
            }
        }

        buffer.append("
\n");

        return buffer.toString();
    }

    public void addBenchmark(Benchmark benchmark) {
        if (benchmarks == null)
            benchmarks = new ArrayList<Benchmark>();

        benchmarks.add(benchmark);
    }
}


text:
describe("Ext.direct.RemotingMethod", function() {
    var cb  = jasmine.createSpy('callback'),
        opt = { timeout: 10 },
        method;

    function makeMethod(params) {
        method = new Ext.direct.RemotingMethod(params || {});
    }

    afterEach(function() {
        method = null;
    });

    describe("Ordered parameters", function() {
        beforeEach(function() {
            makeMethod({
                name: 'foo',
                len: 2
            });
        });

        it("should instantiate", function() {
            expect(method).toBeDefined();
        });

        it("should set ordered property", function() {
            expect(method.ordered).toBe(true);
        });

        it("should return call data", function() {
            var data = method.getCallData(['foo', 'bar', cb, method, opt]);

            expect(data).toEqual({
                data: ['foo', 'bar'],
                metadata: undefined,
                callback: cb,
                scope: method,
                options: opt
            });
        });
    });

    describe("Named parameters", function() {
        beforeEach(function() {
            makeMethod({
                name: 'bar',
                params: ['foo', 'bar']
            });
        });

        it("should instantiate", function() {
            expect(method).toBeDefined();
        });

        it("should accept parameter names as array of strings", function() {
            expect(method.params).toEqual({
                foo: true,
                bar: true
            });
        });

        it("should accept parameter names as array of objects", function() {
            makeMethod({
                name: 'baz',
                params: [{
                    name: 'foo'
                }, {
                    name: 'bar'
                }]
            });

            expect(method.params).toEqual({
                foo: true,
                bar: true
            });
        });

        it("should return call data with less than specified params", function() {
            var data = method.getCallData([{ foo: 'foo' }, cb, method, opt]);

            expect(data).toEqual({
                data: {
                    foo: 'foo'
                },
                metadata: undefined,
                callback: cb,
                scope: method,
                options: opt
            });
        });

        it("should filter out unspecified params", function() {
            makeMethod({
                name: 'baz',
                params: ['foo']
            });

            var data = method.getCallData([{ foo: 'bar', bar: 'qux' }, cb, method, opt]);

            expect(data).toEqual({
                data: {
                    foo: 'bar'
                },
                metadata: undefined,
                callback: cb,
                scope: method,
                options: opt
            });
        });

        it("should not filter params with strict: false", function() {
            makeMethod({
                name: 'blerg',
                params: [],
                strict: false
            });

            var data = method.getCallData([{ foo: 'bar', qux: 'fred' }, cb, method, opt]);

            expect(data).toEqual({
                data: {
                    foo: 'bar',
                    qux: 'fred'
                },
                metadata: undefined,
                callback: cb,
                scope: method,
                options: opt
            });
        });
    });

    describe("metadata", function() {
        describe("declaration", function() {
            var metadata;

            describe("ordered meta-params", function() {
                beforeEach(function() {
                    makeMethod({
                        name: 'metaOrdered',
                        len: 0,
                        metadata: {
                            len: 42
                        }
                    });

                    metadata = method.metadata;
                });

                it("should define metadata property", function() {
                    expect(metadata).toBeDefined();
                });

                it("should set metadata.len to 42", function() {
                    expect(metadata.len).toBe(42);
                });

                it("should not set metadata.params", function() {
                    expect(metadata.params).not.toBeDefined();
                });

                it("should not set metadata.strict", function() {
                    expect(metadata.strict).not.toBeDefined();
                });
            });

            describe("named meta-params", function() {
                beforeEach(function() {
                    makeMethod({
                        name: 'metaNamed',
                        len: 0,
                        metadata: {
                            params: ['foo', 'bar']
                        }
                    });

                    metadata = method.metadata;
                });

                it("should define metadata property", function() {
                    expect(metadata).toBeDefined();
                });

                it("should set metadata.params", function() {
                    expect(metadata.params).toEqual({ foo: true, bar: true });
                });

                it("should set metadata.strict to true", function() {
                    expect(metadata.strict).toBe(true);
                });

                it("should set metadata.strict to false", function() {
                    method = null;

                    makeMethod({
                        name: 'metaNamed2',
                        len: 0,
                        metadata: {
                            params: ['foo', 'bar'],
                            strict: false
                        }
                    });

                    expect(method.metadata.strict).toBe(false);
                });
            });
        });

        describe("getCallData", function() {
            describe("ordered", function() {
                beforeEach(function() {
                    makeMethod({
                        name: 'metaOrdered',
                        len: 1,
                        metadata: {
                            len: 1
                        }
                    });
                });

                it("should return required number of metadata params", function() {
                    var data = method.getCallData([1, cb, null, { metadata: [42] }]);

                    expect(data).toEqual({
                        data: [1],
                        metadata: [42],
                        callback: cb,
                        scope: null,
                        options: {}
                    });
                });

                it("should not return more than len metadata params", function() {
                    var data = method.getCallData([1, cb, null, { metadata: [42, 43] }]);

                    expect(data).toEqual({
                        data: [1],
                        metadata: [42],
                        callback: cb,
                        scope: null,
                        options: {}
                    });
                });

                it("should throw exception when there is not enough metadata params", function() {
                    spyOn(Ext, 'log');

                    expect(function() {
                        method.getCallData([1, cb, null, { metadata: [] }]);
                    }).toThrow("Not enough parameters in options.metadata " +
                               "for Ext.Direct method metaOrdered");
                });
            });

            describe("named strict", function() {
                beforeEach(function() {
                    makeMethod({
                        name: 'metaNamedStrict',
                        len: 0,
                        metadata: {
                            params: ['foo', 'bar']
                        }
                    });
                });

                it("should return all required metadata params", function() {
                    var data = method.getCallData([cb, null, { metadata: { foo: 1, bar: 2 } }]);

                    expect(data).toEqual({
                        data: null,
                        metadata: { foo: 1, bar: 2 },
                        callback: cb,
                        scope: null,
                        options: {}
                    });
                });

                it("should strip non-required metadata params", function() {
                    var data = method.getCallData([
                        cb, null, { metadata: { foo: 1, bar: 2, baz: 3 } }
                    ]);

                    expect(data).toEqual({
                        data: null,
                        metadata: { foo: 1, bar: 2 },
                        callback: cb,
                        scope: null,
                        options: {}
                    });
                });

                it("should throw exception when there is not enough required params", function() {
                    spyOn(Ext, 'log');

                    expect(function() {
                        method.getCallData([cb, null, { metadata: { foo: 1 } }]);
                    }).toThrow("Named parameter bar is missing in options.metadata " +
                               "for Ext.Direct method metaNamedStrict");
                });
            });

            describe("named non-strict", function() {
                beforeEach(function() {
                    makeMethod({
                        name: 'metaNamedNonStrict',
                        len: 0,
                        metadata: {
                            params: ['foo'],
                            strict: false
                        }
                    });
                });

                it("should return all required metadata params", function() {
                    var data = method.getCallData([cb, null, { metadata: { foo: 1 } }]);

                    expect(data).toEqual({
                        data: null,
                        metadata: { foo: 1 },
                        callback: cb,
                        scope: null,
                        options: {}
                    });
                });

                it("should not strip non-required metadata params", function() {
                    var data = method.getCallData([cb, null, { metadata: { foo: 1, bar: 2 } }]);

                    expect(data).toEqual({
                        data: null,
                        metadata: { foo: 1, bar: 2 },
                        callback: cb,
                        scope: null,
                        options: {}
                    });
                });

                it("should throw exception when there is not enough required params", function() {
                    spyOn(Ext, 'log');

                    expect(function() {
                        method.getCallData([cb, null, { metadata: { bar: 2 } }]);
                    }).toThrow("Named parameter foo is missing in options.metadata " +
                               "for Ext.Direct method metaNamedNonStrict");
                });
            });
        });
    });
});


text:
using System.Windows.Forms;

namespace Gma.System.MouseKeyHook.Implementation
{
    internal static class KeysExtensions
    {
        public static Keys Normalize(this Keys key)
        {
            if ((key & Keys.LControlKey) == Keys.LControlKey ||
                (key & Keys.RControlKey) == Keys.RControlKey) return Keys.Control;
            if ((key & Keys.LShiftKey) == Keys.LShiftKey ||
                (key & Keys.RShiftKey) == Keys.RShiftKey) return Keys.Shift;
            if ((key & Keys.LMenu) == Keys.LMenu ||
                (key & Keys.RMenu) == Keys.RMenu) return Keys.Alt;
            return key;
        }
    }
}


text:
namespace DuiLib
{
	class DUILIB_API CApngButtonUI : public CApngAnimUI
	{
	public:
		CApngButtonUI(void);
		~CApngButtonUI(void);

		LPCTSTR GetClass() const;
		LPVOID GetInterface(LPCTSTR pstrName);
		UINT GetControlFlags() const;

		bool Activate();
		void SetEnabled(bool bEnable = true);
		void DoEvent(TEventUI& event);

		void PaintBkColor(HDC hDC);
		void PaintText(HDC hDC);

		void SetAttribute(LPCTSTR pstrName, LPCTSTR pstrValue);
		CDuiString GetCursor();
		void SetCursor(LPCTSTR pStrCursor);

		void SetHotBkColor(DWORD dwColor);
		DWORD GetHotBkColor() const;
		void SetHotTextColor(DWORD dwColor);
		DWORD GetHotTextColor() const;
		void SetPushedTextColor(DWORD dwColor);
		DWORD GetPushedTextColor() const;

		UINT GetButtonState() {return m_uButtonState;};
	protected:
		UINT m_uButtonState;
		CDuiString m_sCursor;			//¹â±êÐÎ×´ arrow/hand ÆäËû¸ù¾ÝÐèÒªÌí¼Ó

		DWORD m_dwHotBkColor;
		DWORD m_dwHotTextColor;
		DWORD m_dwPushedTextColor;
	};
}

#endif // ApngButtonUI_h__


text:
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;

namespace nzbcli
{
    public class XmlNzbFile
    {
        [XmlAttribute("poster")]
        public string Poster { get; set; }
        [XmlAttribute("date")]
        public int Unixtime { get; set; }
        [XmlAttribute("subject")]
        public string Subject { get; set; }
        [XmlArray("groups")]
        [XmlArrayItem("group")]
        public List<string> Groups { get; set; }
        [XmlArray("segments")]
        [XmlArrayItem("segment")]
        public List<XmlNzbSegment> Segments { get; set; }
    }
}


text:
/**
 * Metadata on a language's in depth interface properties.
 */
export class InterfaceProperties {
    /**
     * Keyword that indicates interface declaration.
     */
    public declareStartLeft: string;

    /**
     * Starts interface declaration.
     */
    public declareStartRight: string;

    /**
     * Keyword that indicates to extend from parent interfaces.
     */
    public declareExtendsLeft: string;

    /**
     * Seperator of multiple parent interfaces.
     */
    public declareExtendsRight: string;

    /**
     * Ends interface declaration.
     */
    public declareEnd: string;

    /**
     * Starts method declaration.
     */
    public declareMethodLeft: string;

    /**
     * Middle of method declaration.
     */
    public declareMethodMiddle: string;

    /**
     * End of method declaration.
     */
    public declareMethodRight: string;

    /**
     * Whether the implements keyword needs to be explicitly called after a class has been extended.
     */
    public declareImplementsExplicit: boolean;

    /**
     * Whether the method type is declared after the method is define.
     */
    public methodTypeAfter: boolean;

    /**
     * Whether the language supports interfaces.
     */
    public supported: boolean;
}


text:
using AmplaData.WebService;

namespace AmplaData.AmplaData2008
{
    public class DataWebServiceFactory : WebServiceFactory<IDataWebServiceClient>, IDataWebServiceClient
    {
        public GetDataResponse GetData(GetDataRequest request)
        {
            return Create().GetData(request);
        }

        public GetAuditDataResponse GetAuditData(GetAuditDataRequest request)
        {
            return Create().GetAuditData(request);
        }

        public GetNavigationHierarchyResponse GetNavigationHierarchy(GetNavigationHierarchyRequest request)
        {
            return Create().GetNavigationHierarchy(request);
        }

        public SubmitDataResponse SubmitData(SubmitDataRequest request)
        {
            return Create().SubmitData(request);
        }

        public DeleteRecordsResponse DeleteRecords(DeleteRecordsRequest request)
        {
            return Create().DeleteRecords(request);
        }

        public UpdateRecordStatusResponse UpdateRecordStatus(UpdateRecordStatusRequest request)
        {
            return Create().UpdateRecordStatus(request);
        }

        public GetViewsResponse GetViews(GetViewsRequest request)
        {
            return Create().GetViews(request);
        }

        public SplitRecordsResponse SplitRecords(SplitRecordsRequest request)
        {
            return Create().SplitRecords(request);
        }
    }
}