text:
<?php

namespace Brainstrap\Core\NCBundle\Controller\Client;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\Encoder\XmlEncoder;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer;

use Brainstrap\Core\NCBundle\Entity\Client\Client;
use Brainstrap\Core\NCBundle\Form\Client\ClientType;

/**
 * Client\Client controller.
 *
 */
class ClientController extends Controller
{

    /**
     * Lists all Client\Client entities.
     *
     */
    public function indexAction()
    {
        $em = $this->getDoctrine()->getManager();

        $entities = $em->getRepository('BrainstrapCoreNCBundle:Client\Client')->findAll();

        return $this->render('BrainstrapCoreNCBundle:Client/Client:index.html.twig', array(
            'entities' => $entities,
        ));
    }
    /**
     * Creates a new Client\Client entity.
     *
     */
    public function createAction(Request $request)
    {
        if($request->isXmlHttpRequest())
        {
            $entity = new Client();
            $form = $this->createCreateForm($entity);
            $form->handleRequest($request);

            if ($form->isValid()) {
                $cartId = $form['cart_id']->getData();
                if(empty($cartId) || !is_numeric($cartId))
                {
                    $return = array("responseCode"=>500, "msg" => "Не удалось получить id карты клиента");
                }
                else
                {
                    $em = $this->getDoctrine()->getManager();
                    $entityCart = $em->getRepository('BrainstrapCoreNCBundle:Cart\Cart')->find($cartId);
                    if(!$entityCart)
                    {
                        $return = array("responseCode"=>500, "msg" => "Не удалось получить карту клиента с переданным id");
                    }
                    else
                    {
                        // Add cart to client
                        $entity->setCart($entityCart);
                        $em->persist($entity);

                        // Add client to cart
                        $entityCart->setClient($entity);
                        $em->persist($entityCart);

                        $em->flush();

                        $ans = array(
                                // Client
                                'clientId'      => $entity->getId(),
                                'clientName'    => $entity->getName(),
                                'clientSname'   => $entity->getSname(),
                                // Cart
                                'cartId'        => $entityCart->getId(),
                                'cartCode'      => $entityCart->getCode(),

                            );
                        $ans = json_encode($ans);
                        // die('plplpl');
                        $return = array("responseCode"=>200, "entity" => $ans);
                    }
                }

                // return $this->redirect($this->generateUrl('client_show', array('id' => $entity->getId())));
            }
            else
            {
                $return = array("responseCode"=>500, "msg" => "Не валидные данные");
            }
        }
        else
        {
            $return=array("responseCode"=>500, "msg"=>"Для обработка доступны только асинхронные запросы");
        }

        $return=json_encode($return);

        return new Response($return, 200, array('Content-Type'=>'application/json'));

            // return $this->render('BrainstrapCoreNCBundle:Client/Client:new.html.twig', array(
            //     'entity' => $entity,
            //     'form'   => $form->createView(),
            // ));
    }

    /**
    * Creates a form to create a Client\Client entity.
    *
    * @param Client $entity The entity
    *
    * @return \Symfony\Component\Form\Form The form
    */
    private function createCreateForm(Client $entity)
    {
        $form = $this->createForm(new ClientType(), $entity, array(
            'action' => $this->generateUrl('client_create'),
            'method' => 'POST',
        ));

        $form->add('submit', 'submit', array('label' => 'Create'));

        return $form;
    }

    /**
     * Displays a form to create a new Client\Client entity.
     *
     */
    public function newAction()
    {
        $entity = new Client();
        $form   = $this->createCreateForm($entity);

        return $this->render('BrainstrapCoreNCBundle:Client/Client:new.html.twig', array(
            'entity' => $entity,
            'form'   => $form->createView(),
        ));
    }

    /**
     * Finds and displays a Client\Client entity.
     *
     */
    public function showAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('BrainstrapCoreNCBundle:Client\Client')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Client\Client entity.');
        }

        $deleteForm = $this->createDeleteForm($id);

        return $this->render('BrainstrapCoreNCBundle:Client/Client:show.html.twig', array(
            'entity'      => $entity,
            'delete_form' => $deleteForm->createView(),        ));
    }

    /**
     * Displays a form to edit an existing Client\Client entity.
     *
     */
    public function editAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('BrainstrapCoreNCBundle:Client\Client')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Client\Client entity.');
        }

        $editForm = $this->createEditForm($entity);
        $deleteForm = $this->createDeleteForm($id);

        return $this->render('BrainstrapCoreNCBundle:Client/Client:edit.html.twig', array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        ));
    }

    /**
    * Creates a form to edit a Client\Client entity.
    *
    * @param Client $entity The entity
    *
    * @return \Symfony\Component\Form\Form The form
    */
    private function createEditForm(Client $entity)
    {
        $form = $this->createForm(new ClientType(), $entity, array(
            'action' => $this->generateUrl('client_update', array('id' => $entity->getId())),
            'method' => 'PUT',
        ));

        $form->add('submit', 'submit', array('label' => 'Update'));

        return $form;
    }
    /**
     * Edits an existing Client\Client entity.
     *
     */
    public function updateAction(Request $request, $id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('BrainstrapCoreNCBundle:Client\Client')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Client\Client entity.');
        }

        $deleteForm = $this->createDeleteForm($id);
        $editForm = $this->createEditForm($entity);
        $editForm->handleRequest($request);

        if ($editForm->isValid()) {
            $em->flush();

            return $this->redirect($this->generateUrl('client_edit', array('id' => $id)));
        }

        return $this->render('BrainstrapCoreNCBundle:Client/Client:edit.html.twig', array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        ));
    }
    /**
     * Deletes a Client\Client entity.
     *
     */
    public function deleteAction(Request $request, $id)
    {
        $form = $this->createDeleteForm($id);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $entity = $em->getRepository('BrainstrapCoreNCBundle:Client\Client')->find($id);

            if (!$entity) {
                throw $this->createNotFoundException('Unable to find Client\Client entity.');
            }

            $em->remove($entity);
            $em->flush();
        }

        return $this->redirect($this->generateUrl('client'));
    }

    /**
     * Creates a form to delete a Client\Client entity by id.
     *
     * @param mixed $id The entity id
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createDeleteForm($id)
    {
        return $this->createFormBuilder()
            ->setAction($this->generateUrl('client_delete', array('id' => $id)))
            ->setMethod('DELETE')
            ->add('submit', 'submit', array('label' => 'Delete'))
            ->getForm()
        ;
    }

    /**
     * Created object serializer
     */
    private function getSerializer()
    {
        $encoders = array(new XmlEncoder(), new JsonEncoder());
        $normalizers = array(new GetSetMethodNormalizer());
        $serializer = new Serializer($normalizers, $encoders);

        return $serializer;
    }
}


text:
// Force istanbul to make coverage off all files.
// Not just the files that have been required.

const glob = require('glob');
const path = require('path');
glob(__dirname + '/../src/**/*.js', (err, files) => {
  files.map((file) => {
    if (path.basename(file) !== 'app.js') {
      require(file);
    }
  });
});

global.chai = require('chai');
global.expect = global.chai.expect;
global.spyOn = global.expect.spyOn;

redpajama_set_name: RedPajamaGithub


text:
package org.zmpp.vm;

/**
 * This defines the operations that can be performed on a text cursor.
 *
 * @author Wei-ju Wu
 * @version 1.0
 */
public interface TextCursor {

    /**
     * Returns the current line.
     *
     * @return the current line
     */
    int getLine();

    /**
     * Returns the current column.
     *
     * @return the current column
     */
    int getColumn();

    /**
     * Sets the current line. A value <= 0 will set the line to 1.
     *
     * @param line the new current line
     */
    void setLine(int line);

    /**
     * Sets the current column. A value <= 0 will set the column to 1.
     *
     * @param column the new current column
     */
    void setColumn(int column);

    /**
     * Sets the new position. Values <= 0 will set the corresponding values to
     * 1.
     *
     * @param line the new line
     * @param column the new column
     */
    void setPosition(int line, int column);
}


text:
from lifestream.plugins import FeedPlugin

class TwitterPlugin(FeedPlugin):

    feed = None

    def __init__(self, feed):
        self.feed = feed

    def name(self):
        return "Generic Feed"

    def post_process(self, item):
        super(TwitterPlugin,self).post_process(item)

        #Remove the username from the title data.
        if item.title:
            index = item.title.find(":")
            if index != -1:
                item.title = item.title[index+2:]

        if item.content:
            index = item.content.find(":")
            if index != -1:
                item.content = item.content[index+2:]


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Eduardo Frias | Week 5 Technical</title>
    <link rel="stylesheet" href="../css/normalize.css">
    <link href='http://fonts.googleapis.com/css?family=Changa+One|Open+Sans:400italic,700italic,400,700,800' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" href="../css/main.css">
    <link rel="stylesheet" href="../css/responsive.css">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

Eduardo Frias

DevBootcamp Student

Home

Blog Posts

 The Best Ruby Shortcut

          This week I was introduced to the "to_proc" shortcut. The best way to explain it is by actually showing you. Take the code  below for instance:

          In this example the array object [1,2,3] calls map, and says "Give me a block of code, and I will execute it on every element in this array." It will iterate through each item in array [1,2,3] and will execute the block. In this case the the &, and symbol :to_s are being passed into map which invokes the to_proc method. Which returns the following:

          Under the hood a method called to_proc is being called with the symbol, then :to_s. In this example the proc returned the result of calling to_s on each element of the array.

© 2014 Eduardo Frias.


text:
#ifndef CARTOGRAPHER_MAPPING_INTERNAL_OPTIMIZATION_COST_FUNCTIONS_ROTATION_COST_FUNCTION_3D_H_
#define CARTOGRAPHER_MAPPING_INTERNAL_OPTIMIZATION_COST_FUNCTIONS_ROTATION_COST_FUNCTION_3D_H_

#include "Eigen/Core"
#include "Eigen/Geometry"
#include "ceres/ceres.h"

namespace cartographer {
namespace mapping {

// Penalizes differences between IMU data and optimized orientations.
class RotationCostFunction3D {
 public:
  static ceres::CostFunction* CreateAutoDiffCostFunction(
      const double scaling_factor,
      const Eigen::Quaterniond& delta_rotation_imu_frame) {
    return new ceres::AutoDiffCostFunction<
        RotationCostFunction3D, 3 /* residuals */, 4 /* rotation variables */,
        4 /* rotation variables */, 4 /* rotation variables */
        >(new RotationCostFunction3D(scaling_factor, delta_rotation_imu_frame));
  }

  template <typename T>
  bool operator()(const T* const start_rotation, const T* const end_rotation,
                  const T* const imu_calibration, T* residual) const {
    const Eigen::Quaternion<T> start(start_rotation[0], start_rotation[1],
                                     start_rotation[2], start_rotation[3]);
    const Eigen::Quaternion<T> end(end_rotation[0], end_rotation[1],
                                   end_rotation[2], end_rotation[3]);
    const Eigen::Quaternion<T> eigen_imu_calibration(
        imu_calibration[0], imu_calibration[1], imu_calibration[2],
        imu_calibration[3]);
    const Eigen::Quaternion<T> error =
        end.conjugate() * start * eigen_imu_calibration *
        delta_rotation_imu_frame_.cast<T>() * eigen_imu_calibration.conjugate();
    residual[0] = scaling_factor_ * error.x();
    residual[1] = scaling_factor_ * error.y();
    residual[2] = scaling_factor_ * error.z();
    return true;
  }

 private:
  RotationCostFunction3D(const double scaling_factor,
                         const Eigen::Quaterniond& delta_rotation_imu_frame)
      : scaling_factor_(scaling_factor),
        delta_rotation_imu_frame_(delta_rotation_imu_frame) {}

  RotationCostFunction3D(const RotationCostFunction3D&) = delete;
  RotationCostFunction3D& operator=(const RotationCostFunction3D&) = delete;

  const double scaling_factor_;
  const Eigen::Quaterniond delta_rotation_imu_frame_;
};

}  // namespace mapping
}  // namespace cartographer

#endif  // CARTOGRAPHER_MAPPING_INTERNAL_OPTIMIZATION_COST_FUNCTIONS_ROTATION_COST_FUNCTION_3D_H_


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>AdminLTE 2 | Mailbox</title>

  <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
    <link rel="stylesheet" href="../../content/ui/global/bootstrap/css/bootstrap.min.css">

    <link href="../../content/ui/global/font-awesome/css/font-awesome.css" rel="stylesheet" />

    <link rel="stylesheet" href="../../content/adminlte/dist/css/AdminLTE.css">
    <link rel="stylesheet" href="../../content/adminlte/dist/css/skins/_all-skins.min.css">
    <link href="../../content/min/css/supershopui.common.min.css" rel="stylesheet" />
    <link rel="stylesheet" href="../../content/plugins/fullcalendar/fullcalendar.min.css">
    <link rel="stylesheet" href="../../content/plugins/fullcalendar/fullcalendar.print.css" media="print">

    <link rel="stylesheet" href="../../content/plugins/iCheck/flat/blue.css">

    <link rel="stylesheet" href="../../content/plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.min.css">

            Mailbox
            13 new messages

 Home

Mailbox

                Compose

Folders

                            <button type="button" class="btn btn-box-tool" data-widget="collapse">

                            </button>

                                     Inbox
                                    12

 Sent

 Drafts

                                 Junk 65

 Trash

Labels

                            <button type="button" class="btn btn-box-tool" data-widget="collapse">

                            </button>

 Important

 Promotions

 Social

Inbox

                                <input type="text" class="form-control input-sm" placeholder="Search Mail">

                            <button type="button" class="btn btn-default btn-sm checkbox-toggle">

                            </button>

                                <button type="button" class="btn btn-default btn-sm"></button>
                                <button type="button" class="btn btn-default btn-sm"></button>
                                <button type="button" class="btn btn-default btn-sm"></button>

                            <button type="button" class="btn btn-default btn-sm"></button>

                                1-50/200

                                    <button type="button" class="btn btn-default btn-sm"></button>
                                    <button type="button" class="btn btn-default btn-sm"></button>

                                        <input type="checkbox">

                                        Alexander Pierce

                                            AdminLTE 2.0 Issue - Trying to find a solution to this problem...

                                        5 mins ago

                                        <input type="checkbox">

                                        Alexander Pierce

                                            AdminLTE 2.0 Issue - Trying to find a solution to this problem...

                                        28 mins ago

                                        <input type="checkbox">

                                        Alexander Pierce

                                            AdminLTE 2.0 Issue - Trying to find a solution to this problem...

                                        11 hours ago

                                        <input type="checkbox">

                                        Alexander Pierce

                                            AdminLTE 2.0 Issue - Trying to find a solution to this problem...

                                        15 hours ago

                                        <input type="checkbox">

                                        Alexander Pierce

                                            AdminLTE 2.0 Issue - Trying to find a solution to this problem...

                                        Yesterday

                                        <input type="checkbox">

                                        Alexander Pierce

                                            AdminLTE 2.0 Issue - Trying to find a solution to this problem...

                                        2 days ago

                                        <input type="checkbox">

                                        Alexander Pierce

                                            AdminLTE 2.0 Issue - Trying to find a solution to this problem...

                                        2 days ago

                                        <input type="checkbox">

                                        Alexander Pierce

                                            AdminLTE 2.0 Issue - Trying to find a solution to this problem...

                                        2 days ago

                                        <input type="checkbox">

                                        Alexander Pierce

                                            AdminLTE 2.0 Issue - Trying to find a solution to this problem...

                                        2 days ago

                                        <input type="checkbox">

                                        Alexander Pierce

                                            AdminLTE 2.0 Issue - Trying to find a solution to this problem...

                                        2 days ago

                                        <input type="checkbox">

                                        Alexander Pierce

                                            AdminLTE 2.0 Issue - Trying to find a solution to this problem...

                                        4 days ago

                                        <input type="checkbox">

                                        Alexander Pierce

                                            AdminLTE 2.0 Issue - Trying to find a solution to this problem...

                                        12 days ago

                                        <input type="checkbox">

                                        Alexander Pierce

                                            AdminLTE 2.0 Issue - Trying to find a solution to this problem...

                                        12 days ago

                                        <input type="checkbox">

                                        Alexander Pierce

                                            AdminLTE 2.0 Issue - Trying to find a solution to this problem...

                                        14 days ago

                                        <input type="checkbox">

                                        Alexander Pierce

                                            AdminLTE 2.0 Issue - Trying to find a solution to this problem...

                                        15 days ago

                            <button type="button" class="btn btn-default btn-sm checkbox-toggle">

                            </button>

                                <button type="button" class="btn btn-default btn-sm"></button>
                                <button type="button" class="btn btn-default btn-sm"></button>
                                <button type="button" class="btn btn-default btn-sm"></button>

                            <button type="button" class="btn btn-default btn-sm"></button>

                                1-50/200

                                    <button type="button" class="btn btn-default btn-sm"></button>
                                    <button type="button" class="btn btn-default btn-sm"></button>


text:
<?php

namespace general\controllers;

use general\helpers\Conexao;

class RelacionamentoApi
{
    private $PDO;
    private $tabela = "relacionamento";
    private $caminhoLocal;
    private $imgUserDefault = "/webfiles/images/perfil.png";

    function __construct($baseUrl = null)
    {
        $conexao = new Conexao();
        $this->PDO = $conexao->retornaConexao();
        $this->caminhoLocal = $baseUrl;
    }

    public function solicitaAmizade($userPediu, $userRecebeu)
    {
        if ($this->existeRelacionamento($userPediu,$userRecebeu)){
            $valido["mensagem"] = "Erro ao solicitar amizade,já foi feita uma soliticação ou são amigos";
            $valido["status"] = 0;
            return $valido;
        }else{
            try {
                $stmt = $this->PDO->prepare("INSERT INTO ".
                    $this->tabela .
                    "(id_usuario_princ,id_user_seguidor)".
                    " VALUES (:usuarioprinc,:usuarioseguidor)");

                $stmt->bindValue(':usuarioprinc', $userPediu);
                $stmt->bindValue(":usuarioseguidor", $userRecebeu);
                $stmt->execute();
                if ($stmt->rowCount()){
                    $valido["mensagem"] = "Solicitação Realizada com sucesso";
                    $valido["status"] = 1;
                }else{
                    $valido["mensagem"] = "Erro ao solicitar amizade ou solicitação já foi feita";
                    $valido["status"] = 0;
                }
                return $valido;
            } catch (Exception $ex) {
                $this->PDO->rollback();
                $valido["mensagem"] = "Erro ao solicitar amizade";
                $valido["status"] = 0;
                return $valido;
            }
        }

    }

    public function aceitarSolicitacao($idSolicitacao)
    {

        try {
            $stmt = $this->PDO->prepare("UPDATE relacionamento SET ".
                "status_relacionamento = 2".
                " WHERE id = :idsolic");
            $stmt->bindValue(':idsolic', $idSolicitacao);
            $stmt->execute();
            if ($stmt->rowCount()){
                $valido["mensagem"] = "Sucesso ao aceitar soliticação";
                $valido["status"] = 1;
            }else{
                $valido["mensagem"] = "Solicitação já foi aceita";
                $valido["status"] = 0;
            }
            return $valido;
        } catch (Exception $ex) {
            $this->PDO->rollback();
            $valido["mensagem"] = "Erro ao aceitar solicitação";
            $valido["status"] = 0;
            return $valido;
        }
    }

    public function recusarSolicitacao($idSolicitacao)
    {

        try {
            $stmt = $this->PDO->prepare("UPDATE relacionamento SET ".
                "status_relacionamento = 0".
                " WHERE id = :idsolic");
            $stmt->bindValue(':idsolic', $idSolicitacao);
            $stmt->execute();
            if ($stmt->rowCount()){
                $valido["mensagem"] = "Sucesso ao recusar soliticação";
                $valido["status"] = 1;
            }else{
                $valido["mensagem"] = "Solicitação já foi recusada";
                $valido["status"] = 0;
            }
            return $valido;
        } catch (Exception $ex) {
            $this->PDO->rollback();
            $valido["mensagem"] = "Erro ao recusar solicitação";
            $valido["status"] = 0;
            return $valido;
        }
    }

    public function desfazerAmizade($usuarioLogado,$usuarioPerfil){

        if ($this->ehAmigo($usuarioLogado,$usuarioPerfil)){
            try{

                $stmt = $this->PDO->prepare("UPDATE relacionamento SET ".
                    " status_relacionamento = 0".
                    " WHERE id_usuario_princ = :usuariologado ".
                    " and id_user_seguidor = :usuarioperfil".
                    " OR id_usuario_princ = :usuarioperfil and id_user_seguidor = :usuariologado".
                    " AND status_relacionamento = 2");
                $stmt->bindValue(':usuariologado', $usuarioLogado);
                $stmt->bindValue(':usuarioperfil', $usuarioPerfil);
                $stmt->execute();
                $valido["mensagem"] = "Amizade desfeita com sucesso";
                $valido["status"] = 1;
                return $valido;

            }catch (Exception $ex) {
                $this->PDO->rollback();
            }
        }else{
            $valido["mensagem"] = "Erro ao desfazer amizade, não existe amizades entre os dois usuários";
            $valido["status"] = 0;
            return $valido;
        }

    }

    public function retornaSolicitacoes($usuarioId)
    {
        $stmt = $this->PDO->prepare("SELECT usuario.id as id_usuario,usuario.caminho_imagem as imagem_usuario, ".
        " usuario.usuario as login, relacionamento.data_solicitacao as data_solicitacao, " .
        " usuario.nome as nome_usuario, ".
        " relacionamento.id as relacionamento_id ".
        " FROM relacionamento INNER JOIN usuario".
        " WHERE usuario.id != :usuarioid ".
        " AND (relacionamento.id_usuario_princ = usuario.id) ".
        " AND (relacionamento.id_user_seguidor = :usuarioid) ".
        " AND relacionamento.status_relacionamento = 1 AND usuario.status_usuario = 1"
        );
        $stmt->bindValue(':usuarioid',$usuarioId);
        $stmt->execute();
        $result = $stmt->fetchAll(\PDO::FETCH_OBJ);
        foreach ($result as $key => $value) {
            if ($value->imagem_usuario != null){
                $caminho = $value->imagem_usuario;
                $value->imagem_usuario = $this->caminhoLocal . $caminho;
            }else{
                $value->imagem_usuario = $this->caminhoLocal . $this->imgUserDefault;
            }
            $value->data_solicitacao = date( 'd/m/Y' , strtotime($value->data_solicitacao)) . " às " . date('h:m',strtotime($value->data_solicitacao));;
        }

        return $result;
    }

    public function retornaAmigos($usuarioId)
    {
        $stmt = $this->PDO->prepare("SELECT usuario.id as id_usuario,usuario.caminho_imagem as imagem_usuario, ".
        " usuario.usuario as login, relacionamento.data_solicitacao as data_solicitacao, " .
        " usuario.nome as nome_usuario, ".
        " usuario.descricao as descricao_usuario, ".
        " usuario.email as email_usuario ".
        " FROM relacionamento INNER JOIN usuario".
        " WHERE usuario.id != :usuarioid ".
        " AND (relacionamento.id_usuario_princ = usuario.id OR relacionamento.id_user_seguidor = usuario.id) ".
        " AND (relacionamento.id_usuario_princ = :usuarioid OR relacionamento.id_user_seguidor = :usuarioid) ".
        " AND relacionamento.status_relacionamento = 2 AND usuario.status_usuario = 1"
        );
        $stmt->bindValue(':usuarioid',$usuarioId);
        $stmt->execute();
        $result = $stmt->fetchAll(\PDO::FETCH_OBJ);
        foreach ($result as $key => $value) {
            if ($value->imagem_usuario != null){
                $caminho = $value->imagem_usuario;
                $value->imagem_usuario = $this->caminhoLocal . $caminho;
            }else{
                $value->imagem_usuario = $this->caminhoLocal . $this->imgUserDefault;
            }
        }
        return $result;
    }

    public function retornaQuantAmigos($usuarioId)
    {
        $stmt = $this->PDO->prepare("SELECT relacionamento.id as id ".
        " FROM relacionamento INNER JOIN usuario".
        " WHERE usuario.id != :usuarioid ".
        " AND (relacionamento.id_usuario_princ = usuario.id OR relacionamento.id_user_seguidor = usuario.id) ".
        " AND (relacionamento.id_usuario_princ = :usuarioid OR relacionamento.id_user_seguidor = :usuarioid) ".
        " AND relacionamento.status_relacionamento = 2 AND usuario.status_usuario = 1"
        );
        $stmt->bindValue(':usuarioid',$usuarioId);
        $stmt->execute();
        $result = $stmt->fetchAll(\PDO::FETCH_OBJ);
        $quantidade = count($result);
        return $quantidade;
    }

    private function existeRelacionamento($userPediu, $userRecebeu){
        $stmt = $this->PDO->prepare("SELECT id FROM ".
            $this->tabela .
            " WHERE ( id_usuario_princ = :usuariologado and id_user_seguidor = :usuarioperfil".
            " OR id_usuario_princ = :usuarioperfil and id_user_seguidor = :usuariologado )" .
            " AND (status_relacionamento = 2 OR status_relacionamento = 1 )");
        $stmt->bindValue(':usuariologado',$userPediu);
        $stmt->bindValue(':usuarioperfil',$userRecebeu);
        $stmt->execute();
        $result = $stmt->fetchAll();

        if (count($result) > 0){
            return true;
        }else {
            return false;
        }
    }

    private function ehAmigo($userPediu,$userRecebeu){
        $stmt = $this->PDO->prepare("SELECT id FROM ".
            $this->tabela .
            " WHERE ( id_usuario_princ = :usuariologado and id_user_seguidor = :usuarioperfil".
            " OR id_usuario_princ = :usuarioperfil and id_user_seguidor = :usuariologado )" .
            " AND status_relacionamento = 2 ");
        $stmt->bindValue(':usuariologado',$userPediu);
        $stmt->bindValue(':usuarioperfil',$userRecebeu);
        $stmt->execute();
        $result = $stmt->fetchAll();

        if (count($result) > 0){
            return true;
        }else {
            return false;
        }

    }
}


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

<title>OntologyLookup</title>
<meta name="date" content="2015-04-13">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

com.diskoverorta.ontology

Class OntologyLookup

java.lang.Object

com.diskoverorta.ontology.OntologyLookup

public class OntologyLookup
extends java.lang.Object

Created by naren on 4/2/15.

Constructor Summary

Constructors

Constructor and Description

OntologyLookup()

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

java.util.Map<java.lang.String,java.lang.String>
getDocumentsForCase(java.lang.String caseno)

java.util.Set<java.lang.String>
matchOntologies(java.lang.String content,
               java.lang.String kind)

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

OntologyLookup

public OntologyLookup()

Method Detail

matchOntologies

public java.util.Set<java.lang.String> matchOntologies(java.lang.String content,
                                                       java.lang.String kind)

getDocumentsForCase

public java.util.Map<java.lang.String,java.lang.String> getDocumentsForCase(java.lang.String caseno)

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
Prez Project in Symfony 2
========================

[![Build Status](https://travis-ci.org/Symfomany/prez.svg?branch=master)](https://travis-ci.org/Symfomany/prez)
![Project Status](http://stillmaintained.com/Symfomany/prez.png)

[![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/Symfomany/prez/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/Symfomany/prez/?branch=master)
[![SensioLabsInsight](https://insight.sensiolabs.com/projects/df27ca15-3f18-4fd3-9467-85b42aecbfc3/big.png)](https://insight.sensiolabs.com/account/widget?project=df27ca15-3f18-4fd3-9467-85b42aecbfc3)
[![Gitter](https://badges.gitter.im/Join Chat.svg)](https://gitter.im/Symfomany/prez?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge)

Projet d'apprentissage Symfony 2 pour Presentation by Boyer Julien

Presentation of Symfony 2 by Boyer Julien
========================

[Presentation de Symfony 2](https://slides.com/julienboyer/symfony-2 " Presentation de Symfony 2")

1) Installing the Standard Edition
----------------------------------

### Use Composer (*recommended*)

  - curl -s http://getcomposer.org/installer | php --
  - php composer.phar install --dev
  - php app/console doctrine:database:drop --force
  - php app/console doctrine:database:create
  - php app/console doctrine:schema:update --force

### Download an Archive File

To quickly test App in SYmfony 2, you can also download an [archive][3] of the Standard
Edition and unpack it somewhere under your web server root directory.

If you downloaded an archive "without vendors", you also need to install all
the necessary dependencies. Download composer (see above) and run the
following command:

    php composer.phar install

2) Testing my app
-------------------------------
 phpunit -c app/

2) Loading datas
-------------------------------
 php app/console doctrine:fixtures:load

3) View documentation
-------------------------------
 /docs/api/index.html


text:
<jump-workbench>
   <extension>com.vividsolutions.jtsplugin.JTSExtension</extension>
</jump-workbench>


text:
package com.cosium.spring.data.jpa.entity.graph.domain2;

import static org.assertj.core.api.Assertions.assertThat;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

class DynamicEntityGraphTest {

  @Test
  @DisplayName("Test graphs with same paths equal")
  void test1() {
    List<String> paths = new ArrayList<>();
    paths.add("path1");
    paths.add("path2");
    paths.add("path3");
    final DynamicEntityGraph graph1 = DynamicEntityGraph.loading(paths);
    final DynamicEntityGraph graph2 = DynamicEntityGraph.loading(paths);

    assertThat(graph1).isEqualTo(graph2).hasSameHashCodeAs(graph2);
  }

  @Test
  @DisplayName("Test graphs with different types not equal")
  void test2() {
    List<String> paths = new ArrayList<>();
    paths.add("path1");
    paths.add("path2");
    paths.add("path3");
    final DynamicEntityGraph graph1 = new DynamicEntityGraph(EntityGraphType.FETCH, paths);
    final DynamicEntityGraph graph2 = new DynamicEntityGraph(EntityGraphType.LOAD, paths);

    assertThat(graph1).isNotEqualTo(graph2).doesNotHaveSameHashCodeAs(graph2);
  }

  @Test
  @DisplayName("Test graphs with different class not equal")
  void test3() {
    final EntityGraph namedEntityGraph = new NamedEntityGraph(EntityGraphType.LOAD, "graph");
    final EntityGraph dynamicEntityGraph =
        new DynamicEntityGraph(EntityGraphType.LOAD, Collections.singletonList("path"));

    assertThat(dynamicEntityGraph)
        .isNotEqualTo(namedEntityGraph)
        .doesNotHaveSameHashCodeAs(namedEntityGraph);
  }
}


text:
import { collection, create, property, text } from 'ember-cli-page-object';
import item from './single-event-learningmaterial-list-item';

const definition = {
  scope: '[data-test-single-event-learningmaterial-list]',
  items: collection('[data-test-single-event-learningmaterial-list-item]', item),
  prework: collection('[data-test-prework-event]', {
    url: property('href', 'a'),
    name: text('[data-test-name]'),
    items: collection('[data-test-single-event-learningmaterial-list-item]', item),
  }),
  noContent: {
    scope: '[data-test-no-content]',
  },
};

export default definition;
export const component = create(definition);


text:
<%
var uid = _.uniqueId('settings-port-widget');
%>

    <label class="settings-label" for="port-input-<%=uid%>"><%=strings.label%>
    <input id="port-input-<%=uid%>" class="settings-port-input" name="port" type="number" min="1" max="65535" maxlength="5"  value="" placeholder="<%-strings.placeholder%>">

    <%-strings.validatePortBlank%>


text:
package org.zstack.test.lb;

import junit.framework.Assert;
import org.junit.Before;
import org.junit.Test;
import org.zstack.core.cloudbus.CloudBus;
import org.zstack.core.componentloader.ComponentLoader;
import org.zstack.core.db.DatabaseFacade;
import org.zstack.header.identity.SessionInventory;
import org.zstack.header.network.l3.L3NetworkInventory;
import org.zstack.header.vm.VmInstanceInventory;
import org.zstack.header.vm.VmNicInventory;
import org.zstack.network.service.lb.*;
import org.zstack.network.service.vip.VipVO;
import org.zstack.network.service.virtualrouter.lb.VirtualRouterLoadBalancerBackend.LbTO;
import org.zstack.network.service.virtualrouter.lb.VirtualRouterLoadBalancerBackend.RefreshLbCmd;
import org.zstack.simulator.appliancevm.ApplianceVmSimulatorConfig;
import org.zstack.simulator.virtualrouter.VirtualRouterSimulatorConfig;
import org.zstack.test.Api;
import org.zstack.test.ApiSenderException;
import org.zstack.test.DBUtil;
import org.zstack.test.WebBeanConstructor;
import org.zstack.test.deployer.Deployer;
import org.zstack.utils.CollectionUtils;
import org.zstack.utils.function.Function;

import static org.zstack.utils.CollectionDSL.e;
import static org.zstack.utils.CollectionDSL.list;
import static org.zstack.utils.CollectionDSL.map;

/**
 *
 * @author frank
 *
 * 1. create a lb
 * 2. add a listener with a nic
 *
 * confirm the system tags are created as default
 *
 * 3. remove the listener
 *
 * confirm the system tags are removed
 *
 * 4. add the listener again with system tags specified with a nic
 *
 * confirm the system tags are created as specified
 *
 */
public class TestVirtualRouterLb13 {
    Deployer deployer;
    Api api;
    ComponentLoader loader;
    CloudBus bus;
    DatabaseFacade dbf;
    SessionInventory session;
    VirtualRouterSimulatorConfig vconfig;
    ApplianceVmSimulatorConfig aconfig;

    @Before
    public void setUp() throws Exception {
        DBUtil.reDeployDB();
        WebBeanConstructor con = new WebBeanConstructor();
        deployer = new Deployer("deployerXml/lb/TestVirtualRouterLb.xml", con);
        deployer.addSpringConfig("VirtualRouter.xml");
        deployer.addSpringConfig("VirtualRouterSimulator.xml");
        deployer.addSpringConfig("KVMRelated.xml");
        deployer.addSpringConfig("vip.xml");
        deployer.addSpringConfig("lb.xml");
        deployer.build();
        api = deployer.getApi();
        loader = deployer.getComponentLoader();
        vconfig = loader.getComponent(VirtualRouterSimulatorConfig.class);
        aconfig = loader.getComponent(ApplianceVmSimulatorConfig.class);
        bus = loader.getComponent(CloudBus.class);
        dbf = loader.getComponent(DatabaseFacade.class);
        session = api.loginAsAdmin();
    }

    @Test
    public void test() throws ApiSenderException {
        LoadBalancerInventory lb = deployer.loadBalancers.get("lb");
        VmNicInventory nic = deployer.vms.get("TestVm").getVmNics().get(0);

        vconfig.refreshLbCmds.clear();
        LoadBalancerListenerInventory listener1 = new LoadBalancerListenerInventory();
        listener1.setName("test");
        listener1.setLoadBalancerPort(100);
        listener1.setInstancePort(100);
        listener1.setLoadBalancerUuid(lb.getUuid());
        listener1.setProtocol("http");
        final LoadBalancerListenerInventory l = api.createLoadBalancerListener(listener1, null);
        LoadBalancerVO lbvo = dbf.findByUuid(lb.getUuid(), LoadBalancerVO.class);
        Assert.assertEquals(2, lbvo.getListeners().size());
        LoadBalancerListenerVO listenerVO = CollectionUtils.find(lbvo.getListeners(), new Function<LoadBalancerListenerVO, LoadBalancerListenerVO>() {
            @Override
            public LoadBalancerListenerVO call(LoadBalancerListenerVO arg) {
                return arg.getInstancePort() == l.getInstancePort() ? arg : null;
            }
        });
        Assert.assertNotNull(listenerVO);
        api.addVmNicToLoadBalancerListener(l.getUuid(), nic.getUuid());

        RefreshLbCmd cmd = vconfig.refreshLbCmds.get(0);
        LbTO to = cmd.getLbs().get(0);

        final String s1 = LoadBalancerSystemTags.CONNECTION_IDLE_TIMEOUT.getTokenByResourceUuid(l.getUuid(), LoadBalancerSystemTags.CONNECTION_IDLE_TIMEOUT_TOKEN);
        Long val = Long.valueOf(s1);
        Assert.assertEquals(val, LoadBalancerGlobalConfig.CONNECTION_IDLE_TIMEOUT.value(Long.class));
        String tval = CollectionUtils.find(to.getParameters(), new Function<String, String>() {
            @Override
            public String call(String arg) {
                return arg.equals(LoadBalancerSystemTags.CONNECTION_IDLE_TIMEOUT.getTag(l.getUuid())) ? arg : null;
            }
        });
        Assert.assertNotNull(tval);

        final String s2 = LoadBalancerSystemTags.HEALTH_INTERVAL.getTokenByResourceUuid(l.getUuid(), LoadBalancerSystemTags.HEALTH_INTERVAL_TOKEN);
        val = Long.valueOf(s2);
        Assert.assertEquals(val, LoadBalancerGlobalConfig.HEALTH_INTERVAL.value(Long.class));
        tval = CollectionUtils.find(to.getParameters(), new Function<String, String>() {
            @Override
            public String call(String arg) {
                return arg.equals(LoadBalancerSystemTags.HEALTH_INTERVAL.getTag(l.getUuid())) ? arg : null;
            }
        });
        Assert.assertNotNull(tval);

        final String s3 = LoadBalancerSystemTags.HEALTHY_THRESHOLD.getTokenByResourceUuid(l.getUuid(), LoadBalancerSystemTags.HEALTHY_THRESHOLD_TOKEN);
        val = Long.valueOf(s3);
        Assert.assertEquals(val, LoadBalancerGlobalConfig.HEALTHY_THRESHOLD.value(Long.class));
        tval = CollectionUtils.find(to.getParameters(), new Function<String, String>() {
            @Override
            public String call(String arg) {
                return arg.equals(LoadBalancerSystemTags.HEALTHY_THRESHOLD.getTag(l.getUuid())) ? arg : null;
            }
        });
        Assert.assertNotNull(tval);

        final String s4 = LoadBalancerSystemTags.UNHEALTHY_THRESHOLD.getTokenByResourceUuid(l.getUuid(), LoadBalancerSystemTags.UNHEALTHY_THRESHOLD_TOKEN);
        val = Long.valueOf(s4);
        Assert.assertEquals(val, LoadBalancerGlobalConfig.UNHEALTHY_THRESHOLD.value(Long.class));
        tval = CollectionUtils.find(to.getParameters(), new Function<String, String>() {
            @Override
            public String call(String arg) {
                return arg.equals(LoadBalancerSystemTags.UNHEALTHY_THRESHOLD.getTag(l.getUuid())) ? arg : null;
            }
        });
        Assert.assertNotNull(tval);

        final String s5 = LoadBalancerSystemTags.HEALTH_TIMEOUT.getTokenByResourceUuid(l.getUuid(), LoadBalancerSystemTags.HEALTH_TIMEOUT_TOKEN);
        val = Long.valueOf(s5);
        Assert.assertEquals(val, LoadBalancerGlobalConfig.HEALTH_TIMEOUT.value(Long.class));
        tval = CollectionUtils.find(to.getParameters(), new Function<String, String>() {
            @Override
            public String call(String arg) {
                return arg.equals(LoadBalancerSystemTags.HEALTH_TIMEOUT.getTag(l.getUuid())) ? arg : null;
            }
        });
        Assert.assertNotNull(tval);

        final String s6 = LoadBalancerSystemTags.MAX_CONNECTION.getTokenByResourceUuid(l.getUuid(), LoadBalancerSystemTags.MAX_CONNECTION_TOKEN);
        val = Long.valueOf(s6);
        Assert.assertEquals(val, LoadBalancerGlobalConfig.MAX_CONNECTION.value(Long.class));
        tval = CollectionUtils.find(to.getParameters(), new Function<String, String>() {
            @Override
            public String call(String arg) {
                return arg.equals(LoadBalancerSystemTags.MAX_CONNECTION.getTag(l.getUuid())) ? arg : null;
            }
        });
        Assert.assertNotNull(tval);

        final String s7 = LoadBalancerSystemTags.BALANCER_ALGORITHM.getTokenByResourceUuid(l.getUuid(), LoadBalancerSystemTags.BALANCER_ALGORITHM_TOKEN);
        Assert.assertEquals(s7, LoadBalancerGlobalConfig.BALANCER_ALGORITHM.value());
        tval = CollectionUtils.find(to.getParameters(), new Function<String, String>() {
            @Override
            public String call(String arg) {
                return arg.equals(LoadBalancerSystemTags.BALANCER_ALGORITHM.getTag(l.getUuid())) ? arg : null;
            }
        });
        Assert.assertNotNull(tval);

        final String s8 = LoadBalancerSystemTags.HEALTH_TARGET.getTokenByResourceUuid(l.getUuid(), LoadBalancerSystemTags.HEALTH_TARGET_TOKEN);
        Assert.assertEquals(s8, LoadBalancerGlobalConfig.HEALTH_TARGET.value());
        tval = CollectionUtils.find(to.getParameters(), new Function<String, String>() {
            @Override
            public String call(String arg) {
                return arg.equals(LoadBalancerSystemTags.HEALTH_TARGET.getTag(l.getUuid())) ? arg : null;
            }
        });
        Assert.assertNotNull(tval);

        api.deleteLoadBalancerListener(l.getUuid(), null);
        Assert.assertFalse(LoadBalancerSystemTags.CONNECTION_IDLE_TIMEOUT.hasTag(l.getUuid()));
        Assert.assertFalse(LoadBalancerSystemTags.HEALTH_INTERVAL.hasTag(l.getUuid()));
        Assert.assertFalse(LoadBalancerSystemTags.HEALTHY_THRESHOLD.hasTag(l.getUuid()));
        Assert.assertFalse(LoadBalancerSystemTags.UNHEALTHY_THRESHOLD.hasTag(l.getUuid()));
        Assert.assertFalse(LoadBalancerSystemTags.HEALTH_TIMEOUT.hasTag(l.getUuid()));
        Assert.assertFalse(LoadBalancerSystemTags.MAX_CONNECTION.hasTag(l.getUuid()));
        Assert.assertFalse(LoadBalancerSystemTags.BALANCER_ALGORITHM.hasTag(l.getUuid()));
        Assert.assertFalse(LoadBalancerSystemTags.HEALTH_TARGET.hasTag(l.getUuid()));

        Long CONNECTION_IDLE_TIMEOUT = Long.valueOf(100);
        final String ns1 = LoadBalancerSystemTags.CONNECTION_IDLE_TIMEOUT.instantiateTag(
                map(e(LoadBalancerSystemTags.CONNECTION_IDLE_TIMEOUT_TOKEN, CONNECTION_IDLE_TIMEOUT))
        );
        Long HEALTH_INTERVAL = Long.valueOf(100);
        final String ns2 = LoadBalancerSystemTags.HEALTH_INTERVAL.instantiateTag(
                map(e(LoadBalancerSystemTags.HEALTH_INTERVAL_TOKEN, HEALTH_INTERVAL))
        );
        Long HEALTHY_THRESHOLD = Long.valueOf(100);
        final String ns3 = LoadBalancerSystemTags.HEALTHY_THRESHOLD.instantiateTag(
                map(e(LoadBalancerSystemTags.HEALTHY_THRESHOLD_TOKEN, HEALTHY_THRESHOLD))
        );
        Long UNHEALTHY_THRESHOLD = Long.valueOf(10);
        final String ns4 = LoadBalancerSystemTags.UNHEALTHY_THRESHOLD.instantiateTag(
                map(e(LoadBalancerSystemTags.UNHEALTHY_THRESHOLD_TOKEN, UNHEALTHY_THRESHOLD))
        );
        Long HEALTH_TIMEOUT = Long.valueOf(8);
        final String ns5 = LoadBalancerSystemTags.HEALTH_TIMEOUT.instantiateTag(
                map(e(LoadBalancerSystemTags.HEALTH_TIMEOUT_TOKEN, HEALTH_TIMEOUT))
        );
        Long MAX_CONNECTION = Long.valueOf(10000);
        final String ns6 = LoadBalancerSystemTags.MAX_CONNECTION.instantiateTag(
                map(e(LoadBalancerSystemTags.MAX_CONNECTION_TOKEN, MAX_CONNECTION))
        );
        String BALANCER_ALGORITHM = "source";
        final String ns7 = LoadBalancerSystemTags.BALANCER_ALGORITHM.instantiateTag(
                map(e(LoadBalancerSystemTags.BALANCER_ALGORITHM_TOKEN, BALANCER_ALGORITHM))
        );
        String HEALTH_TARGET = "TCP:5000";
        final String ns8 = LoadBalancerSystemTags.HEALTH_TARGET.instantiateTag(
                map(e(LoadBalancerSystemTags.HEALTH_TARGET_TOKEN, HEALTH_TARGET))
        );

        vconfig.refreshLbCmds.clear();
        LoadBalancerListenerInventory l2 = api.createLoadBalancerListener(l, list(ns1, ns2, ns3, ns4, ns5, ns6, ns7, ns8), null);
        api.addVmNicToLoadBalancerListener(l2.getUuid(), nic.getUuid());

        cmd = vconfig.refreshLbCmds.get(0);
        to = cmd.getLbs().get(0);
        String ss1 = LoadBalancerSystemTags.CONNECTION_IDLE_TIMEOUT.getTokenByResourceUuid(l.getUuid(), LoadBalancerSystemTags.CONNECTION_IDLE_TIMEOUT_TOKEN);
        val = Long.valueOf(ss1);
        Assert.assertEquals(CONNECTION_IDLE_TIMEOUT, val);
        tval = CollectionUtils.find(to.getParameters(), new Function<String, String>() {
            @Override
            public String call(String arg) {
                return arg.equals(ns1) ? arg : null;
            }
        });
        Assert.assertNotNull(tval);

        String ss2 = LoadBalancerSystemTags.HEALTH_INTERVAL.getTokenByResourceUuid(l.getUuid(), LoadBalancerSystemTags.HEALTH_INTERVAL_TOKEN);
        val = Long.valueOf(ss2);
        Assert.assertEquals(HEALTH_INTERVAL, val);
        tval = CollectionUtils.find(to.getParameters(), new Function<String, String>() {
            @Override
            public String call(String arg) {
                return arg.equals(ns2) ? arg : null;
            }
        });
        Assert.assertNotNull(tval);

        String ss3 = LoadBalancerSystemTags.HEALTHY_THRESHOLD.getTokenByResourceUuid(l.getUuid(), LoadBalancerSystemTags.HEALTHY_THRESHOLD_TOKEN);
        val = Long.valueOf(ss3);
        Assert.assertEquals(HEALTHY_THRESHOLD, val);
        tval = CollectionUtils.find(to.getParameters(), new Function<String, String>() {
            @Override
            public String call(String arg) {
                return arg.equals(ns3) ? arg : null;
            }
        });
        Assert.assertNotNull(tval);

        String ss4 = LoadBalancerSystemTags.UNHEALTHY_THRESHOLD.getTokenByResourceUuid(l.getUuid(), LoadBalancerSystemTags.UNHEALTHY_THRESHOLD_TOKEN);
        val = Long.valueOf(ss4);
        Assert.assertEquals(UNHEALTHY_THRESHOLD, val);
        tval = CollectionUtils.find(to.getParameters(), new Function<String, String>() {
            @Override
            public String call(String arg) {
                return arg.equals(ns4) ? arg : null;
            }
        });
        Assert.assertNotNull(tval);

        String ss5 = LoadBalancerSystemTags.HEALTH_TIMEOUT.getTokenByResourceUuid(l.getUuid(), LoadBalancerSystemTags.HEALTH_TIMEOUT_TOKEN);
        val = Long.valueOf(ss5);
        Assert.assertEquals(HEALTH_TIMEOUT, val);
        tval = CollectionUtils.find(to.getParameters(), new Function<String, String>() {
            @Override
            public String call(String arg) {
                return arg.equals(ns5) ? arg : null;
            }
        });
        Assert.assertNotNull(tval);

        String ss6 = LoadBalancerSystemTags.MAX_CONNECTION.getTokenByResourceUuid(l.getUuid(), LoadBalancerSystemTags.MAX_CONNECTION_TOKEN);
        val = Long.valueOf(ss6);
        Assert.assertEquals(MAX_CONNECTION, val);
        tval = CollectionUtils.find(to.getParameters(), new Function<String, String>() {
            @Override
            public String call(String arg) {
                return arg.equals(ns6) ? arg : null;
            }
        });
        Assert.assertNotNull(tval);

        String ss7 = LoadBalancerSystemTags.BALANCER_ALGORITHM.getTokenByResourceUuid(l.getUuid(), LoadBalancerSystemTags.BALANCER_ALGORITHM_TOKEN);
        Assert.assertEquals(BALANCER_ALGORITHM, ss7);
        tval = CollectionUtils.find(to.getParameters(), new Function<String, String>() {
            @Override
            public String call(String arg) {
                return arg.equals(ns7) ? arg : null;
            }
        });
        Assert.assertNotNull(tval);

        String ss8 = LoadBalancerSystemTags.HEALTH_TARGET.getTokenByResourceUuid(l.getUuid(), LoadBalancerSystemTags.HEALTH_TARGET_TOKEN);
        Assert.assertEquals(HEALTH_TARGET, ss8);
        tval = CollectionUtils.find(to.getParameters(), new Function<String, String>() {
            @Override
            public String call(String arg) {
                return arg.equals(ns8) ? arg : null;
            }
        });
        Assert.assertNotNull(tval);
    }
}


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Estadisticas_model extends CI_Model

{
     function __construct(){
		parent:: __construct();
		$this->load->database();

    }

    function getTiposEstadisticas(){

    	$this->db->select('*');
		$this->db->from('tb_tipo_estadistica');
		$this->db->where('codTipoEstadistica != 3 and codTipoEstadistica != 5 and codTipoEstadistica != 4');
		$query = $this->db->get();
		$result = $query->result();
		if(isset($result)){
			return $result;
		}else{
			return array();
		}

    }

     function getCantCamasLibres(){
    	$this->db->select('COUNT(*) as cant_camas_libres');
		$this->db->from('tb_cama');
		$this->db->where('tb_cama.idEstadoCama=1 ');

		if($_POST['servicios'] != '0'){
			$this->db->join('tb_habitacion','tb_habitacion.codHabitacion=tb_cama.codHabitacion');
			$this->db->where('tb_habitacion.codServicio',$_POST['servicios']);
		}
		$query = $this->db->get();
		$result = $query->result();
		if(isset($result[0])){
			return $result[0]->cant_camas_libres;
		}else{
			return 0;
		}

    }
    function getCantCamasOcupadas(){
    	//SELECT COUNT(*) FROM tb_cama WHERE tb_cama.`idEstadoCama`=3
    	$this->db->select('COUNT(*) as cant_camas_ocupadas');
		$this->db->from('tb_cama');
		if($_POST['servicios'] != '0'){
			$this->db->join('tb_habitacion','tb_habitacion.codHabitacion=tb_cama.codHabitacion');
			$this->db->where('tb_habitacion.codServicio',$_POST['servicios']);
		}
		$this->db->where('(tb_cama.idEstadoCama=3 or tb_cama.idEstadoCama=2)');

		$query = $this->db->get();
		$result = $query->result();
		if(isset($result[0])){
			return $result[0]->cant_camas_ocupadas;
		}else{
			return 0;
		}

    }
    function getCantCamas(){
    	//SELECT COUNT(*) FROM tb_cama WHERE tb_cama.`idEstadoCama`=3
    	$this->db->select('COUNT(*) as cant_camas');
		$this->db->from('tb_cama');
		if($_POST['servicios'] != '0'){
			$this->db->join('tb_habitacion','tb_habitacion.codHabitacion=tb_cama.codHabitacion');
			$this->db->where('tb_habitacion.codServicio',$_POST['servicios']);
		}
		$query = $this->db->get();
		$result = $query->result();
		if(isset($result[0])){
			return $result[0]->cant_camas;
		}else{
			return 0;
		}

    }
    function getServicios(){

    	$this->db->select('*');
		$this->db->from('tb_servicio');

		$query = $this->db->get();
		$result = $query->result();

		return $result;

    }
    function getServicio($codServicio){

    	$this->db->select('nombreServicio');
		$this->db->from('tb_servicio');
		$this->db->where('codServicio',$codServicio);

		$query = $this->db->get();
		$result = $query->result();
		if(isset($result[0])){
			return $result[0]->nombreServicio;
		}else{
			return 0;
		}

    }
    function getCantDeInternados($codServicio){

    	$this->db->select('COUNT(*) as cant_internados');
		$this->db->from('tb_internacion');
		$this->db->join('tb_cama','tb_cama.nroCama=tb_internacion.nroCama');
		$this->db->join('tb_habitacion','tb_habitacion.codHabitacion=tb_cama.codHabitacion');
		$this->db->where('tb_habitacion.codServicio',$codServicio);
		if($_POST['fechaDesde'] != '' && $_POST['fechaHasta'] != ''){

			$this->db->where('tb_internacion.fechaIngreso >=', $_POST['fechaDesde']);
			$this->db->where('tb_internacion.fechaIngreso <=', $_POST['fechaHasta']);
		}
		$query = $this->db->get();
		$result = $query->result();
		if(isset($result[0])){
			return $result[0]->cant_internados;
		}else{
			return 0;
		}
    }
    function getCantDefunciones($codServicio){

    	$this->db->select('COUNT(*) as cant_internados');
		$this->db->from('tb_internacion');
		$this->db->join('tb_cama','tb_cama.nroCama=tb_internacion.nroCama');
		$this->db->join('tb_habitacion','tb_habitacion.codHabitacion=tb_cama.codHabitacion');
		$this->db->where('tb_habitacion.codServicio',$codServicio);
		$this->db->where('codTipoAlta=4');

		if($_POST['fechaDesde'] != '' && $_POST['fechaHasta'] != ''){

			$this->db->where('tb_internacion.fechaIngreso >=', $_POST['fechaDesde']);
			$this->db->where('tb_internacion.fechaIngreso <=', $_POST['fechaHasta']);
		}
		$query = $this->db->get();
		$result = $query->result();
		if(isset($result[0])){
			return $result[0]->cant_internados;
		}else{
			return 0;
		}
    }
    function getPorcentaje($codServicio){

    	$porcentaje=0;
    	$cant_internados=$this->estadisticas_model->getCantDeInternados($codServicio);
    	$cant_defunciones=$this->estadisticas_model->getCantDefunciones($codServicio);
    	if($cant_internados != 0){
    		$porcentaje=($cant_defunciones/$cant_internados)*100;
    	}else{
    		$porcentaje=0;
       	}

       	return $porcentaje;

    }
    function getPromedioDiasEstadia($codServicio){
    	$promedio=0;
    	$cantInternados=$this->estadisticas_model->getCantDeInternados($codServicio);
    	$cantDiasInternado=$this->estadisticas_model->getCantDiasInternado($codServicio);
    	if($cantInternados != 0){
    		$pomedio=($cantDiasInternado/$cantInternados);
    	}else{
    		$pomedio=0;
       	}

       	return $pomedio;

    }
    function getCantDiasInternado($codServicio){

    	$this->db->select( array('DATEDIFF(fechaEgreso,fechaIngreso) as cantDiasInternado'));
    	$this->db->from('tb_internacion');
    	$this->db->join('tb_cama','tb_cama.nroCama=tb_internacion.nroCama');
		$this->db->join('tb_habitacion','tb_habitacion.codHabitacion=tb_cama.codHabitacion');
		$this->db->where('tb_habitacion.codServicio',$codServicio);
		$query = $this->db->get();
		$result = $query->result();
		if(isset($result[0])){
			return $result[0]->cantDiasInternado;
		}else{
			return 0;
		}
    }

    function devuelveArrayFechasEntreOtrasDos($fechaInicio, $fechaFin)
	{
		$arrayFechas=array();
		$fechaMostrar = $fechaInicio;

		while(strtotime($fechaMostrar) <= strtotime($fechaFin)) {

			$fechaMostrar = date("d-m-Y", strtotime($fechaMostrar . " + 1 day"));
			$arrayFechas[]=$fechaMostrar;
		}

	return $arrayFechas;
	}

}


text:
<?php

/**
 * This file override default PHP Ldap functions for the specified namespace
 */
namespace FR3D\LdapBundle\Driver;

/** @var \FR3D\LdapBundle\Tests\Driver\LDAPVirtual\LDAPVirtualInterface $ldapServer */
$ldapServer = null;

function ldap_bind($ress, $username = null, $password = null)
{
    global $ldapServer;

    if (!is_resource($ress)) {
        throw new \Exception('Invalid LDAP resource');
    }

    if (null == $username) {
        return true;
    }

    return $ldapServer->ldap_bind($username, $password);
}

function ldap_connect($host, $port = 389)
{
    global $ldapServer;

    $url = parse_url($host);

    if (isset($url['host'])) {
        if ($ldapServer->ldap_connect($url['host'], $url['port'])) {
            return \ldap_connect();
        }
    } else {
        if ($ldapServer->ldap_connect($host, $port)) {
            return \ldap_connect();
        }
    }

    return false;
}

function ldap_search($ress, $baseDn, $filter, array $attributes = array())
{
    global $ldapServer;

    if (!is_resource($ress)) {
        throw new \Exception('Invalid LDAP resource');
    }

    return $ldapServer->ldap_search($baseDn, $filter, $attributes);
}

function ldap_set_option($ress, $option, $value)
{
    global $ldapServer;

    if (!is_resource($ress)) {
        throw new \Exception('Invalid LDAP resource');
    }

    $return = $ldapServer->ldap_set_option($option, $value);

    // If ldap_set_option is not mocked we'll return true.
    return ($return) ? $return : true;
}

function ldap_start_tls($ress)
{
    global $ldapServer;

    if (!is_resource($ress)) {
        throw new \Exception('Invalid LDAP resource');
    }

    if (!$ldapServer->ldap_start_tls($ress)) {
        throw new \Exception('TLS not supported');
    }

    $return = $ldapServer->ldap_start_tls();

    // If ldap_set_option is not mocked we'll return true.
    return ($return) ? $return : true;
}

function ldap_get_entries($ress, $result)
{
    global $ldapServer;

    if (!is_resource($ress)) {
        throw new \Exception('Invalid LDAP resource');
    }

    return $ldapServer->ldap_get_entries($result);
}


text:
package com.google.android.exoplayer2.source.chunk;

import androidx.annotation.Nullable;

/** Holds a chunk or an indication that the end of the stream has been reached. */
public final class ChunkHolder {

  /** The chunk. */
  @Nullable public Chunk chunk;

  /** Indicates that the end of the stream has been reached. */
  public boolean endOfStream;

  /** Clears the holder. */
  public void clear() {
    chunk = null;
    endOfStream = false;
  }
}


text:
package io.teiler.server.services.util.settleup;

import io.teiler.server.dto.Debt;

import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;

/**
 * Implements methods by choosing the persons with the highest and the lowest balance.
 *
 * @author dthoma
 */
public class TopBottomChooser implements PersonChooser {

    private final SortedSet<Debt> debts = new TreeSet<>();

    public TopBottomChooser(List<Debt> debtList) {
        debtList.stream().filter(d -> d.getBalance() != 0)
            .forEach(this.debts::add);
    }

    @Override
    public Debt getNextDebitor() {
        return debts.last();
    }

    @Override
    public Debt getNextCreditor() {
        return debts.first();
    }

    @Override
    public boolean personsLeft() {
        return !debts.isEmpty();
    }

    @Override
    public void updateDebt(int newBalance, Debt debt) {
        this.debts.remove(debt);
        if (newBalance != 0) {
            debt.setBalance(newBalance);
            debts.add(debt);
        }
    }

}


text:
package main

import (
	"log"
	"github.com/ligato/cn-infra/agent"
	"github.com/ligato/cn-infra/db/keyval/etcd"
	"github.com/ligato/cn-infra/logging"
	"github.com/ligato/cn-infra/servicelabel"
	"github.com/ligato/cn-infra/db/cryptodata"
	"io/ioutil"
	"encoding/pem"
	"crypto/x509"
	"crypto/rsa"
	"github.com/pkg/errors"
	"encoding/base64"
	"github.com/ligato/cn-infra/db/keyval"
	"github.com/ligato/cn-infra/examples/cryptodata-proto-plugin/ipsec"
)

// PluginName represents name of plugin.
const PluginName = "example"

func main() {
	// Start Agent with ExamplePlugin using ETCDPlugin, CryptoDataPlugin, logger and service label.
	p := &ExamplePlugin{
		Deps: Deps{
			Log:          logging.ForPlugin(PluginName),
			ServiceLabel: &servicelabel.DefaultPlugin,
			KvProto:      &etcd.DefaultPlugin,
			CryptoData:   &cryptodata.DefaultPlugin,
		},
		exampleFinished: make(chan struct{}),
	}

	if err := agent.NewAgent(
		agent.AllPlugins(p),
		agent.QuitOnClose(p.exampleFinished),
	).Run(); err != nil {
		log.Fatal(err)
	}
}

// Deps lists dependencies of ExamplePlugin.
type Deps struct {
	Log          logging.PluginLogger
	ServiceLabel servicelabel.ReaderAPI
	KvProto      keyval.KvProtoPlugin
	CryptoData   cryptodata.ClientAPI
}

// ExamplePlugin demonstrates the usage of cryptodata API.
type ExamplePlugin struct {
	Deps
	exampleFinished chan struct{}
}

// String returns plugin name
func (plugin *ExamplePlugin) String() string {
	return PluginName
}

// Init starts the consumer.
func (plugin *ExamplePlugin) Init() error {
	// Read public key
	publicKey, err := readPublicKey("../cryptodata-lib/key-pub.pem")
	if err != nil {
		return err
	}

	// Prepare data
	key1, err := plugin.encryptData("cryptoKey1", publicKey)
	if err != nil {
		return err
	}
	key2, err := plugin.encryptData("cryptoKey2", publicKey)
	if err != nil {
		return err
	}
	encryptedData := &ipsec.TunnelInterfaces{
		Tunnels: []*ipsec.TunnelInterfaces_Tunnel{
			{
				Name:           "tunnel1",
				LocalCryptoKey: key1,
				IpAddresses: []string{
					"192.168.0.1",
					"192.168.0.2",
				},
			},
			{
				Name:            "tunnel2",
				RemoteCryptoKey: key2,
				IpAddresses: []string{
					"192.168.0.5",
					"192.168.0.8",
				},
			},
		},
	}
	plugin.Log.Infof("Putting value %v", encryptedData)

	// Prepare path for storing the data
	key := plugin.etcdKey(ipsec.KeyPrefix)

	// Prepare mapping
	decrypter := cryptodata.NewDecrypterProto()
	decrypter.RegisterMapping(
		&ipsec.TunnelInterfaces{},
		[]string{"Tunnels", "LocalCryptoKey"},
		[]string{"Tunnels", "RemoteCryptoKey"},
	)

	// Prepare broker and watcher with crypto layer
	crypto := plugin.CryptoData.WrapProto(plugin.KvProto, decrypter)
	broker := crypto.NewBroker(keyval.Root)
	watcher := crypto.NewWatcher(keyval.Root)

	// Start watching
	watcher.Watch(plugin.watchChanges, nil, key)

	// Put proto data to ETCD
	err = broker.Put(key, encryptedData)
	if err != nil {
		return err
	}

	// Get proto data from ETCD and decrypt them with crypto layer
	decryptedData := &ipsec.TunnelInterfaces{}
	_, _, err = broker.GetValue(key, decryptedData)
	if err != nil {
		return err
	}
	plugin.Log.Infof("Got value %v", decryptedData)

	// List all values from ETCD under key and decrypt them with crypto layer
	iter, err := broker.ListValues(key)
	if err != nil {
		return err
	}

	kv, stop := iter.GetNext()
	if !stop {
		decryptedDataList := &ipsec.TunnelInterfaces{}
		kv.GetValue(decryptedDataList)
		plugin.Log.Infof("Listed value %v", decryptedDataList)
	}

	// Close agent and example
	close(plugin.exampleFinished)

	return nil
}

// Close closes ExamplePlugin
func (plugin *ExamplePlugin) Close() error {
	return nil
}

// watchChanges is watching for changes in DB
func (plugin *ExamplePlugin) watchChanges(x keyval.ProtoWatchResp) {
	message := &ipsec.TunnelInterfaces{}
	err := x.GetValue(message)
	if err == nil {
		plugin.Log.Infof("Got watch message %v", message)
	}
}

// The ETCD key prefix used for this example
func (plugin *ExamplePlugin) etcdKey(label string) string {
	return "/vnf-agent/" + plugin.ServiceLabel.GetAgentLabel() + "/api/v1/example/db/simple/" + label
}

// encryptData first encrypts the provided value using crypto layer and then encodes
// the data with base64 for JSON compatibility
func (plugin *ExamplePlugin) encryptData(value string, publicKey *rsa.PublicKey) (string, error) {
	encryptedValue, err := plugin.CryptoData.EncryptData([]byte(value), publicKey)
	if err != nil {
		return "", err
	}
	return base64.URLEncoding.EncodeToString(encryptedValue), nil
}

// readPublicKey reads rsa public key from PEM file on provided path
func readPublicKey(path string) (*rsa.PublicKey, error) {
	bytes, err := ioutil.ReadFile(path)
	if err != nil {
		return nil, err
	}
	block, _ := pem.Decode(bytes)
	if block == nil {
		return nil, errors.New("failed to decode PEM for key " + path)
	}
	pubInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
	if err != nil {
		return nil, err
	}
	publicKey, ok := pubInterface.(*rsa.PublicKey)
	if !ok {
		return nil, errors.New("failed to convert public key to rsa.PublicKey")
	}

	return publicKey, nil
}


text:
#pragma once

#include <modules/discretedata/discretedatamoduledefine.h>
#include <inviwo/core/common/inviwo.h>

#include <modules/discretedata/discretedatatypes.h>
#include <modules/discretedata/connectivity/elementiterator.h>

namespace inviwo {
namespace discretedata {

class ConnectionRange;
class Connectivity;

/**
 * Iterates over one GridPrimitive type in a Connectivity.
 */
class IVW_MODULE_DISCRETEDATA_API ConnectionIterator {
    friend ConnectionIterator operator+(ind, ConnectionIterator&);
    friend ConnectionIterator operator-(ind, ConnectionIterator&);

public:
    ConnectionIterator(const Connectivity* parent, GridPrimitive dimension,
                       std::shared_ptr<const std::vector<ind>> neighborhood, ind index = 0)
        : toIndex_(index), parent_(parent), toDimension_(dimension), connection_(neighborhood) {}

    ConnectionIterator()
        : toIndex_(-1), parent_(nullptr), toDimension_(GridPrimitive(-1)), connection_() {}

    ~ConnectionIterator() = default;

    ElementIterator operator*() const;

    // Bidirectional iterator
    ConnectionIterator& operator++() {
        toIndex_++;
        return *this;
    }
    ConnectionIterator operator++(int) {
        auto i = *this;
        toIndex_++;
        return i;
    }
    ConnectionIterator& operator--() {
        toIndex_--;
        return *this;
    }
    ConnectionIterator operator--(int) {
        auto i = *this;
        toIndex_--;
        return i;
    }

    // Random access iterator
    ConnectionIterator operator+(ind offset) {
        return ConnectionIterator(parent_, toDimension_, connection_, toIndex_ + offset);
    }
    ConnectionIterator& operator+=(ind offset) {
        toIndex_ += offset;
        return *this;
    }
    ConnectionIterator operator-(ind offset) {
        return ConnectionIterator(parent_, toDimension_, connection_, toIndex_ - offset);
    }
    ConnectionIterator& operator-=(ind offset) {
        toIndex_ -= offset;
        return *this;
    }

    /**
     * Compare. Has false positives with iterators started from different elements but suffices for
     * iteration
     */
    bool operator==(ConnectionIterator& other) {
        return other.parent_ == parent_  // Compare pointers.
               && other.toDimension_ == toDimension_ && other.toIndex_ == toIndex_;
    }
    bool operator!=(ConnectionIterator& other) { return !(other == *this); }

    //! GridPrimitive type the iterator walks through
    GridPrimitive getType() const { return toDimension_; }

    //! The current index. Equivalent to dereferencing.
    ind getIndex() const { return connection_->at(toIndex_); }

    //! Iterate over connected GridPrimitives (neighbors etc)
    ConnectionRange connection(GridPrimitive type) const;

protected:
    //! Index to the current element
    ind toIndex_;

    //! Pointer to Connectivity iterated through - Does not delete
    const Connectivity* parent_;

    //! GridPrimitive type iterated over (0D vertices etc)
    const GridPrimitive toDimension_;

    // TODO: Find better solution. Keeping a ChannelIterator?
    //! List of neighborhood indices
    std::shared_ptr<const std::vector<ind>> connection_;
};

class ConnectionRange {
public:
    ConnectionRange(ind fromIndex, GridPrimitive fromDim, GridPrimitive toDim,
                    const Connectivity* parent);

    ConnectionIterator begin() {
        return ConnectionIterator(parent_, toDimension_, connections_, 0);
    }
    ConnectionIterator end() {
        return ConnectionIterator(parent_, toDimension_, connections_, connections_->size());
    }
    ind size() { return connections_->size(); }

protected:
    const Connectivity* parent_;
    GridPrimitive toDimension_;
    std::shared_ptr<const std::vector<ind>> connections_;
};

}  // namespace discretedata
}  // namespace inviwo


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Substrate;
using Substrate.Core;

namespace NBTStats
{
    public class ChunkProcessor
    {
        private readonly NbtWorld _world;
        private readonly Dictionary<int, Dictionary<int, BlockType>> _blockIds;
        private readonly List<BlockType> _blockArgs;

        private int _processedChunks;
        private int _totalChunks;

        private static object SyncRoot = new object();

        public ChunkProcessor(NbtWorld world, List<BlockType> blockArgs)
        {
            _world = world;
            _blockIds = new Dictionary<int, Dictionary<int, BlockType>>();
            foreach (var blockArg in blockArgs)
            {
                if (_blockIds.ContainsKey(blockArg.Id))
                {
                    _blockIds[blockArg.Id][blockArg.Data] = blockArg;
                    continue;
                }
                _blockIds[blockArg.Id] = new Dictionary<int, BlockType>();
                _blockIds[blockArg.Id][blockArg.Data] = blockArg;
            }

            _blockArgs = blockArgs;
        }

        public void Run()
        {
            Console.Clear();
            var cm = _world.GetChunkManager();

            _totalChunks = cm.Count();

            Console.WriteLine("# Chunks: {0}", _totalChunks);

            Task.WaitAll(cm.Select(chunkRef => Task.Factory.StartNew(() => ProcessChunk(chunkRef))).ToArray());

            Console.WriteLine();

            foreach (var block in _blockArgs)
            {
                block.PrintValues(_totalChunks);
                Console.WriteLine();
                Console.WriteLine();
            }
        }

        private void ProcessChunk(IChunk chunk1)
        {
            var xdim = chunk1.Blocks.XDim;
            var ydim = chunk1.Blocks.YDim;
            var zdim = chunk1.Blocks.ZDim;

            for (var x = 0; x < xdim; x++)
            {
                for (var z = 0; z < zdim; z++)
                {
                    for (var y = 0; y < ydim; y++)
                    {
                        var id = chunk1.Blocks.GetID(x, y, z);
                        var blocks = _blockIds.Get(id);
                        if (blocks == null) continue;

                        var data = chunk1.Blocks.GetData(x, y, z);
                        var block = blocks.Get(data);
                        if (block == null) continue;

                        block.AddYValue(y);
                    }
                }
            }

            Interlocked.Increment(ref _processedChunks);
            if (_processedChunks%10 != 0 && _processedChunks < _totalChunks - 20) return;

            lock (SyncRoot)
            {
                Console.CursorLeft = 0;
                Console.CursorTop = 1;
                foreach (var blockArg in _blockArgs)
                {
                    blockArg.PrintAvg(_processedChunks);
                }
                Console.WriteLine("Block # {0} {1:P} complete", _processedChunks, ((float)_processedChunks)/_totalChunks);
            }
        }

    }
}


text:
namespace odin
{
    namespace io
    {
        Keyboard::Keyboard()
        {
            for (auto& key : m_keyStates)
                key = false;
        }

        void Keyboard::setButtonState(int button, bool pressed)
        {
            assert(button >= 0);
            assert(button < ODIN_KEY_LAST);

            m_keyStates[button] = pressed;
        }

        bool Keyboard::getButtonState(int button) const
        {
            assert(button >= 0);
            assert(button < ODIN_KEY_LAST);

            return m_keyStates[button];
        }
    }
}


text:
/** @file
 * @brief ICMPv6 related functions
 */

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

#include <zephyr/logging/log.h>
LOG_MODULE_REGISTER(net_icmpv6, CONFIG_NET_ICMPV6_LOG_LEVEL);

#include <errno.h>
#include <zephyr/sys/slist.h>
#include <zephyr/sys/byteorder.h>
#include <zephyr/net/net_core.h>
#include <zephyr/net/net_pkt.h>
#include <zephyr/net/net_if.h>
#include "net_private.h"
#include "icmpv6.h"
#include "ipv6.h"
#include "net_stats.h"

#define PKT_WAIT_TIME K_SECONDS(1)

static sys_slist_t handlers;

const char *net_icmpv6_type2str(int icmpv6_type)
{
	switch (icmpv6_type) {
	case NET_ICMPV6_DST_UNREACH:
		return "Destination Unreachable";
	case NET_ICMPV6_PACKET_TOO_BIG:
		return "Packet Too Big";
	case NET_ICMPV6_TIME_EXCEEDED:
		return "Time Exceeded";
	case NET_ICMPV6_PARAM_PROBLEM:
		return "IPv6 Bad Header";
	case NET_ICMPV6_ECHO_REQUEST:
		return "Echo Request";
	case NET_ICMPV6_ECHO_REPLY:
		return "Echo Reply";
	case NET_ICMPV6_MLD_QUERY:
		return "Multicast Listener Query";
	case NET_ICMPV6_RS:
		return "Router Solicitation";
	case NET_ICMPV6_RA:
		return "Router Advertisement";
	case NET_ICMPV6_NS:
		return "Neighbor Solicitation";
	case NET_ICMPV6_NA:
		return "Neighbor Advertisement";
	case NET_ICMPV6_MLDv2:
		return "Multicast Listener Report v2";
	}

	return "?";
}

void net_icmpv6_register_handler(struct net_icmpv6_handler *handler)
{
	sys_slist_prepend(&handlers, &handler->node);
}

void net_icmpv6_unregister_handler(struct net_icmpv6_handler *handler)
{
	sys_slist_find_and_remove(&handlers, &handler->node);
}

int net_icmpv6_finalize(struct net_pkt *pkt)
{
	NET_PKT_DATA_ACCESS_CONTIGUOUS_DEFINE(icmp_access,
					      struct net_icmp_hdr);
	struct net_icmp_hdr *icmp_hdr;

	icmp_hdr = (struct net_icmp_hdr *)net_pkt_get_data(pkt, &icmp_access);
	if (!icmp_hdr) {
		return -ENOBUFS;
	}

	icmp_hdr->chksum = 0U;
	if (net_if_need_calc_rx_checksum(net_pkt_iface(pkt))) {
		icmp_hdr->chksum = net_calc_chksum_icmpv6(pkt);
	}

	return net_pkt_set_data(pkt, &icmp_access);
}

int net_icmpv6_create(struct net_pkt *pkt, uint8_t icmp_type, uint8_t icmp_code)
{
	NET_PKT_DATA_ACCESS_CONTIGUOUS_DEFINE(icmp_access,
					      struct net_icmp_hdr);
	struct net_icmp_hdr *icmp_hdr;

	icmp_hdr = (struct net_icmp_hdr *)net_pkt_get_data(pkt, &icmp_access);
	if (!icmp_hdr) {
		return -ENOBUFS;
	}

	icmp_hdr->type   = icmp_type;
	icmp_hdr->code   = icmp_code;
	icmp_hdr->chksum = 0U;

	return net_pkt_set_data(pkt, &icmp_access);
}

static
enum net_verdict icmpv6_handle_echo_request(struct net_pkt *pkt,
					    struct net_ipv6_hdr *ip_hdr,
					    struct net_icmp_hdr *icmp_hdr)
{
	struct net_pkt *reply = NULL;
	const struct in6_addr *src;
	int16_t payload_len;

	ARG_UNUSED(icmp_hdr);

	NET_DBG("Received Echo Request from %s to %s",
		net_sprint_ipv6_addr(&ip_hdr->src),
		net_sprint_ipv6_addr(&ip_hdr->dst));

	payload_len = ntohs(ip_hdr->len) -
		net_pkt_ipv6_ext_len(pkt) - NET_ICMPH_LEN;
	if (payload_len < NET_ICMPV6_UNUSED_LEN) {
		/* No identifier or sequence number present */
		goto drop;
	}

	reply = net_pkt_alloc_with_buffer(net_pkt_iface(pkt), payload_len,
					  AF_INET6, IPPROTO_ICMPV6,
					  PKT_WAIT_TIME);
	if (!reply) {
		NET_DBG("DROP: No buffer");
		goto drop;
	}

	if (net_ipv6_is_addr_mcast((struct in6_addr *)ip_hdr->dst)) {
		src = net_if_ipv6_select_src_addr(net_pkt_iface(pkt),
						  (struct in6_addr *)ip_hdr->dst);
	} else {
		src = (struct in6_addr *)ip_hdr->dst;
	}

	/* We must not set the destination ll address here but trust
	 * that it is set properly using a value from neighbor cache.
	 * Same for source as it points to original pkt ll src address.
	 */
	net_pkt_lladdr_dst(reply)->addr = NULL;
	net_pkt_lladdr_src(reply)->addr = NULL;

	net_pkt_set_ip_dscp(reply, net_pkt_ip_dscp(pkt));
	net_pkt_set_ip_ecn(reply, net_pkt_ip_ecn(pkt));

	if (net_ipv6_create(reply, src, (struct in6_addr *)ip_hdr->src)) {
		NET_DBG("DROP: wrong buffer");
		goto drop;
	}

	if (net_icmpv6_create(reply, NET_ICMPV6_ECHO_REPLY, 0) ||
	    net_pkt_copy(reply, pkt, payload_len)) {
		NET_DBG("DROP: wrong buffer");
		goto drop;
	}

	net_pkt_cursor_init(reply);
	net_ipv6_finalize(reply, IPPROTO_ICMPV6);

	NET_DBG("Sending Echo Reply from %s to %s",
		net_sprint_ipv6_addr(src),
		net_sprint_ipv6_addr(&ip_hdr->src));

	if (net_send_data(reply) < 0) {
		goto drop;
	}

	net_stats_update_icmp_sent(net_pkt_iface(reply));

	net_pkt_unref(pkt);

	return NET_OK;

drop:
	if (reply) {
		net_pkt_unref(reply);
	}

	net_stats_update_icmp_drop(net_pkt_iface(pkt));

	return NET_DROP;
}

int net_icmpv6_send_error(struct net_pkt *orig, uint8_t type, uint8_t code,
			  uint32_t param)
{
	NET_PKT_DATA_ACCESS_CONTIGUOUS_DEFINE(ipv6_access, struct net_ipv6_hdr);
	int err = -EIO;
	struct net_ipv6_hdr *ip_hdr;
	const struct in6_addr *src;
	struct net_pkt *pkt;
	size_t copy_len;
	int ret;

	net_pkt_cursor_init(orig);

	ip_hdr = (struct net_ipv6_hdr *)net_pkt_get_data(orig, &ipv6_access);
	if (!ip_hdr) {
		goto drop_no_pkt;
	}

	if (ip_hdr->nexthdr == IPPROTO_ICMPV6) {
		NET_PKT_DATA_ACCESS_CONTIGUOUS_DEFINE(icmpv6_access,
						      struct net_icmp_hdr);
		struct net_icmp_hdr *icmp_hdr;

		net_pkt_acknowledge_data(orig, &ipv6_access);

		icmp_hdr = (struct net_icmp_hdr *)net_pkt_get_data(
							orig, &icmpv6_access);
		if (!icmp_hdr || icmp_hdr->code < 128) {
			/* We must not send ICMP errors back */
			err = -EINVAL;
			goto drop_no_pkt;
		}

		net_pkt_cursor_init(orig);
	}

	if (ip_hdr->nexthdr == IPPROTO_UDP) {
		copy_len = sizeof(struct net_ipv6_hdr) +
			sizeof(struct net_udp_hdr);
	} else if (ip_hdr->nexthdr == IPPROTO_TCP) {
		copy_len = sizeof(struct net_ipv6_hdr) +
			sizeof(struct net_tcp_hdr);
	} else {
		copy_len = net_pkt_get_len(orig);
	}

	pkt = net_pkt_alloc_with_buffer(net_pkt_iface(orig),
					net_pkt_lladdr_src(orig)->len * 2 +
					copy_len + NET_ICMPV6_UNUSED_LEN,
					AF_INET6, IPPROTO_ICMPV6,
					PKT_WAIT_TIME);
	if (!pkt) {
		err = -ENOMEM;
		goto drop_no_pkt;
	}

	/* We created above a new packet that contains some extra space that we
	 * will use to store the destination and source link addresses. This is
	 * needed because we cannot use the original pkt, which contains the
	 * link address where the new packet will be sent, as that pkt might
	 * get re-used before we have managed to set the link addresses in L2
	 * as that (link address setting) happens in a different thread (TX)
	 * than this one.
	 * So we copy the destination and source link addresses here, then set
	 * the link address pointers correctly, and skip the needed space
	 * as the link address will be set in the pkt when the packet is
	 * constructed in L2. So basically all this for just to create some
	 * extra space for link addresses so that we can set the lladdr
	 * pointers in net_pkt.
	 */
	ret = net_pkt_write(pkt, net_pkt_lladdr_src(orig)->addr,
			    net_pkt_lladdr_src(orig)->len);
	if (ret < 0) {
		err = ret;
		goto drop;
	}

	net_pkt_lladdr_dst(pkt)->addr = pkt->buffer->data;

	ret = net_pkt_write(pkt, net_pkt_lladdr_dst(orig)->addr,
			    net_pkt_lladdr_dst(orig)->len);
	if (ret < 0) {
		err = ret;
		goto drop;
	}

	net_buf_pull_mem(pkt->buffer, net_pkt_lladdr_dst(orig)->len);

	net_pkt_lladdr_src(pkt)->addr = pkt->buffer->data;

	net_buf_pull_mem(pkt->buffer, net_pkt_lladdr_src(orig)->len);

	net_pkt_lladdr_src(pkt)->len = net_pkt_lladdr_dst(orig)->len;
	net_pkt_lladdr_dst(pkt)->len = net_pkt_lladdr_src(orig)->len;

	if (net_ipv6_is_addr_mcast((struct in6_addr *)ip_hdr->dst)) {
		src = net_if_ipv6_select_src_addr(net_pkt_iface(pkt),
						  (struct in6_addr *)ip_hdr->dst);
	} else {
		src = (struct in6_addr *)ip_hdr->dst;
	}

	if (net_ipv6_create(pkt, src, (struct in6_addr *)ip_hdr->src) ||
	    net_icmpv6_create(pkt, type, code)) {
		goto drop;
	}

	/* Depending on error option, we store the param into the ICMP message.
	 */
	if (type == NET_ICMPV6_PARAM_PROBLEM) {
		err = net_pkt_write_be32(pkt, param);
	} else {
		err = net_pkt_memset(pkt, 0, NET_ICMPV6_UNUSED_LEN);
	}

	/* Allocator might not have been able to allocate all requested space,
	 * so let's copy as much as we can.
	 */
	copy_len = net_pkt_available_buffer(pkt);

	if (err || net_pkt_copy(pkt, orig, copy_len)) {
		goto drop;
	}

	net_pkt_cursor_init(pkt);
	net_ipv6_finalize(pkt, IPPROTO_ICMPV6);

	NET_DBG("Sending ICMPv6 Error Message type %d code %d param %d"
		" from %s to %s", type, code, param,
		net_sprint_ipv6_addr(src),
		net_sprint_ipv6_addr(&ip_hdr->src));

	if (net_send_data(pkt) >= 0) {
		net_stats_update_icmp_sent(net_pkt_iface(pkt));
		return 0;
	}

drop:
	net_pkt_unref(pkt);

drop_no_pkt:
	net_stats_update_icmp_drop(net_pkt_iface(orig));

	return err;
}

int net_icmpv6_send_echo_request(struct net_if *iface,
				 struct in6_addr *dst,
				 uint16_t identifier,
				 uint16_t sequence,
				 uint8_t tc,
				 const void *data,
				 size_t data_size)
{
	NET_PKT_DATA_ACCESS_CONTIGUOUS_DEFINE(icmpv6_access,
					      struct net_icmpv6_echo_req);
	int ret = -ENOBUFS;
	struct net_icmpv6_echo_req *echo_req;
	const struct in6_addr *src;
	struct net_pkt *pkt;

	src = net_if_ipv6_select_src_addr(iface, dst);

	pkt = net_pkt_alloc_with_buffer(iface,
					sizeof(struct net_icmpv6_echo_req)
					+ data_size,
					AF_INET6, IPPROTO_ICMPV6,
					PKT_WAIT_TIME);
	if (!pkt) {
		return -ENOMEM;
	}

	net_pkt_set_ip_dscp(pkt, net_ipv6_get_dscp(tc));
	net_pkt_set_ip_ecn(pkt, net_ipv6_get_ecn(tc));

	if (net_ipv6_create(pkt, src, dst) ||
	    net_icmpv6_create(pkt, NET_ICMPV6_ECHO_REQUEST, 0)) {
		goto drop;
	}

	echo_req = (struct net_icmpv6_echo_req *)net_pkt_get_data(
							pkt, &icmpv6_access);
	if (!echo_req) {
		goto drop;
	}

	echo_req->identifier = htons(identifier);
	echo_req->sequence   = htons(sequence);

	net_pkt_set_data(pkt, &icmpv6_access);
	net_pkt_write(pkt, data, data_size);

	net_pkt_cursor_init(pkt);
	net_ipv6_finalize(pkt, IPPROTO_ICMPV6);

	NET_DBG("Sending ICMPv6 Echo Request type %d from %s to %s",
		NET_ICMPV6_ECHO_REQUEST,
		net_sprint_ipv6_addr(src),
		net_sprint_ipv6_addr(dst));

	if (net_send_data(pkt) >= 0) {
		net_stats_update_icmp_sent(iface);
		return 0;
	}

	net_stats_update_icmp_drop(iface);

	ret = -EIO;

drop:
	net_pkt_unref(pkt);

	return ret;
}

enum net_verdict net_icmpv6_input(struct net_pkt *pkt,
				  struct net_ipv6_hdr *ip_hdr)
{
	NET_PKT_DATA_ACCESS_CONTIGUOUS_DEFINE(icmp_access,
					      struct net_icmp_hdr);
	struct net_icmp_hdr *icmp_hdr;
	struct net_icmpv6_handler *cb;

	icmp_hdr = (struct net_icmp_hdr *)net_pkt_get_data(pkt, &icmp_access);
	if (!icmp_hdr) {
		NET_DBG("DROP: NULL ICMPv6 header");
		return NET_DROP;
	}

	if (net_if_need_calc_rx_checksum(net_pkt_iface(pkt))) {
		if (net_calc_chksum_icmpv6(pkt) != 0U) {
			NET_DBG("DROP: invalid checksum");
			goto drop;
		}
	}

	net_pkt_acknowledge_data(pkt, &icmp_access);

	NET_DBG("ICMPv6 %s received type %d code %d",
		net_icmpv6_type2str(icmp_hdr->type),
		icmp_hdr->type, icmp_hdr->code);

	net_stats_update_icmp_recv(net_pkt_iface(pkt));

	SYS_SLIST_FOR_EACH_CONTAINER(&handlers, cb, node) {
		if (cb->type == icmp_hdr->type &&
		    (cb->code == icmp_hdr->code || cb->code == 0U)) {
			return cb->handler(pkt, ip_hdr, icmp_hdr);
		}
	}
drop:
	net_stats_update_icmp_drop(net_pkt_iface(pkt));

	return NET_DROP;
}

static struct net_icmpv6_handler echo_request_handler = {
	.type = NET_ICMPV6_ECHO_REQUEST,
	.code = 0,
	.handler = icmpv6_handle_echo_request,
};

void net_icmpv6_init(void)
{
	net_icmpv6_register_handler(&echo_request_handler);
}


text:
import os
from setuptools import setup

setup(
        name = "csv2xlsx",
        version = "0.1",
        author = "Dillon Barker",
        author_email = "dorbarker@github.com",
        description = "Wraps CSV files as worksheets in a MS Excel workbook",
        license = "BSD",
        url = "https://github.com/dorbarker/csv2xlsx",
        keywords = "csv xlsx excel",
        install_requires = ["xlsxwriter"],
        py_modules = ['csv2xlsx'],
        entry_points =  {
            'console_scripts': [
                'csv2xlsx=csv2xlsx:main'
                ]
            },
        classifiers = [
            "Development Status :: 3 - Alpha",
            "Topic :: Utilities",
            "License :: OSI Approved :: BSD License",
            "Programming Language :: Python :: 2.7",
            "Programming Language :: Python :: 3.0",
            "Programming Language :: Python :: 3.1",
            "Programming Language :: Python :: 3.2",
            "Programming Language :: Python :: 3.4"
            ]

)


text:
<!DOCTYPE html>
<html>
<head>
	<title>Witness Panels</title>
	<link rel="stylesheet" type="text/css" href="css/main.css">

	<script type="x-shader/x-vertex" id="vert">
		uniform mediump vec2 u_resolution;		// Canvas resolution in pixels
		uniform mediump float u_fill;			// How much is the element filled?
		uniform mediump int u_fillDirection;	// From which direction is the element filled?
		attribute vec2 a_position;				// Vertex position in pixels
		attribute vec2 a_uv;					// Vertex uv position in uv space
		varying mediump vec2 v_worldPos;		// Position in clip space
		varying mediump vec2 v_localPos;		// Position in uv space

		void main()
		{
			vec2 clipPos = vec2((a_position.x / u_resolution.x) * 2.0 - 1.0, (a_position.y / u_resolution.y) * 2.0 - 1.0);
			gl_Position = vec4(clipPos, 0, 1);
			v_worldPos = gl_Position.xy;
			v_localPos = a_uv;
		}
	</script>
	<script type="x-shader/x-fragment" id="frag-circle">
		uniform mediump vec2 u_resolution;
		uniform mediump float u_fill;
		varying mediump vec2 v_worldPos;
		varying mediump vec2 v_localPos;

		void main()
		{
			highp vec4 color = vec4(1,1,1,1);

			if (u_fill != 0.0)
			{
				color = vec4(1,1,0,1);
			}

			gl_FragColor = color * ceil(1.0 - (v_localPos.x * v_localPos.x + v_localPos.y * v_localPos.y));
		}
	</script>
	<script type="x-shader/x-fragment" id="frag-rect">
		uniform mediump vec2 u_resolution;
		uniform mediump float u_fill;
		uniform mediump int u_fillDirection;
		varying mediump vec2 v_worldPos;
		varying mediump vec2 v_localPos;

		void main()
		{
			highp vec4 color = vec4(1,1,0,1);

			if(u_fillDirection == 0) //Right->Left
			{
				gl_FragColor = color * ceil(v_localPos.x / 2.0 - 0.5 + u_fill);
			}
			else if (u_fillDirection == 1) //Left->Right
			{
				gl_FragColor = color * 1.0 - ceil(v_localPos.x / 2.0 + 0.5 - u_fill);
			}
			else if (u_fillDirection == 2) //Down->Up
			{
				gl_FragColor = color * 1.0 - ceil(v_localPos.y / 2.0 + 0.5 - u_fill);
			}
			else //Up->Down
			{
				gl_FragColor = color * ceil(v_localPos.y / 2.0 - 0.5 + u_fill);
			}
		}
	</script>
</head>
<body>
	<canvas id="canvas" style="background-color: red;"></canvas>
</body>
</html>

<script src="js/main.js" type="text/javascript"></script>
<script src="js/game.js" type="text/javascript"></script>


text:
Introduction

If you imagine a film set, there's a guy pointing a camera at a scene of different props, and he can do so from different angles. It's all pretty similar in three.js, which is made up of objects that make coding 3D experiences much more natural to us. For example, three of the tools we have at our disposal when using three.js are below:

 Scene - this contains all the 3D object data (all the props)

 Camera - this has a field of view, position and rotation

 Renderer - this figures out what objects look like from the camera's point of view

Three.js simplifies WebGL, enabling us to use simple concepts such as those above to produce 3D experiences with minimal code. The same would have required hundreds of lines of JavaScript when using WebGL directly.

In this tutorial, we'll be setting up the three.js environment in step 1, then using the Scene, Camera and Renderer objects listed above, getting an understanding of each in step 2. In the final step 3, we'll add an animating cube to the scene we've created.

The Outcome

Here's what we'll end up with - if you just want the code you can grab it from the codepen below or github. Otherwise, to learn about what's going on, continue reading from step 1.

See the Pen Three.js starter by Graeme Fulton (@GraemeFulton) on CodePen.

Step 1: Download three.js & setup the HTML project

Download three.js

First, get a copy of three.js from its GitHub repository, and save it locally.

The reason I'm storing this locally is to prevent the applicaiton breaking if a different release of three.js is used. The latest version at the time of this tutorial was revision 71, so you should use r71 if you're having any issues.

Apart from three.js, we're just going to be coding everything else within a single HTML file for simplicity.

Create the HTML project file

All we're doing below is including our local three.js library, and opening some script tags where most of the code will go.

<!doctype html>
<html lang="en">
<head>
  <title>Three.js Tutorial</title>
  <meta charset="utf-8">
</head>
<body>

  <script src="three.js"></script>

  <script>

    //code will go here...

  </script>

</body>
</html>

Step 2: Create a Scene, Camera and Renderer

Now, we'll declare 3 global variables, and assign each of them with a three.js object. First we'll create a Scene, then add a Camera, followed by the Renderer.

Create the Scene

The scene is really simple:

//declare scene variable
var scene;

//create the scene
scene = new THREE.Scene();

Add the Camera

To add the camera, we assign a PerspectiveCamera object to a camera variable. There's a few different other camera options, but we'll use the PerspectiveCamera above:

//declare camera variable
var camera;

//assign three.js perspective camera to variable
camera = new THREE.PerspectiveCamera(75, window.innerWidth/ window.innerHeight, 0.1, 1000);

Let's step through the arguments provided to the PerspectiveCamera:

The first argument we have provided, 75, is the field of view for the camera.

Second, window.innerWidth/ window.innerHeight is the aspect ratio.

The final two arguments are the clipping plane for far and near.

Add the Renderer

For rendering, we'll use the WebGLRenderer object, which will display our scene using WebGL. Alternatively, canvasRenderer() could have been used, which uses the canvas element - it's a good fallback for when WebGL is not available.

//declare renderer variable
var renderer;

//assign WebGL renderer object
renderer = new THREE.WebGLRenderer();

//set the size of the renderer
renderer.setSize( window.innerWidth, window.innerHeight );

//add the renderer to the html document body element
document.body.appendChild( renderer.domElement );

Bring it all together

You can then combine all of the above code into something more manageable as seen in the snippet below. The variables are declared globally, and then we have an init() function, which we call at the bottom to build our scene.

    //Declare three.js variables
	var camera, scene, renderer;

	//assign three.js objects to each variable
	function init(){

		//camera
		camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );

		//scene
		scene = new THREE.Scene();

		//renderer
		renderer = new THREE.WebGLRenderer();
		//set the size of the renderer
		renderer.setSize( window.innerWidth, window.innerHeight );

		//add the renderer to the html document body
		document.body.appendChild( renderer.domElement );

	}

At this point, you still won't actually see anything if you run the code as there's nothing on the scene, and it isn't actually rendered. So let's fix that in the next step:

Step 3: Rendering a cube onto the scene

In this step, we'll first create a cube and add it to our scene, and then create a rendering loop which will run our scene.

Create the Cube

First, we declare the cube variable globally, so it can be used in other methods if necessary, then create the cube within an addCube function. To do this, we use BoxGeometry to create a geometry object, then create some material with a colour, and then Mesh them together to create to cube. After we add the cube to the scene, we have to set the camera position so that the cube becomes visible.

If that sounded complicated, it's actually really simple if you look at it line by line:

var cube;

function addCube(){

		//create box geometry object
		var geometry = new THREE.BoxGeometry( 1, 1, 1 );
		//create material with colour
		var material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
		//combine geometry with material to create the cube
		cube = new THREE.Mesh( geometry, material );
		//add the cube to the scene
		scene.add( cube );

		//set the camera position
		camera.position.z = 5;
	}

Render the scene

Here, we define a render() function, which basically acts as a loop, firing 60 times a second:

	function render() {
		//get the frame
		requestAnimationFrame( render );
		//render the scene
		renderer.render( scene, camera );
	}

Now to run all of this, just add the following to the bottom of your script:

	init();
	addCube();
	render();

Animate the cube

To demonstrate how this render loop is actually working, we can animate the cube just by adding a couple lines within the render function:

	function render() {
		//get the frame
		requestAnimationFrame( render );

		//animate the cube
		cube.rotation.x += 0.1;
		cube.rotation.y += 0.1;

		//render the scene
		renderer.render( scene, camera );
	}

Because the render function acts in a loop, it adds 0.1 to the x and y rotations of the cube 60 times a second, creating a rotating animation.

Well done

Good work, you've learned some of the very basics of three.js. I'll be adding a new tutorial to further manipulate the cube in the future.