text:
///
$CAPostFx::enabled = false;

/// The lens distortion coefficient.
$CAPostFx::distCoeffecient =  -0.05;

/// The cubic distortion value.
$CAPostFx::cubeDistortionFactor =  -0.1;

/// The amount and direction of the maxium shift for
/// the red, green, and blue channels.
$CAPostFx::colorDistortionFactor = "0.005 -0.005 0.01";

singleton GFXStateBlockData( PFX_DefaultChromaticLensStateBlock )
{
   zDefined = true;
   zEnable = false;
   zWriteEnable = false;
   samplersDefined = true;
   samplerStates[0] = SamplerClampPoint;
};

singleton ShaderData( PFX_ChromaticLensShader )
{
   DXVertexShaderFile 	= "shaders/common/postFx/postFxV.hlsl";
   DXPixelShaderFile 	= "shaders/common/postFx/chromaticLens.hlsl";
   pixVersion = 3.0;
};

singleton PostEffect( ChromaticLensPostFX )
{
   renderTime = "PFXAfterDiffuse";
   renderPriority = 0.2;
   isEnabled = false;
   allowReflectPass = false;

   shader = PFX_ChromaticLensShader;
   stateBlock = PFX_DefaultChromaticLensStateBlock;
   texture[0] = "$backBuffer";
   target = "$backBuffer";
};

function ChromaticLensPostFX::setShaderConsts( %this )
{
   %this.setShaderConst( "$distCoeff", $CAPostFx::distCoeffecient );
   %this.setShaderConst( "$cubeDistort", $CAPostFx::cubeDistortionFactor );
   %this.setShaderConst( "$colorDistort", $CAPostFx::colorDistortionFactor );
}


text:
package org.cleanas2.message;

import org.cleanas2.common.MdnAttributes;

/**
 * Base class for both IncomingAsyncMdn and IncomingSyncMdn.
 *
 * The fields in this base class are used when initializing an MDN from an incoming MIME message
 *
 * @author Andrew Backer {@literal awbacker@gmail.com / andrew.backer@powere2e.com}
 */
public abstract class IncomingMdnBase {

    /**
     * The content of the "text/plain" body part (contained in the multipart)
     */
    public String bodyText;

    /**
     * The attributes in the "message/disposition-notification" body part (contained in the multipart)
     */
    public final MdnAttributes attributes = new MdnAttributes();
}

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Globalization;
using System.Text;
using Nett.Extensions;
using Nett.Parser;
using static System.Math;

namespace Nett
{
    public sealed class TomlDuration : TomlValue<TimeSpan>
    {
        internal TomlDuration(ITomlRoot root, TimeSpan value)
            : base(root, value)
        {
        }

        public override string ReadableTypeName => "duration";

        public override TomlObjectType TomlType => TomlObjectType.TimeSpan;

        public override void Visit(ITomlObjectVisitor visitor)
        {
            visitor.Visit(this);
        }

        public override string ToString()
        {
            StringBuilder sb = new StringBuilder();

            if (this.Value < TimeSpan.Zero) { sb.Append('-'); }

            if (this.Value.Days != 0) { sb.Append(Abs(this.Value.Days)).Append("d"); }
            if (this.Value.Hours != 0) { sb.Append(Abs(this.Value.Hours)).Append("h"); }
            if (this.Value.Minutes != 0) { sb.Append(Abs(this.Value.Minutes)).Append("m"); }
            if (this.Value.Seconds != 0) { sb.Append(Abs(this.Value.Seconds)).Append("s"); }
            if (this.Value.Milliseconds != 0) { sb.Append(Abs(this.Value.Milliseconds)).Append("ms"); }

            if (sb.Length <= 0) { sb.Append("0ms"); }

            return sb.ToString();
        }

        // This method is only capable of processing lexer input. Lexer did all validation and error handling already
        // so in this impl. here we know exactly what the input data looks like and do not need to do any checks or specialized
        // handling.
        internal static TomlDuration Parse(ITomlRoot root, string input)
        {
            var value = new StringBuilder(16);
            var unit = new StringBuilder(2);
            TimeSpan result = TimeSpan.Zero;

            int startIndex = input[0] == '+' || input[0] == '-' ? 1 : 0;
            for (int i = startIndex; i < input.Length; i++)
            {
                var c = input[i];
                if (c == '_') { continue; }
                else if (c.IsDigit() || c == '.') { value.Append(input[i]); }
                else { unit.Append(c); }

                if (SegmentDone(i))
                {
                    result += TimeSpanFromTokens(value.ToString(), unit.ToString());
                    value.Clear();
                    unit.Clear();
                }
            }

            bool SegmentDone(int i)
                => unit.Length > 0 && (i == input.Length - 1 || input[i + 1].IsDigit());

            return input[0] == '-' ? new TomlDuration(root, -result) : new TomlDuration(root, result);
        }

        internal override TomlObject CloneFor(ITomlRoot root) => this.CloneTimespanFor(root);

        internal TomlDuration CloneTimespanFor(ITomlRoot root) => CopyComments(new TomlDuration(root, this.Value), this);

        private static TimeSpan TimeSpanFromTokens(string value, string unit)
        {
            switch (unit)
            {
                case "d": return ToTimeSpan(TimeSpan.TicksPerDay);
                case "h": return ToTimeSpan(TimeSpan.TicksPerHour);
                case "m": return ToTimeSpan(TimeSpan.TicksPerMinute);
                case "s": return ToTimeSpan(TimeSpan.TicksPerSecond);
                case "ms": return ToTimeSpan(TimeSpan.TicksPerMillisecond);
                case "us": return ToTimeSpan(TimeSpan.TicksPerMillisecond / 1000);
                default: throw new ArgumentException($"Unknown timespan unit '{unit}'.");
            }

            // Work-around for .Net design issue:
            // https://stackoverflow.com/questions/5450439/timespan-frommilliseconds-strange-implementation
            TimeSpan ToTimeSpan(long ticksPer)
                => TimeSpan.FromTicks((long)(double.Parse(value, CultureInfo.InvariantCulture) * ticksPer));
        }
    }
}


text:
<?php

namespace frontend\controllers;

use Yii;
use app\models\PerancanganProgramPlanMaster;
use frontend\models\PerancanganProgramPlanMasterSearch;
use app\models\PerancanganProgramPlan;
use frontend\models\PerancanganProgramPlanSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\web\Session;
use yii\helpers\Url;
use yii\helpers\Json;
use yii\web\UploadedFile;
use yii\web\Response;
use yii\helpers\BaseUrl;

use app\models\general\Upload;

// contant values
use app\models\general\GeneralVariable;
use common\models\general\GeneralFunction;

// table reference
use app\models\RefJenisProgram;
use app\models\RefBahagianProgram;
use app\models\RefCawangan;
use app\models\RefProgramSemasaSukanAtlet;
use app\models\RefJenisAktiviti;
use app\models\RefStatusProgram;
use app\models\RefSukan;
use app\models\RefKategoriPelan;
use app\models\RefJenisPelan;
use app\models\RefKedudukanKejohanan;
use app\models\RefStatusPermohonanProgramBinaan;
use app\models\MsnLaporan;

/**
 * PerancanganProgramPlanController implements the CRUD actions for PerancanganProgramPlan model.
 */
class PerancanganProgramPlanController extends Controller
{
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ];
    }

    /**
     * Lists all PerancanganProgramPlan models.
     * @return mixed
     */
    public function actionIndex()
    {
        if (Yii::$app->user->isGuest) {
            return $this->redirect(array(GeneralVariable::loginPagePath));
        }

        $queryParams = Yii::$app->request->queryParams;

        if(isset(Yii::$app->user->identity->peranan_akses['MSN']['perancangan-program']['view_own_data'])){
            $queryParams['PerancanganProgramPlanMasterSearch']['created_by'] = Yii::$app->user->identity->id;
        }

        $searchModel = new PerancanganProgramPlanMasterSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single PerancanganProgramPlan model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        if (Yii::$app->user->isGuest) {
            return $this->redirect(array(GeneralVariable::loginPagePath));
        }

        $model = $this->findModel($id);

		$queryPar = null;

        $queryPar['PerancanganProgramPlanSearch']['perancangan_program_plan_master_id'] = $id;

		$searchModelPerancanganProgramPlanItem  = new PerancanganProgramPlanSearch();
        $dataProviderPerancanganProgramPlanItem = $searchModelPerancanganProgramPlanItem->search($queryPar);

        $ref = RefCawangan::findOne(['id' => $model->cawangan]);
        $model->cawangan = $ref['desc'];

        $ref = RefProgramSemasaSukanAtlet::findOne(['id' => $model->program]);
        $model->program = $ref['desc'];

        $ref = RefSukan::findOne(['id' => $model->sukan]);
        $model->sukan = $ref['desc'];

        if($model->tarikh_mula != "") {$model->tarikh_mula = GeneralFunction::convert($model->tarikh_mula, GeneralFunction::TYPE_DATE);}
        if($model->tarikh_tamat != "") {$model->tarikh_tamat = GeneralFunction::convert($model->tarikh_tamat, GeneralFunction::TYPE_DATE);}

        return $this->render('view', [
            'model' => $model,
            'readonly' => true,
			'searchModelPerancanganProgramPlanItem' => $searchModelPerancanganProgramPlanItem,
            'dataProviderPerancanganProgramPlanItem' => $dataProviderPerancanganProgramPlanItem,
        ]);
    }

    /**
     * Creates a new PerancanganProgramPlan model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        if (Yii::$app->user->isGuest) {
            return $this->redirect(array(GeneralVariable::loginPagePath));
        }

        $model = new PerancanganProgramPlanMaster();

		$queryPar = null;

        Yii::$app->session->open();

        if(isset(Yii::$app->session->id)){
            $queryPar['PerancanganProgramPlanSearch']['session_id'] = Yii::$app->session->id;
        }

		$searchModelPerancanganProgramPlanItem  = new PerancanganProgramPlanSearch();
        $dataProviderPerancanganProgramPlanItem = $searchModelPerancanganProgramPlanItem->search($queryPar);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            if(isset(Yii::$app->session->id)){
                PerancanganProgramPlan::updateAll(['perancangan_program_plan_master_id' => $model->perancangan_program_plan_master_id], 'session_id = "'.Yii::$app->session->id.'"');
                PerancanganProgramPlan::updateAll(['session_id' => ''], 'perancangan_program_plan_master_id = "'.$model->perancangan_program_plan_master_id.'"');
            }
            //if($model->save()){
			$this->updateChildItem($model);
            return $this->redirect(['view', 'id' => $model->perancangan_program_plan_master_id]);
            //}
        }

        return $this->render('create', [
            'model' => $model,
            'readonly' => false,
			'searchModelPerancanganProgramPlanItem' => $searchModelPerancanganProgramPlanItem,
            'dataProviderPerancanganProgramPlanItem' => $dataProviderPerancanganProgramPlanItem,
        ]);
    }

    /**
     * Updates an existing PerancanganProgramPlan model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        if (Yii::$app->user->isGuest) {
            return $this->redirect(array(GeneralVariable::loginPagePath));
        }

        $model = $this->findModel($id);

		$queryPar = null;

        $queryPar['PerancanganProgramPlanSearch']['perancangan_program_plan_master_id'] = $id;

		$searchModelPerancanganProgramPlanItem  = new PerancanganProgramPlanSearch();
        $dataProviderPerancanganProgramPlanItem = $searchModelPerancanganProgramPlanItem->search($queryPar);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {

            if($model->save()){
				$this->updateChildItem($model);
                return $this->redirect(['view', 'id' => $model->perancangan_program_plan_master_id]);
            }
        } else {
            return $this->render('update', [
                'model' => $model,
                'readonly' => false,
				'searchModelPerancanganProgramPlanItem' => $searchModelPerancanganProgramPlanItem,
				'dataProviderPerancanganProgramPlanItem' => $dataProviderPerancanganProgramPlanItem,
            ]);
        }
    }

    /**
     * Deletes an existing PerancanganProgramPlan model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        if (Yii::$app->user->isGuest) {
            return $this->redirect(array(GeneralVariable::loginPagePath));
        }

        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the PerancanganProgramPlan model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return PerancanganProgramPlan the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = PerancanganProgramPlanMaster::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

    public function actionGetProgram($id){
        // find Ahli Jawatankuasa Induk
        $model = PerancanganProgramPlan::findOne($id);

        echo Json::encode($model);
    }

    public function updateChildItem($model)
    {
            $update = PerancanganProgramPlan::updateAll(['jenis_program' => $model->program, 'cawangan' => $model->cawangan, 'sukan' => $model->sukan], 'perancangan_program_plan_master_id = "'. $model->perancangan_program_plan_master_id.'"');
    }

    public function actionGetProgramPlan()
    {
        if (Yii::$app->request->isAjax) {
            Yii::$app->response->format = Response::FORMAT_JSON;
            $id = $_GET['id'];
            $model = PerancanganProgramPlan::findOne(['perancangan_program_id' => $id]);
			if(isset($model->perancangan_program_plan_master_id) && $model->perancangan_program_plan_master_id != NULL){
				$parent = PerancanganProgramPlanMaster::findOne(['perancangan_program_plan_master_id' => $model->perancangan_program_plan_master_id]);
				$arr = ['sukan' => $parent->sukan,
                                    'program' => $parent->program,
                                    'cawangan' => $parent->cawangan,
                                    'tarikh_mula' => $model->tarikh_mula,
                                    'tarikh_tamat' => $model->tarikh_tamat,
                                    'tempat' => $model->tempat,
                                    'sasaran' => $parent->sasaran,
                                    'target' => $parent->target,];
			} else {
				$arr = [];
			}

            return $arr;
        }
    }

    /**
     * Get Bandars base on Negeri id
     * @param integer $id actionHryye
     * @return mixed
     */
    public function actionSubitems()
    {
        $out = [];
        if (isset($_POST['depdrop_parents'])) {
            $parents = $_POST['depdrop_parents'];
            if ($parents != null) {
                $cat_id = $parents[0];
                $out = self::getItemsByKategori($cat_id);
                // the getSubCatList function will query the database based on the
                // cat_id and return an array like below:
                // [
                //    ['id'=>'<sub-cat-id-1>', 'name'=>'<sub-cat-name1>'],
                //    ['id'=>'<sub-cat_id_2>', 'name'=>'<sub-cat-name2>']
                // ]
                echo Json::encode(['output'=>$out, 'selected'=>'']);
                return;
            }
        }
        echo Json::encode(['output'=>'', 'selected'=>'']);
    }

    /**
     * get list of Bandar by Negeri
     * @param integer $id
     * @return Array Bandars
     */
    public static function getItemsByKategori($kategori_id) {
        $data = PerancanganProgramPlan::find()
                ->where(['IS NOT', 'perancangan_program_plan_master_id', NULL])
                            ->andWhere(['=', 'bahagian', $kategori_id])->select(['perancangan_program_id as id','nama_program AS name'])->asArray()->all();
        $value = (count($data) == 0) ? ['' => ''] : $data;

        return $value;
    }

    public function actionLaporanKewangan()
    {

        if (Yii::$app->user->isGuest) {
            return $this->redirect(array(GeneralVariable::loginPagePath));
        }

        $model = new MsnLaporan();
        $model->format = 'html';

        if ($model->load(Yii::$app->request->post())) {

            if($model->format == "html") {
                $report_url = BaseUrl::to(['generate-laporan-kewangan-plan-periodisasi'
                    , 'tarikh_dari' => $model->tarikh_dari
                    , 'tarikh_hingga' => $model->tarikh_hingga
                    , 'sukan' => $model->sukan
                    , 'program' => $model->program
                    , 'format' => $model->format
                ], true);
                echo "<script type=\"text/javascript\" language=\"Javascript\">window.open('".$report_url."');</script>";
            } else {
                return $this->redirect(['generate-laporan-kewangan-plan-periodisasi'
                    , 'tarikh_dari' => $model->tarikh_dari
                    , 'tarikh_hingga' => $model->tarikh_hingga
                    , 'sukan' => $model->sukan
                    , 'program' => $model->program
                    , 'format' => $model->format
                ]);
            }
        }

        return $this->render('laporan_kewangan_plan', [
            'model' => $model,
            'readonly' => false,
        ]);

    }

    public function actionGenerateLaporanKewanganPlanPeriodisasi($tarikh_dari, $tarikh_hingga, $sukan, $program, $format)
    {
        if($tarikh_dari == "") $tarikh_dari = array();
        else $tarikh_dari = array($tarikh_dari);

        if($tarikh_hingga == "") $tarikh_hingga = array();
        else $tarikh_hingga = array($tarikh_hingga);

        if($sukan == "") $sukan = array();
        else $sukan = array($sukan);

        if($program == "") $program = array();
        else $program = array($program);

        $controls = array(
            'FROM_DATE' => $tarikh_dari,
            'TO_DATE' => $tarikh_hingga,
            'SUKAN' => $sukan,
            'PROGRAM' => $program,
        );

        GeneralFunction::generateReport('/spsb/MSN/LaporanKewanganPlanPeriodisasi', $format, $controls, 'laporan_kewangan_plan');
    }

    public function actionLaporanPelanPeriodisasi($id)
    {

        if (Yii::$app->user->isGuest) {
            return $this->redirect(array(GeneralVariable::loginPagePath));
        }

        $model = new MsnLaporan();
        $model->format = 'html';

        if ($model->load(Yii::$app->request->post())) {

            if($model->format == "html") {
                $report_url = BaseUrl::to(['generate-laporan-pelan-periodisasi'
                    , 'id' => $id
                    , 'format' => $model->format
                ], true);
                echo "<script type=\"text/javascript\" language=\"Javascript\">window.open('".$report_url."');</script>";
            } else {
                return $this->redirect(['generate-laporan-pelan-periodisasi'
                    , 'id' => $id
                    , 'format' => $model->format
                ]);
            }
        }

        return $this->render('laporan_pelan_periodisasi', [
            'model' => $model,
            'readonly' => false,
        ]);

    }

    public function actionGenerateLaporanPelanPeriodisasi($id, $format)
    {
        if($id == "") $id = array();
        else $id = array($id);

        $controls = array(
            'ID' => $id,
        );

        GeneralFunction::generateReport('/spsb/MSN/LaporanPelanPeriodisasi', $format, $controls, 'laporan_pelan_periodisasi');
    }
}


text:
<!doctype html>

	<meta charset="utf-8" />
	<link rel="apple-touch-icon" sizes="76x76" href="<?php echo base_url(); ?>assets/img/favicon/apple-icon-76x76.png">
	<link rel="icon" type="image/png" href="<?php echo base_url(); ?>assets/img/favicon/favicon-96x96.png">
	<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
	<meta content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0' name='viewport' />
	<title>Tienda | Vino de Misa</title>
	<link rel="stylesheet" type="text/css" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Roboto+Slab:400,700|Material+Icons" />
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/latest/css/font-awesome.min.css" />
	<link href="<?php echo base_url(); ?>assets/css/bootstrap.min.css" rel="stylesheet" />
	<link href="<?php echo base_url(); ?>assets/css/material-kit.min.css" rel="stylesheet"/>
	<link href="<?php echo base_url(); ?>assets/css/custom.min.css" rel="stylesheet"/>

		<?php $this->load->view('plantillas/nav');?>

	<div class="page-header header-filter" data-parallax="active"
	style="background-image: url('<?php echo base_url();?>assets/img/fondoTienda.jpg');">

Nuestros vinos

Le invitamos a disfrutar un vino artesanal y de uso exclusivo para el altar.

				<img width="140" src="<?php echo base_url();?>assets/img/CruzTransparente.png">

Estimado cliente, a continuación, usted podrá comprar nuestros vinos en nuestra tienda online. Selecciones el tipo de producto, variedad y cantidades que desea solicitar.
						Pedido mínimo de una caja para despacho dentro del territorio nacional.
						Para compras de unidad de botella, sólo retiro en tienda.

Variedades

										Vino asoleado
										keyboard_arrow_down

									Es un vino de cepa especial traída desde España que se procesa cortando la uva y asoleándola por unos quince días, luego se muele y se lleva a fermentación, proceso que dura cuatro meses y luego se lleva a bodega para su madurez, almacenándola en vasijas de roble. Al cabo de un año se procesa nuevamente para sacar impurezas y borras por decantación natural y finalmente se guarda en bodega para su madurez por tres años y al cuarto se envasa para su comercialización.

										Vino cocido
										keyboard_arrow_down

									Vino de cepa de uva de mesa seleccionada por calidad y tamaño, se procesa moliendo la uva y llevándola a grandes pailas, se hierve hasta deshidratarla al 50%. Se enfría y se lleva a fermentación, proceso que dura cuatro meses y luego se lleva a bodega para madurez, almacenándola en vasijas de roble. Al cabo de un año se procesa nuevamente para sacar impurezas y borras por decantación natural y se guarda en bodega para su madurez por tres años y al cuarto se envasa para su comercialización.

Catálogo

			<?php $indice = 1;?>
			<?php foreach ($productos as $producto): ?>
				<?php if($indice == 1):?>

					<?php endif;?>

									<img class="img img-raised" src="<?php echo base_url().$producto['imagen'];?>" />

								<h6 class="category text-<?=$producto['clase'];?>"><?php echo $producto['nombre'];?>

									<?php
									$nombre = $producto['nombre'];
									$indiceEspacio = stripos($nombre, ' ');
									$unidad = substr($producto['nombre'], 0, $indiceEspacio);
									?>
									<?php echo "Precio: $".str_replace(',', '.', number_format($producto['precio']))." por " . $unidad;?>

							<button class="btn btn-rose btn-round js-abrir-modal">

								 Agregar
								<input type="hidden" value="<?php echo $producto['id'];?>"/>
							</button>

					<?php if($indice == 2):?>
<?php $indice = 0; endif;?>
					<?php $indice = $indice + 1; endforeach; ?>

		<?php include("plantillas/fab-button.php");?>

						<button type="button" class="close" data-dismiss="modal" aria-hidden="true">clear</button>

Por favor, selecciona la cantidad deseada

									Paso 1

Presiona los botones habilitados para sumar o descontar unidades.

									Paso 2

Presiona el botón "Seguir agregando" para seleccionar otros productos o el botón "Terminar" para realizar el pedido. En caso de que quieras cancelar, presiona el boton "x".

								<button id="restar" class="btn btn-round btn-rose btn-md"> remove

</button>
								<button id="sumar" class="btn btn-round btn-rose btn-md"> add

</button>

							<text class="cantidad-asignada" id="cantidadSeleccionada"></text>

						<button id="seguirComprando" type="button" class="btn btn-info btn-round" data-dismiss="modal">Seguir agregando</button>

						<button id="terminarCompra" type="button" class="btn btn-info btn-simple" data-dismiss="modal">Terminar</button>

							<button type="button" class="close" data-dismiss="modal" aria-hidden="true">clear</button>

							<button type="button" class="btn btn-success btn-simple" data-dismiss="modal">Entendido</button>

			<?php $this->load->view('plantillas/footer');?>

		<?php $this->load->view('plantillas/token');?>

		<?php if(!$this->session->userdata('mayor_edad')):?>

		<?php endif;?>


text:
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Security.Claims;
using System.Threading.Channels;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Internal;
using Microsoft.AspNetCore.SignalR.Protocol;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Internal;
using Microsoft.Extensions.Logging;
using Log = Microsoft.AspNetCore.SignalR.Internal.DefaultHubDispatcherLog;

namespace Microsoft.AspNetCore.SignalR.Internal;

internal sealed partial class DefaultHubDispatcher<THub> : HubDispatcher<THub> where THub : Hub
{
    private readonly Dictionary<string, HubMethodDescriptor> _methods = new(StringComparer.OrdinalIgnoreCase);
    private readonly Utf8HashLookup _cachedMethodNames = new();
    private readonly IServiceScopeFactory _serviceScopeFactory;
    private readonly IHubContext<THub> _hubContext;
    private readonly ILogger<HubDispatcher<THub>> _logger;
    private readonly bool _enableDetailedErrors;
    private readonly Func<HubInvocationContext, ValueTask<object?>>? _invokeMiddleware;
    private readonly Func<HubLifetimeContext, Task>? _onConnectedMiddleware;
    private readonly Func<HubLifetimeContext, Exception?, Task>? _onDisconnectedMiddleware;
    private readonly HubLifetimeManager<THub> _hubLifetimeManager;

    public DefaultHubDispatcher(IServiceScopeFactory serviceScopeFactory, IHubContext<THub> hubContext, bool enableDetailedErrors,
        bool disableImplicitFromServiceParameters, ILogger<DefaultHubDispatcher<THub>> logger, List<IHubFilter>? hubFilters, HubLifetimeManager<THub> lifetimeManager)
    {
        _serviceScopeFactory = serviceScopeFactory;
        _hubContext = hubContext;
        _enableDetailedErrors = enableDetailedErrors;
        _logger = logger;
        _hubLifetimeManager = lifetimeManager;
        DiscoverHubMethods(disableImplicitFromServiceParameters);

        var count = hubFilters?.Count ?? 0;
        if (count != 0)
        {
            _invokeMiddleware = (invocationContext) =>
            {
                var arguments = invocationContext.HubMethodArguments as object?[] ?? invocationContext.HubMethodArguments.ToArray();
                if (invocationContext.ObjectMethodExecutor != null)
                {
                    return ExecuteMethod(invocationContext.ObjectMethodExecutor, invocationContext.Hub, arguments);
                }
                return ExecuteMethod(invocationContext.HubMethod.Name, invocationContext.Hub, arguments);
            };

            _onConnectedMiddleware = (context) => context.Hub.OnConnectedAsync();
            _onDisconnectedMiddleware = (context, exception) => context.Hub.OnDisconnectedAsync(exception);

            for (var i = count - 1; i > -1; i--)
            {
                var resolvedFilter = hubFilters![i];
                var nextFilter = _invokeMiddleware;
                _invokeMiddleware = (context) => resolvedFilter.InvokeMethodAsync(context, nextFilter);

                var connectedFilter = _onConnectedMiddleware;
                _onConnectedMiddleware = (context) => resolvedFilter.OnConnectedAsync(context, connectedFilter);

                var disconnectedFilter = _onDisconnectedMiddleware;
                _onDisconnectedMiddleware = (context, exception) => resolvedFilter.OnDisconnectedAsync(context, exception, disconnectedFilter);
            }
        }
    }

    public override async Task OnConnectedAsync(HubConnectionContext connection)
    {
        await using var scope = _serviceScopeFactory.CreateAsyncScope();

        var hubActivator = scope.ServiceProvider.GetRequiredService<IHubActivator<THub>>();
        var hub = hubActivator.Create();
        try
        {
            // OnConnectedAsync won't work with client results (ISingleClientProxy.InvokeAsync)
            InitializeHub(hub, connection, invokeAllowed: false);

            if (_onConnectedMiddleware != null)
            {
                var context = new HubLifetimeContext(connection.HubCallerContext, scope.ServiceProvider, hub);
                await _onConnectedMiddleware(context);
            }
            else
            {
                await hub.OnConnectedAsync();
            }
        }
        finally
        {
            hubActivator.Release(hub);
        }
    }

    public override async Task OnDisconnectedAsync(HubConnectionContext connection, Exception? exception)
    {
        await using var scope = _serviceScopeFactory.CreateAsyncScope();

        var hubActivator = scope.ServiceProvider.GetRequiredService<IHubActivator<THub>>();
        var hub = hubActivator.Create();
        try
        {
            InitializeHub(hub, connection);

            if (_onDisconnectedMiddleware != null)
            {
                var context = new HubLifetimeContext(connection.HubCallerContext, scope.ServiceProvider, hub);
                await _onDisconnectedMiddleware(context, exception);
            }
            else
            {
                await hub.OnDisconnectedAsync(exception);
            }
        }
        finally
        {
            hubActivator.Release(hub);
        }
    }

    public override Task DispatchMessageAsync(HubConnectionContext connection, HubMessage hubMessage)
    {
        // Messages are dispatched sequentially and will stop other messages from being processed until they complete.
        // Streaming methods will run sequentially until they start streaming, then they will fire-and-forget allowing other messages to run.

        // With parallel invokes enabled, messages run sequentially until they go async and then the next message will be allowed to start running.

        switch (hubMessage)
        {
            case InvocationBindingFailureMessage bindingFailureMessage:
                return ProcessInvocationBindingFailure(connection, bindingFailureMessage);

            case StreamBindingFailureMessage bindingFailureMessage:
                return ProcessStreamBindingFailure(connection, bindingFailureMessage);

            case InvocationMessage invocationMessage:
                Log.ReceivedHubInvocation(_logger, invocationMessage);
                return ProcessInvocation(connection, invocationMessage, isStreamResponse: false);

            case StreamInvocationMessage streamInvocationMessage:
                Log.ReceivedStreamHubInvocation(_logger, streamInvocationMessage);
                return ProcessInvocation(connection, streamInvocationMessage, isStreamResponse: true);

            case CancelInvocationMessage cancelInvocationMessage:
                // Check if there is an associated active stream and cancel it if it exists.
                // The cts will be removed when the streaming method completes executing
                if (connection.ActiveRequestCancellationSources.TryGetValue(cancelInvocationMessage.InvocationId!, out var cts))
                {
                    Log.CancelStream(_logger, cancelInvocationMessage.InvocationId!);
                    cts.Cancel();
                }
                else
                {
                    // Stream can be canceled on the server while client is canceling stream.
                    Log.UnexpectedCancel(_logger);
                }
                break;

            case PingMessage _:
                connection.StartClientTimeout();
                break;

            case StreamItemMessage streamItem:
                return ProcessStreamItem(connection, streamItem);

            case CompletionMessage completionMessage:
                // closes channels, removes from Lookup dict
                // user's method can see the channel is complete and begin wrapping up
                if (connection.StreamTracker.TryComplete(completionMessage))
                {
                    Log.CompletingStream(_logger, completionMessage);
                }
                // InvocationId is always required on CompletionMessage, it's nullable because of the base type
                else if (_hubLifetimeManager.TryGetReturnType(completionMessage.InvocationId!, out _))
                {
                    return _hubLifetimeManager.SetConnectionResultAsync(connection.ConnectionId, completionMessage);
                }
                else
                {
                    Log.UnexpectedCompletion(_logger, completionMessage.InvocationId!);
                }
                break;

            // Other kind of message we weren't expecting
            default:
                Log.UnsupportedMessageReceived(_logger, hubMessage.GetType().FullName!);
                throw new NotSupportedException($"Received unsupported message: {hubMessage}");
        }

        return Task.CompletedTask;
    }

    private Task ProcessInvocationBindingFailure(HubConnectionContext connection, InvocationBindingFailureMessage bindingFailureMessage)
    {
        Log.InvalidHubParameters(_logger, bindingFailureMessage.Target, bindingFailureMessage.BindingFailure.SourceException);

        var errorMessage = ErrorMessageHelper.BuildErrorMessage($"Failed to invoke '{bindingFailureMessage.Target}' due to an error on the server.",
            bindingFailureMessage.BindingFailure.SourceException, _enableDetailedErrors);
        return SendInvocationError(bindingFailureMessage.InvocationId, connection, errorMessage);
    }

    private Task ProcessStreamBindingFailure(HubConnectionContext connection, StreamBindingFailureMessage bindingFailureMessage)
    {
        var errorString = ErrorMessageHelper.BuildErrorMessage(
            "Failed to bind Stream message.",
            bindingFailureMessage.BindingFailure.SourceException, _enableDetailedErrors);

        var message = CompletionMessage.WithError(bindingFailureMessage.Id, errorString);
        Log.ClosingStreamWithBindingError(_logger, message);

        // ignore failure, it means the client already completed the stream or the stream never existed on the server
        connection.StreamTracker.TryComplete(message);

        // TODO: Send stream completion message to client when we add it
        return Task.CompletedTask;
    }

    private Task ProcessStreamItem(HubConnectionContext connection, StreamItemMessage message)
    {
        if (!connection.StreamTracker.TryProcessItem(message, out var processTask))
        {
            Log.UnexpectedStreamItem(_logger);
            return Task.CompletedTask;
        }

        Log.ReceivedStreamItem(_logger, message);
        return processTask;
    }

    private Task ProcessInvocation(HubConnectionContext connection,
        HubMethodInvocationMessage hubMethodInvocationMessage, bool isStreamResponse)
    {
        if (!_methods.TryGetValue(hubMethodInvocationMessage.Target, out var descriptor))
        {
            Log.UnknownHubMethod(_logger, hubMethodInvocationMessage.Target);

            if (!string.IsNullOrEmpty(hubMethodInvocationMessage.InvocationId))
            {
                // Send an error to the client. Then let the normal completion process occur
                return connection.WriteAsync(CompletionMessage.WithError(
                    hubMethodInvocationMessage.InvocationId, $"Unknown hub method '{hubMethodInvocationMessage.Target}'")).AsTask();
            }
            else
            {
                return Task.CompletedTask;
            }
        }
        else
        {
            bool isStreamCall = descriptor.StreamingParameters != null;
            if (!isStreamCall && !isStreamResponse)
            {
                return connection.ActiveInvocationLimit.RunAsync(static state =>
                {
                    var (dispatcher, descriptor, connection, invocationMessage) = state;
                    return dispatcher.Invoke(descriptor, connection, invocationMessage, isStreamResponse: false, isStreamCall: false);
                }, (this, descriptor, connection, hubMethodInvocationMessage)).AsTask();
            }
            else
            {
                return Invoke(descriptor, connection, hubMethodInvocationMessage, isStreamResponse, isStreamCall);
            }
        }
    }

    private async Task<bool> Invoke(HubMethodDescriptor descriptor, HubConnectionContext connection,
        HubMethodInvocationMessage hubMethodInvocationMessage, bool isStreamResponse, bool isStreamCall)
    {
        var methodExecutor = descriptor.MethodExecutor;

        var wasSemaphoreReleased = false;
        var disposeScope = true;
        var scope = _serviceScopeFactory.CreateAsyncScope();
        IHubActivator<THub>? hubActivator = null;
        THub? hub = null;
        try
        {
            hubActivator = scope.ServiceProvider.GetRequiredService<IHubActivator<THub>>();
            hub = hubActivator.Create();

            if (!await IsHubMethodAuthorized(scope.ServiceProvider, connection, descriptor, hubMethodInvocationMessage.Arguments, hub))
            {
                Log.HubMethodNotAuthorized(_logger, hubMethodInvocationMessage.Target);
                await SendInvocationError(hubMethodInvocationMessage.InvocationId, connection,
                    $"Failed to invoke '{hubMethodInvocationMessage.Target}' because user is unauthorized");
                return true;
            }

            if (!await ValidateInvocationMode(descriptor, isStreamResponse, hubMethodInvocationMessage, connection))
            {
                return true;
            }

            try
            {
                var clientStreamLength = hubMethodInvocationMessage.StreamIds?.Length ?? 0;
                var serverStreamLength = descriptor.StreamingParameters?.Count ?? 0;
                if (clientStreamLength != serverStreamLength)
                {
                    var ex = new HubException($"Client sent {clientStreamLength} stream(s), Hub method expects {serverStreamLength}.");
                    Log.InvalidHubParameters(_logger, hubMethodInvocationMessage.Target, ex);
                    await SendInvocationError(hubMethodInvocationMessage.InvocationId, connection,
                        ErrorMessageHelper.BuildErrorMessage($"An unexpected error occurred invoking '{hubMethodInvocationMessage.Target}' on the server.", ex, _enableDetailedErrors));
                    return true;
                }

                InitializeHub(hub, connection);
                Task? invocation = null;

                var arguments = hubMethodInvocationMessage.Arguments;
                CancellationTokenSource? cts = null;
                if (descriptor.HasSyntheticArguments)
                {
                    ReplaceArguments(descriptor, hubMethodInvocationMessage, isStreamCall, connection, scope, ref arguments, out cts);
                }

                if (isStreamCall || isStreamResponse)
                {
                    Debug.Assert(hub.Clients is HubCallerClients);
                    // Streaming invocations aren't involved with the semaphore.
                    // Setting the semaphore released flag avoids potential client result calls from the streaming hub method
                    // releasing the semaphore which would cause a SemaphoreFullException.
                    ((HubCallerClients)hub.Clients).TrySetSemaphoreReleased();
                }

                if (isStreamResponse)
                {
                    _ = StreamAsync(hubMethodInvocationMessage.InvocationId!, connection, arguments, scope, hubActivator, hub, cts, hubMethodInvocationMessage, descriptor);
                }
                else
                {
                    // Invoke or Send
                    static async Task ExecuteInvocation(DefaultHubDispatcher<THub> dispatcher,
                                                        ObjectMethodExecutor methodExecutor,
                                                        THub hub,
                                                        object?[] arguments,
                                                        AsyncServiceScope scope,
                                                        IHubActivator<THub> hubActivator,
                                                        HubConnectionContext connection,
                                                        HubMethodInvocationMessage hubMethodInvocationMessage,
                                                        bool isStreamCall)
                    {
                        var logger = dispatcher._logger;
                        var enableDetailedErrors = dispatcher._enableDetailedErrors;

                        object? result;
                        try
                        {
                            result = await dispatcher.ExecuteHubMethod(methodExecutor, hub, arguments, connection, scope.ServiceProvider);
                            Log.SendingResult(logger, hubMethodInvocationMessage.InvocationId, methodExecutor);
                        }
                        catch (Exception ex)
                        {
                            Log.FailedInvokingHubMethod(logger, hubMethodInvocationMessage.Target, ex);
                            await SendInvocationError(hubMethodInvocationMessage.InvocationId, connection,
                                ErrorMessageHelper.BuildErrorMessage($"An unexpected error occurred invoking '{hubMethodInvocationMessage.Target}' on the server.", ex, enableDetailedErrors));
                            return;
                        }
                        finally
                        {
                            // Stream response handles cleanup in StreamResultsAsync
                            // And normal invocations handle cleanup below in the finally
                            if (isStreamCall)
                            {
                                await CleanupInvocation(connection, hubMethodInvocationMessage, hubActivator, hub, scope);
                            }
                        }

                        // No InvocationId - Send Async, no response expected
                        if (!string.IsNullOrEmpty(hubMethodInvocationMessage.InvocationId))
                        {
                            // Invoke Async, one reponse expected
                            await connection.WriteAsync(CompletionMessage.WithResult(hubMethodInvocationMessage.InvocationId, result));
                        }
                    }

                    invocation = ExecuteInvocation(this, methodExecutor, hub, arguments, scope, hubActivator, connection, hubMethodInvocationMessage, isStreamCall);
                }

                if (isStreamCall || isStreamResponse)
                {
                    // don't await streaming invocations
                    // leave them running in the background, allowing dispatcher to process other messages between streaming items
                    disposeScope = false;
                }
                else
                {
                    // complete the non-streaming calls now
                    await invocation!;
                }
            }
            catch (TargetInvocationException ex)
            {
                Log.FailedInvokingHubMethod(_logger, hubMethodInvocationMessage.Target, ex);
                await SendInvocationError(hubMethodInvocationMessage.InvocationId, connection,
                    ErrorMessageHelper.BuildErrorMessage($"An unexpected error occurred invoking '{hubMethodInvocationMessage.Target}' on the server.", ex.InnerException ?? ex, _enableDetailedErrors));
            }
            catch (Exception ex)
            {
                Log.FailedInvokingHubMethod(_logger, hubMethodInvocationMessage.Target, ex);
                await SendInvocationError(hubMethodInvocationMessage.InvocationId, connection,
                    ErrorMessageHelper.BuildErrorMessage($"An unexpected error occurred invoking '{hubMethodInvocationMessage.Target}' on the server.", ex, _enableDetailedErrors));
            }
        }
        finally
        {
            if (disposeScope)
            {
                if (hub?.Clients is HubCallerClients hubCallerClients)
                {
                    wasSemaphoreReleased = !hubCallerClients.TrySetSemaphoreReleased();
                }
                await CleanupInvocation(connection, hubMethodInvocationMessage, hubActivator, hub, scope);
            }
        }

        return !wasSemaphoreReleased;
    }

    private static ValueTask CleanupInvocation(HubConnectionContext connection, HubMethodInvocationMessage hubMessage, IHubActivator<THub>? hubActivator,
        THub? hub, AsyncServiceScope scope)
    {
        if (hubMessage.StreamIds != null)
        {
            foreach (var stream in hubMessage.StreamIds)
            {
                connection.StreamTracker.TryComplete(CompletionMessage.Empty(stream));
            }
        }

        if (hub != null)
        {
            hubActivator?.Release(hub);
        }

        return scope.DisposeAsync();
    }

    private async Task StreamAsync(string invocationId, HubConnectionContext connection, object?[] arguments, AsyncServiceScope scope,
        IHubActivator<THub> hubActivator, THub hub, CancellationTokenSource? streamCts, HubMethodInvocationMessage hubMethodInvocationMessage, HubMethodDescriptor descriptor)
    {
        string? error = null;

        streamCts ??= CancellationTokenSource.CreateLinkedTokenSource(connection.ConnectionAborted);

        try
        {
            if (!connection.ActiveRequestCancellationSources.TryAdd(invocationId, streamCts))
            {
                Log.InvocationIdInUse(_logger, invocationId);
                error = $"Invocation ID '{invocationId}' is already in use.";
                return;
            }

            object? result;
            try
            {
                result = await ExecuteHubMethod(descriptor.MethodExecutor, hub, arguments, connection, scope.ServiceProvider);
            }
            catch (Exception ex)
            {
                Log.FailedInvokingHubMethod(_logger, hubMethodInvocationMessage.Target, ex);
                error = ErrorMessageHelper.BuildErrorMessage($"An unexpected error occurred invoking '{hubMethodInvocationMessage.Target}' on the server.", ex, _enableDetailedErrors);
                return;
            }

            if (result == null)
            {
                Log.InvalidReturnValueFromStreamingMethod(_logger, descriptor.MethodExecutor.MethodInfo.Name);
                error = $"The value returned by the streaming method '{descriptor.MethodExecutor.MethodInfo.Name}' is not a ChannelReader<> or IAsyncEnumerable<>.";
                return;
            }

            await using var enumerator = descriptor.FromReturnedStream(result, streamCts.Token);
            Log.StreamingResult(_logger, invocationId, descriptor.MethodExecutor);
            var streamItemMessage = new StreamItemMessage(invocationId, null);

            while (await enumerator.MoveNextAsync())
            {
                streamItemMessage.Item = enumerator.Current;
                // Send the stream item
                await connection.WriteAsync(streamItemMessage);
            }
        }
        catch (ChannelClosedException ex)
        {
            // If the channel closes from an exception in the streaming method, grab the innerException for the error from the streaming method
            Log.FailedStreaming(_logger, invocationId, descriptor.MethodExecutor.MethodInfo.Name, ex.InnerException ?? ex);
            error = ErrorMessageHelper.BuildErrorMessage("An error occurred on the server while streaming results.", ex.InnerException ?? ex, _enableDetailedErrors);
        }
        catch (Exception ex)
        {
            // If the streaming method was canceled we don't want to send a HubException message - this is not an error case
            if (!(ex is OperationCanceledException && streamCts.IsCancellationRequested))
            {
                Log.FailedStreaming(_logger, invocationId, descriptor.MethodExecutor.MethodInfo.Name, ex);
                error = ErrorMessageHelper.BuildErrorMessage("An error occurred on the server while streaming results.", ex, _enableDetailedErrors);
            }
        }
        finally
        {
            await CleanupInvocation(connection, hubMethodInvocationMessage, hubActivator, hub, scope);

            streamCts.Dispose();
            connection.ActiveRequestCancellationSources.TryRemove(invocationId, out _);

            await connection.WriteAsync(CompletionMessage.WithError(invocationId, error));
        }
    }

    private ValueTask<object?> ExecuteHubMethod(ObjectMethodExecutor methodExecutor, THub hub, object?[] arguments, HubConnectionContext connection, IServiceProvider serviceProvider)
    {
        if (_invokeMiddleware != null)
        {
            var invocationContext = new HubInvocationContext(methodExecutor, connection.HubCallerContext, serviceProvider, hub, arguments);
            return _invokeMiddleware(invocationContext);
        }

        // If no Hub filters are registered
        return ExecuteMethod(methodExecutor, hub, arguments);
    }

    private ValueTask<object?> ExecuteMethod(string hubMethodName, Hub hub, object?[] arguments)
    {
        if (!_methods.TryGetValue(hubMethodName, out var methodDescriptor))
        {
            throw new HubException($"Unknown hub method '{hubMethodName}'");
        }
        var methodExecutor = methodDescriptor.MethodExecutor;
        return ExecuteMethod(methodExecutor, hub, arguments);
    }

    private static async ValueTask<object?> ExecuteMethod(ObjectMethodExecutor methodExecutor, Hub hub, object?[] arguments)
    {
        if (methodExecutor.IsMethodAsync)
        {
            if (methodExecutor.MethodReturnType == typeof(Task))
            {
                await (Task)methodExecutor.Execute(hub, arguments)!;
                return null;
            }
            else
            {
                return await methodExecutor.ExecuteAsync(hub, arguments);
            }
        }
        else
        {
            return methodExecutor.Execute(hub, arguments);
        }
    }

    private static async Task SendInvocationError(string? invocationId,
        HubConnectionContext connection, string errorMessage)
    {
        if (string.IsNullOrEmpty(invocationId))
        {
            return;
        }

        await connection.WriteAsync(CompletionMessage.WithError(invocationId, errorMessage));
    }

    private void InitializeHub(THub hub, HubConnectionContext connection, bool invokeAllowed = true)
    {
        hub.Clients = new HubCallerClients(_hubContext.Clients, connection.ConnectionId, connection.ActiveInvocationLimit) { InvokeAllowed = invokeAllowed };
        hub.Context = connection.HubCallerContext;
        hub.Groups = _hubContext.Groups;
    }

    private static Task<bool> IsHubMethodAuthorized(IServiceProvider provider, HubConnectionContext hubConnectionContext, HubMethodDescriptor descriptor, object?[] hubMethodArguments, Hub hub)
    {
        // If there are no policies we don't need to run auth
        if (descriptor.Policies.Count == 0)
        {
            return TaskCache.True;
        }

        return IsHubMethodAuthorizedSlow(provider, hubConnectionContext.User, descriptor.Policies, new HubInvocationContext(hubConnectionContext.HubCallerContext, provider, hub, descriptor.MethodExecutor.MethodInfo, hubMethodArguments));
    }

    private static async Task<bool> IsHubMethodAuthorizedSlow(IServiceProvider provider, ClaimsPrincipal principal, IList<IAuthorizeData> policies, HubInvocationContext resource)
    {
        var authService = provider.GetRequiredService<IAuthorizationService>();
        var policyProvider = provider.GetRequiredService<IAuthorizationPolicyProvider>();

        var authorizePolicy = await AuthorizationPolicy.CombineAsync(policyProvider, policies);
        // AuthorizationPolicy.CombineAsync only returns null if there are no policies and we check that above
        Debug.Assert(authorizePolicy != null);

        var authorizationResult = await authService.AuthorizeAsync(principal, resource, authorizePolicy);
        // Only check authorization success, challenge or forbid wouldn't make sense from a hub method invocation
        return authorizationResult.Succeeded;
    }

    private async Task<bool> ValidateInvocationMode(HubMethodDescriptor hubMethodDescriptor, bool isStreamResponse,
        HubMethodInvocationMessage hubMethodInvocationMessage, HubConnectionContext connection)
    {
        if (hubMethodDescriptor.IsStreamResponse && !isStreamResponse)
        {
            // Non-null/empty InvocationId? Blocking
            if (!string.IsNullOrEmpty(hubMethodInvocationMessage.InvocationId))
            {
                Log.StreamingMethodCalledWithInvoke(_logger, hubMethodInvocationMessage);
                await connection.WriteAsync(CompletionMessage.WithError(hubMethodInvocationMessage.InvocationId,
                    $"The client attempted to invoke the streaming '{hubMethodInvocationMessage.Target}' method with a non-streaming invocation."));
            }

            return false;
        }

        if (!hubMethodDescriptor.IsStreamResponse && isStreamResponse)
        {
            Log.NonStreamingMethodCalledWithStream(_logger, hubMethodInvocationMessage);
            await connection.WriteAsync(CompletionMessage.WithError(hubMethodInvocationMessage.InvocationId!,
                $"The client attempted to invoke the non-streaming '{hubMethodInvocationMessage.Target}' method with a streaming invocation."));

            return false;
        }

        return true;
    }

    private void ReplaceArguments(HubMethodDescriptor descriptor, HubMethodInvocationMessage hubMethodInvocationMessage, bool isStreamCall,
        HubConnectionContext connection, AsyncServiceScope scope, ref object?[] arguments, out CancellationTokenSource? cts)
    {
        cts = null;
        // In order to add the synthetic arguments we need a new array because the invocation array is too small (it doesn't know about synthetic arguments)
        arguments = new object?[descriptor.OriginalParameterTypes!.Count];

        var streamPointer = 0;
        var hubInvocationArgumentPointer = 0;
        for (var parameterPointer = 0; parameterPointer < arguments.Length; parameterPointer++)
        {
            if (hubMethodInvocationMessage.Arguments?.Length > hubInvocationArgumentPointer &&
                (hubMethodInvocationMessage.Arguments[hubInvocationArgumentPointer] == null ||
                descriptor.OriginalParameterTypes[parameterPointer].IsAssignableFrom(hubMethodInvocationMessage.Arguments[hubInvocationArgumentPointer]?.GetType())))
            {
                // The types match so it isn't a synthetic argument, just copy it into the arguments array
                arguments[parameterPointer] = hubMethodInvocationMessage.Arguments[hubInvocationArgumentPointer];
                hubInvocationArgumentPointer++;
            }
            else
            {
                if (descriptor.OriginalParameterTypes[parameterPointer] == typeof(CancellationToken))
                {
                    cts = CancellationTokenSource.CreateLinkedTokenSource(connection.ConnectionAborted);
                    arguments[parameterPointer] = cts.Token;
                }
                else if (descriptor.IsServiceArgument(parameterPointer))
                {
                    arguments[parameterPointer] = scope.ServiceProvider.GetRequiredService(descriptor.OriginalParameterTypes[parameterPointer]);
                }
                else if (isStreamCall && ReflectionHelper.IsStreamingType(descriptor.OriginalParameterTypes[parameterPointer], mustBeDirectType: true))
                {
                    Log.StartingParameterStream(_logger, hubMethodInvocationMessage.StreamIds![streamPointer]);
                    var itemType = descriptor.StreamingParameters![streamPointer];
                    arguments[parameterPointer] = connection.StreamTracker.AddStream(hubMethodInvocationMessage.StreamIds[streamPointer],
                        itemType, descriptor.OriginalParameterTypes[parameterPointer]);

                    streamPointer++;
                }
                else
                {
                    // This should never happen
                    Debug.Assert(false, $"Failed to bind argument of type '{descriptor.OriginalParameterTypes[parameterPointer].Name}' for hub method '{descriptor.MethodExecutor.MethodInfo.Name}'.");
                }
            }
        }
    }

    private void DiscoverHubMethods(bool disableImplicitFromServiceParameters)
    {
        var hubType = typeof(THub);
        var hubTypeInfo = hubType.GetTypeInfo();
        var hubName = hubType.Name;

        using var scope = _serviceScopeFactory.CreateScope();

        IServiceProviderIsService? serviceProviderIsService = null;
        if (!disableImplicitFromServiceParameters)
        {
            serviceProviderIsService = scope.ServiceProvider.GetService<IServiceProviderIsService>();
        }

        foreach (var methodInfo in HubReflectionHelper.GetHubMethods(hubType))
        {
            if (methodInfo.IsGenericMethod)
            {
                throw new NotSupportedException($"Method '{methodInfo.Name}' is a generic method which is not supported on a Hub.");
            }

            var methodName =
                methodInfo.GetCustomAttribute<HubMethodNameAttribute>()?.Name ??
                methodInfo.Name;

            if (_methods.ContainsKey(methodName))
            {
                throw new NotSupportedException($"Duplicate definitions of '{methodName}'. Overloading is not supported.");
            }

            var executor = ObjectMethodExecutor.Create(methodInfo, hubTypeInfo);
            var authorizeAttributes = methodInfo.GetCustomAttributes<AuthorizeAttribute>(inherit: true);
            _methods[methodName] = new HubMethodDescriptor(executor, serviceProviderIsService, authorizeAttributes);
            _cachedMethodNames.Add(methodName);

            Log.HubMethodBound(_logger, hubName, methodName);
        }
    }

    public override IReadOnlyList<Type> GetParameterTypes(string methodName)
    {
        if (!_methods.TryGetValue(methodName, out var descriptor))
        {
            throw new HubException("Method does not exist.");
        }
        return descriptor.ParameterTypes;
    }

    public override string? GetTargetName(ReadOnlySpan<byte> targetUtf8Bytes)
    {
        if (_cachedMethodNames.TryGetValue(targetUtf8Bytes, out var targetName))
        {
            return targetName;
        }

        return null;
    }
}


text:
class Tram::Policy
  #
  # Enumerable collection of unique unordered validation errors
  #
  # Notice: A collection is context-dependent;
  #         it knows about a scope of policy it belongs to,
  #         and how to translate error messages in that scope.
  #
  class Errors
    include Enumerable

    # @!attribute [r] scope
    # @return [Array<String>] the scope for error messages' translation
    attr_reader :scope

    # @!method add(message, tags)
    # Adds error message to the collection
    #
    # @param [#to_s] message Either a message, or a symbolic key for translation
    # @param [Hash<Symbol, Object>] tags Tags to be attached to the message
    # @return [self] the collection
    #
    def add(message, **tags)
      raise ArgumentError.new("Error message should be defined") unless message

      tap do
        tags = { scope: scope }.merge(tags) if message.is_a?(Symbol)
        @set << Tram::Policy::Error.new(message, **tags)
      end
    end

    # Iterates by collected errors
    #
    # @yeldparam [Tram::Policy::Error]
    # @return [Enumerator<Tram::Policy::Error>]
    #
    def each
      @set.each { |error| yield(error) }
    end

    # @!method filter(key = nil, tags)
    # Filter errors by optional key and tags
    #
    # @param  [#to_s] key The key to filter errors by
    # @param  [Hash<Symbol, Object>] tags The list of tags to filter errors by
    # @return [Tram::Policy::Errors]
    #
    def filter(key = nil, **tags)
      list = each_with_object(Set.new) do |error, obj|
        obj << error if error.contain?(key, **tags)
      end
      self.class.new(scope: scope, errors: list)
    end

    # @!method empty?
    # Checks whether a collection is empty
    #
    # @return [Boolean]
    #
    def empty?(&block)
      block ? !any?(&block) : !any?
    end

    # The array of error items for translation
    #
    # @return [Array<Array>]
    #
    def items
      @set.map(&:item)
    end

    # The array of ordered error messages
    #
    # @return [Array<String>]
    #
    def messages
      @set.map(&:message).sort
    end

    # @!method merge(other, options)
    # Merges other collection to the current one and returns new collection
    # with the current scope
    #
    # @param [Tram::Policy::Errors] other   Collection to be merged
    # @param [Hash<Symbol, Object>] options Options to be added to merged errors
    # @yieldparam [Hash<Symbol, Object>] hash of error options
    # @return [self]
    #
    # @example Add some tag to merged errors
    #   policy.merge(other) { |err| err[:source] = "other" }
    #
    def merge(other, **options)
      return self unless other.is_a?(self.class)

      other.each do |err|
        key, opts = err.item
        opts = yield(opts) if block_given?
        add key, **opts.merge(options)
      end

      self
    end

    private

    def initialize(**options)
      @scope = options[:scope] || Error::DEFAULT_SCOPE
      @set   = Set.new options[:errors].to_a
    end
  end
end


text:
package griffon.plugins.gsql;

import groovy.sql.Sql;

import griffon.annotations.core.Nonnull;

/**
 * @author Andres Almiray
 */
public interface GsqlCallback<R> {
    R handle(@Nonnull String datasourceName, @Nonnull Sql sql);
}


text:
namespace cc {
class TimingFunction;

// A small helper class that does the math for zoom animations, primarily for
// double-tap zoom. Initialize it with starting and ending scroll/page scale
// positions and an animation length time, then call ...AtTime() at every frame
// to obtain the current interpolated position. The supplied timing function
// is used to ease the animation.
//
// All sizes and vectors in this class's public methods are in the root scroll
// layer's coordinate space.
class PageScaleAnimation {
 public:
  // Construct with the state at the beginning of the animation.
  static scoped_ptr<PageScaleAnimation> Create(
      gfx::Vector2dF start_scroll_offset,
      float start_page_scale_factor,
      gfx::SizeF viewport_size,
      gfx::SizeF root_layer_size,
      scoped_ptr<TimingFunction> timing_function);

  ~PageScaleAnimation();

  // The following methods initialize the animation. Call one of them
  // immediately after construction to set the final scroll and page scale.

  // Zoom while explicitly specifying the top-left scroll position.
  void ZoomTo(gfx::Vector2dF target_scroll_offset,
              float target_page_scale_factor,
              double duration);

  // Zoom based on a specified anchor. The animator will attempt to keep it
  // at the same position on the physical display throughout the animation,
  // unless the edges of the root layer are hit. The anchor is specified
  // as an offset from the content layer.
  void ZoomWithAnchor(gfx::Vector2dF anchor,
                      float target_page_scale_factor,
                      double duration);

  // These should be called before the first frame of animation to initialize
  // the start time. StartAnimation should only be called once after creation.
  bool IsAnimationStarted() const;
  void StartAnimation(double time);

  // Call these functions while the animation is in progress to output the
  // current state.
  gfx::Vector2dF ScrollOffsetAtTime(double time) const;
  float PageScaleFactorAtTime(double time) const;
  bool IsAnimationCompleteAtTime(double time) const;

  // The following methods return state which is invariant throughout the
  // course of the animation.
  double start_time() const { return start_time_; }
  double duration() const { return duration_; }
  double end_time() const { return start_time_ + duration_; }
  gfx::Vector2dF target_scroll_offset() const { return target_scroll_offset_; }
  float target_page_scale_factor() const { return target_page_scale_factor_; }

 protected:
  PageScaleAnimation(gfx::Vector2dF start_scroll_offset,
                     float start_page_scale_factor,
                     gfx::SizeF viewport_size,
                     gfx::SizeF root_layer_size,
                     scoped_ptr<TimingFunction> timing_function);

 private:
  void ClampTargetScrollOffset();
  void InferTargetScrollOffsetFromStartAnchor();
  void InferTargetAnchorFromScrollOffsets();

  gfx::SizeF StartViewportSize() const;
  gfx::SizeF TargetViewportSize() const;
  float InterpAtTime(double time) const;
  gfx::SizeF ViewportSizeAt(float interp) const;
  gfx::Vector2dF ScrollOffsetAt(float interp) const;
  gfx::Vector2dF AnchorAt(float interp) const;
  gfx::Vector2dF ViewportRelativeAnchorAt(float interp) const;
  float PageScaleFactorAt(float interp) const;

  float start_page_scale_factor_;
  float target_page_scale_factor_;
  gfx::Vector2dF start_scroll_offset_;
  gfx::Vector2dF target_scroll_offset_;

  gfx::Vector2dF start_anchor_;
  gfx::Vector2dF target_anchor_;

  gfx::SizeF viewport_size_;
  gfx::SizeF root_layer_size_;

  double start_time_;
  double duration_;

  scoped_ptr<TimingFunction> timing_function_;

  DISALLOW_COPY_AND_ASSIGN(PageScaleAnimation);
};

}  // namespace cc

#endif  // CC_INPUT_PAGE_SCALE_ANIMATION_H_


text:
#ifndef US_TESTUTIL_H
#define US_TESTUTIL_H

#include "us_world.h"

#include "us_buffer.h"

#include "us_logger.h"

/**
 \addtogroup us_testutil  Test Utilities
 */
/*@{*/

#if US_ENABLE_PRINTING
#include "us_print.h"
#endif

#ifdef __cplusplus
extern "C" {
#endif

#ifndef US_TESTUTIL_PRINTBUFFER_SIZE
#define US_TESTUTIL_PRINTBUFFER_SIZE ( 8192 )
#endif

#ifndef US_TESTUTIL_BUFFER_SIZE_IN_WORDS
#define US_TESTUTIL_BUFFER_SIZE_IN_WORDS ( 4096 )
#endif

bool us_testutil_start( int32_t sys_allocator_size, int32_t session_allocator_size, int argc, const char **argv );

void us_testutil_finish( void );

extern us_allocator_t *us_testutil_sys_allocator;
extern us_allocator_t *us_testutil_session_allocator;

#if US_ENABLE_PRINTING
extern us_print_t *us_testutil_printer_stdout;
extern us_print_t *us_testutil_printer_stderr;

#if US_ENABLE_STDIO
extern us_print_file_t us_testutil_printer_stdout_impl;
extern us_print_file_t us_testutil_printer_stderr_impl;
#else
extern us_printraw_t us_testutil_printer_stdout_impl;
extern us_printraw_t us_testutil_printer_stderr_impl;
extern char us_testutil_printbuffer_stdout[US_TESTUTIL_PRINTBUFFER_SIZE];
extern char us_testutil_printbuffer_stderr[US_TESTUTIL_PRINTBUFFER_SIZE];
#endif
#endif

#if US_ENABLE_MALLOC
extern us_malloc_allocator_t us_testutil_sys_allocator_impl;
#else
extern us_simple_allocator_t us_testutil_sys_allocator_impl;

extern int32_t us_testutil_sys_buffer[US_TESTUTIL_BUFFER_SIZE_IN_WORDS];
#endif
extern us_simple_allocator_t us_testutil_session_allocator_impl;
extern int32_t us_testutil_session_buffer[US_TESTUTIL_BUFFER_SIZE_IN_WORDS];

/*@}*/
#ifdef __cplusplus
}
#endif

#endif


text:
<?php

namespace frdl\ApplicationComposer;

class Download  extends \frdl\Crud {

		   const VERSION = '0.0.2';
		   const ALIAS = 'Downloads';

			# Your Table name
			protected $table = 'downloads';

			# Primary Key of the Table
			protected $pk	 = 'id';

			public function shema(){
				return array(
				  'version' => self::VERSION,
				  'schema' => "(
				      `id` BIGINT(255) NOT NULL  AUTO_INCREMENT,
				      `success` TINYINT(1) NOT NULL DEFAULT '0',
				      `unpacked` TINYINT(1) NOT NULL DEFAULT '0',
				      `lid` BIGINT(255) NOT NULL DEFAULT '0',
				      `id_version` BIGINT(255) NOT NULL DEFAULT '0',
				      `size` BIGINT(255) NOT NULL DEFAULT '0',
				      `protocoll` varchar(16) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
				      `type` varchar(8) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'zip',
				      `repos` varchar(64) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
				      `host`  varchar(256) COLLATE utf8_unicode_ci NOT NULL,
				      `vendor` varchar(128) COLLATE utf8_unicode_ci NOT NULL DEFAULT '' ,
				      `package` varchar(128) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
				      `version` varchar(64) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
				      `checksum` varchar(40) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
				      `time` INT(11) NOT NULL DEFAULT '0',
				      `time_download_start` INT(11) NOT NULL DEFAULT '0',
				      `time_download_end` INT(11) NOT NULL DEFAULT '0',
				      `note` varchar(512) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
				      `file` varchar(1024) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
				      `dir` varchar(1024) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
				       PRIMARY KEY (`id`)
				     )ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ",
				);
			}

	        public function field($label = null){
				$l = array(

				);
				if(null === $label){
					return $l;
				}

				return (isset($l[$label])) ? $l[$label] : null;
			}

			/*
	        public function label($field  = null){
				$f = array_flip($this->field(null));
				return (isset($f[$field])) ? $f[$field] : null;
			}
			*/
}


text:
package org.apache.camel.swagger;

import java.util.Collections;
import java.util.Locale;
import java.util.Map;

import io.swagger.jaxrs.config.BeanConfig;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.spi.RestConfiguration;
import org.apache.camel.support.PatternHelper;
import org.apache.camel.util.ObjectHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class RestSwaggerProcessor implements Processor {

    private static final Logger LOG = LoggerFactory.getLogger(RestSwaggerProcessor.class);
    private final BeanConfig swaggerConfig;
    private final RestSwaggerSupport support;
    private final String contextIdPattern;
    private final boolean contextIdListing;
    private final RestConfiguration configuration;

    @SuppressWarnings("unchecked")
    public RestSwaggerProcessor(String contextIdPattern, boolean contextIdListing, Map<String, Object> parameters, RestConfiguration configuration) {
        this.contextIdPattern = contextIdPattern;
        this.contextIdListing = contextIdListing;
        this.configuration = configuration;
        this.support = new RestSwaggerSupport();
        this.swaggerConfig = new BeanConfig();

        if (parameters == null) {
            parameters = Collections.EMPTY_MAP;
        }
        support.initSwagger(swaggerConfig, parameters);
    }

    @Override
    public void process(Exchange exchange) throws Exception {

        String contextId = exchange.getContext().getName();
        String route = exchange.getIn().getHeader(Exchange.HTTP_PATH, String.class);
        String accept = exchange.getIn().getHeader("Accept", String.class);

        RestApiResponseAdapter adapter = new ExchangeRestApiResponseAdapter(exchange);

        // whether to use json or yaml
        boolean json = false;
        boolean yaml = false;
        if (route != null && route.endsWith("/swagger.json")) {
            json = true;
            route = route.substring(0, route.length() - 13);
        } else if (route != null && route.endsWith("/swagger.yaml")) {
            yaml = true;
            route = route.substring(0, route.length() - 13);
        }
        if (accept != null && !json && !yaml) {
            json = accept.toLowerCase(Locale.US).contains("json");
            yaml = accept.toLowerCase(Locale.US).contains("yaml");
        }
        if (!json && !yaml) {
            // json is default
            json = true;
        }

        try {
            // render list of camel contexts as root
            if (contextIdListing && (ObjectHelper.isEmpty(route) || route.equals("/"))) {
                support.renderCamelContexts(adapter, contextId, contextIdPattern, json, yaml, configuration);
            } else {
                String name;
                if (ObjectHelper.isNotEmpty(route)) {
                    // first part is the camel context
                    if (route.startsWith("/")) {
                        route = route.substring(1);
                    }
                    // the remainder is the route part
                    name = route.split("/")[0];
                    if (route.startsWith(contextId)) {
                        route = route.substring(name.length());
                    }
                } else {
                    // listing not enabled then get current camel context as the name
                    name = exchange.getContext().getName();
                }

                boolean match = true;
                if (contextIdPattern != null) {
                    if ("#name#".equals(contextIdPattern)) {
                        match = name.equals(contextId);
                    } else {
                        match = PatternHelper.matchPattern(name, contextIdPattern);
                    }
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("Match contextId: {} with pattern: {} -> {}", name, contextIdPattern, match);
                    }
                }

                if (!match) {
                    adapter.noContent();
                } else {
                    support.renderResourceListing(exchange.getContext(), adapter, swaggerConfig, name, route, json, yaml,
                        exchange.getIn().getHeaders(), exchange.getContext().getClassResolver(), configuration);
                }
            }
        } catch (Exception e) {
            LOG.warn("Error rendering Swagger API due " + e.getMessage(), e);
        }
    }

}


text:
id: 587d7fa7367417b2b2512bc8
title: Add Classes with D3
required:
  - src: 'https://cdnjs.cloudflare.com/ajax/libs/d3/4.3.0/d3.min.js'
challengeType: 6
videoUrl: ''
localeTitle: ''
---

## Description
undefined

## Instructions
undefined

## Tests

```yml
tests:
  - text: ''
    testString: 'assert($("div").attr("class") == "bar", "Your <code>div</code> elements should have a class of <code>bar</code>.");'
  - text: ''
    testString: 'assert(code.match(/\.attr/g), "Your code should use the <code>attr()</code> method.");'

```

## Challenge Seed

```html
<style>
  .bar {
    width: 25px;
    height: 100px;
    display: inline-block;
    background-color: blue;
  }
</style>
<body>
  <script>
    const dataset = [12, 31, 22, 17, 25, 18, 29, 14, 9];

    d3.select("body").selectAll("div")
      .data(dataset)
      .enter()
      .append("div")
      // Add your code below this line

      // Add your code above this line
  </script>
</body>

```

## Solution

```js
// solution required
```


text:
package io.fabric8.kubernetes.api;

import io.fabric8.kubernetes.api.model.ReplicationControllerSchema;

/**
 */
public class PodIdToReplicationControllerIDExample {
    public static void main(String[] args) {
        if (args.length < 2) {
            System.out.println("Arguments: kuberneteMasterUrl podID");
            return;
        }
        String kuberneteMasterUrl = args[0];
        String podID = args[1];
        System.out.println("Looking up ReplicationController for pod ID: " + podID);
        KubernetesClient client = new KubernetesClient(kuberneteMasterUrl);
        ReplicationControllerSchema replicationController = client.getReplicationControllerForPod(podID);
        if (replicationController != null ){
            String id = replicationController.getId();
            System.out.println("Found replication controller: " + id);
        } else {
            System.out.println("Could not find replication controller!");
        }
    }
}


text:
<!--
 Copyright 2020 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

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

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-->
<AssignMessage name="AM.SetTargetAudience">
    <AssignVariable>
        <Name>gcp.target_audience</Name>
        <Value>https://example.apigee.com</Value>
    </AssignVariable>
    <IgnoreUnresolvedVariables>false</IgnoreUnresolvedVariables>
</AssignMessage>


text:
import struct

from .message import Message
from libbgp.net.family import Family

@Message.register
class CiscoRouteRefresh(Message):

    TYPE = Message.CISCO_ROUTE_REFRESH
    TYPE_STR = 'cisco-route-refresh'

    @classmethod
    def unpack(cls, data, length, capability):

        afi, res, safi = struct.unpack("!HBB", data)
        return cls(value=str(Family(afi, safi)), length=length)

    @classmethod
    def pack(cls, data, capability):
        afi, safi = Family.str_2_int(data)
        if afi and safi:
            msg_body = struct.pack('!H', afi) + b'\x00' + struct.pack('!B', safi)
            return cls(value=data, hex_value=msg_body)
        else:
            raise RuntimeError('AFI/SAFI error')


text:
from hazelcast.serialization.bits import *
from hazelcast.protocol.builtin import FixSizedTypesCodec
from hazelcast.protocol.client_message import OutboundMessage, REQUEST_HEADER_SIZE, create_initial_buffer, RESPONSE_HEADER_SIZE
from hazelcast.protocol.builtin import StringCodec

# hex: 0x040300
_REQUEST_MESSAGE_TYPE = 262912
# hex: 0x040301
_RESPONSE_MESSAGE_TYPE = 262913

_REQUEST_REGISTRATION_ID_OFFSET = REQUEST_HEADER_SIZE
_REQUEST_INITIAL_FRAME_SIZE = _REQUEST_REGISTRATION_ID_OFFSET + UUID_SIZE_IN_BYTES
_RESPONSE_RESPONSE_OFFSET = RESPONSE_HEADER_SIZE

def encode_request(name, registration_id):
    buf = create_initial_buffer(_REQUEST_INITIAL_FRAME_SIZE, _REQUEST_MESSAGE_TYPE)
    FixSizedTypesCodec.encode_uuid(buf, _REQUEST_REGISTRATION_ID_OFFSET, registration_id)
    StringCodec.encode(buf, name, True)
    return OutboundMessage(buf, True)

def decode_response(msg):
    initial_frame = msg.next_frame()
    return FixSizedTypesCodec.decode_boolean(initial_frame.buf, _RESPONSE_RESPONSE_OFFSET)


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Bull. Torrey bot. Club 10: 75 (1883)

#### Original name
Microsphaera nemopanthi Peck

### Remarks
null


text:
<?php

namespace Ivory\Tests\HttpAdapter\Event\Subscriber;

use Ivory\HttpAdapter\Event\Events;
use Ivory\HttpAdapter\Event\Subscriber\RetrySubscriber;
use Ivory\HttpAdapter\Message\InternalRequestInterface;

/**
 * Retry subscriber test.
 *
 * @author GeLo <geloen.eric@gmail.com>
 */
class RetrySubscriberTest extends AbstractSubscriberTest
{
    /** @var \Ivory\HttpAdapter\Event\Subscriber\RetrySubscriber */
    private $retrySubscriber;

    /** @var \Ivory\HttpAdapter\Event\Retry\RetryInterface|\PHPUnit_Framework_MockObject_MockObject */
    private $retry;

    /**
     * {@inheritdoc}
     */
    protected function setUp()
    {
        $this->retrySubscriber = new RetrySubscriber($this->retry = $this->createRetryMock());
    }

    /**
     * {@inheritdoc}
     */
    protected function tearDown()
    {
        unset($this->retry);
        unset($this->retrySubscriber);
    }

    public function testDefaultState()
    {
        $this->retrySubscriber = new RetrySubscriber();

        $this->assertInstanceOf('Ivory\HttpAdapter\Event\Retry\Retry', $this->retrySubscriber->getRetry());
    }

    public function testInitialState()
    {
        $this->assertSame($this->retry, $this->retrySubscriber->getRetry());
    }

    public function testSubscribedEvents()
    {
        $events = RetrySubscriber::getSubscribedEvents();

        $this->assertArrayHasKey(Events::REQUEST_ERRORED, $events);
        $this->assertSame(array('onRequestErrored', 0), $events[Events::REQUEST_ERRORED]);

        $this->assertArrayHasKey(Events::MULTI_REQUEST_ERRORED, $events);
        $this->assertSame(array('onMultiResponseErrored', 0), $events[Events::MULTI_REQUEST_ERRORED]);
    }

    public function testRequestErroredEventRetried()
    {
        $this->retry
            ->expects($this->once())
            ->method('retry')
            ->with($this->identicalTo($request = $this->createRequestMock()))
            ->will($this->returnValue($retryRequest = $this->createRequestMock()));

        $httpAdapter = $this->createHttpAdapterMock();
        $httpAdapter
            ->expects($this->once())
            ->method('sendRequest')
            ->with($this->identicalTo($retryRequest))
            ->will($this->returnValue($retryResponse = $this->createResponseMock()));

        $exception = $this->createExceptionMock($request);
        $exception
            ->expects($this->once())
            ->method('setRequest')
            ->with($this->identicalTo($retryRequest));

        $this->retrySubscriber->onRequestErrored($event = $this->createRequestErroredEvent($httpAdapter, $exception));

        $this->assertSame($retryResponse, $event->getResponse());
    }

    public function testRequestErroredEventRetriedThrowException()
    {
        $this->retry
            ->expects($this->once())
            ->method('retry')
            ->with($this->identicalTo($request = $this->createRequestMock()))
            ->will($this->returnValue($retryRequest = $this->createRequestMock()));

        $httpAdapter = $this->createHttpAdapterMock();
        $httpAdapter
            ->expects($this->once())
            ->method('sendRequest')
            ->with($this->identicalTo($retryRequest))
            ->will($this->throwException($exception = $this->createExceptionMock()));

        $this->retrySubscriber->onRequestErrored(
            $event = $this->createRequestErroredEvent($httpAdapter, $this->createExceptionMock($request))
        );

        $this->assertFalse($event->hasResponse());
        $this->assertSame($exception, $event->getException());
    }

    public function testRequestErroredEventNotRetried()
    {
        $this->retry
            ->expects($this->once())
            ->method('retry')
            ->with($this->identicalTo($request = $this->createRequestMock()))
            ->will($this->returnValue(false));

        $httpAdapter = $this->createHttpAdapterMock();
        $httpAdapter
            ->expects($this->never())
            ->method('sendRequest');

        $this->retrySubscriber->onRequestErrored($event = $this->createRequestErroredEvent(
            $httpAdapter,
            $this->createExceptionMock($request)
        ));

        $this->assertNull($event->getResponse());
    }

    public function testMultiRequestErroredEventRetried()
    {
        $requests = array(
            $request1 = $this->createRequestMock(),
            $request2 = $this->createRequestMock(),
        );

        $responses = array(
            $response1 = $this->createResponseMock($request1),
            $response2 = $this->createResponseMock($request2),
        );

        $exceptions = array(
            $this->createExceptionMock($request1, $response1),
            $this->createExceptionMock($request2, $response2),
        );

        $retryResponses = array($this->createResponseMock(), $this->createResponseMock());

        $this->retry
            ->expects($this->exactly(count($responses)))
            ->method('retry')
            ->will($this->returnValueMap(array(
                array($request1, false, $retryRequest1 = $this->createRequestMock()),
                array($request2, false, $retryRequest2 = $this->createRequestMock()),
            )));

        $httpAdapter = $this->createHttpAdapterMock();
        $httpAdapter
            ->expects($this->once())
            ->method('sendRequests')
            ->with($this->identicalTo(array($retryRequest1, $retryRequest2)))
            ->will($this->returnValue($retryResponses));

        $this->retrySubscriber->onMultiResponseErrored($event = $this->createMultiRequestErroredEvent($httpAdapter, $exceptions));

        $this->assertFalse($event->hasExceptions());
        $this->assertSame($retryResponses, $event->getResponses());
    }

    public function testMultiRequestErroredEventRetriedThrowException()
    {
        $requests = array(
            $request1 = $this->createRequestMock(),
            $request2 = $this->createRequestMock(),
        );

        $exceptions = array(
            $this->createExceptionMock($request1, $response1 = $this->createResponseMock($request1)),
            $this->createExceptionMock($request2, $response2 = $this->createResponseMock($request2)),
        );

        $this->retry
            ->expects($this->exactly(count($requests)))
            ->method('retry')
            ->will($this->returnValueMap(array(
                array($request1, false, $retryRequest1 = $this->createRequestMock()),
                array($request2, false, $retryRequest2 = $this->createRequestMock()),
            )));

        $httpAdapter = $this->createHttpAdapterMock();
        $httpAdapter
            ->expects($this->once())
            ->method('sendRequests')
            ->with($this->identicalTo(array($retryRequest1, $retryRequest2)))
            ->will($this->throwException($exception = $this->createMultiExceptionMock($exceptions)));

        $this->retrySubscriber->onMultiResponseErrored($event = $this->createMultiRequestErroredEvent($httpAdapter, $exceptions));

        $this->assertSame($exceptions, $event->getExceptions());
        $this->assertFalse($event->hasResponses());
    }

    public function testMultiRequestErroredEventNotRetried()
    {
        $responses = array(
            $this->createResponseMock($request1 = $this->createRequestMock()),
            $this->createResponseMock($request2 = $this->createRequestMock()),
        );

        $this->retry
            ->expects($this->exactly(count($responses)))
            ->method('retry')
            ->will($this->returnValueMap(array(
                array($request1, false, false),
                array($request2, false, false),
            )));

        $httpAdapter = $this->createHttpAdapterMock();
        $httpAdapter
            ->expects($this->never())
            ->method('sendRequests');

        $this->retrySubscriber->onMultiResponseErrored($event = $this->createMultiRequestErroredEvent(
            $httpAdapter,
            array($this->createExceptionMock($request1), $this->createExceptionMock($request2))
        ));
    }

    /**
     * {@inheritdoc}
     */
    protected function createResponseMock(InternalRequestInterface $internalRequest = null)
    {
        $response = parent::createResponseMock();
        $response
            ->expects($this->any())
            ->method('getParameter')
            ->with($this->identicalTo('request'))
            ->will($this->returnValue($internalRequest));

        return $response;
    }

    /**
     * Creates a retry mock.
     *
     * @return \Ivory\HttpAdapter\Event\Retry\RetryInterface|\PHPUnit_Framework_MockObject_MockObject The retry mock.
     */
    private function createRetryMock()
    {
        return $this->getMock('Ivory\HttpAdapter\Event\Retry\RetryInterface');
    }
}


text:
<?
$feeds = $this->FeedModel->getFeeds();
$items = array();
foreach($feeds as $feed) {
    $feedItems = $this->ItemModel->getFeedItems($feed->id);
    foreach($feedItems as $item) {
        $item->feed = $feed->title;
        array_push($items, $item);
    }
}
?>

<? // Actions  ?>

        <input type="hidden" ng-model="currentContent">

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean condimentum euismod enim, in dapibus arcu
                    ornare nec. Aliquam erat volutpat. Quisque id nunc vitae augue tempor sodales a non metus. Nullam euismod
                    nibh ligula. Nullam placerat ac tortor sed tempor. Phasellus aliquam vehicula erat, vel pharetra eros
                    vehicula sit amet. Maecenas orci erat, bibendum sed fringilla in, aliquam eu metus. Aliquam a magna est.
                    Vivamus ac ante suscipit, laoreet elit et, sollicitudin elit. Pellentesque sed augue eget eros accumsan gravida.

                    <input type="checkbox" id="chkAllItems" data-toggle="tooltip" data-placement="top" title="Check All">
                    Date
                    Title
                    Description
                    Feed
                    Author
                    Notifications

                <?
                foreach ($items as $item) {
                    echo "
id}' class='itemRow' data-toggle='context' data-target='#context-menu' title='Right-click for more actions'>";
                    echo "<input type='checkbox' class='itemCheckBox' value='{$item->id}'>	";
                    echo "" . $item->date . "	";
                    echo "" . limitCharacters($item->title) . "	";
                    echo "" . limitCharacters($item->description) . "	";
                    echo "" . $item->feed . "	";
                    echo "" . $item->author . "	";

                    if($item->notified) {
                        echo "Sent	";
                    } else {
                        echo "Not Sent	";
                    }
                    echo "
";
                }
                ?>

Edit

Delete


text:
title: L'API REST
id: tuto-5-the-rest-api
slug: 5-the-rest-api
---

Bien, pour l'instant, vous avez un frontend qui fonctionne correctement et quelques todos dans votre base de données. Il est maintenant temps de coder une API REST pour relier les deux.

Pour ce faire, vous allez utiliser un *contrôleur*. Les contrôleurs reçoivent les requêtes HTTP et les traitent. Ils peuvent appeler des *services* en arrière-plan pour les aider à le faire. Nous n'étudierons pas les services dans ce tutoriel.

Ouvrez le fichier `api.controller.ts` dans le répertoire `src/app/controllers/` et remplacez son contenu.

```typescript
import { Get, HttpResponseOK } from '@foal/core';

export class ApiController {

  @Get('/todos')
  getTodos() {
    const todos = [
      { id: 1, text: 'My task 1' },
      { id: 2, text: 'My task 2' }
    ];
    return new HttpResponseOK(todos);
  }

}
```
Les contrôleurs disposent de méthodes spéciales qui définissent les routes et leurs gestionnaires respectifs. Ces fonctions sont décorées par l'un des décorateurs `Get`, `Post`, `Patch`, `Put` ou `Delete` qui définissent la méthode HTTP et le chemin de la route.

Dans ce cas, le contrôleur répond avec un statut 200 et une donnée *mock* (les deux faux todos).

Rafraîchissez votre navigateur, vous devriez voir les deux todos affichés.

Maintenant, nous aimerions retourner les todos stockés dans la base de données. Mettez à jour le code comme suit :

```typescript
import {
  Context, Delete, Get, HttpResponseCreated, HttpResponseNoContent,
  HttpResponseNotFound, HttpResponseOK, Post
} from '@foal/core';

import { Todo } from '../entities';

export class ApiController {

  @Get('/todos')
  async getTodos() {
    const todos = await Todo.find();
    return new HttpResponseOK(todos);
  }

}
```

Si vous rafraîchissez votre navigateur, vous devriez maintenant voir les tâches que nous avons créées avec la ligne de commande.

Ajoutez les fonctionnalités de création et de suppression.

```typescript
  @Post('/todos')
  async postTodo(ctx: Context) {
    // Create a new todo with the body of the HTTP request.
    const todo = new Todo();
    todo.text = ctx.request.body.text;

    // Save the todo in the database.
    await todo.save();

    // Return the new todo with the id generated by the database. The status is 201.
    return new HttpResponseCreated(todo);
  }

  @Delete('/todos/:id')
  async deleteTodo(ctx: Context) {
    // Get the todo with the id given in the URL if it exists.
    const todo = await Todo.findOne({ id: ctx.request.params.id });

    // Return a 404 Not Found response if no such todo exists.
    if (!todo) {
      return new HttpResponseNotFound();
    }

    // Remove the todo from the database.
    await todo.remove();

    // Returns an successful empty response. The status is 204.
    return new HttpResponseNoContent();
  }
```

L'objet `Context`, qui est transmis à chaque gestionnaire de route, contient l'[objet requête d'Express](https://expressjs.com/en/4x/api.html#req). Celui-ci représente la requête HTTP et possède des propriétés pour les paramètres d'URL de la requête, son corps, ses en-têtes HTTP, etc.

Tapez maintenant un nouveau todo dans le champs de texte et appuyez sur Entrée. La tâche apparaît dans la liste des tâches. Rafraîchissez la page, elle devrait toujours y être. Si vous cliquez sur la case à cocher, le todo est supprimé avec succès.

La dernière chose à savoir est la manière dont l'`ApiController` est lié au gestionnaire de requêtes. Vous avez défini jusqu'à présent des routes dans ce contrôleur mais vous n'avez jamais lié le contrôleur nulle part. Cela se fait dans le fichier `app.controller.ts`, le point d'entrée de votre application.

Ouvrez le fichier `app.controller.ts` dans `src/app`.

```typescript
import { controller, IAppController } from '@foal/core';
import { createConnection } from 'typeorm';

import { ApiController } from './controllers';

export class AppController implements IAppController {
  subControllers = [
    controller('/api', ApiController),
  ];

  async init() {
    await createConnection();
  }
}
```

Ce contrôleur est le contrôleur principal de l'application. Il est directement appelé lorsqu'une requête est reçue. Il peut avoir des sous-contrôleurs qui vont dans le répertoire `controllers/`.


text:
<!DOCTYPE html>

    <meta charset="UTF-8" />


text:
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models

class Migration(SchemaMigration):

    def forwards(self, orm):
        # Adding model 'TwitterButtonPluginModel'
        db.create_table('cmsplugin_twitterbuttonpluginmodel', (
            ('cmsplugin_ptr', self.gf('django.db.models.fields.related.OneToOneField')(to=orm['cms.CMSPlugin'], unique=True, primary_key=True)),
            ('tweet_text', self.gf('django.db.models.fields.CharField')(default=None, max_length=60, blank=True)),
            ('hash_tag', self.gf('django.db.models.fields.CharField')(default=None, max_length=60, blank=True)),
            ('large_button', self.gf('django.db.models.fields.BooleanField')(default=False)),
        ))
        db.send_create_signal('twitter_button', ['TwitterButtonPluginModel'])

    def backwards(self, orm):
        # Deleting model 'TwitterButtonPluginModel'
        db.delete_table('cmsplugin_twitterbuttonpluginmodel')

    models = {
        'cms.cmsplugin': {
            'Meta': {'object_name': 'CMSPlugin'},
            'changed_date': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
            'creation_date': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2013, 2, 25, 0, 0)'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'language': ('django.db.models.fields.CharField', [], {'max_length': '15', 'db_index': 'True'}),
            'level': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
            'lft': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
            'parent': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['cms.CMSPlugin']", 'null': 'True', 'blank': 'True'}),
            'placeholder': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['cms.Placeholder']", 'null': 'True'}),
            'plugin_type': ('django.db.models.fields.CharField', [], {'max_length': '50', 'db_index': 'True'}),
            'position': ('django.db.models.fields.PositiveSmallIntegerField', [], {'null': 'True', 'blank': 'True'}),
            'rght': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
            'tree_id': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'})
        },
        'cms.placeholder': {
            'Meta': {'object_name': 'Placeholder'},
            'default_width': ('django.db.models.fields.PositiveSmallIntegerField', [], {'null': 'True'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'slot': ('django.db.models.fields.CharField', [], {'max_length': '50', 'db_index': 'True'})
        },
        'twitter-button.twitterbuttonpluginmodel': {
            'Meta': {'object_name': 'TwitterButtonPluginModel', 'db_table': "'cmsplugin_twitterbuttonpluginmodel'", '_ormbases': ['cms.CMSPlugin']},
            'cmsplugin_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['cms.CMSPlugin']", 'unique': 'True', 'primary_key': 'True'}),
            'hash_tag': ('django.db.models.fields.CharField', [], {'default': 'None', 'max_length': '60', 'blank': 'True'}),
            'large_button': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'tweet_text': ('django.db.models.fields.CharField', [], {'default': 'None', 'max_length': '60', 'blank': 'True'})
        }
    }

    complete_apps = ['twitter_button']