text:
<?php

namespace TenilBase\Controller;

/**
 * Description of CrudController
 *
 * C: Create - INSERT - Criar ou adicionar novas entradas
 * R: Read (Retrieve) - SELECT - Ler, recuperar ou ver entradas existentes
 * U: Update - UPDATE - Atualizar ou editar entradas existentes
 * D: Delete - DELETE - Remover entradas existentes
 *
 * @author Roberto Tenil
 */

use Doctrine\ORM\EntityManager;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Zend\Paginator\Paginator;
use Zend\Paginator\Adapter\ArrayAdapter;

abstract class CrudController extends AbstractActionController
{

    protected $em;

    protected $controller;
    protected $entity;
    protected $form;
    protected $formEdit;
    protected $route;
    protected $service;

    public function createAction()
    {
        // Get ObjectManager from the ServiceManager
        $objectManager = $this->getServiceLocator()->get('Doctrine\ORM\EntityManager');

        // Create the form and inject the ObjectManager
        $form = new $this->form($objectManager);

        // Create a new, empty entity and bind it to the form
        $entity = new $this->entity();

        $form->bind($entity);

        if ($this->request->isPost()) {
            $form->setData($this->request->getPost());

            if ($form->isValid()) {

                $service = $this->getServiceLocator()->get($this->service);
                $service->insert($entity);

                $this->flashMessenger()->setNamespace('Tenil')->addSuccessMessage('Cadastro realizado com sucesso!');
                return $this->redirect()->toRoute($this->route, array('controller' => $this->controller, 'action' => 'list'));
            }

        }

        return array('form' => $form);
    }

    /**
     * @return ViewModel
     */
    public function listAction()
    {
//        $em = $this->getServiceLocator()->get('Doctrine\ORM\EntityManager');
//        $list = $em->getRepository('TenilEvento\Entity\Evento')->findAll();

        $list = $this->getEm()->getRepository($this->entity)->findAll();

        $pageNumber = $this->params()->fromRoute('page');
        $count = 5;

        $paginator = new Paginator(new ArrayAdapter($list));
        $paginator->setCurrentPageNumber($pageNumber)->setDefaultItemCountPerPage($count);

        return new ViewModel(array('data' => $paginator, 'page' => $pageNumber));
    }

    public function indexAction()
    {

        $list = $this->getEm()->getRepository($this->entity)->findAll();

        $pageNumber = $this->params()->fromRoute('page');
        $count = 5;

        $paginator = new Paginator(new ArrayAdapter($list));
        $paginator->setCurrentPageNumber($pageNumber)->setDefaultItemCountPerPage($count);

        return new ViewModel(array('data' => $paginator, 'page' => $pageNumber));
    }

    /**
     *
     * @return EntityManager
     */
    protected function getEm()
    {
        if (null === $this->em) {
            $this->em = $this->getServiceLocator()->get('Doctrine\ORM\EntityManager');
        }

        return $this->em;
    }

    public function editAction()
    {

        // Get ObjectManager from the ServiceManager
        $objectManager = $this->getServiceLocator()->get('Doctrine\ORM\EntityManager');

        // Create the form and inject the ObjectManager
        $form = new $this->formEdit($objectManager);

        // Create a new, empty entity and bind it to the form
        $repository = $this->getEm()->getRepository($this->entity);
        $id = $this->params()->fromRoute('id', 0);

        $entity = $repository->find($id);

        $form->bind($entity);

        $request = $this->getRequest();

        if ($request->isPost()) {

            $form->setData($request->getPost());

            if ($form->isValid()) {

                $service = $this->getServiceLocator()->get($this->service);
                $service->update($entity);

                $this->flashMessenger()->setNamespace('Tenil')->addSuccessMessage('Atualizado com sucesso!');

                return $this->redirect()->toRoute($this->route, array('controller' => $this->controller, 'action' => 'edit', 'id' => $id ));
            }
        }

        return new ViewModel(array('form' => $form));

    }

    /*
    public function editAction()
    {

        $form = new $this->form();
        $request = $this->getRequest();

        $repository = $this->getEm()->getRepository($this->entity);
        $entity = $repository->find($this->params()->fromRoute('id', 0));

        //Teste muito sem vergonha
        if ($this->params()->fromRoute('id', 0)) {
            $data = $entity->toArray();
            unset($data['password']);
            $form->setData($data);
        }

        if ($request->isPost()) {

            $form->setData($request->getPost());

            if ($form->isValid()) {

                $service = $this->getServiceLocator()->get($this->service);
                $service->update($request->getPost()->toArray());

                $this->flashMessenger()->setNamespace('Tenil')->addSuccessMessage('Atualizado com sucesso!');

                return $this->redirect()->toRoute($this->route, array('controller' => $this->controller));
            }
        }

        return new ViewModel(array('form' => $form));

    }
    */
    public function deleteAction()
    {

        $service = $this->getServiceLocator()->get($this->service);
        if ($service->delete($this->params()->fromRoute('id', 0))) {
            $this->flashMessenger()->setNamespace('Tenil')->addSuccessMessage('Excluído com sucesso!');
        }

        return $this->redirect()->toRoute($this->route, array('controller' => $this->controller));

    }

    public function testeAction()
    {
        $data = array(
            'controller' => $this->controller,
            'entity' => $this->entity,
            'form' => $this->form,
            'route' => $this->route,
            'service' => $this->service
        );

        // $sl instanceof Zend\ServiceManager\ServiceManager

        $config = $this->getServiceLocator()->get('Config');
        $routes = $config['router']['routes'];

        return new ViewModel(array('data' => $data, 'routes' => $routes));
    }

    private function getAuthService()
    {
        return $this->getServiceLocator()->get('Zend\Authentication\AuthenticationService');
    }

    /**
     * Retorna uma String com uma mascara definida
     * Ex.: $this->mask($inscricao->getCpf(), '###.###.###-##')
     *
     * @param $val
     * @param $mask
     * @return string
     */
    private function mask($val, $mask)
    {
        $maskared = '';
        $k = 0;
        for ($i = 0; $i <= strlen($mask) - 1; $i++) {
            if ($mask[$i] == '#') {
                if (isset($val[$k]))
                    $maskared .= $val[$k++];
            } else {
                if (isset($mask[$i]))
                    $maskared .= $mask[$i];
            }
        }
        return $maskared;
    }
}


text:
package algorithm.implementation;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

import org.junit.Test;

/**
 *
 * @version $Revision$
 * @version $Date$
 * @author $Author$
 * @owner Sandro Mario Zbinden
 */
public class GridSearchTest {

    @Test
    public void test() throws FileNotFoundException {
        try (Scanner in = new Scanner(new File("d:\\temp\\input05.txt"))) {
            int t = in.nextInt();
            for (int i = 0; i < t; i++) {
                StringBuilder lines = new StringBuilder();
                List<String> patterns = new ArrayList();
                int rows = in.nextInt();
                int columns = in.nextInt();
                for (int j = 0; j < rows; j++) {
                    lines.append(in.next());
                }
                int patternRows = in.nextInt();
                int patternColumns = in.nextInt();
                for (int j = 0; j < patternRows; j++) {
                    patterns.add(in.next());
                }
                if (GridSearch.Solution.gridSearch(lines.toString(), columns, patterns)) {
                    System.out.println("YES");
                } else {
                    System.out.println("NO");
                }
            }
        }

    }
}

redpajama_set_name: RedPajamaGithub


text:
import * as jQuery from "jquery";
/* tslint:disable:no-string-literal */
window["$"] = window["jQuery"] = jQuery;
/* tslint:enable:no-string-literal */
import * as GoldenLayout from "golden-layout";

const config = {
    content: [{

        content: [{
            content: [{
                componentName: "testComponent",
                title: "Component 1",
                type: "component",
            }, {
                componentName: "testComponent",
                title: "Component 2",
                type: "component",
            }],
            type: "stack",
            width: 60,
        }, {
            content: [{

                componentName: "testComponent",
                type: "component",
            }, {
                componentName: "testComponent",
                type: "component",
            }],
            type: "column",
        }],
        type: "row",
    }],
};

const myLayout = new GoldenLayout(config, document.getElementById("layout"));

myLayout.registerComponent("testComponent", (container, componentState) => {
    container.getElement().html("<h2>" + componentState.label + "</h2>");
});

myLayout.init();

const picker = document.getElementById("layout-picker") as HTMLSelectElement;

picker.addEventListener("change", (event) => {
    document.body.className = "golden-layout " + picker.value;
});


text:
A base image for Java apps, builds, etc.

The Java executables are linked to `/usr/bin`, similar to the Debian package for OpenJDK.

The JDK is installed to `/usr/lib/jvm/oracle_jdk8`.


text:
mbedtls_net_context *net_create()
{
    auto *ctx = new mbedtls_net_context;
    mbedtls_net_init(ctx);
    return ctx;
}

mbedtls_ssl_context *ssl_create()
{
    auto *ctx = new mbedtls_ssl_context;
    mbedtls_ssl_init(ctx);
    return ctx;
}

void ssl_free(mbedtls_ssl_context *ctx)
{
    mbedtls_ssl_free(ctx);
    delete ctx;
}

void web_free(mbedtls_net_context *ctx)
{
    mbedtls_net_free(ctx);
    delete ctx;
}

namespace fr
{
    SSLSocket::SSLSocket(std::shared_ptr<SSLContext> ssl_context_) noexcept
    :  ssl_context(std::move(ssl_context_)),
       ssl_socket_descriptor(nullptr, web_free),
       ssl(nullptr, ssl_free),
       should_verify(true),
       receive_timeout(0),
       is_blocking(true)
    {
        //Initialise mbedtls structures
        mbedtls_ssl_config_init(&conf);
    }

    SSLSocket::~SSLSocket()
    {
        //Close connection if active
        close_socket();

        //Cleanup mbedtls stuff
        mbedtls_ssl_config_free(&conf);
    }

    void SSLSocket::close_socket()
    {
        ssl = nullptr;
        ssl_socket_descriptor = nullptr;
    }

    Socket::Status SSLSocket::send_raw(const char *data, size_t size, size_t &sent)
    {
        sent = 0;
        ssize_t status = 0;

        while(sent < size)
        {
            status = mbedtls_ssl_write(ssl.get(), (const unsigned char *)data + sent, size - sent);
            if(status < 0)
            {
                if(status == MBEDTLS_ERR_SSL_WANT_READ || status == MBEDTLS_ERR_SSL_WANT_WRITE)
                {
                    if(is_blocking)
                    {
                        return Socket::Status::Timeout;
                    }
                    return Socket::Status::WouldBlock;
                }

                errno = status;
                return Socket::Status::SSLError;
            }

            sent += status;
        }

        return Socket::Status::Success;
    }

    Socket::Status SSLSocket::receive_raw(void *data, size_t data_size, size_t &received)
    {
        ssize_t status = 0;
        if(receive_timeout == 0)
        {
            do
            {
                status = mbedtls_ssl_read(ssl.get(), (unsigned char *) data, data_size);
                if(status == 0)
                {
                    return Socket::Status::Disconnected;
                }
                if(status < 0)
                {
                    if(status == MBEDTLS_ERR_SSL_WANT_READ || status == MBEDTLS_ERR_SSL_WANT_WRITE)
                    {
                        if(is_blocking)
                        {
                            return Socket::Status::Timeout;
                        }
                        continue;
                    }

                    errno = static_cast<int>(status);
                    return Socket::Status::SSLError;
                }
                break;
            } while(true);
        }
        else
        {
            do
            {
                status = mbedtls_net_recv_timeout(ssl.get(), (unsigned char *)data, data_size, receive_timeout);
                if(status == 0)
                {
                    return Socket::Status::Disconnected;
                }

                if(status < 0)
                {
                    if(status == MBEDTLS_ERR_SSL_TIMEOUT)
                    {
                        return Socket::Status::WouldBlock;
                    }

                    if(status == MBEDTLS_ERR_SSL_WANT_READ)
                    {
                        continue; //try again, interrupted before anything could be received
                    }

                    errno = static_cast<int>(status);
                    return Socket::Status::SSLError;
                }
                break;
            } while(true);
        }

        received = static_cast<size_t>(status);
        return Socket::Status::Success;

    }

    Socket::Status SSLSocket::connect(const std::string &address, const std::string &port, std::chrono::seconds timeout)
    {
        //Initialise mbedtls stuff
        ssl.reset(ssl_create());
        ssl_socket_descriptor.reset(net_create());

        //Due to mbedtls not supporting connect timeouts, we have to use an fr::TcpSocket to
        //Open the descriptor, and then steal it. This is a hack.
        {
            fr::TcpSocket socket;
            auto ret = socket.connect(address, port, timeout);
            if(ret != fr::Socket::Status::Success)
                return ret;
            ssl_socket_descriptor->fd = socket.get_socket_descriptor();
            set_remote_address(socket.get_remote_address());
            socket.set_descriptor(nullptr);
        }

        //Initialise SSL data structures
        int error = 0;
        if((error = mbedtls_ssl_config_defaults(&conf, MBEDTLS_SSL_IS_CLIENT, MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_PRESET_DEFAULT)) != 0)
        {
            errno = error;
            return Socket::Status::SSLError;
        }

        mbedtls_ssl_conf_authmode(&conf, should_verify ? MBEDTLS_SSL_VERIFY_REQUIRED : MBEDTLS_SSL_VERIFY_NONE);
        mbedtls_ssl_conf_ca_chain(&conf, &ssl_context->cacert, nullptr);
        mbedtls_ssl_conf_rng(&conf, mbedtls_ctr_drbg_random, &ssl_context->ctr_drbg);

        if((error = mbedtls_ssl_setup(ssl.get(), &conf)) != 0)
        {
            errno = error;
            return Socket::Status::SSLError;
        }

        if((error = mbedtls_ssl_set_hostname(ssl.get(), address.c_str())) != 0)
        {
            errno = error;
            return Socket::Status::SSLError;
        }

        mbedtls_ssl_set_bio(ssl.get(), ssl_socket_descriptor.get(), mbedtls_net_send, mbedtls_net_recv, nullptr);

        //Do SSL handshake
        while((error = mbedtls_ssl_handshake(ssl.get())) != 0)
        {
            if(error != MBEDTLS_ERR_SSL_WANT_READ && error != MBEDTLS_ERR_SSL_WANT_WRITE)
            {
                errno = error;
                return Socket::Status::SSLError;
            }
        }

        //Verify server certificate
        if(should_verify)
        {
            if(mbedtls_ssl_get_verify_result(ssl.get()) != 0)
            {
                return Socket::Status::VerificationFailed;
            }
        }

        //Update state
        reconfigure_socket();

        return Socket::Status::Success;
    }

    void SSLSocket::set_ssl_context(std::unique_ptr<mbedtls_ssl_context> context)
    {
        ssl.reset(context.release());
    }

    void SSLSocket::set_descriptor(void *descriptor)
    {
        ssl_socket_descriptor.reset(static_cast<mbedtls_net_context*>(descriptor));
        if(descriptor)
            reconfigure_socket();
    }

    void SSLSocket::verify_certificates(bool should_verify_)
    {
        should_verify = should_verify_;
    }

    fr::Socket::Status SSLSocket::set_blocking(bool should_block)
    {
        int ret = mbedtls_net_set_block(ssl_socket_descriptor.get());
        if(ret != 0)
        {
            errno = ret;
            return fr::Socket::Status::SSLError;
        }

        is_blocking = should_block;
        return fr::Socket::Status::Success;
    }

    void SSLSocket::reconfigure_socket()
    {
        if(!connected())
        {
            return;
        }

        int one = 1;
#ifndef _WIN32
        //Disable Nagle's algorithm
        setsockopt(get_socket_descriptor(), SOL_TCP, TCP_NODELAY, (char*)&one, sizeof(one));
#else
        //Disable Nagle's algorithm
        setsockopt(get_socket_descriptor(), IPPROTO_TCP, TCP_NODELAY, (char*)&one, sizeof(one));
        setsockopt(get_socket_descriptor(), SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (char*)&one, sizeof(one));

        //Apply receive timeout
        DWORD timeout_dword = static_cast<DWORD>(get_receive_timeout());
        setsockopt(get_socket_descriptor(), SOL_SOCKET, SO_RCVTIMEO, (const char*)&timeout_dword, sizeof timeout_dword);
#endif
    }

    int32_t SSLSocket::get_socket_descriptor() const
    {
        if(!ssl_socket_descriptor)
            return -1;
        return ssl_socket_descriptor->fd;
    }

    bool SSLSocket::connected() const
    {
        return ssl_socket_descriptor && ssl_socket_descriptor->fd > -1;
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=1024, user-scalable=no">

    <title>Bars Level Up - Javascript</title>

    <link rel="stylesheet" href="../libs/deck/core/deck.core.css">

    <link rel="stylesheet" href="../libs/deck/extensions/goto/deck.goto.css">
    <link rel="stylesheet" href="../libs/deck/extensions/menu/deck.menu.css">
    <link rel="stylesheet" href="../libs/deck/extensions/navigation/deck.navigation.css">
    <link rel="stylesheet" href="../libs/deck/extensions/status/deck.status.css">
    <link rel="stylesheet" href="../libs/deck/extensions/hash/deck.hash.css">
    <link rel="stylesheet" href="../libs/deck/extensions/scale/deck.scale.css">

    <link rel="stylesheet" href="../libs/deck/themes/style/swiss.css">

    <link rel="stylesheet" href="../libs/deck/themes/transition/horizontal-slide.css">

    <link rel="stylesheet" href="../libs/highlight.js/styles/default.css">

Bars Level Up - Javascript 01

План

Simple Types

Objects

Functions

Inheritance

Caution!

Simple Types

Objects

var obj = {};

Functions

    var add = function(a,b){
        return a + b;
    }

Inheritance

Caution!

Источники

JavaScript: The Good Parts

JavsScript Garden http://shamansir.github.io/JavaScript-Garden/

←
→

    /

<form action="." method="get" class="goto-form">
    Go to slide:
    <input type="text" name="slidenum" id="goto-slide" list="goto-datalist">
    <datalist id="goto-datalist"></datalist>
    <input type="submit" value="Go">
</form>

#


text:
namespace Paintown{

class OpenborMod: public Mod {
public:
    OpenborMod(const Filesystem::AbsolutePath & path);

    const std::string getMenu();
    virtual Filesystem::AbsolutePath selectPlayer(const std::string & message, const Level::LevelInfo & info, int & remap, const InputSource & source);
    virtual std::vector<Level::LevelInfo> getLevels();
    virtual Graphics::Bitmap * createBitmap(const Filesystem::RelativePath & path);

    Bor::PackReader reader;
};

}

#endif


text:
using namespace std;

// qPoS
map<txnouttype, QPKeyType> mapQPoSKeyTypes = boost::assign::map_list_of
      (TX_SETOWNER, QPKEY_OWNER)
      (TX_SETMANAGER, QPKEY_MANAGER)
      (TX_SETDELEGATE, QPKEY_DELEGATE)
      (TX_SETCONTROLLER, QPKEY_CONTROLLER);

void ExtractPurchase(const valtype &vch, qpos_purchase &prchsRet)
{
    valtype::const_iterator first = vch.begin();
    valtype::const_iterator last = first;
    if (!IncrementN(vch, last, 8))
    {
        return;
    }
    prchsRet.value = GETUINT64(first, last);
    first = last;
    prchsRet.keys.clear();
    while (true)
    {
        if (!IncrementN(vch, last, 33))
        {
            break;
        }
        prchsRet.keys.push_back(CPubKey(valtype(first, last)));
        first = last;
    }
    last = first;
    if ((prchsRet.keys.size() == 3) || (prchsRet.keys.size() == 4))
    {
        if (!IncrementN(vch, last, 4))
        {
            return;
        }
        prchsRet.pcm = GETUINT32(first, last);
    }
    else
    {
        prchsRet.pcm = 0;
    }
    first = last;
    last = vch.end();
    string sTemp(first, last);
    prchsRet.alias.clear();
    bool fAllInt = true;
    for (unsigned int i = 0; i < sTemp.size(); ++i)
    {
        char c = sTemp[i];
        if (c)
        {
            if ((c < '0') || (c > '9'))
            {
                fAllInt = false;
            }
            prchsRet.alias.push_back(c);
        }
        else
        {
            break;
        }
    }
    prchsRet.nft = 0;
    if (fAllInt)
    {
        int k = 1;
        for (int i = prchsRet.alias.size() - 1; i >= 0; --i)
        {
            prchsRet.nft += k * (prchsRet.alias[i] - '0');
            // prevents overflow -- there will never be this many NFTs
            if (prchsRet.nft > 100000)
            {
                break;
            }
            k *= 10;
        }
        // since nft retains full info of original alias, we can reassign here
        if (mapNfts.count(k))
        {
            prchsRet.alias = mapNfts[k].strNickname;
        }
    }
    else
    {
        string sLC = ToLowercaseSafe(prchsRet.alias);
        if (mapNftLookup.count(sLC))
        {
            prchsRet.nft = mapNftLookup[sLC];
            // prchsRet.alias = mapNft[prchsRet.nft].strNickname;
        }
    }
}

void ExtractPurchase(const valtype &vch, QPTxDetails &deetsRet)
{
    deetsRet.Clear();
    qpos_purchase purchase;
    ExtractPurchase(vch, purchase);
    deetsRet.alias = purchase.alias;
    deetsRet.keys = purchase.keys;
    deetsRet.pcm = purchase.pcm;
    deetsRet.value = purchase.value;
    deetsRet.id = purchase.nft;
}

// ensure setkeyRet.keytype is assigned
void ExtractSetKey(const valtype &vch, qpos_setkey &setkeyRet)
{
    valtype::const_iterator first = vch.begin();
    valtype::const_iterator last = first;
    if (!IncrementN(vch, last, 4))
    {
        return;
    }
    setkeyRet.id = GETUINT(first, last);
    first = last;
    if (!IncrementN(vch, last, 33))
    {
        return;
    }
    setkeyRet.key = CPubKey(valtype(first, last));
    if (setkeyRet.keytype == QPKEY_DELEGATE)
    {
        first = last;
        if (!IncrementN(vch, last, 4))
        {
            return;
        }
        setkeyRet.pcm = GETUINT32(first, last);
    }
    else
    {
        setkeyRet.pcm = 0;
    }
}

void ExtractSetKey(const valtype &vch, QPTxDetails &deetsRet)
{
    deetsRet.Clear();
    qpos_setkey setkey;
    if (mapQPoSKeyTypes.count(static_cast<txnouttype>(deetsRet.t)))
    {
        setkey.keytype = mapQPoSKeyTypes[static_cast<txnouttype>(deetsRet.t)];
    }
    ExtractSetKey(vch, setkey);
    deetsRet.id = setkey.id;
    deetsRet.keys.clear();
    deetsRet.keys.push_back(setkey.key);
    deetsRet.pcm = setkey.pcm;
}

void ExtractSetState(const valtype &vch, qpos_setstate &setstateRet)
{
    valtype::const_iterator first = vch.begin();
    valtype::const_iterator last = first;
    if (!IncrementN(vch, last, 4))
    {
        return;
    }
    setstateRet.id = GETUINT(first, last);
}

void ExtractSetState(const valtype &vch, QPTxDetails &deetsRet)
{
    deetsRet.Clear();
    qpos_setstate setstate;
    ExtractSetState(vch, setstate);
    deetsRet.id = setstate.id;
}

void ExtractClaim(const valtype &vch, qpos_claim &claimRet)
{
    valtype::const_iterator first = vch.begin();
    valtype::const_iterator last = first;
    if (!IncrementN(vch, last, 33))
    {
        return;
    }
    claimRet.key = CPubKey(valtype(first, last));
    first = last;
    if (!IncrementN(vch, last, 8))
    {
        return;
    }
    claimRet.value = GETUINT64(first, last);
}

void ExtractClaim(const valtype &vch, QPTxDetails &deetsRet)
{
    deetsRet.Clear();
    qpos_claim claim;
    ExtractClaim(vch, claim);
    deetsRet.keys.clear();
    deetsRet.keys.push_back(claim.key);
    deetsRet.value = claim.value;
}

void ExtractSetMeta(const valtype &vch, qpos_setmeta &setmetaRet)
{
    valtype::const_iterator first = vch.begin();
    valtype::const_iterator last = first;
    if (!IncrementN(vch, last, 4))
    {
        return;
    }
    setmetaRet.id = GETUINT(first, last);

    first = last;
    if (!IncrementN(vch, last, 16))
    {
        return;
    }

    valtype::const_iterator e;
    for (e = first; e != last; ++e)
    {
        if (*e == static_cast<unsigned char>(0))
        {
            break;
        }
    }
    setmetaRet.key = string(first, e);

    first = last;
    if (!IncrementN(vch, last, 40))
    {
        return;
    }

    for (e = first; e != last; ++e)
    {
        if (*e == static_cast<unsigned char>(0))
        {
            break;
        }
    }
    setmetaRet.value = string(first, e);
}

void ExtractSetMeta(const valtype &vch, QPTxDetails &deetsRet)
{
    deetsRet.Clear();
    qpos_setmeta setmeta;
    ExtractSetMeta(vch, setmeta);
    deetsRet.id = setmeta.id;
    deetsRet.meta_key = setmeta.key;
    deetsRet.meta_value = setmeta.value;
}


text:
<?php

namespace ONGR\ElasticsearchBundle\Client;

use Elasticsearch\Client;
use Elasticsearch\Common\Exceptions\Forbidden403Exception;
use ONGR\ElasticsearchBundle\Cache\WarmerInterface;
use ONGR\ElasticsearchBundle\Cache\WarmersContainer;
use ONGR\ElasticsearchBundle\Mapping\MappingTool;

/**
 * This class interacts with elasticsearch using injected client.
 */
class Connection
{
    /**
     * @var Client
     */
    private $client;

    /**
     * Holds index information. Similar structure to elasticsearch docs.
     *
     * Example:
     *
     * ```php
     * array(
     *      'index' => 'index name'
     *      'body' => [
     *          'settings' => [...],
     *          'mappings' => [...]
     *      ]
     * )
     * ```
     *
     * @var array
     */
    private $settings;

    /**
     * @var array Container for bulk queries.
     */
    private $bulkQueries;

    /**
     * @var array Holder for consistency, refresh and replication parameters.
     */
    private $bulkParams;

    /**
     * @var WarmersContainer
     */
    private $warmers;

    /**
     * @var bool
     */
    private $readOnly;

    /**
     * Construct.
     *
     * @param Client $client   Elasticsearch client.
     * @param array  $settings Settings array.
     */
    public function __construct($client, $settings)
    {
        $this->client = $client;
        $this->settings = $settings;
        $this->bulkQueries = [];
        $this->bulkParams = [];
        $this->warmers = new WarmersContainer();
    }

    /**
     * @return Client
     */
    public function getClient()
    {
        return $this->client;
    }

    /**
     * Adds query to bulk queries container.
     *
     * @param string       $operation One of: index, update, delete, create.
     * @param string|array $type      Elasticsearch type name.
     * @param array        $query     DSL to execute.
     *
     * @throws \InvalidArgumentException
     */
    public function bulk($operation, $type, array $query)
    {
        $this->isReadOnly('Bulk');

        if (!in_array($operation, ['index', 'create', 'update', 'delete'])) {
            throw new \InvalidArgumentException('Wrong bulk operation selected');
        }

        $this->bulkQueries['body'][] = [
            $operation => array_filter(
                [
                    '_index' => $this->getIndexName(),
                    '_type' => $type,
                    '_id' => isset($query['_id']) ? $query['_id'] : null,
                    '_ttl' => isset($query['_ttl']) ? $query['_ttl'] : null,
                    '_parent' => isset($query['_parent']) ? $query['_parent'] : null,
                ]
            ),
        ];
        unset($query['_id'], $query['_ttl'], $query['_parent']);

        switch ($operation) {
            case 'index':
            case 'create':
                $this->bulkQueries['body'][] = $query;
                break;
            case 'update':
                $this->bulkQueries['body'][] = ['doc' => $query];
                break;
            case 'delete':
                // Body for delete operation is not needed to apply.
            default:
                // Do nothing.
                break;
        }
    }

    /**
     * Optional setter to change bulk query params.
     *
     * @param array $params Possible keys:
     *                      ['consistency'] = (enum) Explicit write consistency setting for the operation.
     *                      ['refresh']     = (boolean) Refresh the index after performing the operation.
     *                      ['replication'] = (enum) Explicitly set the replication type.
     */
    public function setBulkParams(array $params)
    {
        $this->bulkParams = $params;
    }

    /**
     * Flushes the current query container to the index, used for bulk queries execution.
     */
    public function commit()
    {
        $this->bulkQueries = array_merge($this->bulkQueries, $this->bulkParams);
        $this->getClient()->bulk($this->bulkQueries);
        $this->flush();

        $this->bulkQueries = [];
    }

    /**
     * Send refresh call to index.
     *
     * Makes your documents available for search.
     */
    public function refresh()
    {
        $this->getClient()->indices()->refresh();
    }

    /**
     * Send flush call to index.
     *
     * Causes a Lucene commit to happen (more expensive than refresh).
     */
    public function flush()
    {
        $this->getClient()->indices()->flush();
    }

    /**
     * Removes a single document.
     *
     * @param array $params Parameters.
     *
     *                      $params = [
     *                      'index' => 'index_name',
     *                      'type' => 'document_type',
     *                      'id' => 'id',
     *                      ];.
     *
     * @return array
     */
    public function delete($params)
    {
        $this->isReadOnly('Delete');

        return $this->getClient()->delete($params);
    }

    /**
     * Delete by query.
     *
     * @param array $types List of types to search in.
     * @param array $query Query to execute.
     *
     * @return array
     */
    public function deleteByQuery(array $types, array $query)
    {
        $params = [];
        $params['index'] = $this->getIndexName();
        $params['type'] = implode(',', $types);
        $params['body'] = $query;

        return $this->getClient()->deleteByQuery($params);
    }

    /**
     * Executes search query in the index.
     *
     * @param array $types             List of types to search in.
     * @param array $query             Query to execute.
     * @param array $queryStringParams Query parameters.
     *
     * @return array
     */
    public function search(array $types, array $query, array $queryStringParams = [])
    {
        $params = [];
        $params['index'] = $this->getIndexName();
        $params['type'] = implode(',', $types);
        $params['body'] = $query;

        if (!empty($queryStringParams)) {
            $params = array_merge($queryStringParams, $params);
        }

        return $this->getClient()->search($params);
    }

    /**
     * Execute scrolled search.
     *
     * @param string $scrollId       Scroll id.
     * @param string $scrollDuration Specify how long a consistent view of the index should be maintained
     *                               for scrolled search.
     *
     * @return array
     */
    public function scroll($scrollId, $scrollDuration)
    {
        $params = [];
        $params['scroll_id'] = $scrollId;
        $params['scroll'] = $scrollDuration;

        return $this->getClient()->scroll($params);
    }

    /**
     * Creates fresh elasticsearch index.
     *
     * @param bool $putWarmers Determines if warmers should be loaded.
     * @param bool $noMapping  Determines if mapping should be included.
     */
    public function createIndex($putWarmers = false, $noMapping = false)
    {
        $this->isReadOnly('Create index');

        $settings = $this->settings;

        if ($noMapping) {
            unset($settings['body']['mappings']);
        }
        $this->getClient()->indices()->create($settings);

        if ($putWarmers) {
            // Sometimes Elasticsearch gives service unavailable.
            usleep(200000);
            $this->putWarmers();
        }
    }

    /**
     * Drops elasticsearch index.
     */
    public function dropIndex()
    {
        $this->isReadOnly('Drop index');

        $this->getClient()->indices()->delete(['index' => $this->getIndexName()]);
    }

    /**
     * Puts mapping into elasticsearch client.
     *
     * @param array $types Specific types to put.
     *
     * @return int
     */
    public function createTypes(array $types = [])
    {
        $this->isReadOnly('Create types');

        $mapping = $this->getMapping($types);
        if (empty($mapping)) {
            return 0;
        }

        $mapping = array_diff_key($mapping, $this->getMappingFromIndex($types));
        if (empty($mapping)) {
            return -1;
        }

        $this->loadMappingArray($mapping);

        return 1;
    }

    /**
     * Drops mapping from elasticsearch client.
     *
     * @param array $types Specific types to drop.
     *
     * @return int
     */
    public function dropTypes(array $types = [])
    {
        $this->isReadOnly('Drop types');

        $mapping = $this->getMapping($types);

        if (empty($mapping)) {
            return 0;
        }

        $this->unloadMappingArray(array_keys($mapping));

        return 1;
    }

    /**
     * Updates elasticsearch client mapping.
     *
     * @param array $types Specific types to update.
     *
     * @return int
     */
    public function updateTypes(array $types = [])
    {
        $this->isReadOnly('Update types');

        if (!$this->getMapping($types)) {
            return -1;
        }

        $tempSettings = $this->settings;
        $tempSettings['index'] = uniqid('mapping_check_');
        $mappingCheckConnection = new Connection($this->getClient(), $tempSettings);
        $mappingCheckConnection->createIndex();
        $mappingCheckConnection->createTypes($types);

        $newMapping = $mappingCheckConnection->getMappingFromIndex($types);
        $oldMapping = $this->getMappingFromIndex($types);

        $mappingCheckConnection->dropIndex();

        $tool = new MappingTool();
        $updated = (int)$tool->checkMapping($oldMapping, $newMapping);

        if ($updated) {
            $this->unloadMappingArray($tool->getRemovedTypes());
            $this->loadMappingArray($tool->getUpdatedTypes());
        }

        return $updated;
    }

    /**
     * Tries to drop and create fresh elasticsearch index.
     *
     * @param bool $putWarmers Determines if warmers should be loaded.
     * @param bool $noMapping  Determines if mapping should be included.
     */
    public function dropAndCreateIndex($putWarmers = false, $noMapping = false)
    {
        try {
            $this->dropIndex();
        } catch (\Exception $e) {
            // Do nothing because I'm only trying.
        }

        $this->createIndex($putWarmers, $noMapping);
    }

    /**
     * Checks if connection index is already created.
     *
     * @return bool
     */
    public function indexExists()
    {
        return $this->getClient()->indices()->exists(['index' => $this->getIndexName()]);
    }

    /**
     * Returns index name this connection is attached to.
     *
     * @return string
     */
    public function getIndexName()
    {
        return $this->settings['index'];
    }

    /**
     * Sets index name this connection is attached to.
     *
     * @param string $name
     */
    public function setIndexName($name)
    {
        $this->settings['index'] = $name;
    }

    /**
     * Returns mapping by type if defined.
     *
     * @param string|array $type Type names.
     *
     * @return array|null
     */
    public function getMapping($type = [])
    {
        if (isset($this->settings['body']['mappings'])) {
            return $this->filterMapping($type, $this->settings['body']['mappings']);
        }

        return null;
    }

    /**
     * Sets whole mapping, deleting non-existent types.
     *
     * @param array $mapping Mapping structure to force.
     */
    public function forceMapping(array $mapping)
    {
        $this->settings['body']['mappings'] = $mapping;
    }

    /**
     * Sets mapping by type.
     *
     * @param string $type    Type name.
     * @param array  $mapping Mapping structure.
     */
    public function setMapping($type, array $mapping)
    {
        $this->settings['body']['mappings'][$type] = $mapping;
    }

    /**
     * Sets multiple mappings.
     *
     * @param array $mapping Mapping to set.
     * @param bool  $cleanUp Cleans current mapping.
     */
    public function setMultipleMapping(array $mapping, $cleanUp = false)
    {
        if ($cleanUp === true) {
            unset($this->settings['body']['mappings']);
        }

        foreach ($mapping as $type => $map) {
            $this->setMapping($type, $map);
        }
    }

    /**
     * Mapping is compared with loaded, if needed updates it and returns true.
     *
     * @param array $types Types to update.
     *
     * @return bool
     *
     * @throws \LogicException
     *
     * @deprecated Will be removed in 1.0. Please now use Connection#updateTypes().
     */
    public function updateMapping(array $types = [])
    {
        return $this->updateTypes($types);
    }

    /**
     * Closes index.
     */
    public function close()
    {
        $this->isReadOnly('Close index');

        $this->getClient()->indices()->close(['index' => $this->getIndexName()]);
    }

    /**
     * Returns whether the index is opened.
     *
     * @return bool
     */
    public function isOpen()
    {
        try {
            $this->getClient()->indices()->recovery(['index' => $this->getIndexName()]);
        } catch (Forbidden403Exception $ex) {
            return false;
        }

        return true;
    }

    /**
     * Opens index.
     */
    public function open()
    {
        $this->isReadOnly('Open index');

        $this->getClient()->indices()->open(['index' => $this->getIndexName()]);
    }

    /**
     * Returns mapping from index.
     *
     * @param array|string $types Returns only certain set of types if set.
     *
     * @return array
     */
    public function getMappingFromIndex($types = [])
    {
        $mapping = $this
            ->getClient()
            ->indices()
            ->getMapping(['index' => $this->getIndexName()]);

        if (array_key_exists($this->getIndexName(), $mapping)) {
            return $this->filterMapping($types, $mapping[$this->getIndexName()]['mappings']);
        }

        return [];
    }

    /**
     * Returns Elasticsearch version number.
     *
     * @return string
     */
    public function getVersionNumber()
    {
        return $this->getClient()->info()['version']['number'];
    }

    /**
     * Updates index settings recursive.
     *
     * @param array $settings Settings.
     * @param bool  $force    Should replace structure instead of merging.
     */
    public function updateSettings(array $settings, $force = false)
    {
        if ($force) {
            $this->settings = $settings;
        } else {
            $this->settings = array_replace_recursive($this->settings, $settings);
        }
    }

    /**
     * Clears elasticsearch client cache.
     */
    public function clearCache()
    {
        $this->isReadOnly('Clear cache');

        $this->getClient()->indices()->clearCache(['index' => $this->getIndexName()]);
    }

    /**
     * Adds warmer to container.
     *
     * @param WarmerInterface $warmer
     */
    public function addWarmer(WarmerInterface $warmer)
    {
        $this->warmers->addWarmer($warmer);
    }

    /**
     * Loads warmers into elasticseach.
     *
     * @param array $names Warmers names to put.
     *
     * @return bool
     */
    public function putWarmers(array $names = [])
    {
        return $this->warmersAction('put', $names);
    }

    /**
     * Deletes warmers from elasticsearch index.
     *
     * @param array $names Warmers names to delete.
     *
     * @return bool
     */
    public function deleteWarmers(array $names = [])
    {
        return $this->warmersAction('delete', $names);
    }

    /**
     * Set connection to read only state.
     *
     * @param bool $readOnly
     */
    public function setReadOnly($readOnly)
    {
        $this->readOnly = $readOnly;
    }

    /**
     * Checks if connection is read only.
     *
     * @param string $message Error message.
     *
     * @throws Forbidden403Exception
     */
    public function isReadOnly($message = '')
    {
        if ($this->readOnly) {
            throw new Forbidden403Exception("Manager is readonly! {$message} operation not permitted.");
        }
    }

    /**
     * Executes warmers actions.
     *
     * @param string $action Action name.
     * @param array  $names  Warmers names.
     *
     * @return bool
     *
     * @throws \LogicException
     */
    private function warmersAction($action, $names = [])
    {
        $this->isReadOnly('Warmer edit');

        $status = false;
        $warmers = $this->warmers->getWarmers();
        $this->validateWarmers($names, array_keys($warmers));

        foreach ($warmers as $name => $body) {
            if (empty($names) || in_array($name, $names)) {
                switch ($action) {
                    case 'put':
                        $this->getClient()->indices()->putWarmer(
                            [
                                'index' => $this->getIndexName(),
                                'name' => $name,
                                'body' => $body,
                            ]
                        );
                        break;
                    case 'delete':
                        $this->getClient()->indices()->deleteWarmer(
                            [
                                'index' => $this->getIndexName(),
                                'name' => $name,
                            ]
                        );
                        break;
                    default:
                        throw new \LogicException('Unknown warmer action');
                }
            }

            $status = true;
        }

        return $status;
    }

    /**
     * Warmer names validation.
     *
     * @param array $names       Names to check.
     * @param array $warmerNames Warmer names loaded.
     *
     * @throws \RuntimeException
     */
    private function validateWarmers($names, $warmerNames = [])
    {
        if (empty($warmerNames)) {
            $warmerNames = array_keys($this->warmers->getWarmers());
        }

        $unknown = array_diff($names, $warmerNames);

        if (!empty($unknown)) {
            throw new \RuntimeException(
                'Warmer(s) named ' . implode(', ', $unknown)
                . ' do not exist. Available: ' . implode(', ', $warmerNames)
            );
        }
    }

    /**
     * Puts mapping into elasticsearch.
     *
     * @param array $mapping Mapping to put into client.
     */
    private function loadMappingArray(array $mapping)
    {
        foreach ($mapping as $type => $properties) {
            $this->getClient()->indices()->putMapping(
                [
                    'index' => $this->getIndexName(),
                    'type' => $type,
                    'body' => [
                        $type => $properties,
                    ],
                ]
            );
        }
    }

    /**
     * Drops mapping from elasticsearch client.
     *
     * @param array $mapping Mapping to drop from client.
     */
    private function unloadMappingArray(array $mapping)
    {
        foreach ($mapping as $type) {
            $this->getClient()->indices()->deleteMapping(
                [
                    'index' => $this->getIndexName(),
                    'type' => $type,
                ]
            );
        }
    }

    /**
     * Filters out mapping from given type.
     *
     * @param string|array $type    Types to filter from mapping.
     * @param array        $mapping Mapping array.
     *
     * @return array
     */
    private function filterMapping($type, $mapping)
    {
        if (empty($type)) {
            return $mapping;
        } elseif (is_string($type) && array_key_exists($type, $mapping)) {
            return $mapping[$type];
        } elseif (is_array($type)) {
            return array_intersect_key($mapping, array_flip($type));
        }

        return [];
    }
}


text:
/* 24_bump_map_torus.c - OpenGL-based bump mapping example using Cg programs
   from Chapter 8 of "The Cg Tutorial" (Addison-Wesley, ISBN 0321194969). */

/* Requires the OpenGL Utility Toolkit (GLUT) and Cg runtime (version
   1.5 or higher). */

#include <stdio.h>    /* for printf and NULL */
#include <stdlib.h>   /* for exit */
#include <math.h>     /* for sqrt, sin, and cos */
#include <assert.h>   /* for assert */

#include <GL/glew.h>

#ifdef __APPLE__
#include <GLUT/glut.h>
#else
#include <GL/glut.h>
#endif

#ifdef _WIN32
#include <GL/wglew.h>
#else
#ifdef __APPLE__
#include <OpenGL/OpenGL.h>
#else
#include <GL/glxew.h>
#endif
#endif

#include <Cg/cg.h>    /* Can't include this?  Is Cg Toolkit installed! */
#include <Cg/cgGL.h>

static CGcontext   myCgContext;
static CGprofile   myCgVertexProfile,
                   myCgFragmentProfile;
static CGprogram   myCgVertexProgram,
                   myCgFragmentProgram;
static CGparameter myCgVertexParam_lightPosition,
                   myCgVertexParam_eyePosition,
                   myCgVertexParam_modelViewProj,
                   myCgVertexParam_torusInfo,
                   myCgFragmentParam_ambient,
                   myCgFragmentParam_LMd,
                   myCgFragmentParam_LMs,
                   myCgFragmentParam_normalMap,
                   myCgFragmentParam_normalizeCube,
                   myCgFragmentParam_normalizeCube2;

static const char *myProgramName = "24_bump_map_torus",
                  *myVertexProgramFileName = "C8E6v_torus.cg",
/* page 223 */    *myVertexProgramName = "C8E6v_torus",
                  *myFragmentProgramFileName = "C8E4f_specSurf.cg",
/* page 209 */    *myFragmentProgramName = "C8E4f_specSurf";

static float myEyeAngle = 0,
             myAmbient[4] = { 0.3f, 0.3f, 0.3f, 0.3f }, /* Dull white */
             myLMd[4] = { 0.9f, 0.6f, 0.3f, 1.0f },     /* Gold */
             myLMs[4] = { 1.0f, 1.0f, 1.0f, 1.0f };     /* Bright white */

/* OpenGL texture object (TO) handles. */
enum {
  TO_NORMALIZE_VECTOR_CUBE_MAP = 1,
  TO_NORMAL_MAP = 2,
};

static const GLubyte
myBrickNormalMapImage[3*(128*128+64*64+32*32+16*16+8*8+4*4+2*2+1*1)] = {
/* RGB8 image data for a mipmapped 128x128 normal map for a brick pattern */
#include "brick_image.h"
};

static const GLubyte
myNormalizeVectorCubeMapImage[6*3*32*32] = {
/* RGB8 image data for a normalization vector cube map with 32x32 faces */
#include "normcm_image.h"
};

static void checkForCgError(const char *situation)
{
  CGerror error;
  const char *string = cgGetLastErrorString(&error);

  if (error != CG_NO_ERROR) {
    printf("%s: %s: %s\n",
      myProgramName, situation, string);
    if (error == CG_COMPILER_ERROR) {
      printf("%s\n", cgGetLastListing(myCgContext));
    }
    exit(1);
  }
}

/* Forward declared GLUT callbacks registered by main. */
static void display(void);
static void keyboard(unsigned char c, int x, int y);
static void menu(int item);
static void requestSynchronizedSwapBuffers(void);

int main(int argc, char **argv)
{
  const GLubyte *image;
  unsigned int size, level;
  int face;

  glutInitWindowSize(400, 400);
  glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);
  glutInit(&argc, argv);

  glutCreateWindow(myProgramName);
  glutDisplayFunc(display);
  glutKeyboardFunc(keyboard);

  /* Initialize OpenGL entry points. */
  if (glewInit()!=GLEW_OK || !GLEW_VERSION_1_3) {
    fprintf(stderr, "%s: failed to initialize GLEW, OpenGL 1.3 required.\n", myProgramName);
    exit(1);
  }

  requestSynchronizedSwapBuffers();
  glClearColor(0.1, 0.3, 0.6, 0.0);  /* Blue background */
  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();
  gluPerspective(
    60.0,   /* Field of view in degree */
    1.0,    /* Aspect ratio */
    0.1,    /* Z near */
    100.0); /* Z far */
  glMatrixMode(GL_MODELVIEW);
  glEnable(GL_DEPTH_TEST);

  glPixelStorei(GL_UNPACK_ALIGNMENT, 1); /* Tightly packed texture data. */

  glBindTexture(GL_TEXTURE_2D, TO_NORMAL_MAP);
  /* Load each mipmap level of range-compressed 128x128 brick normal
     map texture. */
  for (size = 128, level = 0, image = myBrickNormalMapImage;
       size > 0;
       image += 3*size*size, size /= 2, level++) {
    glTexImage2D(GL_TEXTURE_2D, level,
      GL_RGB8, size, size, 0, GL_RGB, GL_UNSIGNED_BYTE, image);
  }
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,
    GL_LINEAR_MIPMAP_LINEAR);

  glBindTexture(GL_TEXTURE_CUBE_MAP, TO_NORMALIZE_VECTOR_CUBE_MAP);
  /* Load each 32x32 face (without mipmaps) of range-compressed "normalize
     vector" cube map. */
  for (face = 0, image = myNormalizeVectorCubeMapImage;
       face < 6;
       face++, image += 3*32*32) {
    glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, 0,
      GL_RGB8, 32, 32, 0, GL_RGB, GL_UNSIGNED_BYTE, image);
  }
  glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
  glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

  myCgContext = cgCreateContext();
  checkForCgError("creating context");
  cgGLSetDebugMode(CG_FALSE);
  cgSetParameterSettingMode(myCgContext, CG_DEFERRED_PARAMETER_SETTING);

  myCgVertexProfile = cgGLGetLatestProfile(CG_GL_VERTEX);
  cgGLSetOptimalOptions(myCgVertexProfile);
  checkForCgError("selecting vertex profile");

  myCgVertexProgram =
    cgCreateProgramFromFile(
      myCgContext,              /* Cg runtime context */
      CG_SOURCE,                /* Program in human-readable form */
      myVertexProgramFileName,  /* Name of file containing program */
      myCgVertexProfile,        /* Profile: OpenGL ARB vertex program */
      myVertexProgramName,      /* Entry function name */
      NULL);                    /* No extra compiler options */
  checkForCgError("creating vertex program from file");
  cgGLLoadProgram(myCgVertexProgram);
  checkForCgError("loading vertex program");

  myCgVertexParam_lightPosition =
    cgGetNamedParameter(myCgVertexProgram, "lightPosition");
  checkForCgError("could not get lightPosition parameter");

  myCgVertexParam_eyePosition =
    cgGetNamedParameter(myCgVertexProgram, "eyePosition");
  checkForCgError("could not get eyePosition parameter");

  myCgVertexParam_modelViewProj =
    cgGetNamedParameter(myCgVertexProgram, "modelViewProj");
  checkForCgError("could not get modelViewProj parameter");

  myCgVertexParam_torusInfo =
    cgGetNamedParameter(myCgVertexProgram, "torusInfo");
  checkForCgError("could not get torusInfo parameter");

  myCgFragmentProfile = cgGLGetLatestProfile(CG_GL_FRAGMENT);
  cgGLSetOptimalOptions(myCgFragmentProfile);
  checkForCgError("selecting fragment profile");

  myCgFragmentProgram =
    cgCreateProgramFromFile(
      myCgContext,                /* Cg runtime context */
      CG_SOURCE,                  /* Program in human-readable form */
      myFragmentProgramFileName,  /* Name of file containing program */
      myCgFragmentProfile,        /* Profile: OpenGL ARB vertex program */
      myFragmentProgramName,      /* Entry function name */
      NULL);                      /* No extra compiler options */
  checkForCgError("creating fragment program from file");
  cgGLLoadProgram(myCgFragmentProgram);
  checkForCgError("loading fragment program");

  myCgFragmentParam_ambient =
    cgGetNamedParameter(myCgFragmentProgram, "ambient");
  checkForCgError("getting ambient parameter");

  myCgFragmentParam_LMd =
    cgGetNamedParameter(myCgFragmentProgram, "LMd");
  checkForCgError("getting LMd parameter");

  myCgFragmentParam_LMs =
    cgGetNamedParameter(myCgFragmentProgram, "LMs");
  checkForCgError("getting LMs parameter");

  myCgFragmentParam_normalMap =
    cgGetNamedParameter(myCgFragmentProgram, "normalMap");
  checkForCgError("getting normalMap parameter");

  myCgFragmentParam_normalizeCube =
    cgGetNamedParameter(myCgFragmentProgram, "normalizeCube");
  checkForCgError("getting normalizeCube parameter");

  myCgFragmentParam_normalizeCube2 =
    cgGetNamedParameter(myCgFragmentProgram, "normalizeCube2");
  checkForCgError("getting normalizeCube2 parameter");

  cgGLSetTextureParameter(myCgFragmentParam_normalMap,
    TO_NORMAL_MAP);
  checkForCgError("setting normal map 2D texture");

  cgGLSetTextureParameter(myCgFragmentParam_normalizeCube,
    TO_NORMALIZE_VECTOR_CUBE_MAP);
  checkForCgError("setting 1st normalize vector cube map");

  cgGLSetTextureParameter(myCgFragmentParam_normalizeCube2,
    TO_NORMALIZE_VECTOR_CUBE_MAP);
  checkForCgError("setting 2nd normalize vector cube map");

  glutCreateMenu(menu);
  glutAddMenuEntry("[ ] Animate", ' ');
  glutAttachMenu(GLUT_RIGHT_BUTTON);

  glutMainLoop();
  return 0;
}

/* Draw a flat 2D patch that can be "rolled & bent" into a 3D torus by
   a vertex program. */
void
drawFlatPatch(float rows, float columns)
{
  const float m = 1.0f/columns;
  const float n = 1.0f/rows;
  int i, j;

  for (i=0; i<columns; i++) {
    glBegin(GL_QUAD_STRIP);
    for (j=0; j<=rows; j++) {
      glVertex2f(i*m, j*n);
      glVertex2f((i+1)*m, j*n);
    }
    glVertex2f(i*m, 0);
    glVertex2f((i+1)*m, 0);
    glEnd();
  }
}

static void display(void)
{
  const float outerRadius = 6, innerRadius = 2;
  const int sides = 20, rings = 40;
  const float eyeRadius = 18.0;
  const float eyeElevationRange = 8.0;
  float eyePosition[3];

  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

  eyePosition[0] = eyeRadius * sin(myEyeAngle);
  eyePosition[1] = eyeElevationRange * sin(myEyeAngle);
  eyePosition[2] = eyeRadius * cos(myEyeAngle);

  glLoadIdentity();
  gluLookAt(
    eyePosition[0], eyePosition[1], eyePosition[2],
    0.0 ,0.0,  0.0,   /* XYZ view center */
    0.0, 1.0,  0.0);  /* Up is in positive Y direction */

  cgGLBindProgram(myCgVertexProgram);
  checkForCgError("binding vertex program");

  cgGLSetStateMatrixParameter(myCgVertexParam_modelViewProj,
                              CG_GL_MODELVIEW_PROJECTION_MATRIX,
                              CG_GL_MATRIX_IDENTITY);
  checkForCgError("setting modelview-projection matrix");
  cgSetParameter3f(myCgVertexParam_lightPosition, -8, 0, 15);
  checkForCgError("setting light position");
  cgSetParameter3fv(myCgVertexParam_eyePosition, eyePosition);
  checkForCgError("setting eye position");
  cgSetParameter2f(myCgVertexParam_torusInfo, outerRadius, innerRadius);
  checkForCgError("setting torus information");

  cgGLEnableProfile(myCgVertexProfile);
  checkForCgError("enabling vertex profile");

  cgGLBindProgram(myCgFragmentProgram);
  checkForCgError("binding fragment program");

  cgSetParameter4fv(myCgFragmentParam_ambient, myAmbient);
  checkForCgError("setting ambient");
  cgSetParameter4fv(myCgFragmentParam_LMd, myLMd);
  checkForCgError("setting diffuse material");
  cgSetParameter4fv(myCgFragmentParam_LMs, myLMs);
  checkForCgError("setting specular material");

  cgGLEnableTextureParameter(myCgFragmentParam_normalMap);
  checkForCgError("enable texture normal map");
  cgGLEnableTextureParameter(myCgFragmentParam_normalizeCube);
  checkForCgError("enable 1st normalize vector cube map");
  cgGLEnableTextureParameter(myCgFragmentParam_normalizeCube2);
  checkForCgError("enable 2nd normalize vector cube map");

  cgGLEnableProfile(myCgFragmentProfile);
  checkForCgError("enabling fragment profile");

  cgUpdateProgramParameters(myCgVertexProgram);
  cgUpdateProgramParameters(myCgFragmentProgram);

  drawFlatPatch(sides, rings);

  cgGLDisableProfile(myCgVertexProfile);
  checkForCgError("disabling vertex profile");

  cgGLDisableProfile(myCgFragmentProfile);
  checkForCgError("disabling fragment profile");

  glutSwapBuffers();
}

static void idle(void)
{
  myEyeAngle += 0.05f;
  if (myEyeAngle > 2*3.14159)
    myEyeAngle -= 2*3.14159;
  glutPostRedisplay();
}

static void keyboard(unsigned char c, int x, int y)
{
  static int animating = 0;

  switch (c) {
  case ' ':
    animating = !animating; /* Toggle */
    if (animating) {
      glutIdleFunc(idle);
    } else {
      glutIdleFunc(NULL);
    }
    break;
  case 27:  /* Esc key */
    /* Demonstrate proper deallocation of Cg runtime data structures.
       Not strictly necessary if we are simply going to exit. */
    cgDestroyProgram(myCgVertexProgram);
    cgDestroyContext(myCgContext);
    exit(0);
    break;
  }
}

static void menu(int item)
{
  /* Pass menu item character code to keyboard callback. */
  keyboard((unsigned char)item, 0, 0);
}

/* Platform-specific code to request synchronized buffer swaps. */

static void requestSynchronizedSwapBuffers(void)
{
#if defined(__APPLE__)
#ifdef CGL_VERSION_1_2
  const GLint sync = 1;
#else
  const long sync = 1;
#endif
  CGLSetParameter(CGLGetCurrentContext(), kCGLCPSwapInterval, &sync);

#elif defined(_WIN32)
  if (wglSwapIntervalEXT) {
    wglSwapIntervalEXT(1);
  }
#else
  if (glXSwapIntervalSGI) {
    glXSwapIntervalSGI(1);
  }
#endif
}


text:
<?php

namespace Szenis\Picro;

use Szenis\Picro\Container;
use Szenis\Picro\Exceptions\RouteNotFoundException;
use Szenis\Picro\Exceptions\RouteNotCallableException;
use Symfony\Component\HttpFoundation\Response;

class App
{
	/**
	 * @var Container
	 */
	private $container;

	/**
	 * Initialize the container
	 *
	 * @param array $values
	 */
	public function __construct(array $values = [])
	{
		$this->container = new Container($values);
	}

	/**
	 * @return void
	 */
	public function run()
	{
		$response = $this->resolveRoute();

		if (!($response instanceof Response)) {
			throw new \LogicException('The controller must return a \Symfony\Component\HttpFoundation\Response object');
		}

		$response->send();
	}

	/**
	 * @param mixed  $callable
	 * @param string $slug
	 *
	 * @return App
	 */
	public function get($slug, $callable)
	{
		$this->container->get('router')->get($slug, $callable);

		return $this;
	}

	/**
	 * @param mixed  $callable
	 * @param string $slug
	 *
	 * @return App
	 */
	public function put($slug, $callable)
	{
		$this->container->get('router')->put($slug, $callable);

		return $this;
	}

	/**
	 * @param mixed  $callable
	 * @param string $slug
	 *
	 * @return App
	 */
	public function post($slug, $callable)
	{
		$this->container->get('router')->post($slug, $callable);

		return $this;
	}

	/**
	 * @param mixed  $callable
	 * @param string $slug
	 *
	 * @return App
	 */
	public function patch($slug, $callable)
	{
		$this->container->get('router')->patch($slug, $callable);

		return $this;
	}

	/**
	 * @param mixed  $callable
	 * @param string $slug
	 *
	 * @return App
	 */
	public function delete($slug, $callable)
	{
		$this->container->get('router')->delete($slug, $callable);

		return $this;
	}

	/**
	 * Resolve the route and execute it
	 * Return the response of the action
	 *
	 * @throws RouteNotCallableException
	 * @throws RouteNotFoundException
	 *
	 * @return mixed
	 */
	private function resolveRoute()
	{
		$request = $this->container->get('request');
		$router = $this->container->get('router');

		$route = $router->resolve($request->getPathInfo(), $request->getMethod());

		if ($route['code'] !== \Szenis\Routing\Route::STATUS_FOUND) {
			throw new RouteNotFoundException("Route with uri '".$request->getUri()."' not found");
		}

		$resolver = new ArgumentResolver($this->container);
		$route = $resolver->resolve($route);

		return call_user_func_array($route['handler'], $route['arguments']);
	}
}


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

<title>O-Index</title>
<meta name="date" content="2016-04-04">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes

A B C D E F G H I K L M N O P Q R S T U V W Z

O

onActivityResult(int, int, Intent) - Method in class com.example.suhussai.gameshare.ViewItem

Return from the camera with a new image and add it to the item.

onCreate(Bundle) - Method in class com.example.suhussai.gameshare.ViewImage

onCreate(Bundle) - Method in class com.example.suhussai.gameshare.ViewItem

The method to create the view

onCreate(Bundle) - Method in class com.example.suhussai.gameshare.ViewItemsList

On create method, called to start view

onCreate(Bundle) - Method in class com.example.suhussai.gameshare.ViewLogIn

On create method

onCreate(Bundle) - Method in class com.example.suhussai.gameshare.ViewMap

onCreate(Bundle) - Method in class com.example.suhussai.gameshare.ViewMenu

On create method for setting up view

onCreate(Bundle) - Method in class com.example.suhussai.gameshare.ViewUserProfile

On create method for setting up view

onMapReady(GoogleMap) - Method in class com.example.suhussai.gameshare.ViewItem

onMapReady(GoogleMap) - Method in class com.example.suhussai.gameshare.ViewMap

Sets the position on the map to Location set by lender.

onProgressUpdate(Item...) - Method in class com.example.suhussai.gameshare.ItemController.AddItem

Grabs the user, gameCount, updates gameCount on user, and generates a newId.

onResume() - Method in class com.example.suhussai.gameshare.ViewMenu

On resume method

onStart() - Method in class com.example.suhussai.gameshare.ViewMenu

On start method

onStart() - Method in class com.example.suhussai.gameshare.ViewUserProfile

On start method

overlapAnchor - Static variable in class com.example.suhussai.gameshare.R.attr

Must be a boolean value, either "true" or "false".

owner - Variable in class com.example.suhussai.gameshare.Item

The owner's username

A B C D E F G H I K L M N O P Q R S T U V W Z

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes


text:
#import <iWorkImport/TSWPTextBaseCommand.h>

@class NSURL, TSWPStorage;

// Not exported
@interface TSWPCreateHyperlinkCommand : TSWPTextBaseCommand
{
    TSWPStorage *_storage;
    NSURL *_url;
    struct _NSRange _range;
    struct TSWPStorageTransaction *_undoRedoTransaction;
}

+ (Class)appSpecificCreateHyperlinkCommandClass;
@property(readonly, nonatomic) TSWPStorage *storage; // @synthesize storage=_storage;
- (id).cxx_construct;
- (void)redo;
- (void)undo;
- (void)undoRedo;
- (void)commit;
- (_Bool)process;
- (_Bool)shouldRunSynchronously;
- (id)initFromUnarchiver:(id)arg1;
- (void)loadFromArchive:(const struct CreateHyperlinkCommandArchive *)arg1 unarchiver:(id)arg2;
- (void)saveToArchiver:(id)arg1;
- (void)saveToArchive:(struct CreateHyperlinkCommandArchive *)arg1 archiver:(id)arg2;
- (id)actionString;
- (void)dealloc;
- (id)initWithStorage:(id)arg1 range:(struct _NSRange)arg2 URL:(id)arg3;

@end


text:
extern crate lru_time_cache;
use lib::btsf::*;
use lib::correlate::*;

pub struct CorrelationCache {
    lru: lru_time_cache::LruCache<BinaryTimeSeries, Vec<f32>>,
}

impl<'a> CorrelationCache {
    pub fn new() -> CorrelationCache {
        CorrelationCache {
            lru: lru_time_cache::LruCache::with_capacity(5),
        }
    }
    pub fn correlate(
        &'a mut self,
        data: &BinaryTimeSeries,
        possibilities: &'static [BinaryTimeSeries],
    ) -> Vec<f32> {
        if let Some(correlations) = self.lru.get(data) {
            return correlations.clone();
        }

        let correlations = correlate(data, possibilities);
        self.lru.insert(data.clone(), correlations);
        let corr_ref = self.lru.get(data).unwrap();
        corr_ref.clone()
    }
}


text:
<#compress>
<#if listExtendableResourceActions?? && listExtendableResourceActions?has_content>
<@extendableResourceAction>
<@listGroup>
	<#list listExtendableResourceActions as resourceTypeAction>
		<#if resourceTypeAction.buttonTemplate?? && resourceTypeAction.buttonTemplate!=''>
			<@listGroupItem><@extendableResourceActionList action=resourceTypeAction /></@listGroupItem>
		</#if>
	</#list>
</@listGroup>
</@extendableResourceAction>
</#if>
<#-- extendableResourceAction + extendableResourceActionList -->
<#macro extendableResourceAction>
<@btnGroup class='ms-1 ml-1'>
	<@aButton class='dropdown-toggle' id='extender' dropdownMenu=true href='#' title='#i18n{portal.admin.resource.extend}' buttonIcon='bookmark' hideTitle=['xs','sm','md']>
		<#nested>
	</@aButton>
</@btnGroup>
</#macro>
<#macro extendableResourceActionList action target='_top'>
<#if action.buttonTemplate?has_content><#include action.buttonTemplate /></#if>
</#macro>
</#compress>


text:
// -----------------------------------------------------------------------------
// Name: /public/js/game/components/terrain/floor5.js
// Author: Adam Barreiro
// Description: Floor 5 component.
// -----------------------------------------------------------------------------

/**
 * floor5.js
 */
define (function() {

// -----------------------------------------------------------------------------
// Public
// -----------------------------------------------------------------------------

return {
    /**
     * Registers the component into the game.
     */
    registerComponent: function(edition) {
        Crafty.c('Floor5', {
            /**
             * Inits the component
             */
            init: function() {
                this.requires('Terrain, spr_floor5');
            }
        });
    }
};

});


text:
@interface ApplicationActivationArrayController : NSArrayController

@end


text:
.. _userguide_info:

Learning More
=============

Hopefully this User Guide gets you started with the basics of using Bokeh.

For detailed information about all modules, classes, models, and objects,
consult the :ref:`refguide`. If you are interested in learning how to build
and develop Bokeh, or for information about how to create a new language
binding, see the :ref:`devguide`.

To see ready-made examples of how you might use Bokeh with your own data,
check out the :ref:`gallery` on the main documentation site, as well as
the `Bokeh NBViewer Gallery`_.

For questions and technical assistance, come join the `Bokeh Discourse`_,

Visit the `Bokeh GitHub repository`_ and try the examples.

Be sure to follow us on Twitter `@bokehplots <Twitter_>`_ and `Youtube`_!

.. _Bokeh GitHub repository: https://github.com/bokeh/bokeh
.. _Bokeh Discourse: https://discourse.bokeh.org
.. _Bokeh NBViewer Gallery: http://nbviewer.ipython.org/github/bokeh/bokeh-notebooks/blob/master/index.ipynb
.. _Twitter: http://twitter.com/BokehPlots
.. _YouTube: https://www.youtube.com/channel/UCK0rSk29mmg4UT4bIOvPYhw


text:
#include <pcl/console/parse.h>
#include <pcl/point_types.h>
#include <pcl/point_cloud.h>
#include <pcl/point_representation.h>

#include <pcl/io/pcd_io.h>
#include <pcl/ros/conversions.h>
#include <pcl/keypoints/uniform_sampling.h>
#include <pcl/features/normal_3d.h>
#include <pcl/features/fpfh.h>
#include <pcl/registration/correspondence_estimation.h>
#include <pcl/registration/correspondence_rejection_distance.h>
#include <pcl/registration/transformation_estimation_svd.h>

using namespace std;
using namespace sensor_msgs;
using namespace pcl;
using namespace pcl::io;
using namespace pcl::console;
using namespace pcl::registration;
PointCloud<PointXYZ>::Ptr src, tgt;

////////////////////////////////////////////////////////////////////////////////
void
estimateKeypoints (const PointCloud<PointXYZ>::Ptr &src,
                   const PointCloud<PointXYZ>::Ptr &tgt,
                   PointCloud<PointXYZ> &keypoints_src,
                   PointCloud<PointXYZ> &keypoints_tgt)
{
  PointCloud<int> keypoints_src_idx, keypoints_tgt_idx;
  // Get an uniform grid of keypoints
  UniformSampling<PointXYZ> uniform;
  uniform.setRadiusSearch (1);  // 1m

  uniform.setInputCloud (src);
  uniform.compute (keypoints_src_idx);
  copyPointCloud<PointXYZ, PointXYZ> (*src, keypoints_src_idx.points, keypoints_src);

  uniform.setInputCloud (tgt);
  uniform.compute (keypoints_tgt_idx);
  copyPointCloud<PointXYZ, PointXYZ> (*tgt, keypoints_tgt_idx.points, keypoints_tgt);

  // For debugging purposes only: uncomment the lines below and use pcd_viewer to view the results, i.e.:
  // pcd_viewer source_pcd keypoints_src.pcd -ps 1 -ps 10
  savePCDFileBinary ("keypoints_src.pcd", keypoints_src);
  savePCDFileBinary ("keypoints_tgt.pcd", keypoints_tgt);
}

////////////////////////////////////////////////////////////////////////////////
void
estimateNormals (const PointCloud<PointXYZ>::Ptr &src,
                 const PointCloud<PointXYZ>::Ptr &tgt,
                 PointCloud<Normal> &normals_src,
                 PointCloud<Normal> &normals_tgt)
{
  NormalEstimation<PointXYZ, Normal> normal_est;
  normal_est.setInputCloud (src);
  normal_est.setRadiusSearch (0.5);  // 50cm
  normal_est.compute (normals_src);

  normal_est.setInputCloud (tgt);
  normal_est.compute (normals_tgt);

  // For debugging purposes only: uncomment the lines below and use pcd_viewer to view the results, i.e.:
  // pcd_viewer normals_src.pcd
  PointCloud<PointNormal> s, t;
  copyPointCloud<PointXYZ, PointNormal> (*src, s);
  copyPointCloud<Normal, PointNormal> (normals_src, s);
  copyPointCloud<PointXYZ, PointNormal> (*tgt, t);
  copyPointCloud<Normal, PointNormal> (normals_tgt, t);
  savePCDFileBinary ("normals_src.pcd", s);
  savePCDFileBinary ("normals_tgt.pcd", t);
}

////////////////////////////////////////////////////////////////////////////////
void
estimateFPFH (const PointCloud<PointXYZ>::Ptr &src,
              const PointCloud<PointXYZ>::Ptr &tgt,
              const PointCloud<Normal>::Ptr &normals_src,
              const PointCloud<Normal>::Ptr &normals_tgt,
              const PointCloud<PointXYZ>::Ptr &keypoints_src,
              const PointCloud<PointXYZ>::Ptr &keypoints_tgt,
              PointCloud<FPFHSignature33> &fpfhs_src,
              PointCloud<FPFHSignature33> &fpfhs_tgt)
{
  FPFHEstimation<PointXYZ, Normal, FPFHSignature33> fpfh_est;
  fpfh_est.setInputCloud (keypoints_src);
  fpfh_est.setInputNormals (normals_src);
  fpfh_est.setRadiusSearch (1); // 1m
  fpfh_est.setSearchSurface (src);
  fpfh_est.compute (fpfhs_src);

  fpfh_est.setInputCloud (keypoints_tgt);
  fpfh_est.setInputNormals (normals_tgt);
  fpfh_est.setSearchSurface (tgt);
  fpfh_est.compute (fpfhs_tgt);

  // For debugging purposes only: uncomment the lines below and use pcd_viewer to view the results, i.e.:
  // pcd_viewer fpfhs_src.pcd
  PointCloud2 s, t, out;
  toROSMsg (*src, s); toROSMsg (fpfhs_src, t); concatenateFields (s, t, out);
  savePCDFile ("fpfhs_src.pcd", out);
  toROSMsg (*tgt, s); toROSMsg (fpfhs_tgt, t); concatenateFields (s, t, out);
  savePCDFile ("fpfhs_tgt.pcd", out);
}

////////////////////////////////////////////////////////////////////////////////
void
findCorrespondences (const PointCloud<FPFHSignature33>::Ptr &fpfhs_src,
                     const PointCloud<FPFHSignature33>::Ptr &fpfhs_tgt,
                     Correspondences &all_correspondences)
{
  CorrespondenceEstimation<FPFHSignature33, FPFHSignature33> est;
  est.setInputCloud (fpfhs_src);
  est.setInputTarget (fpfhs_tgt);
  est.determineReciprocalCorrespondences (all_correspondences);
}

////////////////////////////////////////////////////////////////////////////////
void
rejectBadCorrespondences (const CorrespondencesPtr &all_correspondences,
                          const PointCloud<PointXYZ>::Ptr &keypoints_src,
                          const PointCloud<PointXYZ>::Ptr &keypoints_tgt,
                          Correspondences &remaining_correspondences)
{
  CorrespondenceRejectorDistance rej;
  rej.setInputCloud<PointXYZ> (keypoints_src);
  rej.setInputTarget<PointXYZ> (keypoints_tgt);
  rej.setMaximumDistance (1);    // 1m
  rej.setInputCorrespondences (all_correspondences);
  rej.getCorrespondences (remaining_correspondences);
}

////////////////////////////////////////////////////////////////////////////////
void
computeTransformation (const PointCloud<PointXYZ>::Ptr &src,
                       const PointCloud<PointXYZ>::Ptr &tgt,
                       Eigen::Matrix4f &transform)
{
  // Get an uniform grid of keypoints
  PointCloud<PointXYZ>::Ptr keypoints_src (new PointCloud<PointXYZ>),
                            keypoints_tgt (new PointCloud<PointXYZ>);

  estimateKeypoints (src, tgt, *keypoints_src, *keypoints_tgt);
  print_info ("Found %zu and %zu keypoints for the source and target datasets.\n", keypoints_src->points.size (), keypoints_tgt->points.size ());

  // Compute normals for all points keypoint
  PointCloud<Normal>::Ptr normals_src (new PointCloud<Normal>),
                          normals_tgt (new PointCloud<Normal>);
  estimateNormals (src, tgt, *normals_src, *normals_tgt);
  print_info ("Estimated %zu and %zu normals for the source and target datasets.\n", normals_src->points.size (), normals_tgt->points.size ());

  // Compute FPFH features at each keypoint
  PointCloud<FPFHSignature33>::Ptr fpfhs_src (new PointCloud<FPFHSignature33>),
                                   fpfhs_tgt (new PointCloud<FPFHSignature33>);
  estimateFPFH (src, tgt, normals_src, normals_tgt, keypoints_src, keypoints_tgt, *fpfhs_src, *fpfhs_tgt);

  // Copy the data and save it to disk
/*  PointCloud<PointNormal> s, t;
  copyPointCloud<PointXYZ, PointNormal> (*keypoints_src, s);
  copyPointCloud<Normal, PointNormal> (normals_src, s);
  copyPointCloud<PointXYZ, PointNormal> (*keypoints_tgt, t);
  copyPointCloud<Normal, PointNormal> (normals_tgt, t);*/

  // Find correspondences between keypoints in FPFH space
  CorrespondencesPtr all_correspondences (new Correspondences),
                     good_correspondences (new Correspondences);
  findCorrespondences (fpfhs_src, fpfhs_tgt, *all_correspondences);

  // Reject correspondences based on their XYZ distance
  rejectBadCorrespondences (all_correspondences, keypoints_src, keypoints_tgt, *good_correspondences);

  for (int i = 0; i < good_correspondences->size (); ++i)
    std::cerr << good_correspondences->at (i) << std::endl;
  // Obtain the best transformation between the two sets of keypoints given the remaining correspondences
  TransformationEstimationSVD<PointXYZ, PointXYZ> trans_est;
  trans_est.estimateRigidTransformation (*keypoints_src, *keypoints_tgt, *good_correspondences, transform);
}

/* ---[ */
int
main (int argc, char** argv)
{
  // Parse the command line arguments for .pcd files
  std::vector<int> p_file_indices;
  p_file_indices = parse_file_extension_argument (argc, argv, ".pcd");
  if (p_file_indices.size () != 2)
  {
    print_error ("Need one input source PCD file and one input target PCD file to continue.\n");
    print_error ("Example: %s source.pcd target.pcd\n", argv[0]);
    return (-1);
  }

  // Load the files
  print_info ("Loading %s as source and %s as target...\n", argv[p_file_indices[0]], argv[p_file_indices[1]]);
  src.reset (new PointCloud<PointXYZ>);
  tgt.reset (new PointCloud<PointXYZ>);
  if (loadPCDFile (argv[p_file_indices[0]], *src) == -1 || loadPCDFile (argv[p_file_indices[1]], *tgt) == -1)
  {
    print_error ("Error reading the input files!\n");
    return (-1);
  }

  // Compute the best transformtion
  Eigen::Matrix4f transform;
  computeTransformation (src, tgt, transform);

  std::cerr << transform << std::endl;
  // Transform the data and write it to disk
  PointCloud<PointXYZ> output;
  transformPointCloud (*src, output, transform);
  savePCDFileBinary ("source_transformed.pcd", output);
}
/* ]--- */


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<title>web.xml</title>

web.xml

The web.xml below provides a base for you to build your
applications upon. Lines 11 - 14 declare which custom WebappComposer
should be used for your application. The listener registered on
lines 17 - 19 is needed so that Waffle is alerted of application
(ServletContext) and session life-cycle events and does not need changing.
The filter registered on lines 22 - 29 is used by Waffle for
request level life-cycle event.

<textarea class="xml:nogutter:nocontrols" name="code">
01:  <?xml version="1.0" encoding="UTF-8"?>
02:
03:  <web-app version="2.4"
04:         xmlns="http://java.sun.com/xml/ns/j2ee"
05:         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
06:         xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
07:
08:    <display-name>Example Waffle Web-app</display-name>
09:
10:
11:    <context-param>
12:      <param-name>webapp-composer-class</param-name>
13:      <param-value>org.codehaus.waffle.example.MyComposer</param-value>
14:    </context-param>
15:
16:
17:    <listener>
18:      <listener-class>org.codehaus.waffle.pico.WaffleListener</listener-class>
19:    </listener>
20:
21:
22:    <filter>
23:      <filter-name>WaffleRequestFilter</filter-name>
24:      <filter-class>org.codehaus.waffle.pico.WafflePicoServlet$ServletFilter</filter-class>
25:    </filter>
26:    <filter-mapping>
27:      <filter-name>WaffleRequestFilter</filter-name>
28:      <url-pattern>*.waffle</url-pattern>
29:    </filter-mapping>
30:
31:
32:    <servlet>
33:      <servlet-name>waffle</servlet-name>
34:      <servlet-class>org.codehaus.waffle.pico.WafflePicoServlet</servlet-class>
35:      <init-param>
36:        <param-name>view.suffix</param-name>
37:        <param-value>.jspx</param-value>
38:      </init-param>
39:      <load-on-startup>1</load-on-startup>
40:    </servlet>
41:    <servlet-mapping>
42:      <servlet-name>waffle</servlet-name>
43:      <url-pattern>*.waffle</url-pattern>
44:    </servlet-mapping>
45:  </web-app>
</textarea>


text:
# Jeweler: Craft the perfect RubyGem

Jeweler provides the noble ruby developer with two primary features:

 * a library for managing and releasing RubyGem projects
 * a scaffold generator for starting new RubyGem projects

## Hello, world

Use RubyGems to install the heck out of jeweler to get started:

    $ gem install jeweler

With jeweler installed, you can use the `jeweler` command to generate a new project. For the most basic use, just give it a name:

    $ jeweler hello-gem

This requires some Git configuration (like name, email, GitHub account, etc), but `jeweler` will prompt along the way.

Your new `hello-gem` gem is ready in the `hello-gem` directory. Take a peek, and you'll see several files and directories

 * `Rakefile` setup for jeweler, running tests, generating documentation, and releasing to [rubygems.org](http://rubygems.org/)
 * `README.rdoc` with contribution guidelines and copyright info crediting you
 * `LICENSE` with the MIT licensed crediting you
 * `Gemfile` with development dependencies filled in
 * `lib/hello-gem.rb` waiting for you to code
 * `test/` containing a (failing) shoulda test suite [shoulda](http://github.com/thoughtbot/shoulda)

### More `jeweler` options

The `jeweler` command supports a lot of options. Mostly, they are for generating baked in support for this test framework, or that.

Check out `jeweler --help` for the most up to date options.

## Hello, rake tasks

Beyond just editing source code, you'll be interacting with your gem using `rake` a lot. To see all the tasks available with a brief description, you can run:

    $ rake -T

You'll need a version before you can start installing your gem locally. The easiest way is with the `version:write` Rake task. Let's imagine you start with 0.1.0

    $ rake version:write MAJOR=0 MINOR=1 PATCH=0

You can now go forth and develop, now that there's an initial version defined. Eventually, you should install and test the gem:

    $ rake install

The `install` rake task builds the gem and `gem install`s it. You're all set if you're using [RVM](http://rvm.beginrescueend.com/), but you may need to run it with sudo if you have a system-installed ruby:

    $ sudo rake install

### Releasing

At last, it's time to [ship it](http://img.skitch.com/20100310-nrgxbwqm58tibiq2un6mujqmm5.png)! Make sure you have everything committed and pushed, then go wild:

    $ rake release

This will automatically:

 * Generate `hello-gem.gemspec` and commit it
 * Use `git` to tag `v0.1.0` and push it
 * Build `hello-gem-0.1.0.gem` and push it to [rubygems.org](http://rubygems.org/gems/)

### Version bumping

It feels good to release code. Do it, do it often. But before that, bump the version. Then release it. There's a few ways to update the version:

    # version:write like before
    $ rake version:write MAJOR=0 MINOR=3 PATCH=0

    # bump just major, ie 0.1.0 -> 1.0.0
    $ rake version:bump:major

    # bump just minor, ie 0.1.0 -> 0.2.0
    $ rake version:bump:minor

    # bump just patch, ie 0.1.0 -> 0.1.1
    $ rake version:bump:patch

Then it's the same `release` we used before:

    $ rake release

## Customizing your gem

If you've been following along so far, your gem is just a blank slate. You're going to need to make it colorful and full of metadata.

You can customize your gem by updating your `Rakefile`. With a newly generated project, it will look something like this:

    require 'jeweler'
    Jeweler::Tasks.new do |gem|
      # gem is a Gem::Specification... see http://docs.rubygems.org/read/chapter/20 for more options
      gem.name = "whatwhatwhat"
      gem.summary = %Q{TODO: one-line summary of your gem}
      gem.description = %Q{TODO: longer description of your gem}
      gem.email = "josh@technicalpickles.com"
      gem.homepage = "http://github.com/technicalpickles/whatwhatwhat"
      gem.authors = ["Joshua Nichols"]
    end
    Jeweler::RubygemsDotOrgTasks.new

It's crucial to understand the `gem` object is just a Gem::Specification. You can read up about it at [docs.rubygems.org/read/chapter/20](http://docs.rubygems.org/read/chapter/20). This is the most basic way of specifying a gem, Jeweler-managed or not. Jeweler just exposes this to you, in addition to providing some reasonable defaults, which we'll explore now.

### Project information

    gem.name = "whatwhatwhat"

Every gem has a name. Among other things, the gem name is how you are able to `gem install` it. [Reference](http://docs.rubygems.org/read/chapter/20#name)

    gem.summary = %Q{TODO: one-line summary of your gem}

This is a one line summary of your gem. This is displayed, for example, when you use `gem list --details` or view it on [rubygems.org](http://rubygems.org/gems/).

    gem.description = %Q{TODO: longer description of your gem}

Description is a longer description. Scholars ascertain that knowledge of where the description is used was lost centuries ago.

    gem.email = "josh@technicalpickles.com"

This should be a way to get a hold of you regarding the gem.

    gem.homepage = "http://github.com/technicalpickles/whatwhatwhat"

The homepage should have more information about your gem. The jeweler generator guesses this based on the assumption your code lives on [GitHub](http://github.com/), using your Git configuration to find your GitHub username. This is displayed by `gem list --details` and on rubygems.org.

    gem.authors = ["Joshua Nichols"]

Hey, this is you, the author (or me in this case). The `jeweler` generator also guesses this from your Git configuration. This is displayed by `gem list --details` and on rubygems.org.

### Files

The quickest way to add more files is to `git add` them. Jeweler uses your Git repository to populate your gem's files by including added and committed and excluding `.gitignore`d. In most cases, this is reasonable enough.

If you need to tweak the files, that's cool. Jeweler populates `gem.files` as a `Rake::FileList`. It's like a normal array, except you can `include` and `exclude` file globs:

    gem.files.exclude 'tmp' # exclude temporary directory
    gem.files.include 'lib/foo/bar.rb' # explicitly include lib/foo/bar.rb

If that's not enough, you can just set `gem.files` outright

    gem.files = Dir.glob('lib/**/*.rb')

### Dependencies

Dependencies let you define other gems that your gem needs to function. `gem install your-gem` will install your-gem's dependencies along with it, and when you use your-gem in an application, the dependencies will be made available. Use `gem.add_dependency` to register them. [Reference](http://docs.rubygems.org/read/chapter/20#dependencies)

    gem.add_dependency 'nokogiri'

This will ensure a version of `nokogiri` is installed, but it doesn't require anything more than that. You can provide extra args to be more specific:

    gem.add_dependency 'nokogiri', '= 1.2.1' # exactly version 1.2.1
    gem.add_dependency 'nokogiri', '>= 1.2.1' # greater than or equal to 1.2.1, ie, 1.2.1, 1.2.2, 1.3.0, 2.0.0, etc
    gem.add_dependency 'nokogiri', '>= 1.2.1', '< 1.3.0' # greater than or equal to 1.2.1, but less than 1.3.0
    gem.add_dependency 'nokogiri', '~> 1.2.1' # same thing, but more concise

When specifying which version is required, there's a bit of the condunrum. You want to allow the most versions possible, but you want to be sure they are compatible. Using `>= 1.2.1` is fine most of the time, except until the point that 2.0.0 comes out and totally breaks backwards the API. That's when it's good to use `~> 1.2.1`, which requires any version in the `1.2` family, starting with `1.2.1`.

### Executables

Executables let your gem install shell commands. Just put any executable scripts in the `bin/` directory, make sure they are added using `git`, and Jeweler will take care of the rest.

When you need more finely grained control over it, you can set it yourself:

    gem.executables = ['foo'] # note, it's the file name relative to `bin/`, not the project root

### Versioning

We discussed earlier how to bump the version. The rake tasks are really just convience methods for manipulating the `VERSION` file. It just contains a version string, like `1.2.3`.

`VERSION` is a convention used by Jeweler, and is used to populate `gem.version`. You can actually set this yourself, and Jeweler won't try to override it:

    gem.version = '1.2.3'

A common pattern is to have this in a version constant in your library. This is convenient, because users of the library can query the version they are using at runtime.

    # in lib/foo/version.rb
    class Foo
      module Version
        MAJOR = 1
        MINOR = 2
        PATCH = 3
        BUILD = 'pre3'

        STRING = [MAJOR, MINOR, PATCH, BUILD].compact.join('.')
      end
    end

    # in Rakefile
    require 'jeweler'
    require './lib/foo/version.rb'
    Jeweler::Tasks.new do |gem|
      # snip
      gem.version = Foo::Version::STRING
    end

### Rake tasks

Jeweler lives inside of Rake. As a result, they are dear friends. But, that friendship doesn't interfere with typical Rake operations.

That means you can define your own namespaces, tasks, or use third party Rake libraries without cause for concern.

## Contributing to Jeweler

* Check out the latest master to make sure the feature hasn't been implemented or the bug hasn't been fixed yet
* Check out the [issue tracker](http://github.com/technicalpickles/jeweler/issues) to make sure someone already hasn't requested it and/or contributed it
* Fork the project
* Start a feature/bugfix branch
* Commit and push until you are happy with your contribution
* Make sure to add tests for the feature/bugfix. This is important so I don't break it in a future version unintentionally.
* Please try not to mess with the Rakefile, version, or history. If you want to have your own version, or is otherwise necessary, that is fine, but please isolate it to its own commit so I can cherry-pick around it.

## Copyright

Copyright (c) 2008-2010 Josh Nichols. See LICENSE for details.


text:
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;

namespace Examples
{
    class Program
    {
        [STAThread]
        static void Main(string[] args)
        {
            SolidEdgeFramework.Application application = null;
            SolidEdgeFramework.Documents documents = null;
            SolidEdgeDraft.DraftDocument draftDocument = null;
            SolidEdgeDraft.Sheet sheet = null;
            SolidEdgeFrameworkSupport.CenterLines centerLines = null;
            SolidEdgeFrameworkSupport.CenterLine centerLine = null;
            SolidEdgeFrameworkSupport.Circles2d circles2d = null;
            SolidEdgeFrameworkSupport.Circle2d circle2d = null;

            try
            {
                // See "Handling 'Application is Busy' and 'Call was Rejected By Callee' errors" topic.
                OleMessageFilter.Register();

                // Attempt to connect to a running instance of Solid Edge.
                application = (SolidEdgeFramework.Application)Marshal.GetActiveObject("SolidEdge.Application");
                documents = application.Documents;
                draftDocument = (SolidEdgeDraft.DraftDocument)documents.Add("SolidEdge.DraftDocument");
                sheet = draftDocument.ActiveSheet;
                circles2d = sheet.Circles2d;

                circle2d = circles2d.AddByCenterRadius(0.25, 0.25, 0.05);

                centerLines = (SolidEdgeFrameworkSupport.CenterLines)sheet.CenterLines;

                // Drawing a center line on the active sheet using the nearest KeyPoint on the Circle object as reference for the Start point.
                centerLine = centerLines.AddByStart(circle2d, 0.25, 0.5, 0, false, 0.1, 0.1, 0);
            }
            catch (System.Exception ex)
            {
                Console.WriteLine(ex);
            }
            finally
            {
                OleMessageFilter.Unregister();
            }
        }
    }
}