text:
<?php

use Easygd\Color;
use Easygd\Image;
use Easygd\ImageFilterIterator;
use Easygd\Position;
use Easygd\Text;

require '../vendor/autoload.php';

$text = (new Text)->create('Copyright (C) 2013 Florent Brusciano')
	->setFontType(Text::TEXT_FONT_TRUETYPE)
	->setFontfile(Text::TEXT_UNIX_FONT_PATH . '/truetype/dejavu/DejaVuSans.ttf')
	->setSize(5)
	->setColor(Color::White())
	->setPosition((new Position())->create(40, 190));

$path = __DIR__ . '/images/original/';

foreach (new ImageFilterIterator(new DirectoryIterator($path)) as $file) {

	if (($image = (new Image)->load($file->getPathname())) === false) {
		continue;
	}

	$thumb1 = $image->thumbnail(100)->src();
	$thumb2 = $image->thumbnail(200)->addText($text)->src();
	$thumb3 = $image->thumbnail(400)->src();
?>

	<img src="<?php echo $thumb1 ?>" />
	<img src="<?php echo $thumb2 ?>" />
	<img src="<?php echo $thumb3 ?>" />

<?php
}


text:
package com.ispring.gameplane;

import android.app.Activity;
import android.os.Bundle;

import com.ispring.gameplane.game.GameView;

public class GameActivity extends Activity {

    private GameView gameView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_game);
        gameView = (GameView)findViewById(R.id.gameView);
        //0:combatAircraft
        //1:explosion
        //2:yellowBullet
        //3:blueBullet
        //4:smallEnemyPlane
        //5:middleEnemyPlane
        //6:bigEnemyPlane
        //7:bombAward
        //8:bulletAward
        //9:pause1
        //10:pause2
        //11:bomb
        int[] bitmapIds = {
                R.drawable.plane,
                R.drawable.explosion,
                R.drawable.yellow_bullet,
                R.drawable.blue_bullet,
                R.drawable.small,
                R.drawable.middle,
                R.drawable.big,
                R.drawable.bomb_award,
                R.drawable.bullet_award,
                R.drawable.pause1,
                R.drawable.pause2,
                R.drawable.bomb
        };
        gameView.start(bitmapIds);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if(gameView != null){
            gameView.pause();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(gameView != null){
            gameView.destroy();
        }
        gameView = null;
    }
}

redpajama_set_name: RedPajamaGithub


text:
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('geokey_checklist', '0012_auto_20151101_0026'),
    ]

    operations = [
        migrations.AlterField(
            model_name='checklistitem',
            name='pertype',
            field=models.CharField(default=b'individual', max_length=100, choices=[(b'individual', b'Per Individual'), (b'location', b'Per Location')]),
        ),
        migrations.AlterField(
            model_name='checklistsettings',
            name='frequencybeforeexpiration',
            field=models.CharField(default=180, max_length=100, choices=[(180, b'six months'), (90, b'three months'), (30, b'one month'), (7, b'one week'), (1, b'one day'), (999999, b'never')]),
        ),
    ]


text:
package org.datasyslab.geospark.spatialOperator;

import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.Point;
import com.vividsolutions.jts.geom.Polygon;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaSparkContext;
import org.datasyslab.geospark.enums.FileDataSplitter;
import org.datasyslab.geospark.enums.IndexType;
import org.datasyslab.geospark.knnJudgement.GeometryDistanceComparator;
import org.datasyslab.geospark.spatialRDD.RectangleRDD;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Properties;

// TODO: Auto-generated Javadoc

/**
 * The Class RectangleKnnTest.
 */
public class RectangleKnnTest
{

    /**
     * The sc.
     */
    public static JavaSparkContext sc;

    /**
     * The prop.
     */
    static Properties prop;

    /**
     * The input.
     */
    static InputStream input;

    /**
     * The Input location.
     */
    static String InputLocation;

    /**
     * The offset.
     */
    static Integer offset;

    /**
     * The splitter.
     */
    static FileDataSplitter splitter;

    /**
     * The index type.
     */
    static IndexType indexType;

    /**
     * The num partitions.
     */
    static Integer numPartitions;

    /**
     * The loop times.
     */
    static int loopTimes;

    /**
     * The query point.
     */
    static Point queryPoint;

    /**
     * The top K.
     */
    static int topK;

    /**
     * Once executed before all.
     */
    @BeforeClass
    public static void onceExecutedBeforeAll()
    {
        SparkConf conf = new SparkConf().setAppName("RectangleKnn").setMaster("local[2]");
        sc = new JavaSparkContext(conf);
        Logger.getLogger("org").setLevel(Level.WARN);
        Logger.getLogger("akka").setLevel(Level.WARN);
        prop = new Properties();
        input = RectangleKnnTest.class.getClassLoader().getResourceAsStream("rectangle.test.properties");

        //Hard code to a file in resource folder. But you can replace it later in the try-catch field in your hdfs system.
        InputLocation = "file://" + RectangleKnnTest.class.getClassLoader().getResource("primaryroads.csv").getPath();

        offset = 0;
        splitter = null;
        indexType = null;
        numPartitions = 0;
        GeometryFactory fact = new GeometryFactory();
        try {
            // load a properties file
            prop.load(input);
            // There is a field in the property file, you can edit your own file location there.
            // InputLocation = prop.getProperty("inputLocation");
            InputLocation = "file://" + RectangleKnnTest.class.getClassLoader().getResource(prop.getProperty("inputLocation")).getPath();
            offset = Integer.parseInt(prop.getProperty("offset"));
            splitter = FileDataSplitter.getFileDataSplitter(prop.getProperty("splitter"));
            indexType = IndexType.getIndexType(prop.getProperty("indexType"));
            numPartitions = Integer.parseInt(prop.getProperty("numPartitions"));
            loopTimes = 5;
        }
        catch (IOException ex) {
            ex.printStackTrace();
        }
        finally {
            if (input != null) {
                try {
                    input.close();
                }
                catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        queryPoint = fact.createPoint(new Coordinate(-84.01, 34.01));
        topK = 100;
    }

    /**
     * Teardown.
     */
    @AfterClass
    public static void teardown()
    {
        sc.stop();
    }

    /**
     * Test spatial knn query.
     *
     * @throws Exception the exception
     */
    @Test
    public void testSpatialKnnQuery()
            throws Exception
    {
        RectangleRDD rectangleRDD = new RectangleRDD(sc, InputLocation, offset, splitter, true);

        for (int i = 0; i < loopTimes; i++) {
            List<Polygon> result = KNNQuery.SpatialKnnQuery(rectangleRDD, queryPoint, topK, false);
            assert result.size() > -1;
            assert result.get(0).getUserData().toString() != null;
            //System.out.println(result.get(0).getUserData().toString());
        }
    }

    /**
     * Test spatial knn query using index.
     *
     * @throws Exception the exception
     */
    @Test
    public void testSpatialKnnQueryUsingIndex()
            throws Exception
    {
        RectangleRDD rectangleRDD = new RectangleRDD(sc, InputLocation, offset, splitter, true);
        rectangleRDD.buildIndex(IndexType.RTREE, false);
        for (int i = 0; i < loopTimes; i++) {
            List<Polygon> result = KNNQuery.SpatialKnnQuery(rectangleRDD, queryPoint, topK, true);
            assert result.size() > -1;
            assert result.get(0).getUserData().toString() != null;
            //System.out.println(result.get(0).getUserData().toString());
        }
    }

    /**
     * Test spatial KNN correctness.
     *
     * @throws Exception the exception
     */
    @Test
    public void testSpatialKNNCorrectness()
            throws Exception
    {
        RectangleRDD rectangleRDD = new RectangleRDD(sc, InputLocation, offset, splitter, true);
        List<Polygon> resultNoIndex = KNNQuery.SpatialKnnQuery(rectangleRDD, queryPoint, topK, false);
        rectangleRDD.buildIndex(IndexType.RTREE, false);
        List<Polygon> resultWithIndex = KNNQuery.SpatialKnnQuery(rectangleRDD, queryPoint, topK, true);

        List<Polygon> resultNoIndexModifiable = new ArrayList<Polygon>(resultNoIndex);
        List<Polygon> resultWithIndexModifiable = new ArrayList<Polygon>(resultWithIndex);

        GeometryDistanceComparator rectangleDistanceComparator = new GeometryDistanceComparator(this.queryPoint, true);
        Collections.sort(resultNoIndexModifiable, rectangleDistanceComparator);
        Collections.sort(resultWithIndexModifiable, rectangleDistanceComparator);
        int difference = 0;
        for (int i = 0; i < topK; i++) {
            if (rectangleDistanceComparator.compare(resultNoIndexModifiable.get(i), resultWithIndexModifiable.get(i)) != 0) {
                difference++;
            }
        }
        assert difference == 0;
    }
}


text:
import { createAction } from 'redux-actions'

export const FETCH_EXAMPLE  = 'FETCH_EXAMPLE'
export const DELETE_EXAMPLE = 'DELETE_EXAMPLE'

/**
 * @type {Function}
 * @desc Fetch the specified example.
 *
 * @param  {String} example - The example to fetch.
 * @return {Promise<String, Error>}
 */
export const fetchExample = createAction(FETCH_EXAMPLE,
  example => new Promise(resolve =>
    setTimeout(() => resolve({ name: example }), 2000)))

/**
 * @type {Function}
 * @desc Delete the specified example.
 *
 * @param  {String} example - The example to fetch.
 * @return {Promise<, Error>}
 */
export const deleteExample = createAction(DELETE_EXAMPLE,
  example => new Promise(resolve => setTimeout(() => resolve(), 2000)))


text:
graylog2-docker
===============

This docker image is a ready-to-run graylog2 server instance.

Configuration
--------------
For now there is only 1 configuration option, the admin password, you can set it using the environment variables with docker using `-e "GRAYLOG2_PASSWORD=mypassword"`


text:
#include <aws/codeartifact/model/AllowUpstream.h>
#include <aws/core/utils/HashingUtils.h>
#include <aws/core/Globals.h>
#include <aws/core/utils/EnumParseOverflowContainer.h>

using namespace Aws::Utils;

namespace Aws
{
  namespace CodeArtifact
  {
    namespace Model
    {
      namespace AllowUpstreamMapper
      {

        static const int ALLOW_HASH = HashingUtils::HashString("ALLOW");
        static const int BLOCK_HASH = HashingUtils::HashString("BLOCK");

        AllowUpstream GetAllowUpstreamForName(const Aws::String& name)
        {
          int hashCode = HashingUtils::HashString(name.c_str());
          if (hashCode == ALLOW_HASH)
          {
            return AllowUpstream::ALLOW;
          }
          else if (hashCode == BLOCK_HASH)
          {
            return AllowUpstream::BLOCK;
          }
          EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
          if(overflowContainer)
          {
            overflowContainer->StoreOverflow(hashCode, name);
            return static_cast<AllowUpstream>(hashCode);
          }

          return AllowUpstream::NOT_SET;
        }

        Aws::String GetNameForAllowUpstream(AllowUpstream enumValue)
        {
          switch(enumValue)
          {
          case AllowUpstream::ALLOW:
            return "ALLOW";
          case AllowUpstream::BLOCK:
            return "BLOCK";
          default:
            EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
            if(overflowContainer)
            {
              return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue));
            }

            return {};
          }
        }

      } // namespace AllowUpstreamMapper
    } // namespace Model
  } // namespace CodeArtifact
} // namespace Aws


text:
<?xml version="1.0" encoding="UTF-8"?>
<sem:triples uri="http://www.lds.org/vrl/specific-people/latter-day-figures/bentley-vivian-woodmansee-1901-1967" xmlns:sem="http://marklogic.com/semantics">
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/specific-people/latter-day-figures/bentley-vivian-woodmansee-1901-1967</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#prefLabel</sem:predicate>
    <sem:object datatype="xsd:string" xml:lang="eng">Bentley, Vivian Woodmansee 1901-1967</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/specific-people/latter-day-figures/bentley-vivian-woodmansee-1901-1967</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#inScheme</sem:predicate>
    <sem:object datatype="sem:iri">http://www.lds.org/concept-scheme/vrl</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/specific-people/latter-day-figures/bentley-vivian-woodmansee-1901-1967</sem:subject>
    <sem:predicate>http://www.lds.org/core#entityType</sem:predicate>
    <sem:object datatype="sem:iri">http://www.schema.org/Place</sem:object>
  </sem:triple>
</sem:triples>


text:
class CInventoryOwner;
class CPda;

using PDA_LIST = xr_vector<CPda*>;

class CPda : public CInventoryItemObject, public Feel::Touch {
    typedef CInventoryItemObject inherited;

public:
    CPda();
    virtual ~CPda();

    virtual BOOL net_Spawn(CSE_Abstract* DC);
    virtual void Load(LPCSTR section);
    virtual void net_Destroy();

    virtual void OnH_A_Chield();
    virtual void OnH_B_Independent(bool just_before_destroy);

    virtual void shedule_Update(u32 dt);

    virtual void feel_touch_new(CObject* O);
    virtual void feel_touch_delete(CObject* O);
    virtual BOOL feel_touch_contact(CObject* O);

    virtual u16 GetOriginalOwnerID() { return m_idOriginalOwner; }
    virtual CInventoryOwner* GetOriginalOwner();
    virtual CObject* GetOwnerObject();

    void TurnOn() { m_bTurnedOff = false; }
    void TurnOff() { m_bTurnedOff = true; }

    bool IsActive() { return IsOn(); }
    bool IsOn() { return !m_bTurnedOff; }
    bool IsOff() { return m_bTurnedOff; }

    void ActivePDAContacts(xr_vector<CPda*>& res);
    CPda* GetPdaFromOwner(CObject* owner);
    u32 ActiveContactsNum() { return m_active_contacts.size(); }
    void PlayScriptFunction();
    bool CanPlayScriptFunction() {
        if (!xr_strcmp(m_functor_str, ""))
            return false;
        return true;
    };

    virtual void save(NET_Packet& output_packet);
    virtual void load(IReader& input_packet);

    //*	virtual LPCSTR							Name
    //();

protected:
    void UpdateActiveContacts();

    xr_vector<CObject*> m_active_contacts;
    float m_fRadius;

    u16 m_idOriginalOwner;
    shared_str m_SpecificChracterOwner;
    xr_string m_sFullName;

    bool m_bTurnedOff;
    shared_str m_functor_str;
};


text:
#include "PimInternal.h"

#include "PimVec2.h"
#include "PimGameNode.h"
#include "PimAssert.h"
#include "PimInput.h"
#include "PimGameControl.h"
#include "PimLayer.h"
#include "PimPolygonShape.h"
#include "PimScene.h"
#include "PimLightingSystem.h"
#include "PimAction.h"

#include <iostream>

namespace Pim {
	/*
	=====================
	GameNode::GameNode
	=====================
	*/
	GameNode::GameNode() {
		parent					= NULL;
		rotation				= 0.f;
		zOrder					= 0;
		dirtyZOrder				= false;
		willDelete				= false;
		shadowShape				= NULL;
		dbgShadowShape			= false;
		userData				= NULL;
	}

	/*
	=====================
	GameNode::~GameNode
	=====================
	*/
	GameNode::~GameNode() {
		if (!willDelete) {
			PrepareDeletion();
		}

		RemoveAllChildren();

		UnlistenFrame();
		UnlistenInput();
		UnlistenController();
	}

	/*
	=====================
	GameNode::PrepareDeletion
	=====================
	*/
	void GameNode::PrepareDeletion() {
		if (GetParentLayer()) {
			GetParentLayer()->RemoveLight(this);
			GetParentLayer()->RemoveShadowCaster(this);
		}

		if (shadowShape) {
			delete shadowShape;
		}

		RemoveAllChildren();

		UnlistenInput();
		UnlistenController();

		parent = NULL;
		willDelete = true;
	}

	/*
	=====================
	GameNode::AddChild
	=====================
	*/
	void GameNode::AddChild(GameNode *ch) {
		PimAssert(!ch->GetParent(), "Node already has a parent");

		Layer *layer = dynamic_cast<Layer*>(ch);
		if (layer) {
			layer->LoadResources();
		}

		ch->parent = this;
		children.push_back(ch);

		ch->OnParentChange(this);

		dirtyZOrder = true;
	}

	/*
	=====================
	GameNode::RemoveChild
	=====================
	*/
	void GameNode::RemoveChild(GameNode *ch, bool cleanup) {
		for (unsigned int i=0; i<children.size(); i++) {
			if (children[i] == ch) {
				children.erase(children.begin() + i);

				if (cleanup) {
					GameControl::GetSingleton()->AddNodeToDelete(ch);
				}

				ch->parent = NULL;
				ch->OnParentChange(NULL);
				OnChildRemove(ch);
			}
		}
	}

	/*
	=====================
	GameNode::RemoveAllChildren
	=====================
	*/
	void GameNode::RemoveAllChildren(bool cleanup) {
		// Delete all if required
		for (unsigned i=0; i<children.size(); i++) {
			if (cleanup) {
				GameControl::GetSingleton()->AddNodeToDelete(children[i]);
			}

			children[i]->parent = NULL;
			children[i]->OnParentChange(NULL);
			OnChildRemove(children[i]);
		}

		// THEN clear the array
		children.clear();
	}

	/*
	=====================
	GameNode::RemoveFromParent
	=====================
	*/
	void GameNode::RemoveFromParent(bool cleanup) {
		if (parent) {
			parent->RemoveChild(this, cleanup);
		} else {
			PimWarning("Cannot remove orphan from parent.", "Logical error");
		}
	}

	/*
	=====================
	GameNode::ChildCount

	Sums up the child count and ChildCount() of all children.
	=====================
	*/
	int GameNode::ChildCount() {
		int count = (int)children.size();

		for (unsigned i=0; i<children.size(); i++) {
			count += children[i]->ChildCount();
		}

		return count;
	}

	/*
	=====================
	GameNode::GetParent
	=====================
	*/
	GameNode* GameNode::GetParent() const {
		return parent;
	}

	/*
	=====================
	GameNode::GetParentScene
	=====================
	*/
	Scene* GameNode::GetParentScene() const {
		if (parent) {
			return parent->GetParentScene();
		}
		return NULL;
	}

	/*
	=====================
	GameNode::GetParentLayer
	=====================
	*/
	Layer* GameNode::GetParentLayer() {
		if (parent) {
			return parent->GetParentLayer();
		}
		return NULL;
	}

	/*
	=====================
	GameNode::ListenInput
	=====================
	*/
	void GameNode::ListenInput() {
		GameControl::GetSingleton()->AddKeyListener(this);
		GameControl::GetSingleton()->AddMouseListener(this);
	}

	/*
	=====================
	GameNode::UnlistenInput
	=====================
	*/
	void GameNode::UnlistenInput() {
		GameControl::GetSingleton()->RemoveKeyListener(this);
		GameControl::GetSingleton()->RemoveMouseListener(this);
	}

	/*
	=====================
	GameNode::ListenKeys
	=====================
	*/
	void GameNode::ListenKeys() {
		GameControl::GetSingleton()->AddKeyListener(this);
	}

	/*
	=====================
	GameNode::UnlistenKeys
	=====================
	*/
	void GameNode::UnlistenKeys() {
		GameControl::GetSingleton()->RemoveKeyListener(this);
	}

	/*
	=====================
	GameNode::ListenMouse
	=====================
	*/
	void GameNode::ListenMouse() {
		GameControl::GetSingleton()->AddMouseListener(this);
	}

	/*
	=====================
	GameNode::UnlistenMouse
	=====================
	*/
	void GameNode::UnlistenMouse() {
		GameControl::GetSingleton()->RemoveMouseListener(this);
	}

	/*
	=====================
	GameNode::ListenController
	=====================
	*/
	void GameNode::ListenController() {
		GameControl::GetSingleton()->AddControlListener(this);
	}

	/*
	=====================
	GameNode::UnlistenController
	=====================
	*/
	void GameNode::UnlistenController() {
		GameControl::GetSingleton()->RemoveControlListener(this);
	}

	/*
	=====================
	GameNode::ListenFrame
	=====================
	*/
	void GameNode::ListenFrame() {
		GameControl::GetSingleton()->AddFrameListener(this);
	}

	/*
	=====================
	GameNode::UnlistenFrame
	=====================
	*/
	void GameNode::UnlistenFrame() {
		GameControl::GetSingleton()->RemoveFrameListener(this);
	}

	/*
	=====================
	GameNode::GetWorldPosition
	=====================
	*/
	Vec2 GameNode::GetWorldPosition() const {
		if (parent) {
			return position.RotateAroundPoint(Vec2(0.f, 0.f), parent->GetWorldRotation()) +
					parent->GetWorldPosition();
		}
		return position;
	}

	/*
	=====================
	GameNode::GetLayerPosition
	=====================
	*/
	Vec2 GameNode::GetLayerPosition() const {
		if (parent) {
			return position.RotateAroundPoint(Vec2(0.f, 0.f), parent->GetLayerRotation()) +
					parent->GetLayerPosition();
		}
		return position;
	}

	/*
	=====================
	GameNode::GetWorldRotation
	=====================
	*/
	float GameNode::GetWorldRotation() const {
		if (parent) {
			return rotation + parent->GetWorldRotation();
		}
		return rotation;
	}

	/*
	==================
	GameNode::GetLayerRotation
	==================
	*/
	float GameNode::GetLayerRotation() const {
		if (parent) {
			return rotation + parent->GetLayerRotation();
		}
		return rotation;
	}

	/*
	=====================
	GameNode::Draw
	=====================
	*/
	void GameNode::Draw() {
		glPushMatrix();
		Vec2 fac = GameControl::GetSingleton()->GetCoordinateFactor();

		glTranslatef(position.x / fac.x, position.y / fac.y, 0.f);
		glRotatef(rotation, 0.f, 0.f, 1.f);

		if (shadowShape && dbgShadowShape) {
			glPushMatrix();

			fac = GameControl::GetSingleton()->GetWindowScale();
			glScalef(fac.x, fac.y, 1.f);

			shadowShape->DebugDraw();

			glPopMatrix();
		}

		OrderChildren();

		for (unsigned int i=0; i<children.size(); i++) {
			children[i]->Draw();
		}

		glPopMatrix();
	}

	/*
	=====================
	GameNode::BatchDraw
	=====================
	*/
	void GameNode::BatchDraw() {
		glPushMatrix();
		Vec2 fac = GameControl::GetSingleton()->GetCoordinateFactor();

		glTranslatef(position.x / fac.x, position.y / fac.y, 0.f);
		glRotatef(rotation, 0.f, 0.f, 1.f);

		if (shadowShape && dbgShadowShape) {
			glPushMatrix();

			fac = GameControl::GetSingleton()->GetWindowScale();
			glScalef(fac.x, fac.y, 1.f);

			shadowShape->DebugDraw();

			glPopMatrix();
		}

		OrderChildren();

		for (unsigned int i=0; i<children.size(); i++) {
			// This is the only difference from GameNode::draw(): batchDraw is called
			// on the node's children.
			children[i]->BatchDraw();
		}

		glPopMatrix();
	}

	/*
	=====================
	GameNode::SetZOrder
	=====================
	*/
	void GameNode::SetZOrder(const int z) {
		if (parent) {
			parent->dirtyZOrder = true;
		}

		zOrder = z;
	}

	/*
	=====================
	GameNode::GetZOrder
	=====================
	*/
	int GameNode::GetZOrder() const {
		return zOrder;
	}

	/*
	=====================
	GameNode::OrderChildren
	=====================
	*/
	void GameNode::OrderChildren() {
		if (!dirtyZOrder || children.size() <= 1) {
			return;
		}

		// Insertion sorting - the children should be somewhat sorted already.
		for (int j=1; j<children.size(); j++) {
			GameNode *key = children[j];
			int i = j - 1;

			while (i >= 0 && children[i]->zOrder > key->zOrder) {
				children[i+1] = children[i];
				i--;
			}
			children[i+1] = key;
		}

		dirtyZOrder = false;
	}

	/*
	=====================
	GameNode::RunAction
	=====================
	*/
	void GameNode::RunAction(Action *a) {
		AddChild(a);
		a->Activate();
	}

	/*
	=====================
	GameNode::RunActionQueue
	=====================
	*/
	void GameNode::RunActionQueue(ActionQueue *aq) {
		AddChild(aq);
		aq->Activate();
	}

	/*
	==================
	GameNode::RemoveAllActions
	==================
	*/
	void GameNode::RemoveAllActions() {
		for (int i=0; i<children.size(); i++) {
			BaseAction *act = NULL;

			act = dynamic_cast<BaseAction*>(children[i]);
			if (act) {
				RemoveChild(act);
				i--;
			}
		}
	}

	/*
	=====================
	GameNode::SetShadowShape
	=====================
	*/
	void GameNode::SetShadowShape(Vec2 vertices[], const int vertexCount) {
		if (shadowShape) {
			delete shadowShape;
		}

		shadowShape = new PolygonShape(vertices, vertexCount, this);
	}

	/*
	=====================
	GameNode::SetShadowShapeDebugDraw
	=====================
	*/
	void GameNode::SetShadowShapeDebugDraw(const bool flag) {
		dbgShadowShape = flag;
	}

	/*
	=====================
	GameNode::GetShadowShape
	=====================
	*/
	PolygonShape* GameNode::GetShadowShape() const {
		return shadowShape;
	}

	/*
	==================
	GameNode::ReloadTextures
	==================
	*/
	void GameNode::ReloadTextures() {
		for (unsigned i=0; i<children.size(); i++) {
			children[i]->ReloadTextures();
		}
	}
}


text:
const Inert = require('inert');

module.exports = function(server) {
  server.register({ register: Inert })
    .then(function(err) {
      console.log(err);
    })
    .catch(function(err) {
      console.log(err);
    });
}


text:
<?php
/**
 * Created by PhpStorm.
 * User: cedric.gallard
 * Date: 09/04/14
 * Time: 12:31
 */

namespace Users;

use Forms\PostedData;
use Logs\Alert;
use Components\Help;
use Get;
use Sanitize;

/**
 * Classe de gestion des ACL
 *
 * Permet de définir des droits sur des composants du site pour des utilisateurs.
 * l'ID d'utilisateur 0 signifie 'tout le monde' et sert à définir des ACL par défaut pour un composant.
 *
 * Pour gérer les ACL de tout composant, on essaie de faire un tableau associatif de la forme $ACL[$component][$id][$user][$type] = $value
 * Pour les ACL d'un utilisateur, on aura ainsi $userACL[$component][$id][$type] = $value
 * Pour les ACL d'un module, on aura $moduleACL[$user][$type] = $value
 *
 * @package Users
 */
class ACL {

	/**
	 * Types d'autorisations
	 * @var array
	 */
	protected static $typesLabels = array(
		'access' => 'Permet d\'accéder à la ressource',
		'modify' => 'Permet la modification d\'éléments dans la ressource',
	  'admin'  => 'Permet d\'administrer la ressource'
	);

	/**
	 * Retourne les autorisations d'un utilisateur
	 *
	 * @param int $user ID d'un utilisateur
	 *
	 * @return bool|array
	 */
	public static function getUserACL($user){
		global $db;
		if (!is_int($user)){
			new Alert('debug', 'ACL::getUserACL() : $user n\'est pas un nombre entier ! '. Get::varDump($user));
			return false;
		}
		$dbACL = $db->get('ACL', '*', array('user'=>$user));
		if ($dbACL === false) return false;
		$retACL = array();
		foreach ($dbACL as $acl){
			$acl->value = ($acl->value == 1) ? true : false;
			$retACL[$acl->component][$acl->id][$acl->type] = $acl->value;
		}
		$dbACL = $db->get('ACL', '*', array('user'=>10000));
		if ($dbACL === false) return false;
		foreach ($dbACL as $acl){
			$acl->value = ($acl->value == 1) ? true : false;
			if (!isset($retACL[$acl->component][$acl->id][$acl->type])) $retACL[$acl->component][$acl->id][$acl->type] = $acl->value;
		}
		return $retACL;
	}

	/**
	 * Détermine si l'utilisateur a le droit d'administrer un composant
	 * @param string $component Composant (module, site,...)
	 * @param int $componentId Id du composant
	 * @param int $userId Id de l'utilisateur (utilisateur courant si vide)
	 *
	 * @return bool
	 */
	public static function canAdmin($component, $componentId, $userId = null){
		if (self::can('admin', 0, $userId, 'admin')) return true;
		return self::can($component, $componentId, $userId, 'admin');
	}

	/**
	 * Détermine si l'utilisateur a le droit de modifier un composant
	 * @param string $component Composant (module, site,...)
	 * @param int $componentId Id du composant
	 * @param int $userId Id de l'utilisateur (utilisateur courant si vide)
	 *
	 * @return bool
	 */
	public static function canModify($component, $componentId, $userId = null){
		if (self::can('admin', 0, $userId, 'admin')) return true;
		return self::can($component, $componentId, $userId, 'modify');
	}

	/**
	 * Détermine si l'utilisateur a le droit d'accéder à un composant
	 * @param string $component Composant (module, site,...)
	 * @param int $componentId Id du composant
	 * @param int $userId Id de l'utilisateur (utilisateur courant si vide)
	 *
	 * @return bool
	 */
	public static function canAccess($component, $componentId, $userId = null){
		if (self::can('admin', 0, $userId, 'admin')) return true;
		return self::can($component, $componentId, $userId, 'access');
	}

	/**
	 * Détermine si l'utilisateur a le droit d'effectuer une action $type sur un composant
	 * @param string $component Composant (module, site,...)
	 * @param int $componentId Id du composant
	 * @param int $userId Id de l'utilisateur (utilisateur courant si vide)
	 * @param string $type Type d'ACL (admin, access)
	 *
	 * @return bool
	 */
	public static function can($component, $componentId, $userId = null, $type){
		global $db, $cUser;
		if (!in_array($type, array_keys(self::$typesLabels))){
			New Alert('debug', 'ACL::can() : $type='.$type.' ne fait pas partie des types autorisés !');
			return false;
		}
		if (empty($userId) or $userId == $cUser->getId()){
			// Il va de soi qu'on refuse les utilisateurs non connectés si l'authentification est obligatoire.
			if (!$cUser->isLoggedIn() and \Settings::AUTH_MANDATORY) return false;
			// On demande donc une autorisation pour l'utilisateur courant. Comme on a déjà la liste de ses autorisations, on va la chercher dans son objet
			$userACL = $cUser->getACL();
			return (isset($userACL[$component][$componentId][$type])) ? $userACL[$component][$componentId][$type] : false;
		}else{
			$where = array(
				'component' => $component,
			  'id'        => $componentId,
			  'user'      => $userId,
			  'type'      => $type
			);
			$ret = $db->getVal('ACL', 'value', $where);
			switch ($ret){
				case null:
					// On regarde s'il existe une valeur pour tous les utilisateurs (10000 = tout le monde)
					$where['user'] = 10000;
					$ret = $db->getVal('ACL', 'value', $where);
					if (!is_null($ret) or $ret) return true;
					break;
				case 0:
				case false:
					return false;
				case 1:
				case true:
					return true;
			}
		}
		return false;
	}

	/**
	 * Définit une règle $type sur un composant
	 *
	 * @param string $component Composant (module, site,...)
	 * @param int    $componentId Id du composant
	 * @param int    $userId Id de l'utilisateur
	 * @param string $type Type d'ACL (admin, access)
	 * @param bool   $value Valeur de l'ACL (true : permis, false : refusé)
	 *
	 * @return bool
	 */
	public static function set($component, $componentId, $userId, $type, $value){
		global $db;
		if (!in_array($type, array_keys(self::$typesLabels))){
			New Alert('debug', 'ACL::set() : $type='.$type.' ne fait pas partie des typesLabels autorisés !');
			return false;
		}
		$value = Sanitize::SanitizeForDb($value);
		$types = array_flip(array_keys(self::$typesLabels));
		$ret = false;
		$sql = '';
		if ($value == 1){
			// On inscrit aussi les permissions inférieures si c'est une autorisation
			for ($i = 0; $i <= $types[$type]; $i++){
				$typeI = array_search($i, $types);
				$sql = 'INSERT INTO `ACL` (`component`, `id`, `user`, `type`, `value`) VALUES ("'.$component.'", '.$componentId.', '.$userId.', "'.$typeI.'", '.$value.') ON DUPLICATE KEY UPDATE value = '.$value;
				$ret = $db->query($sql);
				if ($ret === false){
					new Alert('error', 'Impossible de sauvegarder les permissions !
'.$sql);
					return false;
				}
			}
		}else{
			// On inscrit aussi les permissions supérieures si c'est un refus
			for ($i = 2; $i > $types[$type]; $i--){
				$typeI = array_search($i, $types);
				$sql = 'INSERT INTO `ACL` (`component`, `id`, `user`, `type`, `value`) VALUES ("'.$component.'", '.$componentId.', '.$userId.', "'.$typeI.'", '.$value.') ON DUPLICATE KEY UPDATE value = '.$value;
				$ret = $db->query($sql);
				if ($ret === false){
					new Alert('error', 'Impossible de sauvegarder les permissions !
'.$sql);
					return false;
				}
			}
		}
		return true;
	}

	/**
	 * Définit des règles $type sur des composants
	 *
	 * Cette fonction fait la même chose que ACL::set(), mais avec un tableau d'ACL.
	 * @param array $ACLArr Tableau d'ACL de la forme $array[(string)$component][(int)$componentId][(int)$user][(string)$type] = (bool)$value
	 *
	 * @return bool
	 */
	public static function setArray(array $ACLArr){
		global $db;
		$types = array_flip(array_keys(self::$typesLabels));
		$setACLArray = array();
		foreach ($ACLArr as $component => $ACLComponent){
			foreach ($ACLComponent as $componentId => $ACLCompId){
				foreach ($ACLCompId as $user => $ACLUser){
					/*
					 * Si on donne l'autorisation d'admin sur une ressource, il faut également autoriser les accès plus restrictifs.
					 * Ex : Si on donne le droit d'admin sur une ressource, il faut également accorder les droits access et modif.
					 */
					$max = 0;
					$valueMax = 0;
					foreach ($ACLUser as $type => $value){
						if ($types[$type] >= $max and $value === true) {
							$valueMax = Sanitize::SanitizeForDb($value);
							$max = $types[$type];
						}
					}
					foreach ($ACLUser as $type => $value){
						$setACLArray[] = '("'.$component.'", '.$componentId.', '.$user.', "'.$type.'", '.(($types[$type] <= $max) ? $valueMax : Sanitize::SanitizeForDb($value)).')';
					}
				}
			}
		}
		$ret = $db->query('INSERT INTO `ACL` (`component`, `id`, `user`, `type`, `value`) VALUES '.implode(', ', $setACLArray).' ON DUPLICATE KEY UPDATE `value` = VALUES(`value`)');
		return ( $ret === false) ? false : true;
	}

	/**
	 * Récupère l'envoi d'un formulaire pour sauvegarder des ACL
	 *
	 * @param string $action Action à traiter.
	 *  - `restoreDefault` : restaure les droits d'accès par défaut pour un utilisateur
	 *
	 * @return bool
	 */
	public static function requestACLSave($action = null){
		switch ($action){
			case 'restoreDefault':
				$ret = PostedData::checkToken('adminACL', $_REQUEST['token']);
				if (!$ret){
					new Alert('error', 'Erreur de traitement : Ce formulaire a déjà été envoyé, ou bien vous n\'êtes pas la personne qui a initié l\'envoi !');
					return false;
				}
				if (!self::canAdmin('admin', 0)){
					new Alert('error', 'Vous n\'avez pas l\'autorisation de faire ceci !');
					return false;
				}
				$user = (int)$_REQUEST['user'];
				if (!UsersManagement::getDBUsers($user)){
					new Alert('error', 'Cet utilisateur n\'existe pas !');
					return false;
				}
				return self::delete(null, null, $user);
				break;
			case 'updateACL':
			default:
				$ret = PostedData::checkToken('adminACL', $_REQUEST['token']);
				if (!$ret){
					new Alert('error', 'Erreur de traitement : Ce formulaire a déjà été envoyé, ou bien vous n\'êtes pas la personne qui a initié l\'envoi !');
					return false;
				}
				$ACLArr = array();
				foreach ($_REQUEST as $key => $value){
					if (substr($key, 0, 4) == 'ACL_'){
						list($dummy, $component, $componentId, $user, $type, $field) = explode('_', $key);
						if (!self::canAdmin($component, $componentId)){
							new Alert('error', 'Vous n\'avez pas l\'autorisation de faire ceci !');
							return false;
						}
						if (!in_array($type, array_keys(self::$typesLabels))){
							New Alert('debug', 'ACL::requestACLSave() : $type='.$type.' ne fait pas partie des typesLabels autorisés !');
							return false;
						}
						$ACLArr[$component][$componentId][$user][$type][$field] = ($value == 1) ? true : false;
					}
				}
				foreach ($ACLArr as $component => $ACLArrComponent) {
					foreach ($ACLArrComponent as $componentId => $ACLArrComponentId) {
						foreach ($ACLArrComponentId as $user => $ACLUser) {
							foreach ($ACLUser as $type => $ACLType) {
								$ACLArr[$component][$componentId][$user][$type] = (isset($ACLType['checkbox'])) ? $ACLType['checkbox'] : $ACLType['hidden'];
							}
						}
					}
				}
				if ($ret = self::setArray($ACLArr)){
					new Alert('success', 'Les autorisations ont été sauvegardées !');
				}else{
					new Alert('error', 'Les autorisations n\'ont pas été sauvegardées !');
				}
				return $ret;
		}
	}

	/**
	 * Supprime des ACL
	 *
	 * Si $component est vide, alors on supprime tout (si $type est vide) ou une partie (si $type est renseigné) des ACL d'un utilisateur
	 * Si $userId est vide, on réinitialise les ACL pour un composant (ou une partie si $type est renseigné)
	 *
	 * @param string $component Composant (module, site,...)
	 * @param int $componentId Id du composant
	 * @param int $userId Id de l'utilisateur
	 * @param string $type Type d'ACL (admin, access)
	 *
	 * @return bool
	 */
	public static function delete($component = null, $componentId = null, $userId = null, $type = null){
		global $db;
		$where = array();

		if (!is_null($component)){
			if (is_null($componentId)) {
				new Alert('debug', 'ACL::delete() : $componentId est vide alors que $component est renseigné !');
				return false;
			}
			$where['component'] = $component;
			$where['id'] = $componentId;
		}
		if (!is_null($userId)){
			$where['user'] = $userId;
		}
		if (!is_null($type)){
			if (!in_array($type, array_keys(self::$typesLabels))){
				New Alert('debug', 'ACL::delete() : $type='.$type.' ne fait pas partie des typesLabels autorisés !');
				return false;
			}
			$where['type'] = $type;
		}
		if (empty($where) or (isset($where['type']) and count($where) == 1)){
			// Si aucun paramètre (ou seulement le type) n'est renseigné, on annule tout
			new Alert('debug', 'ACL::delete() : Aucun paramètre n\'est renseigné !');
			return false;
		}
		$ret = $db->delete('ACL', $where);
		if ($ret === false){
			new Alert('error', 'Impossible de supprimer les autorisations !');
			return false;
		}
		new Alert('success', 'Les autorisations ont été correctement supprimées !');
		return true;
	}

	/**
	 * Affiche le formulaire de réglage de l'ensemble des autorisations d'un utilisateur
	 *
	 * @param int     $userId
	 */
	public static function adminUserACL($userId){
		global $db;
		$userName = '';
		if ($userId != 10000) {
			$userName = UsersManagement::getUserName($userId);
		}
		if ($userName === false){
			new Alert('error', 'Cet utilisateur n\'existe pas !');
			$userId = 10000;
		}
		$acls = $db->query('SELECT a.user as user, m.name as module, a.id as componentId, a.type as type, a.value as value FROM `modules` as m, `ACL` as a WHERE m.id = a.id AND `user` IN ('.$userId.', 10000) AND `component` = "module" ORDER BY `name`');
		$types = array_flip(array_keys(self::$typesLabels));
		$ACLArr = array();
		foreach ($acls as $acl){
			$ACLArr[$acl->module][$acl->user][$acl->type] = ($acl->value == 1) ? true : false;
			$ACLArr[$acl->module]['componentId'] = $acl->componentId;
		}
		$adminUsers = $db->query('SELECT user FROM `ACL` WHERE `component` = "admin" and `type` = "admin" AND `value` = 1 ORDER BY `user`');
		$admins = array();
		foreach ($adminUsers as $adminUser){
			$admins[] = $adminUser->user;
		}
		?>

<?php echo ($userId == 10000) ? 'Droits par défaut' :'Droits de '.$userName; ?>

				<?php
				if (in_array($userId, $admins)){
					?>
Cet utilisateur est administrateur, il a automatiquement tous les droits sur tous les modules.
<?php
				}
				if ($userId == 10000){
					?>
Vous pouvez ici modifier les droits par défaut pour tous les modules.
<?php
				}else{
					?>

						Si vous modifiez un droit d'accès ici, cela enregistrera les droits d'accès de tous les modules. L'utilisateur n'héritera plus des droits d'accès par défaut.

						Vous pouvez supprimer tous les droits d'accès de l'utilisateur en cliquant sur le bouton Droits par défaut.

				<?php
				}
				?>
				<form id="adminACL" class="" method="post" role="form" action="<?php echo \Front::getModuleUrl().'Admin&page=UserACL'; ?>">

								Module
								<?php
								foreach (self::$typesLabels as $type => $label){
									?>
									<?php echo $type; ?> <?php Help::iconHelp($label); ?>
								<?php
								}
								?>
								Remarques

						<?php
						foreach ($ACLArr as $module=>$acl){
							$component = 'module';
							$componentId = $acl['componentId'];
							$sanitizedModule = Sanitize::sanitizeFilename($module);
							?>
							<tr id="ACL_<?php echo $sanitizedModule; ?>">
								<?php echo $module; ?>
								<?php
								$inherited = true;
								$disabled = false;
								foreach(self::$typesLabels as $type => $label){
									$checked = false;
									if(in_array($userId, $admins)){
										$checked = true;
										$disabled = true;
									}elseif (isset($acl[$userId][$type])){
										if ($acl[$userId][$type]) {
											$checked = true;
										}
										$inherited = false;
									}elseif(isset($acl[10000][$type]) and $acl[10000][$type]){
										$checked = true;
									}
									?>

										<input type="checkbox" class="form-control checkbox-ACL" id="ACL_<?php echo $sanitizedModule.'_'.$type; ?>_checkbox" name="ACL_<?php echo $component.'_'.$componentId.'_'.$userId.'_'.$type; ?>_checkbox" data-type-value="<?php echo $types[$type]; ?>" data-tr-id="#ACL_<?php echo $sanitizedModule; ?>" value="1" <?php if ($checked) echo 'checked'; ?> <?php if ($disabled) echo 'disabled'; ?>>
										<input type="hidden" id="ACL_<?php echo $sanitizedModule.'_'.$type; ?>_hidden" name="ACL_<?php echo  $component.'_'.$componentId.'_'.$userId.'_'.$type;  ?>_hidden" value="0">

								<?php
								}
								?>

										<?php
										if (in_array($userId, $admins)){
											echo 'Administrateur global';
										}elseif ($inherited) {
											echo 'Hérité des ACL par défaut';
										}
										?>

						<?php
						}
						?>

					<input type="hidden" name="user" value="<?php echo $userId; ?>">
					<input type="hidden" name="token" value="<?php echo PostedData::setToken('adminACL'); ?>">
					<input type="hidden" name="formName" value="adminACL">
					<button class="btn btn-primary" type="submit" name="action" value="saveACL" <?php if(in_array($userId, $admins)) echo 'disabled'; ?>>Sauvegarder</button>
					<button class="btn btn-default" type="submit" name="action" value="restoreDefaultACL" <?php if(in_array($userId, $admins) or $userId == 10000) echo 'disabled'; ?>>Droits par défaut</button>
				</form>

		<?php
	}

	/**
	 * Affiche le formulaire de réglage des ACL
	 *
	 * @param string $component   Type de composant (module, admin, etc.)
	 * @param string $componentId ID du composant
	 * @param string $title       Nom du composant administré (facultatif)
	 *
	 * @return bool
	 */
	public static function adminACL($component, $componentId, $title = null){
		global $db;
		if (!self::canAdmin($component, $componentId)){
			new Alert('error', 'Vous n\'avez pas l\'autorisation de faire ceci !');
			return false;
		}
		$users = UsersManagement::getDBUsers();
		$acls = $db->query('SELECT user, type, value FROM `ACL` WHERE `component` = "'.$component.'" AND `id` = '.$componentId.' ORDER BY `user`');
		$adminUsers = $db->query('SELECT user FROM `ACL` WHERE `component` = "admin" and `type` = "admin" AND `value` = 1 ORDER BY `user`');
		$admins = array();
		foreach ($adminUsers as $adminUser){
			$admins[] = $adminUser->user;
		}
		if ($component != 'admin'){
			$types = array_flip(array_keys(self::$typesLabels));
			$typesLabels = self::$typesLabels;
		}else{
			$types = array('admin' => 2);
			$typesLabels = array('admin'  => 'Permet d\'administrer le site entier !');
		}
		$ACLArr = array();
		foreach ($acls as $acl){
			$ACLArr[$acl->user][$acl->type] = ($acl->value == 1) ? true : false;
			if ($acl->user == 10000){
				$ACLArr['default'][$acl->type] = ($acl->value == 1) ? true : false;
			}
		}
		?>

				<?php if (!is_null($title)) { ?>
Droits sur <?php echo $title; ?>
<?php } ?>
				<form id="adminACL" class="" method="post" role="form" action="<?php echo \Front::getBaseUrl().$_SERVER['REQUEST_URI']; ?>">

								Utilisateur
								<?php
								foreach ($typesLabels as $type => $label){
									?>
									<?php echo $type; ?> <?php Help::iconHelp($label); ?>
									<?php
								}
								?>
								Remarques

						<?php
						foreach ($users as $user){

							?>
							<tr id="ACL_<?php echo $component.'_'.$componentId.'_'.$user->id; ?>">
								<?php echo $user->name; ?>
								<?php
								$inherited = true;
								foreach($typesLabels as $type => $label){
									$checked = false;
									if (isset($ACLArr[$user->id][$type])){
										if ($ACLArr[$user->id][$type]) {
											$checked = true;
										}
										$inherited = false;
									}elseif(isset($ACLArr['default'][$type]) and $ACLArr['default'][$type]){
										$checked = true;
									}elseif(in_array($user->id, $admins)){
										$checked = true;
									}
									?>

										<input type="checkbox" class="form-control checkbox-ACL" id="ACL_<?php echo $component.'_'.$componentId.'_'.$user->id.'_'.$type; ?>_checkbox" name="ACL_<?php echo $component.'_'.$componentId.'_'.$user->id.'_'.$type; ?>_checkbox" data-type-value="<?php echo $types[$type]; ?>" data-tr-id="#ACL_<?php echo $component.'_'.$componentId.'_'.$user->id; ?>" value="1" <?php if ($checked) echo 'checked'; ?>>
										<input type="hidden" id="ACL_<?php echo $component.'_'.$componentId.'_'.$user->id.'_'.$type; ?>_hidden" name="ACL_<?php echo $component.'_'.$componentId.'_'.$user->id.'_'.$type; ?>_hidden" value="0">

								<?php
								}
								?>

									<?php
									if (in_array($user->id, $admins)){
										echo 'Administrateur global';
									}elseif ($inherited) {
										echo 'Hérité des ACL par défaut';
                  }
									?>

						<?php
						}
						?>
							<tr id="ACL_<?php echo $component.'_'.$componentId.'_10000'; ?>">
									Tout le monde
							<?php
							foreach($typesLabels as $type => $label){
								?>

									<input type="checkbox" class="form-control checkbox-ACL" id="ACL_<?php echo $component.'_'.$componentId.'_10000_'.$type; ?>_checkbox" name="ACL_<?php echo $component.'_'.$componentId.'_10000_'.$type; ?>_checkbox" data-type-value="<?php echo $types[$type]; ?>" data-tr-id="#ACL_<?php echo $component.'_'.$componentId.'_10000'; ?>" value="1" <?php if (isset($ACLArr['default'][$type]) and $ACLArr['default'][$type]) echo 'checked'; ?>>
									<input type="hidden" id="ACL_<?php echo $component.'_'.$componentId.'_10000_'.$type; ?>_hidden" name="ACL_<?php echo $component.'_'.$componentId.'_10000_'.$type; ?>_hidden" value="0">

							<?php
							}
							?>

					<button class="btn btn-primary" type="submit" name="action" value="saveACL">Sauvegarder</button>
					<input type="hidden" name="token" value="<?php echo PostedData::setToken('adminACL'); ?>">
					<input type="hidden" name="formName" value="adminACL">
				</form>

		<?php
	}
}


text:
namespace media {
namespace test {

namespace {

// Size of the large image to which the thumbnails will be rendered.
constexpr gfx::Size kThumbnailsPageSize(1600, 1200);
// Size of the individual thumbnails that will be rendered.
constexpr gfx::Size kThumbnailSize(160, 120);

// Default filename used to store the thumbnails image.
constexpr const base::FilePath::CharType* kThumbnailFilename =
    FILE_PATH_LITERAL("thumbnail.png");

// Vertex shader used to render thumbnails.
constexpr char kVertexShader[] =
    "varying vec2 interp_tc;\n"
    "attribute vec4 in_pos;\n"
    "attribute vec2 in_tc;\n"
    "uniform bool tex_flip; void main() {\n"
    "  if (tex_flip)\n"
    "    interp_tc = vec2(in_tc.x, 1.0 - in_tc.y);\n"
    "  else\n"
    "   interp_tc = in_tc;\n"
    "  gl_Position = in_pos;\n"
    "}\n";

// Fragment shader used to render thumbnails.
#if !defined(OS_WIN)
constexpr char kFragmentShader[] =
    "#extension GL_OES_EGL_image_external : enable\n"
    "precision mediump float;\n"
    "varying vec2 interp_tc;\n"
    "uniform sampler2D tex;\n"
    "#ifdef GL_OES_EGL_image_external\n"
    "uniform samplerExternalOES tex_external;\n"
    "#endif\n"
    "void main() {\n"
    "  vec4 color = texture2D(tex, interp_tc);\n"
    "#ifdef GL_OES_EGL_image_external\n"
    "  color += texture2D(tex_external, interp_tc);\n"
    "#endif\n"
    "  gl_FragColor = color;\n"
    "}\n";
#else
constexpr char kFragmentShader[] =
    "#ifdef GL_ES\n"
    "precision mediump float;\n"
    "#endif\n"
    "varying vec2 interp_tc;\n"
    "uniform sampler2D tex;\n"
    "void main() {\n"
    "  gl_FragColor = texture2D(tex, interp_tc);\n"
    "}\n";
#endif

GLuint CreateTexture(GLenum texture_target, const gfx::Size& size) {
  GLuint texture_id;
  glGenTextures(1, &texture_id);
  glBindTexture(texture_target, texture_id);
  if (texture_target == GL_TEXTURE_2D) {
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, size.width(), size.height(), 0,
                 GL_RGBA, GL_UNSIGNED_BYTE, nullptr);
  }

  glTexParameteri(texture_target, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  glTexParameteri(texture_target, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  // OpenGLES2.0.25 section 3.8.2 requires CLAMP_TO_EDGE for NPOT textures.
  glTexParameteri(texture_target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
  glTexParameteri(texture_target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

  CHECK_EQ(static_cast<int>(glGetError()), GL_NO_ERROR);
  return texture_id;
}

void DeleteTexture(uint32_t texture_id) {
  glDeleteTextures(1, &texture_id);
  CHECK_EQ(static_cast<int>(glGetError()), GL_NO_ERROR);
}

void RenderTexture(uint32_t texture_target, uint32_t texture_id) {
  // The ExternalOES sampler is bound to GL_TEXTURE1 and the Texture2D sampler
  // is bound to GL_TEXTURE0.
  if (texture_target == GL_TEXTURE_2D) {
    glActiveTexture(GL_TEXTURE0 + 0);
  } else if (texture_target == GL_TEXTURE_EXTERNAL_OES) {
    glActiveTexture(GL_TEXTURE0 + 1);
  }
  glBindTexture(texture_target, texture_id);
  glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
  glBindTexture(texture_target, 0);

  CHECK_EQ(static_cast<int>(glGetError()), GL_NO_ERROR);
}

void CreateShader(GLuint program, GLenum type, const char* source, int size) {
  GLuint shader = glCreateShader(type);
  glShaderSource(shader, 1, &source, &size);
  glCompileShader(shader);
  int result = GL_FALSE;
  glGetShaderiv(shader, GL_COMPILE_STATUS, &result);
  if (!result) {
    char log[4096];
    glGetShaderInfoLog(shader, base::size(log), nullptr, log);
    LOG(FATAL) << log;
  }
  glAttachShader(program, shader);
  glDeleteShader(shader);
  CHECK_EQ(static_cast<int>(glGetError()), GL_NO_ERROR);
}

void GLSetViewPort(const gfx::Rect& area) {
  glViewport(area.x(), area.y(), area.width(), area.height());
  glScissor(area.x(), area.y(), area.width(), area.height());
}

// Helper function to convert from RGBA to RGB. Returns false if any alpha
// channel is not 0xff, otherwise true.
bool ConvertRGBAToRGB(const std::vector<unsigned char>& rgba,
                      std::vector<unsigned char>* rgb) {
  size_t num_pixels = rgba.size() / 4;
  rgb->resize(num_pixels * 3);
  // Drop the alpha channel, but check as we go that it is all 0xff.
  bool solid = true;
  for (size_t i = 0; i < num_pixels; i++) {
    (*rgb)[3 * i] = rgba[4 * i];
    (*rgb)[3 * i + 1] = rgba[4 * i + 1];
    (*rgb)[3 * i + 2] = rgba[4 * i + 2];
    solid = solid && (rgba[4 * i + 3] == 0xff);
  }
  return solid;
}

}  // namespace

bool FrameRendererThumbnail::gl_initialized_ = false;

FrameRendererThumbnail::FrameRendererThumbnail(
    const std::vector<std::string>& thumbnail_checksums,
    const base::FilePath& output_folder)
    : thumbnail_checksums_(thumbnail_checksums), output_folder_(output_folder) {
  DETACH_FROM_SEQUENCE(renderer_sequence_checker_);
}

FrameRendererThumbnail::~FrameRendererThumbnail() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(client_sequence_checker_);

  if (renderer_task_runner_) {
    base::WaitableEvent done;
    renderer_task_runner_->PostTask(
        FROM_HERE, base::BindOnce(&FrameRendererThumbnail::DestroyTask,
                                  base::Unretained(this), &done));
    done.Wait();
  }
}

// static
std::unique_ptr<FrameRendererThumbnail> FrameRendererThumbnail::Create(
    const std::vector<std::string> thumbnail_checksums,
    const base::FilePath& output_folder) {
  auto frame_renderer = base::WrapUnique(
      new FrameRendererThumbnail(thumbnail_checksums, output_folder));
  frame_renderer->Initialize();
  return frame_renderer;
}

bool FrameRendererThumbnail::AcquireGLContext() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(renderer_sequence_checker_);

  return gl_context_->MakeCurrent(gl_surface_.get());
}

gl::GLContext* FrameRendererThumbnail::GetGLContext() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(renderer_sequence_checker_);

  return gl_context_.get();
}

void FrameRendererThumbnail::RenderFrame(
    scoped_refptr<VideoFrame> video_frame) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(renderer_sequence_checker_);

  if (video_frame->metadata()->IsTrue(VideoFrameMetadata::END_OF_STREAM))
    return;

  if (!renderer_task_runner_)
    renderer_task_runner_ = base::ThreadTaskRunnerHandle::Get();

  if (thumbnails_texture_id_ == 0u)
    InitializeThumbnailImageTask();

  if (video_frame->visible_rect().size().IsEmpty()) {
    // This occurs in bitstream buffer in webrtc scenario.
    DLOG(WARNING) << "Skipping rendering, because visible_rect is empty";
    return;
  }

  // Find the texture associated with the video frame's mailbox.
  const gpu::MailboxHolder& mailbox_holder = video_frame->mailbox_holder(0);
  const gpu::Mailbox& mailbox = mailbox_holder.mailbox;
  auto it = mailbox_texture_map_.find(mailbox);
  ASSERT_NE(it, mailbox_texture_map_.end());

  RenderThumbnailTask(mailbox_holder.texture_target, it->second);
}

void FrameRendererThumbnail::WaitUntilRenderingDone() {}

scoped_refptr<VideoFrame> FrameRendererThumbnail::CreateVideoFrame(
    VideoPixelFormat pixel_format,
    const gfx::Size& texture_size,
    uint32_t texture_target,
    uint32_t* texture_id) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(renderer_sequence_checker_);

  // Make the GL context current in the case it's not currently yet.
  AcquireGLContext();

  // Create a mailbox.
  gpu::Mailbox mailbox = gpu::Mailbox::Generate();
  gpu::MailboxHolder mailbox_holders[media::VideoFrame::kMaxPlanes];
  mailbox_holders[0] =
      gpu::MailboxHolder(mailbox, gpu::SyncToken(), texture_target);

  // Create a new video frame associated with the mailbox.
  base::OnceCallback<void(const gpu::SyncToken&)> mailbox_holder_release_cb =
      base::BindOnce(&FrameRendererThumbnail::DeleteTextureTask,
                     base::Unretained(this), mailbox);
  scoped_refptr<VideoFrame> frame = VideoFrame::WrapNativeTextures(
      pixel_format, mailbox_holders, std::move(mailbox_holder_release_cb),
      texture_size, gfx::Rect(texture_size), texture_size, base::TimeDelta());

  // Create a texture and associate it with the mailbox.
  *texture_id = CreateTexture(texture_target, texture_size);

  mailbox_texture_map_.insert(std::make_pair(mailbox, *texture_id));

  return frame;
}

bool FrameRendererThumbnail::ValidateThumbnail() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(client_sequence_checker_);

  if (!renderer_task_runner_)
    return false;

  bool success = false;
  base::WaitableEvent done;
  renderer_task_runner_->PostTask(
      FROM_HERE, base::BindOnce(&FrameRendererThumbnail::ValidateThumbnailTask,
                                base::Unretained(this), &success, &done));
  done.Wait();

  return success;
}

void FrameRendererThumbnail::SaveThumbnailTask() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(renderer_sequence_checker_);

  // Create the directory tree if it doesn't exist yet.
  if (!DirectoryExists(output_folder_))
    base::CreateDirectory(output_folder_);

  const std::vector<uint8_t> rgba = ConvertThumbnailToRGBATask();

  // Convert raw RGBA into PNG for export.
  std::vector<unsigned char> png;
  gfx::PNGCodec::Encode(&rgba[0], gfx::PNGCodec::FORMAT_RGBA,
                        kThumbnailsPageSize, kThumbnailsPageSize.width() * 4,
                        true, std::vector<gfx::PNGCodec::Comment>(), &png);

  base::FilePath filepath =
      base::MakeAbsoluteFilePath(output_folder_).Append(kThumbnailFilename);
  LOG(INFO) << "Saving thumbnails image to " << filepath;

  base::File thumbnail_file(
      filepath, base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE);
  int num_bytes =
      thumbnail_file.Write(0u, reinterpret_cast<char*>(&png[0]), png.size());
  ASSERT_NE(-1, num_bytes);
  EXPECT_EQ(static_cast<size_t>(num_bytes), png.size());
}

void FrameRendererThumbnail::Initialize() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(client_sequence_checker_);

  // Initialize GL rendering and create GL context.
  if (!gl_initialized_) {
    if (!gl::init::InitializeGLOneOff())
      LOG(FATAL) << "Could not initialize GL";
    gl_initialized_ = true;
  }
  gl_surface_ = gl::init::CreateOffscreenGLSurface(gfx::Size());
  gl_context_ = gl::init::CreateGLContext(nullptr, gl_surface_.get(),
                                          gl::GLContextAttribs());
}

void FrameRendererThumbnail::DestroyTask(base::WaitableEvent* done) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(renderer_sequence_checker_);
  DCHECK(mailbox_texture_map_.empty());

  DestroyThumbnailImageTask();

  // Release the |gl_context_| so it can be destroyed on the same thread it was
  // created on. Otherwise random crashes might occur as not all resources are
  // freed correctly.
  gl_context_->ReleaseCurrent(gl_surface_.get());

  done->Signal();
}

void FrameRendererThumbnail::InitializeThumbnailImageTask() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(renderer_sequence_checker_);

  GLint max_texture_size;
  glGetIntegerv(GL_MAX_TEXTURE_SIZE, &max_texture_size);
  CHECK_GE(max_texture_size, kThumbnailsPageSize.width());
  CHECK_GE(max_texture_size, kThumbnailsPageSize.height());

  thumbnails_fbo_size_ = kThumbnailsPageSize;
  thumbnail_size_ = kThumbnailSize;

  glGenFramebuffersEXT(1, &thumbnails_fbo_id_);
  glGenTextures(1, &thumbnails_texture_id_);
  glBindTexture(GL_TEXTURE_2D, thumbnails_texture_id_);
  glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, thumbnails_fbo_size_.width(),
               thumbnails_fbo_size_.height(), 0, GL_RGB,
               GL_UNSIGNED_SHORT_5_6_5, nullptr);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  glBindTexture(GL_TEXTURE_2D, 0);

  glBindFramebufferEXT(GL_FRAMEBUFFER, thumbnails_fbo_id_);
  glFramebufferTexture2DEXT(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,
                            thumbnails_texture_id_, 0);

  GLenum fb_status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER);
  CHECK(fb_status == GL_FRAMEBUFFER_COMPLETE) << fb_status;
  glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
  glClear(GL_COLOR_BUFFER_BIT);
  glBindFramebufferEXT(GL_FRAMEBUFFER,
                       gl_surface_->GetBackingFramebufferObject());

  // These vertices and texture coords map (0,0) in the texture to the bottom
  // left of the viewport. Since we get the video frames with the the top left
  // at (0,0) we need to flip the texture y coordinate in the vertex shader for
  // this to be rendered the right way up. In the case of thumbnail rendering we
  // use the same vertex shader to render the FBO to the screen, where we do not
  // want this flipping. Vertices are 2 floats for position and 2 floats for
  // texcoord each.
  const float kVertices[] = {
      -1, 1,  0, 1,  // Vertex 0
      -1, -1, 0, 0,  // Vertex 1
      1,  1,  1, 1,  // Vertex 2
      1,  -1, 1, 0,  // Vertex 3
  };
  const GLvoid* kVertexPositionOffset = 0;
  const GLvoid* kVertexTexcoordOffset =
      reinterpret_cast<GLvoid*>(sizeof(float) * 2);
  const GLsizei kVertexStride = sizeof(float) * 4;

  glGenBuffersARB(1, &vertex_buffer_);
  glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer_);
  glBufferData(GL_ARRAY_BUFFER, sizeof(kVertices), kVertices, GL_STATIC_DRAW);

  program_ = glCreateProgram();
  CreateShader(program_, GL_VERTEX_SHADER, kVertexShader,
               base::size(kVertexShader));
  CreateShader(program_, GL_FRAGMENT_SHADER, kFragmentShader,
               base::size(kFragmentShader));
  glLinkProgram(program_);
  GLint result = GL_FALSE;
  glGetProgramiv(program_, GL_LINK_STATUS, &result);
  if (!result) {
    constexpr GLsizei kLogBufferSize = 4096;
    char log[kLogBufferSize];
    glGetShaderInfoLog(program_, kLogBufferSize, nullptr, log);
    LOG(FATAL) << log;
  }
  glUseProgram(program_);
  glDeleteProgram(program_);

  glUniform1i(glGetUniformLocation(program_, "tex_flip"), 0);
  glUniform1i(glGetUniformLocation(program_, "tex"), 0);
  GLint tex_external = glGetUniformLocation(program_, "tex_external");
  if (tex_external != -1) {
    glUniform1i(tex_external, 1);
  }
  GLint pos_location = glGetAttribLocation(program_, "in_pos");
  glEnableVertexAttribArray(pos_location);
  glVertexAttribPointer(pos_location, 2, GL_FLOAT, GL_FALSE, kVertexStride,
                        kVertexPositionOffset);
  GLint tc_location = glGetAttribLocation(program_, "in_tc");
  glEnableVertexAttribArray(tc_location);
  glVertexAttribPointer(tc_location, 2, GL_FLOAT, GL_FALSE, kVertexStride,
                        kVertexTexcoordOffset);

  // Unbind the vertex buffer
  glBindBuffer(GL_ARRAY_BUFFER, 0);
}

void FrameRendererThumbnail::DestroyThumbnailImageTask() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(renderer_sequence_checker_);

  glDeleteTextures(1, &thumbnails_texture_id_);
  glDeleteFramebuffersEXT(1, &thumbnails_fbo_id_);
  glDeleteBuffersARB(1, &vertex_buffer_);

  thumbnails_texture_id_ = 0u;
  thumbnails_fbo_id_ = 0u;
  vertex_buffer_ = 0u;
}

void FrameRendererThumbnail::RenderThumbnailTask(uint32_t texture_target,
                                                 uint32_t texture_id) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(renderer_sequence_checker_);

  const int width = thumbnail_size_.width();
  const int height = thumbnail_size_.height();
  const int thumbnails_in_row = thumbnails_fbo_size_.width() / width;
  const int thumbnails_in_column = thumbnails_fbo_size_.height() / height;
  const int row = (frame_count_ / thumbnails_in_row) % thumbnails_in_column;
  const int col = frame_count_ % thumbnails_in_row;
  gfx::Rect area(col * width, row * height, width, height);

  glUniform1i(glGetUniformLocation(program_, "tex_flip"), 0);
  glBindFramebufferEXT(GL_FRAMEBUFFER, thumbnails_fbo_id_);
  GLSetViewPort(area);
  RenderTexture(texture_target, texture_id);
  glBindFramebufferEXT(GL_FRAMEBUFFER,
                       gl_surface_->GetBackingFramebufferObject());
  // We need to flush the GL commands before returning the thumbnail texture to
  // the decoder.
  glFlush();

  ++frame_count_;
}

const std::vector<uint8_t>
FrameRendererThumbnail::ConvertThumbnailToRGBATask() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(renderer_sequence_checker_);

  std::vector<uint8_t> rgba;
  const size_t num_pixels = thumbnails_fbo_size_.GetArea();
  rgba.resize(num_pixels * 4);
  glBindFramebufferEXT(GL_FRAMEBUFFER, thumbnails_fbo_id_);
  glPixelStorei(GL_PACK_ALIGNMENT, 1);
  // We can only count on GL_RGBA/GL_UNSIGNED_BYTE support.
  glReadPixels(0, 0, thumbnails_fbo_size_.width(),
               thumbnails_fbo_size_.height(), GL_RGBA, GL_UNSIGNED_BYTE,
               &(rgba)[0]);
  glBindFramebufferEXT(GL_FRAMEBUFFER,
                       gl_surface_->GetBackingFramebufferObject());

  return rgba;
}

void FrameRendererThumbnail::ValidateThumbnailTask(bool* success,
                                                   base::WaitableEvent* done) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(renderer_sequence_checker_);

  const std::vector<uint8_t> rgba = ConvertThumbnailToRGBATask();

  // Convert the thumbnail from RGBA to RGB.
  std::vector<uint8_t> rgb;
  EXPECT_EQ(ConvertRGBAToRGB(rgba, &rgb), true)
      << "RGBA frame has incorrect alpha";

  // Calculate the thumbnail's checksum and compare it to golden values.
  std::string md5_string = base::MD5String(
      base::StringPiece(reinterpret_cast<char*>(&rgb[0]), rgb.size()));
  *success = base::Contains(thumbnail_checksums_, md5_string);

  // If validation failed, write the thumbnail image to disk.
  if (!(*success))
    SaveThumbnailTask();

  done->Signal();
}

void FrameRendererThumbnail::DeleteTextureTask(const gpu::Mailbox& mailbox,
                                               const gpu::SyncToken&) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(renderer_sequence_checker_);

  auto it = mailbox_texture_map_.find(mailbox);
  ASSERT_NE(it, mailbox_texture_map_.end());
  uint32_t texture_id = it->second;
  mailbox_texture_map_.erase(mailbox);

  DeleteTexture(texture_id);
}

}  // namespace test
}  // namespace media


text:
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "google/cloud/storage/internal/hash_function_impl.h"
#include "google/cloud/storage/internal/openssl_util.h"
#include "google/cloud/internal/big_endian.h"
#include "absl/memory/memory.h"
#include <crc32c/crc32c.h>

namespace google {
namespace cloud {
namespace storage {
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN
namespace internal {
namespace {

using ContextPtr = std::unique_ptr<EVP_MD_CTX, MD5HashFunction::ContextDeleter>;

ContextPtr CreateDigestCtx() {
// The name of the function to create and delete EVP_MD_CTX objects changed
// with OpenSSL 1.1.0.
#if (OPENSSL_VERSION_NUMBER < 0x10100000L)  // Older than version 1.1.0.
  return ContextPtr(EVP_MD_CTX_create());
#else
  return ContextPtr(EVP_MD_CTX_new());
#endif
}

void DeleteDigestCtx(EVP_MD_CTX* context) {
// The name of the function to free an EVP_MD_CTX changed in OpenSSL 1.1.0.
#if (OPENSSL_VERSION_NUMBER < 0x10100000L)  // Older than version 1.1.0.
  EVP_MD_CTX_destroy(context);
#else
  EVP_MD_CTX_free(context);
#endif  // OPENSSL_VERSION_NUMBER >= 0x10100000L
}

}  // namespace

std::string CompositeFunction::Name() const {
  return "composite(" + a_->Name() + "," + b_->Name() + ")";
}

void CompositeFunction::Update(char const* buf, std::size_t n) {
  a_->Update(buf, n);
  b_->Update(buf, n);
}

HashValues CompositeFunction::Finish() && {
  return Merge(std::move(*a_).Finish(), std::move(*b_).Finish());
}

MD5HashFunction::MD5HashFunction() : impl_(CreateDigestCtx()) {
  EVP_DigestInit_ex(impl_.get(), EVP_md5(), nullptr);
}

void MD5HashFunction::Update(char const* buf, std::size_t n) {
  EVP_DigestUpdate(impl_.get(), buf, n);
}

HashValues MD5HashFunction::Finish() && {
  std::vector<std::uint8_t> hash(EVP_MD_size(EVP_md5()));
  unsigned int len = 0;
  // Note: EVP_DigestFinal_ex() consumes an `unsigned char*` for the output
  // array.  On some platforms (read PowerPC and ARM), the default `char` is
  // unsigned. In those platforms it is possible that
  // `std::uint8_t != unsigned char` and the `reinterpret_cast<>` is needed. It
  // should be safe in any case.
  EVP_DigestFinal_ex(impl_.get(), reinterpret_cast<unsigned char*>(hash.data()),
                     &len);
  hash.resize(len);
  return HashValues{/*.crc32c=*/{}, /*.md5=*/Base64Encode(hash)};
}

void MD5HashFunction::ContextDeleter::operator()(EVP_MD_CTX* context) {
  DeleteDigestCtx(context);
}

void Crc32cHashFunction::Update(char const* buf, std::size_t n) {
  current_ =
      crc32c::Extend(current_, reinterpret_cast<std::uint8_t const*>(buf), n);
}

HashValues Crc32cHashFunction::Finish() && {
  std::string const hash = google::cloud::internal::EncodeBigEndian(current_);
  return HashValues{/*.crc32c=*/Base64Encode(hash), /*.md5=*/{}};
}

}  // namespace internal
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END
}  // namespace storage
}  // namespace cloud
}  // namespace google


text:
package io.gatling.core.controller.throttle

import scala.annotation.tailrec
import scala.concurrent.duration._

sealed trait ThrottleStep {

  val durationInSec: Long
  def target(previousLastValue: Int): Int
  def rps(time: Long, previousLastValue: Int): Int
}

case class ReachIntermediate(target: Int) {
  def in(duration: FiniteDuration) = Reach(target, duration)
}

case class Reach(target: Int, duration: FiniteDuration) extends ThrottleStep {
  val durationInSec = duration.toSeconds
  def target(previousLastValue: Int) = target
  def rps(time: Long, previousLastValue: Int): Int = (previousLastValue + (target - previousLastValue) * (time + 1) / durationInSec).toInt
}

case class Hold(duration: FiniteDuration) extends ThrottleStep {
  val durationInSec = duration.toSeconds
  def target(previousLastValue: Int) = previousLastValue
  def rps(time: Long, previousLastValue: Int) = previousLastValue
}

case class Jump(target: Int) extends ThrottleStep {
  val durationInSec = 0L
  def target(previousLastValue: Int) = target
  def rps(time: Long, previousLastValue: Int) = 0
}

trait ThrottlingSupport {
  def reachRps(target: Int) = ReachIntermediate(target)
  def holdFor(duration: FiniteDuration) = Hold(duration)
  def jumpToRps(target: Int) = Jump(target)
}

case class Throttlings(global: Option[Throttling], perScenario: Map[String, Throttling])

object Throttling {

  @tailrec
  private def valueAt(steps: List[ThrottleStep], pendingTime: Long, previousLastValue: Int): Int = steps match {
    case Nil => 0
    case head :: tail =>
      if (pendingTime < head.durationInSec)
        head.rps(pendingTime, previousLastValue)
      else
        valueAt(tail, pendingTime - head.durationInSec, head.target(previousLastValue))
  }

  def apply(steps: Iterable[ThrottleStep]): Throttling = {

    val reversedSteps = steps.toList
    val limit: (Long => Int) = (now: Long) => valueAt(reversedSteps, now, 0)

    val duration: FiniteDuration =
      steps.foldLeft(Duration.Zero) { (acc, step) =>
        step match {
          case Reach(_, d) => acc + d
          case Hold(d)     => acc + d
          case _           => acc
        }
      }

    Throttling(limit, duration)
  }
}

case class Throttling(limit: Long => Int, duration: FiniteDuration)


text:
var conf = require('../config'),
    sql = require('sqlite3'),
    db = new sql.Database(conf.db);

exports.getRental = function (req, res, next) {
    var stmt = db.prepare("SELECT * FROM tblGeneral WHERE PropID = ?");
    stmt.get(req.params.id, function (err, row) {
        res.send(row);
    });
    stmt.finalize();
    return next();
}

exports.getRentals = function (req, res, next) {
    var all = [];
    db.each("SELECT * FROM tblGeneral", function (err, row) {
        all.push(row);
    }, function (err, count) {
        res.send(all);
    });
    return next();
}

exports.deleteRental = function (req, res, next) {
    var stmt = db.prepare("DELETE FROM tblGeneral WHERE PropID = ?");
    stmt.run(req.params.id, function (err, row) {
        var ret = { error: false };
        if (err) {
            ret.error = true;
            ret.errMsg = err;
        } else {
            ret.changes = this.changes;
        }
        res.send(ret);
    });
    return next();
}


text:
import sys

from measurements import smoothness
from metrics import power
from telemetry.core import exceptions
from telemetry.core import wpr_modes
from telemetry.page import page
from telemetry.page import page_test
from telemetry.unittest import options_for_unittests
from telemetry.unittest import page_test_test_case
from telemetry.unittest import test

class FakeTracingController(object):
  def __init__(self):
    self.category_filter = None
  def Start(self, _options, category_filter, _timeout):
    self.category_filter = category_filter

class FakePlatform(object):
  def __init__(self):
    self.tracing_controller = FakeTracingController()
  def IsRawDisplayFrameRateSupported(self):
    return False
  def CanMonitorPower(self):
    return False

class FakeBrowser(object):
  def __init__(self):
    self.platform = FakePlatform()

class AnimatedPage(page.Page):
  def __init__(self, page_set):
    super(AnimatedPage, self).__init__(
      url='file://animated_page.html',
      page_set=page_set, base_dir=page_set.base_dir)

  def RunSmoothness(self, action_runner):
    action_runner.Wait(.2)

class FakeTab(object):
  def __init__(self):
    self.browser = FakeBrowser()

  def ExecuteJavaScript(self, js):
    pass

class SmoothnessUnitTest(page_test_test_case.PageTestTestCase):
  """Smoke test for smoothness measurement

     Runs smoothness measurement on a simple page and verifies
     that all metrics were added to the results. The test is purely functional,
     i.e. it only checks if the metrics are present and non-zero.
  """
  def testSyntheticDelayConfiguration(self):
    test_page = page.Page('http://dummy', None)
    test_page.synthetic_delays = {
        'cc.BeginMainFrame': { 'target_duration': 0.012 },
        'cc.DrawAndSwap': { 'target_duration': 0.012, 'mode': 'alternating' },
        'gpu.PresentingFrame': { 'target_duration': 0.012 }
    }

    tab = FakeTab()
    measurement = smoothness.Smoothness()
    measurement.WillStartBrowser(tab.browser.platform)
    measurement.WillNavigateToPage(test_page, tab)
    measurement.WillRunActions(test_page, tab)

    expected_category_filter = set([
        'DELAY(cc.BeginMainFrame;0.012000;static)',
        'DELAY(cc.DrawAndSwap;0.012000;alternating)',
        'DELAY(gpu.PresentingFrame;0.012000;static)',
        'benchmark'
    ])
    tracing_controller = tab.browser.platform.tracing_controller
    actual_category_filter = (
      tracing_controller.category_filter.included_categories)

    # FIXME: Put blink.console into the expected above and remove these two
    # remove entries when the blink.console change has rolled into chromium.
    actual_category_filter.remove('webkit.console')
    actual_category_filter.remove('blink.console')

    if expected_category_filter != actual_category_filter:
      sys.stderr.write("Expected category filter: %s\n" %
                       repr(expected_category_filter))
      sys.stderr.write("Actual category filter filter: %s\n" %
                       repr(actual_category_filter))
    self.assertEquals(expected_category_filter, actual_category_filter)

  def setUp(self):
    self._options = options_for_unittests.GetCopy()
    self._options.browser_options.wpr_mode = wpr_modes.WPR_OFF

  def testSmoothness(self):
    ps = self.CreatePageSetFromFileInUnittestDataDir('scrollable_page.html')
    measurement = smoothness.Smoothness()
    results = self.RunMeasurement(measurement, ps, options=self._options)
    self.assertEquals(0, len(results.failures))

    frame_times = results.FindAllPageSpecificValuesNamed('frame_times')
    self.assertEquals(len(frame_times), 1)
    self.assertGreater(frame_times[0].GetRepresentativeNumber(), 0)

    mean_frame_time = results.FindAllPageSpecificValuesNamed('mean_frame_time')
    self.assertEquals(len(mean_frame_time), 1)
    self.assertGreater(mean_frame_time[0].GetRepresentativeNumber(), 0)

    jank = results.FindAllPageSpecificValuesNamed('jank')
    self.assertEquals(len(jank), 1)
    self.assertGreater(jank[0].GetRepresentativeNumber(), 0)

    mostly_smooth = results.FindAllPageSpecificValuesNamed('mostly_smooth')
    self.assertEquals(len(mostly_smooth), 1)
    self.assertGreaterEqual(mostly_smooth[0].GetRepresentativeNumber(), 0)

    mean_input_event_latency = results.FindAllPageSpecificValuesNamed(
        'mean_input_event_latency')
    if mean_input_event_latency:
      self.assertEquals(len(mean_input_event_latency), 1)
      self.assertGreater(
          mean_input_event_latency[0].GetRepresentativeNumber(), 0)

  @test.Disabled('mac', 'chromeos')  # http://crbug.com/403903
  def testSmoothnessForPageWithNoGesture(self):
    ps = self.CreateEmptyPageSet()
    ps.AddPage(AnimatedPage(ps))

    measurement = smoothness.Smoothness()
    results = self.RunMeasurement(measurement, ps, options=self._options)
    self.assertEquals(0, len(results.failures))

    mostly_smooth = results.FindAllPageSpecificValuesNamed('mostly_smooth')
    self.assertEquals(len(mostly_smooth), 1)
    self.assertGreaterEqual(mostly_smooth[0].GetRepresentativeNumber(), 0)

  def testCleanUpTrace(self):
    self.TestTracingCleanedUp(smoothness.Smoothness, self._options)

  def testCleanUpPowerMetric(self):
    class FailPage(page.Page):
      def __init__(self, page_set):
        super(FailPage, self).__init__(
            url='file://blank.html',
            page_set=page_set, base_dir=page_set.base_dir)
      def RunSmoothness(self, _):
        raise exceptions.IntentionalException

    class FakePowerMetric(power.PowerMetric):
      start_called = False
      stop_called = True
      def Start(self, _1, _2):
        self.start_called = True
      def Stop(self, _1, _2):
        self.stop_called = True

    ps = self.CreateEmptyPageSet()
    ps.AddPage(FailPage(ps))

    class BuggyMeasurement(smoothness.Smoothness):
      fake_power = None
      # Inject fake power metric.
      def WillStartBrowser(self, platform):
        self.fake_power = self._power_metric = FakePowerMetric(platform)

    measurement = BuggyMeasurement()
    try:
      self.RunMeasurement(measurement, ps)
    except page_test.TestNotSupportedOnPlatformFailure:
      pass

    self.assertTrue(measurement.fake_power.start_called)
    self.assertTrue(measurement.fake_power.stop_called)


text:
#region Copyright
//
// DotNetNuke® - https://www.dnnsoftware.com
// Copyright (c) 2002-2018
// by DotNetNuke Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#endregion

using System;
using System.Data;
using System.IO;
using System.Text;
using System.Web;
using DotNetNuke.Data;

namespace DotNetNuke.Services.OutputCache.Providers
{
    /// <summary>
    /// DatabaseProvider implements the OutputCachingProvider for database storage.
    /// </summary>
    public class DatabaseProvider : OutputCachingProvider
    {
        #region Abstract Method Implementation

        public override int GetItemCount(int tabId)
        {
            return DataProvider.Instance().GetOutputCacheItemCount(tabId);
        }

        public override byte[] GetOutput(int tabId, string cacheKey)
        {
            IDataReader dr = null;
            try
            {
                dr = DataProvider.Instance().GetOutputCacheItem(cacheKey);
                if (dr == null)
                {
                    return null;
                }
                else
                {
                    if (! (dr.Read()))
                    {
                        return null;
                    }

                    return Encoding.UTF8.GetBytes(dr["Data"].ToString());
                }
            }
            finally
            {
                if (dr != null)
                {
                    dr.Close();
                }
            }
        }

        public override OutputCacheResponseFilter GetResponseFilter(int tabId, int maxVaryByCount, Stream responseFilter, string cacheKey, TimeSpan cacheDuration)
        {
            return new DatabaseResponseFilter(tabId, maxVaryByCount, responseFilter, cacheKey, cacheDuration);
        }

        public override void PurgeCache(int portalId)
        {
            DataProvider.Instance().PurgeOutputCache();
        }

        public override void PurgeExpiredItems(int portalId)
        {
            DataProvider.Instance().PurgeExpiredOutputCacheItems();
        }

        public override void Remove(int tabId)
        {
            DataProvider.Instance().RemoveOutputCacheItem(tabId);
        }

        public override void SetOutput(int tabId, string cacheKey, TimeSpan duration, byte[] output)
        {
            string data = Encoding.UTF8.GetString(output);
            DataProvider.Instance().AddOutputCacheItem(tabId, cacheKey, data, DateTime.UtcNow.Add(duration));
        }

        public override bool StreamOutput(int tabId, string cacheKey, HttpContext context)
        {
            IDataReader dr = null;
            try
            {
                dr = DataProvider.Instance().GetOutputCacheItem(cacheKey);
                if (dr == null)
                {
                    return false;
                }
                else
                {
                    if (! (dr.Read()))
                    {
                        return false;
                    }

                	var expireTime = Convert.ToDateTime(dr["Expiration"]);
					if(expireTime < DateTime.UtcNow)
					{
						DataProvider.Instance().RemoveOutputCacheItem(tabId);
						return false;
					}

					context.Response.BinaryWrite(Encoding.Default.GetBytes(dr["Data"].ToString()));
                	return true;
                }
            }
            finally
            {
                if (dr != null)
                {
                    dr.Close();
                }
            }
        }

        #endregion
    }
}


text:
Upgrading to 1.1
================

Testing framework refactor
--------------------------

The most visible change is the way you write tests. With 1.0, you were able to access a ``.test`` property from any casper script and so running a suite using the standard ``casperjs`` executable::

    // 1.0 style test script not using the `casperjs test` subcommand
    var casper = require('casper').create();

    casper.start('http://foo.bar/', function() {
        this.test.assert(true);
    });

    casper.run(function() {
        this.test.done(1);
        this.test.renderResults(true);
    });

In 1.1, the test framework has been heavily refactored to decouple the tester from a casper instance as much as possible, so it's no more possible to run a test suite right from the standard ``casperjs`` command as you would have done with the script shown above.

Instead you now have to use the :doc:`casperjs test <../testing>` subcommand mandatorily to access a tester instance from the ``casper.test`` property.

.. warning::

   As of 1.1:

   - you shouldn't invoke the ``renderResults()`` method directly anymore
   - you shouldn't use the ``done()`` first argument to set planned test as it's been deprecated
   - you can't access the ``casper.test`` property when not using the ``casperjs test`` subcommand

   If you try, you'll get an error::

       // test.js
       var casper = require('casper').create();
       casper.test.assert(true);

   Will give:

   .. code-block:: text

       $ casperjs test.js
       CasperError: casper.test property is only available using the `casperjs test` command

The new ``Tester#begin()`` method
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

However, a new :ref:`begin() <tester_begin>` method as been added to the :ref:`Tester <tester_module>` prototype, to ease describing your tests::

    casper.test.begin('Description of my test', 1, function(test) {
        test.assert(true);
        test.done();
    });

More asynchronously::

    casper.test.begin('Description of my test', 1, function(test) {
        casper.start('http://foo.bar/', function() {
            test.assert(true);
        });

        casper.run(function() {
            test.done();
        });
    });

.. note::

   Please notice ``begin()``'s second argument which is now the place to set the number of planned tests.

require() in custom modules
---------------------------

CasperJS 1.1 now internally uses PhantomJS' native ``require()`` function, but it has side effect if you write your own casperjs modules; in any casperjs module, you now have to use the new global ``patchRequire()`` function first::

    // casperjs module code
    var require = patchRequire(require);
    // now you can require casperjs builtins
    var utils = require('utils');
    exports = {
        // ...
    };

.. note::

    You don't have to use ``patchRequire()`` in a standard casperjs script.

``__file__`` has been removed
-----------------------------

As of 1.1, CasperJS now uses native PhantomJS' ``require()`` function which doesn't support the ``__file__`` builtin variable within custom modules like 1.0 allowed.

``Tester#getFailures()`` and ``Tester#getSuccesses()`` methods removed
----------------------------------------------------------------------

These two methods have been removed from the :doc:`Tester <../modules/tester>` API.

Step and run completion callbacks don't throw anymore
-----------------------------------------------------

Instead, you should listen to the ``step.error`` and ``complete.error`` events; if you really want to keep raising them::

    casper.on("step.error complete.error", function(error) {
      throw error;
    });


text:
FROM ubuntu:trusty
MAINTAINER Paul Bowsher <paul.bowsher@gmail.com>

RUN apt-get update && apt-get install -y -q \
    build-essential \
    git \
    libssl-dev \
    libsqlite3-dev \
    nodejs \
    ruby-dev \
    sqlite3 \
 && apt-get clean \
 && rm -r /var/lib/apt/lists/* \
 && gem install bundler --no-ri --no-rdoc

ADD . /app
WORKDIR /app

RUN bundle install
RUN bundle exec rake assets

EXPOSE 1025
EXPOSE 1080

ENTRYPOINT ["bundle", "exec", "mailcatcher", "-f"]
CMD ["--ip", "0.0.0.0"]