text:
<?php

/**
 * Description of AnalyseController
 * Contiendra toutes les functions concernant les analyses
 * @author BEBEL Jean Raynal
 */

namespace Inra2013\urzBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;

class AnalyseController extends Controller {

    //private $em;

    public function __construct() {

        // $this->em=  $this->getDoctrine()->getEntityManager();
    }

    /**
     * Description of SearchProtocole
     * Permet de recherche le protocole a partir de son id
     * à partir d'un champ input avec autocomplétion
     * @author BEBEL Jean Raynal
     */
    public function SearchProtocoleAction() {

        $request = $this->getRequest();
       $user = $this->container->get('security.context')->getToken()->getUser()->getFonction(); // on récupere la fonction de l'utilisateur connecté

        if ($request->isXmlHttpRequest()) {

            $id = $_REQUEST['id'];

            $array = $this->getDoctrine()->getEntityManager()->getRepository('Inra2013urzBundle:Protocole')->SearchProtocole($id);

            if (empty($array)) {
                $array = array(array("NomProtocole" => "Aucun protocole trouvé"));
            }
            $reponse = new Response(json_encode($array));
            $reponse->headers->set('content-Type', 'application/json');

            return $reponse;
        } elseif ($this->getRequest()->getMethod() == "POST") {

            $id = $request->get("idprotocole");
            $type = $request->get('demande');
            $typage=$request->get('typage');

print_r("Le protocole dans search ".$id);
            $Protocole = $this->getDoctrine()->getEntityManager()->getRepository('Inra2013urzBundle:Protocole')->findBy(array("id" => $id));

            $Analyse = $this->getDoctrine()->getEntityManager()->getRepository('Inra2013urzBundle:Protocole')->AnalyseProtocole($id);

            if ($type == "listing") {

                return $this->render("Inra2013urzBundle:Analyse:CreatExcel.html.twig", array("User" => $user,"protocole" => $Protocole, "Analyse" => $Analyse, 'form_path' => 'Inra2013Bundle_ImportListing', 'form_value' => 'Importer listing', 'type' => $type, 'protocole' => $Protocole));
            } elseif ($type == "createxcel") {
                return $this->render("Inra2013urzBundle:Analyse:CreatExcel.html.twig", array("User" => $user,"protocole" => $Protocole, "Analyse" => $Analyse, 'form_path' => 'Inra2013Bundle_CreateExcel', 'form_value' => 'Générer Fichier Excel', 'type' => $type, 'protocole' => $Protocole,"Typage"=>$typage));
            } elseif ($type == "createanalyse") {
                return $this->render("Inra2013urzBundle:Analyse:CreatExcel.html.twig", array("User" => $user,"protocole" => $Protocole, "Analyse" => $Analyse, 'form_path' => 'Inra2013Bundle_CudAnalyse', 'form_value' => 'Créer analyse', 'type' => $type, 'protocole' => $Protocole));
            } elseif ($type == "ImportResultat") {
                return $this->render("Inra2013urzBundle:Analyse:CreatExcel.html.twig", array("User" => $user,"protocole" => $Protocole, "Analyse" => $Analyse, 'form_path' => 'Inra2013Bundle_ImportResultat', 'form_value' => 'Importer Resultat', 'type' => $type, 'protocole' => $Protocole));
            } elseif ($type == "UpdateAnalyse") {
                return $this->render("Inra2013urzBundle:Analyse:CreatExcel.html.twig", array("User" => $user,"protocole" => $Protocole, "Analyse" => $Analyse, 'form_path' => 'Inra2013Bundle_CudAnalyse', 'form_value' => 'Modification Resultat', 'type' => $type, 'protocole' => $Protocole));
            } elseif ($type == "voiranalyse") {
                return $this->render("Inra2013urzBundle:Analyse:CreatExcel.html.twig", array("User" => $user,"protocole" => $Protocole, "Analyse" => $Analyse, 'form_path' => 'Inra2013Bundle_VoirAnalyse', 'form_value' => 'Voir Resultat', 'type' => $type, 'protocole' => $Protocole));
            } elseif ($type == "voiranalyseChercheur") {
                return $this->render("Inra2013urzBundle:Analyse:CreatExcel.html.twig", array("User" => $user, "protocole" => $Protocole, "Analyse" => $Analyse, 'form_path' => 'Inra2013Bundle_VoirAnalyseChercheur', 'form_value' => 'Voir Resultat', 'type' => $type, 'protocole' => $Protocole));
            }
        }
    }

    /**
     * Description of SearchAnalyseCategorie
     * Permet de recherche à partir du type de categorie,les categorie d'analyse associés
     * renvoie un json.
     * page utilisé:Creer un protocole
     * @author BEBEL Jean Raynal
     */
    public function SearchAnalyseCategorieAction() {

        $request = $this->get('request');

        if ($request->isXmlHttpRequest()) {

            // $id = $request->request->get('id');
            $id = $_REQUEST['id'];
            $array = $this->getDoctrine()->getEntityManager()->getRepository('Inra2013urzBundle:CategorieAnalyse')->SearchCategorieAnalyse($id);

            $reponse = new Response(json_encode($array));

            $reponse->headers->set('content-Type', 'application/json');
            return $reponse;
        }
    }

    /**
     * Description of SearchTypeAnalyse
     * Permet de recherche à partir du type d'analyse qui est associe a une catégorie
     * renvoie un json.
     * page utilisé:Creer un protocole
     * @author BEBEL Jean Raynal
     */
    public function SearchTypeAnalyseAction() {

        $request = $this->get('request');

        if ($request->isXmlHttpRequest()) {
            $id = $_REQUEST['id'];
            // $id = $request->request->get('id');
            $array = $this->getDoctrine()->getEntityManager()->getRepository('Inra2013urzBundle:TypeAnalyse')->SearchTypeAnalyse($id);
            $reponse = new Response(json_encode($array));
            $reponse->headers->set('content-Type', 'application/json');
            return $reponse;
        }
    }

    public function SearchChampAction() {

        $request = $this->get('request');

        if ($request->isXmlHttpRequest()) {
            $id = $_REQUEST['id'];
            // $id = $request->request->get('id');
            $array = $this->getDoctrine()->getEntityManager()->getRepository('Inra2013urzBundle:TypeAnalyse')->SearchChamp($id);
            $reponse = new Response(json_encode($array));
            $reponse->headers->set('content-Type', 'application/json');
            return $reponse;
        }
    }

    /**
     * Description of ValidAnalyse
     * Permet de valider un protocole par un laboratin
     * @author BEBEL Jean Raynal
     */
    function ValidAnalyseAction() {

        $NumProtocole = $this->get('request')->get('NumProtocole');
        $Status = $this->get('request')->get('Status');
        $Commentaire = $this->get('request')->get('Commentaire');
        $responsable = $this->container->get('security.context')->getToken()->getUser();
        /**
         * 3 etats:1 pour validation,2 pour en cours,3 pour refusée
         *
         * * */
        $em = $this->getDoctrine()->getManager();  // On récupére l'EntityManager
        /*         * On cherche le protocole avec son Id* */
        $criteria = array('id' => $NumProtocole);
        $Protocole = $this->getDoctrine()->getEntityManager()->getRepository('Inra2013urzBundle:Protocole')->findBy($criteria);
        $Protocole[0]->setValidation($Status);
        if ($Status == 2) {
            $Protocole[0]->setCommentaire($Protocole[0]->getCommentaire()); // si le commentaire est null
        } else {
            $Protocole[0]->setCommentaire($Commentaire . " Editer par " . $responsable->getPrenom() . " " . $responsable->getNom());
        }
        $em->persist($Protocole[0]);
        $em->flush();
        $this->MailerAction($Protocole);
        return $this->render('Inra2013urzBundle:Analyse:Save.html.twig', array('Status' => $Protocole[0]->getValidation()));
    }

    /**
     * Description of CreateProtocole
     * Permet de Créer un protocole
     * @author BEBEL Jean Raynal
     */
    function CreateProtocoleAction() {

        /*         * On crée le formulaire pour la création du protocole* */
        $typeProtocole = new \Inra2013\urzBundle\Entity\Protocole;
        $responsable = $this->container->get('security.context')->getToken()->getUser();
        $typeProtocole->setResponsable($responsable);
        $typeProtocole->setValidation(FALSE);
        $typeProtocole->setDateValidationAnalyse(NULL);
        $TypeCategorie = $this->getDoctrine()->getRepository("Inra2013urzBundle:TypeCategorie")->findAll();
        //\Doctrine\Common\Util\Debug::dump($CategorieAnalyse); //les champs

        $form = $this->createForm(
                new \Inra2013\urzBundle\Form\ProtocoleType(), $typeProtocole);
        /*         * On crée le formulaire pour les analyse a faire dans le protocole* */
        $request = $this->get('request');
        if ($request->getMethod() == 'POST') {

            /*             * On enregistre les analyses pour le protocole * */

            $form->bind($request);
            if ($form->isValid()) {
                $Protocole = $this->getDoctrine()->getEntityManager()->getRepository('Inra2013urzBundle:Protocole')->find($typeProtocole->getNomProtocole());

                $em = $this->getDoctrine()->getEntityManager();
                $choix_analyse = $this->get('request')->get('choix_analyse');

                foreach ($choix_analyse as $i => $choix) {

                    $ProtocoleAnalyse[$i] = new \Inra2013\urzBundle\Entity\ProtocoleAnalyse;
                    $ProtocoleAnalyse[$i]->setProtocole($typeProtocole);
                    $TypeAnalyse = $this->getDoctrine()->getEntityManager()->getRepository('Inra2013urzBundle:TypeAnalyse')->findBy(array("id" => $choix));
                    $ProtocoleAnalyse[$i]->setProtocole($typeProtocole);

                    $ProtocoleAnalyse[$i]->setTypeAnalyse($TypeAnalyse[0]);
                    $em->persist($ProtocoleAnalyse[$i]);
                }

                $em->persist($typeProtocole);

                $em->flush(); //on sauvegarde le tous

                return $this->render("Inra2013urzBundle:Analyse:CreateProtocole.html.twig", array('Status' => 'Save', 'Num' => $typeProtocole->getNomProtocole()));
            }
        }
        return $this->render("Inra2013urzBundle:Analyse:CreateProtocole.html.twig", array('form' => $form->createView(), "TypeCategorie" => $TypeCategorie));
    }

    /**
     * Description of CreateAnalyse
     * Permet de rentrer les analyses pour un protocole donnée
     * @author BEBEL Jean Raynal
     */
    function CreateAnalyseAction() {

        $Status = $this->get('request')->get('Status');
        $user = $this->container->get('security.context')->getToken()->getUser(); // on récupere la fonction de l'utilisateur connecté
        $numProtocole = $this->get('request')->get('NumProtocole');
        $ResultTypeAnalyse = $this->getDoctrine()->getEntityManager()->getRepository('Inra2013urzBundle:Protocole')->AnalyseProtocole($numProtocole);
        $em = $this->getDoctrine()->getManager();  // On récupére l'EntityManager

        if ($this->getRequest()->getMethod() == 'GET') {  //si c est un GET alors on affiche le formulaire de recherche du protocole
            return $this->render('Inra2013urzBundle:Analyse:CreatExcel.html.twig', array('type' => 'createanalyse'));
        } else if ($this->getRequest()->getMethod() == 'POST') {

            /*             * On fait l'enregistrement des valeurs saisie pour les resultats(stade final du formulaire)* */

            if ($Status == "Enregistrer") {

                $numProtocole = $this->get('request')->get('NumProtocole');
                $ResultTypeAnalyse = $this->getDoctrine()->getEntityManager()->getRepository('Inra2013urzBundle:Protocole')->AnalyseProtocole($numProtocole);

                /*                 * **On crée l'objet pour l'enregistrement*
                 * $ResultTypeAnalyse renvoie les différents type analyse qui sont pour le protocole(Ex:Eosinophile,OPG,PVC)
                 *
                 *  ** */
                foreach ($ResultTypeAnalyse as $value) {

                    /*                     * Pour chaque analyse* */

                    $CodeLabo = $this->getDoctrine()->getEntityManager()->getRepository('Inra2013urzBundle:Protocole')->CodeLaboProtocole($value['Nom'], $numProtocole);

                    /*                     * Faut rechercher les champs pour les différent analyse(Ex: pour Eosino,il y a deux champs EosinoVal et EosinoLu)* */
                    $ChampsAnalyse = $this->getDoctrine()->getEntityManager()->getRepository('Inra2013urzBundle:TypeAnalyse')->findBy(array("Nom" => $value['Nom']));

                    /*                     * On a les valeurs des champs de chaque analyse* */

                    foreach ($CodeLabo as $result) {

                        /*                         * ***if la valeur du $POST[Codelabo] est vide,c'est que la valeur n'a pas été rentrer** */

                        $Analyse = $this->getDoctrine()->getEntityManager()->getRepository('Inra2013urzBundle:Ana' . $value['Nom'])->findBy(array("CodeLabo" => $result->getCodeLabo()));

                        /*                         * *A partir des valeurs recu, on recupere par rapport au champs(Ex:$_POST[EsoinoVal]* */
                        /*                         * Ce sont les champs spécifiques à chaque analyse* */

                        foreach ($ChampsAnalyse[0]->getChamps() as $po) {

                            //les champs
                            if (isset($_POST[$po->getChamp()])) { // on persist pas si le tableau de donnée est vide(pas de valeur rentré dans le formulaire)

                                /*                                 * Il faut regardé si le champ qui contient les valeurs n"est pas vide* */

                                $ValeurChamps = $_POST[$po->getChamp()]; //récupere le tableau de valeur pour le champ s en question

                                if (!empty($ValeurChamps[$result->getCodeLabo()->getCodeLabo()])) {

                                    /*
                                     *           * Ce sont les champs qui sont recurent dans les analyses* */
                                    $Analyse[0]->setCodeLabo($result->getCodeLabo());
                                    $Analyse[0]->setUser($user);

                                    $champs = "set" . $po->getChamp(); //set du champs
                                    $Analyse[0]->$champs($ValeurChamps[$result->getCodeLabo()->getCodeLabo()]);
                                }
                            }
                        }
                    }
                }
                /*                 * *On persit l'objet et on sauvegarde le tout ** */
                $em->persist($Analyse[0]);
                $em->flush();

                return $this->render("Inra2013urzBundle:Analyse:Save.html.twig", array("Status" => "SaveAnalyse"));
            }

            return $this->CudAction($numProtocole);
        }
    }

    public function VoirAnalyseAction() {

        $numProtocole = $this->getRequest()->get('NumProtocole');

        if ($this->getRequest()->getMethod() == 'GET' && !isset($numProtocole)) {  //si c est un GET alors on affiche le formulaire de recherche de protocole
            return $this->render("Inra2013urzBundle:Analyse:CreatExcel.html.twig", array('type' => 'voiranalyse'));
        } elseif ($this->getRequest()->getMethod() == 'POST' || isset($numProtocole)) {

            $Status = $this->get('request')->get('demande');

            $ResultTypeAnalyse = $this->getDoctrine()->getEntityManager()->getRepository('Inra2013urzBundle:Protocole')->AnalyseProtocole($numProtocole);
            $User = $this->container->get('security.context')->getToken()->getUser();

            $Protocole = $this->getDoctrine()->getEntityManager()->getRepository("Inra2013urzBundle:Protocole")->findBy(array('id' => $numProtocole));

            /*             * On crée les formulaires pour les différents type d'analyse* */
            /*             * Une boucle pour créer les formulaires des types analyses * */

            foreach ($ResultTypeAnalyse as $Champs) {

                $CodeLabo[$Champs['Nom']] = array();
                $ResultCodeLabo = $this->getDoctrine()->getEntityManager()->getRepository('Inra2013urzBundle:Protocole')->CodeLaboProtocole($Champs['Nom'], $numProtocole);
                // \Doctrine\Common\Util\Debug::dump($ResultTypeAnalyse);
                $CodeLabo[$Champs['Nom']] = $ResultCodeLabo;

                //$formtype = $this->createForm(
                //       new \Inra2013\urzBundle\Form\AnaOPGType(), $form);
                //  $CodeLabo[$value['Nom']] = $ResultCodeLabo;
                $ChampsId[$Champs['Nom']] = $this->getDoctrine()->getEntityManager()->getRepository('Inra2013urzBundle:Champ')->FindChampAnalyse($Champs['id']);
            }
            // \Doctrine\Common\Util\Debug::dump( $CodeLabo["OPG"]);
            return $this->render("Inra2013urzBundle:Analyse:VoireAnalyse.html.twig", array('Resultat' => $ResultCodeLabo, 'TypeAnalyse' => $ResultTypeAnalyse, 'ResultatCodeLabo' => $CodeLabo, 'Champs' => $ChampsId, 'NumProtocole' => $numProtocole, 'Protocole' => $Protocole, 'Role' => $User->getRoles(), 'type' => $Status));
        }
    }

    public function VoirAnalyseChercheurAction() {

        $numProtocole = $this->getRequest()->get('NumProtocole');
        if ($this->getRequest()->getMethod() == 'GET' && !isset($numProtocole)) {  //si c est un GET alors on affiche le formulaire de recherche de protocole

            return $this->render("Inra2013urzBundle:Analyse:CreatExcel.html.twig", array('type' => 'voiranalyseChercheur', 'User' => 'Chercheur'));
        }
        else
            $ResultTypeAnalyse = $this->getDoctrine()->getEntityManager()->getRepository('Inra2013urzBundle:Protocole')->AnalyseProtocole($numProtocole);
        foreach ($ResultTypeAnalyse as $Champs) {

            $CodeLabo[$Champs['Nom']] = array();
            $ResultCodeLabo = $this->getDoctrine()->getEntityManager()->getRepository('Inra2013urzBundle:Protocole')->CodeLaboProtocole($Champs['Nom'], $numProtocole);

            $CodeLabo[$Champs['Nom']] = $ResultCodeLabo;

            $ChampsId[$Champs['Nom']] = $this->getDoctrine()->getEntityManager()->getRepository('Inra2013urzBundle:Champ')->FindChampAnalyse($Champs['id']);
        }
        return $this->render('Inra2013urzBundle:Analyse:VoirAnalyseCherch.html.twig', array('Resultat' => $ResultCodeLabo, 'TypeAnalyse' => $ResultTypeAnalyse, 'ResultatCodeLabo' => $CodeLabo, 'Champs' => $ChampsId, 'NumProtocole' => $numProtocole));
    }

    public function CudAnalyseAction() {

        $numProtocole = $this->getRequest()->get('numProtocole');

        if ($this->getRequest()->getMethod() == "GET" && !isset($numProtocole)) {

            //si c est un GET alors on affiche le formulaire de recherche du protocole

            return $this->render('Inra2013urzBundle:Analyse:CreatExcel.html.twig', array('type' => 'UpdateAnalyse'));
        }

        $Status = $this->getRequest()->get('demande');
        $Save = $this->getRequest()->get('Save');
        $ResultTypeAnalyse = $this->getDoctrine()->getEntityManager()->getRepository('Inra2013urzBundle:Protocole')->AnalyseProtocole($numProtocole);
        $User = $this->container->get('security.context')->getToken()->getUser();

        $Protocole = $this->getDoctrine()->getEntityManager()->getRepository("Inra2013urzBundle:Protocole")->findBy(array('id' => $numProtocole));

        /*         * On crée les formulaires pour les différents type d'analyse* */
        /*         * Une boucle pour créer les formulaires des types analyses * */

        $type = new
                \Inra2013\urzBundle\Entity\Analyse();
        $form = $this->createFormBuilder($type);

        foreach ($ResultTypeAnalyse as $Champs) {

            $ResultCodeLabo = $this->getDoctrine()->getEntityManager()->getRepository('Inra2013urzBundle:Protocole')->CodeLaboProtocole($Champs['Nom'], $numProtocole);
            // \Doctrine\Common\Util\Debug::dump($ResultTypeAnalyse);
            // $CodeLabo[$Champs['Nom']] = $ResultCodeLabo;

            $CodeLabo[$Champs['Nom']] = array();
            foreach ($ResultCodeLabo as $value) {
                $champs = $this->getDoctrine()->getEntityManager()->getRepository('Inra2013urzBundle:Ana' . $Champs['Nom'])->find($value->getCodeLabo());
                $addChamps = "addChamps" . $Champs['Nom'];
                //  \Doctrine\Common\Util\Debug::dump($value->getCodeLabo());
                //     $type= $this->getDoctrine()->getEntityManager()->getRepository('Inra2013urzBundle:Analyse')->find($value->getCodeLabo());
                //    $type = $this->getDoctrine()->getEntityManager()->getRepository('Inra2013urzBundle:Analyse')->find($value->getCodeLabo());
                //$type->setCodeLabo($value->getCodeLabo());
                if ($Status == "UpdateAnalyse") {

                    array_push($CodeLabo[$Champs['Nom']], $value->getCodeLabo());
                    $type->setCodeLabo($value->getCodeLabo());
                    $type->$addChamps($champs);
                } else {

                    if (!$champs->getUser()) {

                        array_push($CodeLabo[$Champs['Nom']], $value->getCodeLabo());

                        $type->$addChamps($champs);
                    }
                }
            }
            //$formtype = $this->createForm(
            //       new \Inra2013\urzBundle\Form\AnaOPGType(), $form);
            //  $CodeLabo[$value['Nom']] = $ResultCodeLabo;
            $ChampsId[$Champs['Nom']] = $this->getDoctrine()->getEntityManager()->getRepository('Inra2013urzBundle:Champ')->FindChampAnalyse($Champs['id']);

            $Anatype = "\Inra2013\urzBundle\Form\Ana" . $Champs["Nom"] . "Type";
            $Anatype1 = "\Inra2013\urzBundle\Form\AnaOPGType";
            $Anatype2 = "\Inra2013\urzBundle\Form\AnaEosinophileType";
            $Anatype3 = "\Inra2013\urzBundle\Form\AnaPCVType";

            $champsType = "Champs" . $Champs["Nom"];
            $champsType1 = "ChampsOPG";
            $champsType2 = "ChampsEosinophile";
            $champsType3 = "ChampsPCV";
            // print_r("Formuilaire=>".$Anatype."<br>");
            // print_r("Formuilaire=>".$champsType."<br>");
            //         print_r("je fais le formulaire pour ".$Champs["Nom"]."<br>");

            $form->add($champsType, 'collection', array(
                'type' => new $Anatype(),
                'data_class' => NULL,
                'allow_add' => true,
                'by_reference' => false,
                'attr' => array('label' => 'Juniro ')
            ));
        }

        if ($this->get('request')->getMethod() == 'POST' && $Save == "Save") {

            $em = $this->getDoctrine()->getEntityManager();
            $request = $this->get('request');

            $formulaire = $form->getForm()->bind($request);

            if ($formulaire->isValid()) {

                foreach ($ResultTypeAnalyse as $Champs) {

                    $getChamps = "getChamps" . $Champs['Nom'];
                    $ChampsAna = "Champs" . $Champs['Nom'];

                    $ChampsAll = $this->getDoctrine()->getEntityManager()->getRepository('Inra2013urzBundle:Champ')->FindChampAnalyse($Champs['id']);
                    $ChampsId = $this->getDoctrine()->getEntityManager()->getRepository('Inra2013urzBundle:Champ')->FindChampAnalyseNot($Champs['id']);
                    $ChampsIdCalcule = $this->getDoctrine()->getEntityManager()->getRepository('Inra2013urzBundle:Champ')->FindChampsCalcule($Champs['id']);

                    foreach ($type->$getChamps() as $value) {  //recupere les champs
                        $countChampsnull = 0;
                        $Lettre = 'A';
                        $tableau = array();
                        foreach ($ChampsId as $ChampsAnalyse) {
                            /*                             * **********On enregistre un utilisateur si et seulment si tout les champs de l analyse soit rempli,Compteur de valeur avec compteur de champs vide ou pas ************** */
                            $champsanalyse = "get" . $ChampsAnalyse['Champ'];

                            if (!is_null($value->$champsanalyse())) {
                                $tableau[$Lettre] = ($value->$champsanalyse()); //On enregistre les valeur dans le tableau afin de faire le calcule
                                $countChampsnull++;
                                ++$Lettre;
                            }

                            //      \Doctrine\Common\Util\Debug::dump($value->$champsanalyse());
                            //  print_r("Le champsId est de " . count($ChampsId) . "alors que le countChampsnull est de" . $countChampsnull . "<br>");
                            if (count($ChampsId) == $countChampsnull) {
                                /*                                 * *****On fait le calcul pour les champs calcule car on sait cas se stade tout les champs sont renseigné ******* */

                                /*                                 * Attribution des variable pour champs
                                  foreach ($ChampsAll as $resultat) {
                                  $champsanalyse = $resultat->getChamp();

                                  $tableau[$Lettre] = $resultat->getChamp();
                                  }
                                 * * */
                                $setChampsCalcule = "set" . $ChampsIdCalcule[0]->getChamp();
                                $Formule = $this->getDoctrine()->getEntityManager()->getRepository('Inra2013urzBundle:Formule')->FindOneBy(array('Champs' => $ChampsIdCalcule[0]->getId()));
                               if(!is_null($Formule)){
                                $formulMath = $Formule->getFormuMath();
                             //   \Doctrine\Common\Util\Debug::dump($formulMath);
                                eval($formulMath);
                                    $value->$setChampsCalcule($resultat);
                               }
                                //   eval('$p=($tableau["A"]+$tableau["B"])*1200;');
                             //   \Doctrine\Common\Util\Debug::dump($resultat);

                                $value->setUser($User);
                            }
                        }
                    }
                    //print_r("<br>");
                }
                //   \Doctrine\Common\Util\Debug::dump($champs);
                $em->persist($champs);
                $em->flush();

                // return new response('je fauis l essau  ' . $Status);
                return $this->redirect($this->generateUrl('Inra2013Bundle_Save', array("Status" => "SaveAnalyse")));
            }

          //  return $this->render("Inra2013urzBundle:Analyse:CreateAnalyse.html.twig", array('form' => $form->getForm()->createView(), 'Resultat' => $ResultCodeLabo, 'TypeAnalyse' => $ResultTypeAnalyse, 'ResultatCodeLabo' => $CodeLabo, 'Champs' => $ChampsId, 'NumProtocole' => $numProtocole, 'Protocole' => $Protocole, 'Role' => $User->getRoles(), 'type' => $Status));
        }

        return $this->render("Inra2013urzBundle:Analyse:CreateAnalyse.html.twig", array('form' => $form->getForm()->createView(), 'Resultat' => $ResultCodeLabo, 'TypeAnalyse' => $ResultTypeAnalyse, 'ResultatCodeLabo' => $CodeLabo, 'Champs' => $ChampsId, 'NumProtocole' => $numProtocole, 'Protocole' => $Protocole, 'Role' => $User->getRoles(), 'type' => $Status));

        //return $this->render("Inra2013urzBundle:Analyse:CreateAnalyse.html.twig", array('Resultat' => $ResultCodeLabo, 'TypeAnalyse' => $ResultTypeAnalyse, 'ResultatCodeLabo' => $CodeLabo, 'Champs' => $Champs, 'NumProtocole' => $numProtocole, 'Protocole' => $Protocole, 'Role' => $User[0], 'type' => $type));
    }

    public function MailerAction($Protocole) {

        $user = $this->container->get('security.context')->getToken()->getUser(); // on récupere la fonction de l'utilisateur connecté

        if ($Protocole[0]->getValidation() == 1) {

            $Subject = "Demande de validation pour le protocole " . $Protocole[0]->getNomProtocole() . " dirigé par" . $Protocole[0]->getResponsable()->getNom() . "  " . $Protocole[0]->getResponsable()->getPrenom();
        } elseif ($Protocole[0]->getValidation() == 3) {

            $Subject = "Demande de Refus pour le protocole " . $Protocole[0]->getNomProtocole() . " dirigé par" . $Protocole[0]->getResponsable()->getNom() . "  " . $Protocole[0]->getResponsable()->getPrenom();
        } elseif ($Protocole[0]->getValidation() == 2) {

            $Subject = "Validation du protocole " . $Protocole[0]->getNomProtocole() . " dirigé par" . $Protocole[0]->getResponsable()->getNom() . "  " . $Protocole[0]->getResponsable()->getPrenom();
        }

        $From = $user->getemail();
        $To = "jeanraynal.bebel@gmail.com";
        $body = "essai";
        $message = \Swift_Message::newInstance()
                ->setSubject($Subject)
                ->setFrom($From)
                ->setTo($To)
                ->setBody($this->renderView("Inra2013urzBundle:Analyse:Email.html.twig", array("Protocole" => $Protocole)));
        $this->get('mailer')->send($message);
        //return new Response('message a ete envoyé ');
    }

    public function CreateAnalyseBddAction() {

        $typeCategorie = new \Inra2013\urzBundle\Entity\TypeCategorie();
        $formtypeCategorie = $this->createForm(
                new \Inra2013\urzBundle\Form\TypeCategorieType(), $typeCategorie);
        $CategorieAnalyse = new \Inra2013\urzBundle\Entity\CategorieAnalyse();
        $formCategorieAnalyse = $this->createForm(
                new \Inra2013\urzBundle\Form\CategorieAnalyseType(), $CategorieAnalyse);
        $typeAnalyse = new \Inra2013\urzBundle\Entity\TypeAnalyse();
        $formtypeAnalyse = $this->createForm(
                new \Inra2013\urzBundle\Form\TypeAnalyseType(), $typeAnalyse);
        $Champ = new \Inra2013\urzBundle\Entity\Champ();
        $formChamp = $this->createForm(
                new \Inra2013\urzBundle\Form\ChampType(), $Champ);

        if ($this->get('request')->getMethod() == 'GET') {

            return $this->render("Inra2013urzBundle:Analyse:CreateTypeAnalyse.html.twig", array('form_Categorie' => $formtypeCategorie->createView(),
                        'form_CategorieAnalyse' => $formCategorieAnalyse->createView(), 'form_Champ' => $formChamp->createView(), 'form_Analyse' => $formtypeAnalyse->createView()));
        } elseif ($this->get('request')->getMethod() == 'POST') {
            $request = $this->get('request');
            $typeForm = $request->get('typeForm');
            $em = $this->getDoctrine()->getEntityManager();

            if ($typeForm == "Categorie") {
                $formtypeCategorie->bind($request);
                $TypeCategorie = $this->getDoctrine()->getEntityManager()->getRepository('Inra2013urzBundle:TypeCategorie')->FindBy(array("Nom" => $typeCategorie->getNom()));

                if ($formtypeCategorie->isValid() && !$TypeCategorie) {

                    $em->persist($typeCategorie);
                    $em->flush();
                    return $this->redirect($this->generateUrl('Inra2013Bundle_Save', array("Status" => "TypeCategorie")));
                } else {
                    return $this->redirect($this->generateUrl('Inra2013Bundle_Save', array("Status" => "TypeCategorieError")));
                }
            } elseif ($typeForm == "CategorieAnalyse") {

                $formCategorieAnalyse->bind($request);

                $categorieAnalyse = $this->getDoctrine()->getEntityManager()->getRepository('Inra2013urzBundle:CategorieAnalyse')->FindBy(array("Nom" => $CategorieAnalyse->getNom()));

                if ($formCategorieAnalyse->isValid() && !$categorieAnalyse) {

                    $em->persist($CategorieAnalyse);
                    $em->flush();
                    return $this->redirect($this->generateUrl('Inra2013Bundle_Save', array("Status" => "CategorieAnalyse")));
                } else {
                    return $this->redirect($this->generateUrl('Inra2013Bundle_Save', array("Status" => "CategorieAnalyseError")));
                }
            } elseif ($typeForm == "Analyse") {

                $formtypeAnalyse->bind($request);

                $TypeAnalyse = $this->getDoctrine()->getEntityManager()->getRepository('Inra2013urzBundle:TypeAnalyse')->FindBy(array("Nom" => $typeAnalyse->getNom()));

                if ($formtypeAnalyse->isValid() && !$TypeAnalyse) {

                    foreach ($typeAnalyse->getChamps() as $value) {

                        $value->setAnalyse($typeAnalyse);
                    }

                    $em->persist($typeAnalyse);
                    $em->flush();
                    $this->GenerationAnalyse($typeAnalyse);
                    return $this->redirect($this->generateUrl('Inra2013Bundle_Save', array("Status" => "Analyse")));
                } else {

                    return $this->redirect($this->generateUrl('Inra2013Bundle_Save', array("Status" => "AnalyseError")));
                }
            }
        }
    }

    public function GenerationAnalyse($Entity) {

        /*         * ******On crée un fichier dans le dossier entity******* */
        $path = dirname(__FILE__) . "/../Entity";
        $fichier = fopen($path . "/Ana" . $Entity->getNom() . ".php", "w");
        /*         * *On rentre les information voulue comme les champs etc ** */
        $Champs = "";
        foreach ($Entity->getChamps() as $value) {
            $Champs .= ' /**
     * @var integer
     *
     * @ORM\Column(name="' . $value->getChamp() . '", type="integer", nullable=true)
     */
    private $' . $value->getChamp() . '; ';
        }
        ;
        fwrite($fichier, '<?php

namespace Inra2013\urzBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * AnaEssai
 *
 * @ORM\Table()
 * @ORM\Entity
 */
class Ana' . $Entity->getNom() . '
{
      /**
     * @ORM\Id
     * @ORM\ManyToOne(targetEntity="Inra2013\urzBundle\Entity\Analyse")
     * @ORM\JoinColumn(name="CodeLabo", referencedColumnName="CodeLabo")
     */
    private $CodeLabo;

' . $Champs . '

  /**
     *  *@ORM\ManyToOne(targetEntity="Inra2013\urzBundle\Entity\User")
     *
     */
    private $User;

    /**
     * Get id
     *
     * @return integer
     */

     }');

        /*         * *************On crée le champs dans le fichier entity analyse******************* */

        $ChampsAnalyse = "";
        $TypeAnalyse = $this->getDoctrine()->getEntityManager()->getRepository('Inra2013urzBundle:TypeAnalyse')->FindAll();

        foreach ($TypeAnalyse as $valeur) {

            $ChampsAnalyse.='       /**
    * @Assert\Collection(
     *     fields = {
     *       ';

            $ChampsTypeAnalyse = $this->getDoctrine()->getEntityManager()->getRepository('Inra2013urzBundle:Champ')->FindBy(array('Analyse' => $valeur->getId()));

            foreach ($ChampsTypeAnalyse as $value) {

                $ChampsAnalyse.='
     *         "' . $value->getChamp() . '" = {
     *
     *             @Assert\Type(
     *                 type = "integer",message="I pa bon"
     *
     *             ),
     *             @Assert\Max(limit = "5", message = "The max value for the note is 5")
     *         },
     *
  ';
            }
            $ChampsAnalyse.='
     *            },
     *     allowMissingFields = true,
     *     allowExtraFields = true
     * )
     *
     * @ORM\OneToMany(targetEntity ="Inra2013\urzBundle\Entity\Ana' . $valeur->getNom() . '",mappedBy="CodeLabo",cascade={"persist"})
     *
     */
    private $Champs' . $valeur->getNom() . ';

';
        }

        $ChampsAnalyse.=' /**
     * Constructor
     */
    public function __construct()
    {';

        foreach ($TypeAnalyse as $resultat) {

            $ChampsAnalyse.='

  $this->Champs' . $resultat->getNom() . ' = new \Doctrine\Common\Collections\ArrayCollection();
';
        }

        $ChampsAnalyse.='}';

        $fichier = fopen($path . "/Analyse.php", 'w');
        $taille = filesize($path . "/Analyse.php");
        fseek($fichier, $taille - 5);
        fwrite($fichier, '<?php

namespace Inra2013\urzBundle\Entity;
use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\ORM\Mapping as ORM;

/**
 * Analyse
 *
 * @ORM\Table(name="Analyse")
 * @ORM\Entity
 */
class Analyse {

    /**
     * @var integer
     * @ORM\Id
     * @ORM\Column(name="CodeLabo", type="integer", length=255)
     */
    private $CodeLabo;

    /**
     *  *@ORM\ManyToOne(targetEntity="Inra2013\urzBundle\Entity\Protocole")
     *
     */
    private $Protocole;

    /**
     *  *@ORM\ManyToOne(targetEntity="Inra2013\urzBundle\Entity\Animal")
     *  @ORM\JoinColumn(name="Animal", referencedColumnName="id")
     * @ORM\Column(type="integer", nullable=true)
     */
    private $Animal;

    /**
     * @var \Date
     *
     * @ORM\Column(name="DatePrelev",nullable=true)
     */
    private $DatePrelev;

    /**
     * @var \Date
     * @ORM\Column(name="DateAnalyse", type="date", nullable=true)
     */
    private $DateAnalyse;

    /**
     * @var string
     *
     * @ORM\Column(name="Observation", type="string", length=255 , nullable=true)
     */
    private $Observation;

    /**
     * @var string
     *
     * @ORM\Column(name="Lot_Groupe", type="text",nullable=true)
     */
    private $Lot_Groupe;

    /**
     * @var string
     *
     * @ORM\Column(name="NaturEchant", type="string", length=255 ,nullable=true)
     */
    private $NaturEchant;

' . $ChampsAnalyse . '}

');
        fclose($fichier);

        /*         * *******Creation du fichier typeanalyse pour le formulaire******* */

        $fichierType = fopen($path . "/../Form/Ana" . $Entity->getNom() . "Type.php", "w");
        $ChampsType = "";
        foreach ($ChampsTypeAnalyse as $value) {

            $ChampsType.='->add(' . $value->getChamp() . ')';
        }
        fwrite($fichierType, '

<?php

namespace Inra2013\urzBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class Ana' . $Entity->getNom() . 'Type extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder' . $ChampsType . '

        ;
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            \'data_class\' => \'Inra2013\urzBundle\Entity\Ana' . $Entity->getNom() . '\'
        ));
    }

    public function getName()
    {
        return \'inra2013_urzbundle_ana' . $Entity->getNom() . 'type\';
    }
}

');

        fclose($fichierType);

        /*         * *On genere les setters et les getters avec la commande de symfony php console generate:doctrine:entities Inra2013urzBundle:Entity:AnaEssai** */

        $path_console = dirname(__FILE__) . "/../../../../app/";
        $commandeEntities = "console generate:doctrine:entities Inra2013urzBundle:Ana" . $Entity->getNom();
        $commandeEntitiesAna = "console generate:doctrine:entities Inra2013urzBundle:Analyse";

        $resultatEntities = exec("php " . $path_console . $commandeEntities);
        $resultatEntitiesAna = exec("php " . $path_console . $commandeEntitiesAna);
        /*         * **On la cree dans la base de données** */

        $commandeCreate = "console doctrine:schema:update --force";
        $resultatCreate = exec("php " . $path_console . $commandeCreate);

        return new Response("je si dans ");
    }

    public function FormuleChampAction() {

        //    $typeFormulaire = new \Inra2013\urzBundle\Entity\Formule();
        //  $typeChampsEssai=
        //  $champsFormule1 = new \Inra2013\urzBundle\Entity\Formule();
        //  $champsFormule2 = new \Inra2013\urzBundle\Entity\Formule();
        // $champsFormule1 = new \Inra2013\urzBundle\Entity\Formule();
        //  $type= new \Inra2013\urzBundle\Form\ChampType();
        // $champsFormule = array();
        $request = $this->get('request');
        $typeAnalyse = $request->get('typeAnalyse');
        //$typeAnalyse = 1;
        $ChampsEssai = new \Inra2013\urzBundle\Entity\Champ();
        $formtypeFormulaire = $this->createFormBuilder($ChampsEssai);
        // print_r($typeAnalyse);
        $Cham = $this->getDoctrine()->getRepository('Inra2013urzBundle:Champ')->find(1);
        $Cham1 = $this->getDoctrine()->getRepository('Inra2013urzBundle:Champ')->find(2);

        $RequeteCmaps = $this->getDoctrine()->getRepository('Inra2013urzBundle:Champ')->findBy(array('Analyse' => $typeAnalyse));

//$champsFormule1->setChamps($RequeteCmaps[0]);
//$champsFormule1->setChamps($RequeteCmaps[1]);
        //  \Doctrine\Common\Util\Debug::dump($RequeteCmaps);

        /*

          $champsFormule = new \Inra2013\urzBundle\Entity\Formule();
          $champsFormule2 = new \Inra2013\urzBundle\Entity\Formule();

          $champsFormule->setChamps($Cham);
          $champsFormule2->setChamps($Cham1);
         */
        $FindChampsCalcule = $this->getDoctrine()->getRepository('Inra2013urzBundle:Champ')->FindChampsCalcule($typeAnalyse);

        //  \Doctrine\Common\Util\Debug::dump($ChampsEssai);
        //   $champsFormule = new \Inra2013\urzBundle\Entity\Formule();
        //   $ChampsEssai->addChampsForhampsFormule);
        //  $champsFormule1->setChamps($Cham1);

        foreach ($FindChampsCalcule as $key => $value) {

            $ChampsFormule = "ChampsFormule" . $key;
            $champsFormule = new \Inra2013\urzBundle\Entity\Formule();
            $champsFormule->setChamps($value);
            $ChampsEssai->addChampsFormule($champsFormule);
        }

        /*
          $ChampsEssai->addChampsFormule($champsFormule);
          $ChampsEssai->addChampsFormule($champsFormule2);

         */

        //        \Doctrine\Common\Util\Debug::dump($ChampsEssai);
        //$formtypeFormulaire = $this->createForm(
        //             new \Inra2013\urzBundle\Form\FormuleType(), $typeFormulaire);
        //    $formtypeFormulaire= $this->createForm($type,$ChampsEssai);

        $formtypeFormulaire
                ->add('ChampsFormule', 'collection', array(
                    'type' => new \Inra2013\urzBundle\Form\FormuleType(),
                    'allow_add' => true,
                    'attr' => array('label' => ' ')
        ));

        if ($this->getRequest()->getMethod() == 'POST') {

            $form = $formtypeFormulaire->getForm()->bind($request);
            if ($form->isValid()) {
                $em = $this->getDoctrine()->getEntityManager();

                foreach ($ChampsEssai->getChampsFormule() as $value) {

                    $em->persist($value);
                }
                $em->flush();
                //  $a=12;
                //  $b=13;
                // eval('$a = 5+6+7;');
////var_dump($c);
                return $this->redirect($this->generateUrl('Inra2013Bundle_Save', array("Status" => "Formule")));
            }
        }

        return $this->render('Inra2013urzBundle:Analyse:FormuChamp.html.twig', array("RequeteChamp" => $RequeteCmaps, "form_formule" => $formtypeFormulaire->getForm()->createView(), "NumProtocole" => $typeAnalyse, "FindChamps" => $FindChampsCalcule));
    }

    public function SaveAction($Status) {

        return $this->render("Inra2013urzBundle:Analyse:Save.html.twig", array("Status" => $Status));
    }

}


text:
#ifndef _GNU_SOURCE
# define _GNU_SOURCE
#endif

#include <stdlib.h>
#include "internal/cryptlib.h"
#include "internal/e_os.h"

char *ossl_safe_getenv(const char *name)
{
#if defined(_WIN32) && defined(CP_UTF8) && !defined(_WIN32_WCE)
    if (GetEnvironmentVariableW(L"OPENSSL_WIN32_UTF8", NULL, 0) != 0) {
        char *val = NULL;
        int vallen = 0;
        WCHAR *namew = NULL;
        WCHAR *valw = NULL;
        DWORD envlen = 0;
        DWORD dwFlags = MB_ERR_INVALID_CHARS;
        int rsize, fsize;
        UINT curacp;

        curacp = GetACP();

        /*
         * For the code pages listed below, dwFlags must be set to 0.
         * Otherwise, the function fails with ERROR_INVALID_FLAGS.
         */
        if (curacp == 50220 || curacp == 50221 || curacp == 50222 ||
            curacp == 50225 || curacp == 50227 || curacp == 50229 ||
            (57002 <= curacp && curacp <=57011) || curacp == 65000 ||
            curacp == 42)
            dwFlags = 0;

        /* query for buffer len */
        rsize = MultiByteToWideChar(curacp, dwFlags, name, -1, NULL, 0);
        /* if name is valid string and can be converted to wide string */
        if (rsize > 0)
            namew = _malloca(rsize * sizeof(WCHAR));

        if (NULL != namew) {
            /* convert name to wide string */
            fsize = MultiByteToWideChar(curacp, dwFlags, name, -1, namew, rsize);
            /* if conversion is ok, then determine value string size in wchars */
            if (fsize > 0)
                envlen = GetEnvironmentVariableW(namew, NULL, 0);
        }

        if (envlen > 0)
            valw = _malloca(envlen * sizeof(WCHAR));

        if (NULL != valw) {
            /* if can get env value as wide string */
            if (GetEnvironmentVariableW(namew, valw, envlen) < envlen) {
                /* determine value string size in utf-8 */
                vallen = WideCharToMultiByte(CP_UTF8, 0, valw, -1, NULL, 0,
                                             NULL, NULL);
            }
        }

        if (vallen > 0)
            val = OPENSSL_malloc(vallen);

        if (NULL != val) {
            /* convert value string from wide to utf-8 */
            if (WideCharToMultiByte(CP_UTF8, 0, valw, -1, val, vallen,
                                    NULL, NULL) == 0) {
                OPENSSL_free(val);
                val = NULL;
            }
        }

        if (NULL != namew)
            _freea(namew);

        if (NULL != valw)
            _freea(valw);

        return val;
    }
#endif

#if defined(__GLIBC__) && defined(__GLIBC_PREREQ)
# if __GLIBC_PREREQ(2, 17)
#  define SECURE_GETENV
    return secure_getenv(name);
# endif
#endif

#ifndef SECURE_GETENV
    if (OPENSSL_issetugid())
        return NULL;
    return getenv(name);
#endif
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Commerce\Http;

/**
* Represents an Http call in context
*/
class HttpContext
{
    /**
     * Http request sent
     * @var HttpRequest
     */
    private $request = null;

    /**
     * Http response recevied
     * @var HttpResponse
     */
    private $response = null;

    /**
     * Create an instance of HttpContext for an Http Call
     * @param HttpRequest  $request  Request first sent on http call
     * @param HttpResponse $response Response received from http call
     */
    public function __construct(HttpRequest $request, HttpResponse $response) {
        $this->request = $request;
        $this->response = $response;
    }

    /**
     * Getter for the Http Request
     * @return HttpRequest request
     */
    public function getRequest() {
        return $this->request;
    }

    /**
     * Getter for the Http Response
     * @return HttpResponse response
     */
    public function getResponse() {
        return $this->response;
    }
}


text:
#ifndef _MD5_MESH_HPP
#define _MD5_MESH_HPP

#include <boost/fusion/include/adapt_struct.hpp>

#include <md5/types/vertex.hpp>
#include <md5/types/weight.hpp>
#include <md5/types/triangle.hpp>

#include <string>
#include <vector>

namespace md5 {

  template< typename fvec2, typename fvec3 >
    struct mesh {

      typedef vertex< fvec2 > vertex_type;
      typedef weight< fvec3 > weight_type;

      typedef std::vector< vertex_type > verticies_type;
      typedef std::vector< weight_type > weights_type;
      typedef std::vector< triangle >       triangles_type;

      std::string shader_name;
      int num_verts;
      verticies_type verticies;
      int num_tris;
      triangles_type triangles;
      int num_weights;
      weights_type   weights;
    };
} /* namespace md5 */

BOOST_FUSION_ADAPT_TPL_STRUCT
  (
   (fvec2)(fvec3),
   (md5::mesh)(fvec2)(fvec3),
   (std::string, shader_name)
   (int, num_verts)
   (std::vector< md5::vertex< fvec2 > >, verticies)
   (int, num_tris)
   (std::vector< md5::triangle >, triangles)
   (int, num_weights)
   (std::vector< md5::weight< fvec3 > >, weights)
  )

#endif /* end of include guard: _MD5_MESH_HPP */


text:
import Folders from './modules.js';

import './server/publications.js';

export default Folders;


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

namespace ILspect.Syntax
{
    public enum BinaryOperator
    {
        Add,
        And,
        Divide,
        LessThan,
        Equal,
        NotEqual,
        GreaterThanOrEqual,
        GreaterThan,
        LessThanOrEqual,
        Multiply,
        BitOr,
        Remainder,
        ShiftLeft,
        ShiftRight,
        Subtract,
        BitXor,
    }

    public static class BinaryOperatorExtensions
    {
        private static readonly Dictionary<BinaryOperator, string> _symbols = new Dictionary<BinaryOperator, string>()
        {
            { BinaryOperator.Add, "+" },
            { BinaryOperator.And, "&" },
            { BinaryOperator.Divide, "/" },
            { BinaryOperator.LessThan, "<" },
            { BinaryOperator.Equal, "==" },
            { BinaryOperator.NotEqual, "!=" },
            { BinaryOperator.GreaterThanOrEqual, ">=" },
            { BinaryOperator.GreaterThan, ">" },
            { BinaryOperator.LessThanOrEqual, "<=" },
            { BinaryOperator.Multiply, "*" },
            { BinaryOperator.BitOr, "|" },
            { BinaryOperator.Remainder, "%" },
            { BinaryOperator.ShiftLeft, "<<" },
            { BinaryOperator.ShiftRight, ">>" },
            { BinaryOperator.Subtract, "-" },
            { BinaryOperator.BitXor, "^" },
        };

        public static string GetSymbol(this BinaryOperator self)
        {
            if (!_symbols.TryGetValue(self, out var symbol))
            {
                throw new InvalidOperationException($"Unknown symbol: {self}");
            }
            return symbol;
        }
    }
}


text:
"""
.. module:: lesscpy.plib
    :synopsis: Parse Nodes for Lesscpy

    Copyright (c)
    See LICENSE for details.
.. moduleauthor:: Johann T. Mariusson <jtm@robot.is>
"""
__all__ = [
    'Block',
    'Call',
    'Deferred',
    'Expression',
    'Identifier',
    'Mixin',
    'Node',
    'Property',
    'Statement',
    'String',
    'Variable'
]
from .block import Block
from .call import Call
from .deferred import Deferred
from .expression import Expression
from .identifier import Identifier
from .mixin import Mixin
from .node import Node
from .property import Property
from .statement import Statement
from .string import String
from .variable import Variable


text:
var _ = require('lodash');
var proxyquire = require('proxyquire').noCallThru();
var expect = require('salinity').expect;
var appState = require('../../lib/state/appState');

describe('appActions', function() {
  // Mock all I/O
  var config, now, sundial, localStore, api, jellyfish, device, carelink;
  var app;
  var appActions;

  var defaultUploadGroups = [{
    profile: {
      fullName: 'Bob',
      patient: {
        birthday: '2000-01-01',
        diagnosisDate: '2010-04-01',
        about: ''
      }
    },
    userid: '11'
  }, {
    profile: {
      fullName: 'Alice',
      patient: {
        birthday: '1985-07-04',
        diagnosisDate: '1993-03-25',
        about: 'Foo bar'
      }
    },
    userid: '12'
  }];

  beforeEach(function() {

    config = {};
    now = '2014-01-31T22:00:00-05:00';
    sundial = {
      utcDateString: function() { return now; }
    };
    localStore = require('../../lib/core/localStore')({
      devices: {'11': [{
        key: 'carelink',
        timezone: 'oldTz'
      }]}
    });
    api = {};

    jellyfish = {};
    device = {};
    carelink = {};

    app = {
      state: {},
      setState: function(updates) {
        this.state = _.assign(this.state, updates);
      }
    };
    appState.bindApp(app);

    appActions = proxyquire('../../lib/state/appActions', {
      '../config': config,
      'sundial': sundial,
      '../core/localStore': localStore,
      '../core/api': api,
      '../jellyfishClient': function() { return jellyfish; },
      '../core/device': device,
      '../core/carelink': carelink
    });
    appActions.bindApp(app);
  });

  it('binds to app component', function() {
    app.state.FOO = 'bar';
    expect(appActions.app.state.FOO).to.equal('bar');
  });

  describe('load', function() {
    beforeEach(function() {
      api.init = function(options, cb) { cb(); };
      device.init = function(options, cb) { cb(); };
      carelink.init = function(options, cb) { cb(); };

      api.user = {};
      api.user.account = function(cb) { cb(); };
      api.user.profile = function(cb) { cb(); };
      api.user.getUploadGroups = function(cb) { cb(null, defaultUploadGroups); };
      api.setHosts = function() {};
    });

    it('initializes all I/O services', function(done) {
      var initialized = {};
      var mark = function(name, cb) {
        initialized[name] = true;
        cb();
      };
      localStore.init = function(options, cb) { mark('localStore', cb); };
      api.init = function(options, cb) { mark('api', cb); };
      device.init = function(options, cb) { mark('device', cb); };
      carelink.init = function(options, cb) { mark('carelink', cb); };

      appActions.load(function(err) {
        if (err) throw err;
        expect(initialized.localStore).to.be.true;
        expect(initialized.api).to.be.true;
        expect(initialized.device).to.be.true;
        expect(initialized.carelink).to.be.true;
        done();
      });
    });

    it('goes to login page if no session found', function(done) {
      localStore.getInitialState = function() {};
      localStore.init = function(options, cb) { cb(); };

      appActions.load(function(err) {
        if (err) throw err;
        expect(app.state.page).to.equal('login');
        done();
      });
    });

    it('goes to main page if local session found and targeted devices fetched from localStore', function(done) {
      api.init = function(options, cb) { cb(null, {token: '1234'}); };
      api.user.account = function(cb) { cb(null, {userid: '11'}); };
      api.user.profile = function(cb) { cb(null, {fullName: 'Bob', patient: {about: 'Foo'}}); };

      appActions.load(function(err) {
        if (err) throw err;
        expect(app.state.page).to.equal('main');
        done();
      });
    });

    it('goes to settings page if local session found and no targeted devices fetched from localStore', function(done) {
      api.init = function(options, cb) { cb(null, {token: '1234'}); };
      api.user.account = function(cb) { cb(null, {userid: '12'}); };
      api.user.profile = function(cb) { cb(null, {fullName: 'Alice'}); };

      appActions.load(function(err) {
        if (err) throw err;
        expect(app.state.page).to.equal('settings');
        done();
      });
    });

    it('loads logged-in user if local session found', function(done) {
      api.init = function(options, cb) { cb(null, {token: '1234'}); };
      api.user.account = function(cb) { cb(null, {userid: '11'}); };
      api.user.profile = function(cb) { cb(null, {fullName: 'Bob'}); };

      appActions.load(function(err) {
        if (err) throw err;
        expect(app.state.user).to.deep.equal({
          userid: '11',
          profile: {fullName: 'Bob'},
          uploadGroups: defaultUploadGroups
        });
        done();
      });
    });

    it('sets target user id as logged-in userid if data storage exists for logged-in user', function(done) {
      api.init = function(options, cb) { cb(null, {token: '1234'}); };
      api.user.account = function(cb) { cb(null, {userid: '11'}); };
      api.user.profile = function(cb) { cb(null, {fullName: 'Bob', patient: {about: 'Foo'}}); };

      appActions.load(function(err) {
        if (err) throw err;
        expect(app.state.targetId).to.equal('11');
        done();
      });
    });

    it('sets target user id to other userid if data storage does not exist for logged-in user', function(done) {
      api.init = function(options, cb) { cb(null, {token: '1234'}); };
      api.user.account = function(cb) { cb(null, {userid: '2'}); };
      api.user.profile = function(cb) { cb(null, {fullName: 'Cookie'}); };
      api.user.getUploadGroups = function(cb) { cb(null, [defaultUploadGroups[1], {
        profile: {
          fullName: 'Cookie'
        },
        userid: '2'
      }]); };

      appActions.load(function(err) {
        if (err) throw err;
        expect(app.state.targetId).to.equal('12');
        done();
      });
    });

  });

  describe('login', function() {
    var loginMetricsCall = {};

    beforeEach(function() {
      api.user = {};
      api.user.login = function(credentials, options, cb) { cb(); };
      api.user.profile = function(cb) { cb(); };
      api.user.getUploadGroups = function(cb) { cb(null, defaultUploadGroups); };
      api.metrics = { track : function(one, two) { loginMetricsCall.one = one; loginMetricsCall.two = two;  }};
    });

    it('goes to settings page by default', function(done) {
      api.user.profile = function(cb) { cb(null, {fullName: 'Bob', patient: {about: 'Foo'}}); };

      appActions.login({}, {}, function(err) {
        if (err) throw err;
        expect(app.state.page).to.equal('settings');
        expect(loginMetricsCall).to.not.be.empty;
        expect(loginMetricsCall.one).to.equal(appActions.trackedState.LOGIN_SUCCESS);
        done();
      });
    });

    it('goes to main page if login successful and targeted devices fetched from localStore', function(done) {
      api.user.login = function(credentials, options, cb) {
        cb(null, {user: {userid: '11'}});
      };
      api.user.profile = function(cb) { cb(null, {fullName: 'Bob', patient: {about: 'Foo'}}); };

      appActions.login({}, {}, function(err) {
        if (err) throw err;

        expect(app.state.page).to.equal('main');
        done();
      });
    });

    it('goes to settings page if login successful and targeted devices not fetched from localStore', function(done) {
      api.user.login = function(credentials, options, cb) {
        cb(null, {user: {userid: '12'}});
      };
      api.user.profile = function(cb) { cb(null, {fullName: 'Bob', patient: {about: 'Foo'}}); };

      appActions.login({}, {}, function(err) {
        if (err) throw err;

        expect(app.state.page).to.equal('settings');
        done();
      });
    });

    it('loads logged-in user if login successful', function(done) {
      api.user.login = function(credentials, options, cb) {
        cb(null, {user: {userid: '11'}});
      };
      api.user.profile = function(cb) { cb(null, {fullName: 'Bob'}); };

      appActions.login({}, {}, function(err) {
        if (err) throw err;

        expect(app.state.user).to.deep.equal({
          userid: '11',
          profile: {fullName: 'Bob'},
          uploadGroups: defaultUploadGroups
        });
        done();
      });
    });

    it('calls callback with error if login failed', function(done) {

      var loginError = {message: 'login failed', step: 'platform_login'};

      api.user.login = function(credentials, options, cb) {
        cb(loginError);
      };

      appActions.login({}, {}, function(err) {
        expect(err.message).to.contain(loginError.message);
        done();
      });
    });

    it('sets target user id as logged-in user id if data storage exists for logged-in user', function(done) {
      api.user.login = function(credentials, options, cb) {
        cb(null, {user: {userid: '11'}});
      };
      api.user.profile = function(cb) { cb(null, {fullName: 'Bob', patient: {about: 'Foo'}}); };

      appActions.login({}, {}, function(err) {
        if (err) throw err;
        expect(app.state.targetId).to.equal('11');
        done();
      });
    });

    it('sets target user id to other userid if data storage does not exist for logged-in user', function(done) {
      api.user.login = function(credentials, options, cb) {
        cb(null, {user: {userid: '2'}});
      };
      api.user.getUploadGroups = function(cb) { cb(null, [defaultUploadGroups[1], {
        profile: {
          fullName: 'Cookie'
        },
        userid: '2'
      }]); };

      appActions.login({}, {}, function(err) {
        if (err) throw err;
        expect(app.state.targetId).to.equal('12');
        done();
      });
    });

  });

  describe('viewData', function() {

    var viewDataMetricsCall = {};

    beforeEach(function() {
      api.metrics = { track : function(one, two) { viewDataMetricsCall.one = one; viewDataMetricsCall.two = two;  }};
    });

    it('logs metric', function(done) {
      appActions.viewData();
      expect(viewDataMetricsCall).to.not.be.empty;
      expect(viewDataMetricsCall.one).to.equal(appActions.trackedState.SEE_IN_BLIP);
      done();
    });
  });

  describe('logout', function() {

    var logoutMetricsCall = {};

    beforeEach(function() {
      api.user = {};
      api.user.logout = function(cb) { cb(); };
      api.metrics = { track : function(one, two) { logoutMetricsCall.one = one; logoutMetricsCall.two = two;  }};
    });

    it('resets app state', function(done) {
      var uploads = [1, 2, 3];
      app.state = {
        user: {userid: '11'},
        targetId: '11',
        uploads: uploads
      };
      appActions.logout(function(err) {
        if (err) throw err;
        expect(app.state.user).to.not.exist;
        expect(app.state.targetId).to.not.exist;
        expect(app.state.uploads).to.not.equal(uploads);
        expect(logoutMetricsCall).to.not.be.empty;
        expect(logoutMetricsCall.one).to.equal(appActions.trackedState.LOGOUT_CLICKED);
        done();
      });
    });

    it('goes back to login page', function(done) {
      app.state.page = 'main';
      appActions.logout(function(err) {
        if (err) throw err;
        expect(app.state.page).to.equal('login');
        done();
      });
    });

  });

  describe('detectDevices', function() {
    var connectedDevices;

    beforeEach(function() {
      connectedDevices = [];
      device.detectAll = function(cb) {
        return cb(null, connectedDevices);
      };
    });

    it('adds a new device upload', function(done) {

      app.state.uploads = [];
      connectedDevices = [{
        driverId: 'DexcomG4',
        usb: 3
      }];

      appActions.detectDevices(function(err) {
        if (err) throw err;
        expect(app.state.uploads).to.have.length(1);
        expect(app.state.uploads[0].source).to.deep.equal({
          type: 'device',
          driverId: 'DexcomG4',
          usb: 3,
          connected: true
        });
        done();
      });
    });

    it('keeps carelink at the beginning when adding new device', function(done) {
      app.state.uploads = [
        {source: {type: 'carelink'}}
      ];
      connectedDevices = [{
        driverId: 'DexcomG4',
        usb: 3
      }];

      appActions.detectDevices(function(err) {
        if (err) throw err;
        expect(app.state.uploads).to.have.length(2);
        expect(app.state.uploads[0].source.type).to.equal('carelink');
        done();
      });
    });

    it('marks device upload as disconnected', function(done) {
      app.state.uploads = [
        {
          source: {
            type: 'device',
            driverId: 'DexcomG4',
            usb: 3,
            connected: true
          }
        }
      ];
      connectedDevices = [];

      appActions.detectDevices(function(err) {
        if (err) throw err;
        expect(app.state.uploads).to.have.length(1);
        expect(app.state.uploads[0].source.connected).to.be.false;
        done();
      });
    });

    it('resets progress for disconnected device', function(done) {
      app.state.uploads = [
      {
        source: {
          type: 'device',
          driverId: 'DexcomG4',
          usb: 3,
          connected: true
        },
        progress: {}
      }
      ];
      connectedDevices = [];

      appActions.detectDevices(function(err) {
        if (err) throw err;
        expect(app.state.uploads).to.have.length(1);
        expect(app.state.uploads[0].source.progress).to.not.exist;
        done();
      });
    });

    it('marks device upload as connected', function(done) {
      app.state.uploads = [
      {
        source: {
          type: 'device',
          driverId: 'DexcomG4',
          usb: 3,
          connected: false
        }
      }
      ];
      connectedDevices = [{
        driverId: 'DexcomG4',
        usb: 3
      }];

      appActions.detectDevices(function(err) {
        if (err) throw err;
        expect(app.state.uploads).to.have.length(1);
        expect(app.state.uploads[0].source.connected).to.be.true;
        done();
      });
    });

    it('updates connected device info', function(done) {
      app.state.uploads = [
      {
        source: {
          type: 'device',
          driverId: 'DexcomG4',
          usb: 3,
          connected: true
        }
      }
      ];
      connectedDevices = [{
        driverId: 'DexcomG4',
        usb: 11
      }];

      appActions.detectDevices(function(err) {
        if (err) throw err;
        expect(app.state.uploads).to.have.length(1);
        expect(app.state.uploads[0].source.usb).to.equal(11);
        done();
      });
    });

    it('keeps one upload per device driverId', function(done) {
      app.state.uploads = [
      {
        source: {
          type: 'device',
          driverId: 'DexcomG4',
          serialNumber: 'AA11',
          usb: 3,
          connected: true
        }
      }
      ];
      connectedDevices = [{
        driverId: 'DexcomG4',
        serialNumber: 'BB22',
        usb: 11
      }];

      appActions.detectDevices(function(err) {
        if (err) throw err;
        expect(app.state.uploads).to.have.length(1);
        expect(app.state.uploads[0].source.serialNumber).to.equal('BB22');
        done();
      });
    });

  });

  describe('chooseDevices', function() {
    beforeEach(function() {
      app.state = {
        dropMenu: true,
        page: 'main'
      };
    });

    it('redirects to settings page and clears dropMenu', function() {
      appActions.chooseDevices();
      expect(app.state.dropMenu).to.be.false;
      expect(app.state.page).to.equal('settings');
    });
  });

  describe('addOrRemoveTargetDevice', function() {
    beforeEach(function() {
      app.state = {
        targetDevices: []
      };
    });

    it('adds the device if the event target is checked', function() {
      appActions.addOrRemoveTargetDevice({target: {value: 'foo', checked: true}});
      expect(app.state.targetDevices).to.deep.equal(['foo']);
    });

    it('removes the device if the event target is not checked', function() {
      app.state.targetDevices = ['foo', 'Kiwi'];
      appActions.addOrRemoveTargetDevice({target: {value: 'foo', checked: false}});
      appActions.addOrRemoveTargetDevice({target: {value: 'bar', checked: false}});
      expect(app.state.targetDevices).to.deep.equal(['Kiwi']);
    });
  });

  describe('storeUserTargets', function() {
    beforeEach(function() {
      app.state = {
        page: 'settings',
        targetDevices: ['foo', 'bar'],
        targetTimezone: 'fooTz'
      };
    });

    it('saves the current targetDevices in the app state in the localStore under the target userid', function() {
      expect(localStore.getItem('devices')['11'][0].key).to.deep.equal('carelink');
      appActions.storeUserTargets('11');
      expect(_.pluck(localStore.getItem('devices')['11'], 'key')).to.deep.equal(['foo', 'bar']);
    });

    it('saves the current targetTimezone in the app state in the localStore along with each target device', function() {
      expect(localStore.getItem('devices')['11'][0].timezone).to.equal('oldTz');
      appActions.storeUserTargets('11');
      expect(_.uniq(_.pluck(localStore.getItem('devices')['11'], 'timezone'))[0]).to.equal('fooTz');
    });

    it('also redirects to main page', function() {
      expect(app.state.page).to.equal('settings');
      appActions.storeUserTargets('11');
      expect(app.state.page).to.equal('main');
    });
  });

  describe('storeUserTargets, timezone empty', function() {
    beforeEach(function() {
      app.state = {
        page: 'settings',
        targetDevices: ['foo', 'bar'],
        targetTimezone: ''
      };
    });

    it('does not redirect to the main page', function() {
      expect(app.state.page).to.equal('settings');
      appActions.storeUserTargets('11');
      expect(app.state.page).to.equal('settings');
    });
  });

  describe('readFile', function() {
    beforeEach(function() {
      app.state = {
        uploads: [{key: 'foo'}]
      };
    });

    it('should return an error if the filename doesn\'t end in the specified extension', function() {
      var err = appActions.readFile(0, '11', {name: 'foo.bar'}, '.txt');
      expect(err.message).to.equal(appActions.errorText.E_WRONG_FILE_EXT+'.txt');
    });
  });

  describe('uploadDevice', function() {
    var uploadDeviceMetricsCall = {};
    var uploadErrorCall = {};

    beforeEach(function() {
      api.metrics = { track : function(one, two) { uploadDeviceMetricsCall.one = one; uploadDeviceMetricsCall.two = two;  }};
      api.errors = { log : function(one, two, three) { uploadErrorCall.one = one; uploadErrorCall.two = two; uploadErrorCall.three = three; }};
    });

    it('throws an error if upload index is invalid', function() {
      app.state.uploads = [];

      expect(appActions.upload.bind(appActions, 0))
        .to.throw(appActions.errorText.E_INVAILD_UPLOAD_INDEX);
    });

    it('throws an error if an upload is already in progress', function() {
      app.state.uploads = [{
        progress: {}
      }];

      expect(appActions.upload.bind(appActions, 0))
        .to.throw(appActions.errorText.E_UPLOAD_IN_PROGRESS);
    });

    it('starts upload with correct progress data', function() {
      now = '2014-01-31T22:00:00-05:00';
      device.detect = _.noop;
      device.upload = _.noop;
      app.state.targetId = '11';
      app.state.uploads = [{
        source: {
          type: 'device',
          driverId: 'DexcomG4'
        }
      }];
      appActions.upload(0, {}, _.noop);
      expect(app.state.uploads[0].progress).to.deep.equal({
        targetId: '11',
        start: '2014-01-31T22:00:00-05:00',
        step: 'start',
        percentage: 0
      });
      expect(uploadDeviceMetricsCall).to.not.be.empty;
      expect(uploadDeviceMetricsCall.one).to.equal(appActions.trackedState.UPLOAD_STARTED+' DexcomG4');
    });

    it('updates upload with correct progress data', function(done) {
      device.detect = function(driverId, options, cb) { return cb(null, {}); };
      device.upload = function(driverId, options, cb) {
        options.progress('foo', 50);
        expect(app.state.uploads[0].progress).to.have.property('step', 'foo');
        expect(app.state.uploads[0].progress).to.have.property('percentage', 50);
        return cb();
      };
      app.state.targetId = '11';
      app.state.uploads = [{
        source: {
          type: 'device',
          driverId: 'DexcomG4'
        }
      }];

      appActions.upload(0, {}, done);
    });

    it('adds correct object to upload history when complete', function(done) {
      now = '2014-01-31T22:00:00-05:00';
      device.detect = function(driverId, options, cb) { return cb(null, {}); };
      device.upload = function(driverId, options, cb) {
        now = '2014-01-31T22:00:30-05:00';
        options.progress('cleanup', 100);
        var records = [{}, {}];
        return cb(null, records);
      };
      app.state.targetId = '11';
      app.state.uploads = [{
        source: {
          type: 'device',
          driverId: 'DexcomG4'
        }
      }];

      appActions.upload(0, {}, function(err) {
        if (err) throw err;
        var instance = {
          targetId: '11',
          start: '2014-01-31T22:00:00-05:00',
          finish: '2014-01-31T22:00:30-05:00',
          step: 'cleanup',
          percentage: 100,
          success: true,
          count: 2
        };
        expect(app.state.uploads[0].progress).to.deep.equal(instance);
        expect(app.state.uploads[0].history).to.have.length(1);
        expect(app.state.uploads[0].history[0]).to.deep.equal(instance);
        expect(uploadDeviceMetricsCall).to.not.be.empty;
        expect(uploadDeviceMetricsCall.one).to.equal(appActions.trackedState.UPLOAD_SUCCESS+' DexcomG4');
        done();
      });
    });

    it('adds correct object to upload history when upload failed', function(done) {
      now = '2014-01-31T22:00:00-05:00';
      var uploadError = new Error('oops');
      uploadError.step = 'fetching_carelink';
      device.detect = function(driverId, options, cb) { return cb(null, {}); };
      device.upload = function(driverId, options, cb) {
        now = '2014-01-31T22:00:30-05:00';
        options.progress('fetchData', 50);
        return cb(uploadError);
      };
      app.state.targetId = '11';
      app.state.uploads = [{
        source: {
          type: 'device',
          driverId: 'DexcomG4'
        }
      }];

      appActions.upload(0, {}, function() {

        function checkInstance(actual, expected){
          expect(actual.targetId).to.equal(expected.targetId);
          expect(actual.start).to.equal(expected.start);
          expect(actual.percentage).to.equal(expected.percentage);
          expect(actual.error.name).to.equal('Error');
        }

        var instance = {
          targetId: '11',
          start: '2014-01-31T22:00:00-05:00',
          finish: '2014-01-31T22:00:30-05:00',
          step: 'fetchData',
          percentage: 50,
          error: uploadError
        };

        expect(app.state.uploads[0].history).to.have.length(1);
        checkInstance(app.state.uploads[0].progress,instance);
        checkInstance(app.state.uploads[0].history[0],instance);
        expect(uploadErrorCall).to.not.be.empty;
        expect(uploadDeviceMetricsCall).to.not.be.empty;
        expect(uploadErrorCall.two).to.equal(appActions.trackedState.UPLOAD_FAILED+' DexcomG4');
        expect(uploadDeviceMetricsCall.one).to.equal(appActions.trackedState.UPLOAD_FAILED+' DexcomG4');
        done();
      });
    });

    it('adds to upload history most recent first', function(done) {
      device.detect = function(driverId, options, cb) { return cb(null, {}); };
      device.upload = function(driverId, options, cb) { return cb(null, []); };
      app.state.uploads = [{
        source: {
          type: 'device',
          driverId: 'DexcomG4'
        },
        history: [
          {targetId: '1'}
        ]
      }];
      app.state.targetId = '2';

      appActions.upload(0, {}, function(err) {
        if (err) throw err;
        expect(app.state.uploads[0].history).to.have.length(2);
        expect(app.state.uploads[0].history[0].targetId).to.equal('2');
        expect(app.state.uploads[0].history[1].targetId).to.equal('1');
        done();
      });
    });

  });

  describe('reset', function() {

    it('throws an error if upload index is invalid', function() {
      app.state.uploads = [];

      expect(appActions.reset.bind(appActions, 0))
        .to.throw(appActions.errorText.E_INVAILD_UPLOAD_INDEX);
    });

    it('clears upload progress', function() {
      app.state.uploads = [
        {progress: {}}
      ];

      appActions.reset(0);
      expect(app.state.uploads[0].progress).to.not.exists;
    });

  });

  describe('changeGroup', function() {

    it('updates user id for uploading', function() {
      app.state.targetId = 'foo';
      appActions.changeGroup('bar');
      expect(app.state.targetId).to.equal('bar');
    });

  });

  describe('changeTimezone', function() {

    it('updates the timezone ', function() {
      app.state.targetTimezone = 'foo';
      appActions.changeTimezone('bar');
      expect(app.state.targetTimezone).to.equal('bar');
    });

  });

  describe('hideDropMenu', function() {

    it('sets the boolean for the dropdown menu to false, always', function() {
      app.state.dropMenu = true;
      appActions.hideDropMenu();
      expect(app.state.dropMenu).to.be.false;
      appActions.hideDropMenu();
      expect(app.state.dropMenu).to.be.false;
    });

  });

  describe('toggleDropMenu', function() {

    it('toggles the boolean for the dropdown menu', function() {
      app.state.dropMenu = true;
      appActions.toggleDropMenu();
      expect(app.state.dropMenu).to.be.false;
      appActions.toggleDropMenu();
      expect(app.state.dropMenu).to.be.true;
    });

  });

  describe('_handleUploadError', function(){

    var uploadDeviceMetricsCall = {};
    var uploadErrorCall = {};

    beforeEach(function() {
      api.metrics = { track : function(one, two) { uploadDeviceMetricsCall.one = one; uploadDeviceMetricsCall.two = two;  }};
      api.errors = { log : function(one, two, three) { uploadErrorCall.one = one; uploadErrorCall.two = two; uploadErrorCall.three = three; }};
    });

    it('each error has a detailed `debug` string attached for logging', function(done) {
      now = '2014-01-31T22:00:00-05:00';
      device.detect = function(driverId, options, cb) { return cb(null, {}); };
      device.upload = function(driverId, options, cb) {
        now = '2014-01-31T22:00:30-05:00';
        options.progress('fetchData', 50);
        var err = new Error('Oops, we got an error');
        return cb(err);
      };
      app.state.targetId = '11';
      app.state.uploads = [{
        source: {
          type: 'device',
          driverId: 'DexcomG4'
        }
      }];

      appActions.upload(0, {}, function(err) {
        expect(err.debug).to.contain('Detail: ');
        expect(err.debug).to.contain('Error UTC Time: ');
        expect(err.debug).to.contain('Code: E_');
        expect(err.debug).to.contain('Error Type: Error');
        expect(err.debug).to.contain('Version: tidepool-uploader');
        done();
      });
    });

    it('redirects to the `error` page if jellyfish errors because uploader is out-of-date', function(done) {
      now = '2014-01-31T22:00:00-05:00';
      device.detect = function(driverId, options, cb) { return cb(null, {}); };
      device.upload = function(driverId, options, cb) {
        now = '2014-01-31T22:00:30-05:00';
        options.progress('fetchData', 50);
        var err = new Error('Oops, we got an error');
        err.code = 'E_METADATA_UPLOAD';
        return cb(err);
      };
      app.state.targetId = '11';
      app.state.uploads = [{
        source: {
          type: 'device',
          driverId: 'DexcomG4'
        }
      }];

      appActions.upload(0, {}, function(err) {
        expect(app.state.page).to.equal('error');
        done();
      });
    });

  });

});


text:
export * from './export/core';
import { use } from './extension';
import { init } from './core/echarts';

import {install as CanvasRenderer} from './renderer/installCanvasRenderer';
import {install as DatasetComponent} from './component/dataset/install';

// Default to have canvas renderer and dataset for compitatble reason.
use([CanvasRenderer, DatasetComponent]);

// TODO: Compatitable with the following code
// import echarts from 'echarts/lib/echarts'
export default {
    init() {
        if (__DEV__) {
            /* eslint-disable-next-line */
            console.error(`"import echarts from 'echarts/lib/echarts'" is not supported anymore. Use "import * as echarts from 'echarts/lib/echarts'" instead;`);
        }
        // @ts-ignore
        return init.apply(null, arguments);
    }
};

// Import label layout by default.
// TODO remove
import {installLabelLayout} from './label/installLabelLayout';
use(installLabelLayout);


text:
We are always happy for folk to help us out on this project.  Here are some ways how:

### Documentation

* Small Changes (fixes to spelling, inaccuracies, errors) - just do it.
* Larger Changes (whole new sections / pages) - send a mail to [the group](https://groups.google.com/forum/?fromgroups#!forum/job-dsl-plugin) with your proposal at

### New Features
* Feature Requests - Send a mail to [the group](https://groups.google.com/forum/?fromgroups#!forum/job-dsl-plugin) with your request at - if you can include an example snippet of the `config.xml`, so much the better.
* Even better than this is a "New Feature" issue on the [Jenkins JIRA](https://issues.jenkins-ci.org/secure/Dashboard.jspa). Remember to add the `job-dsl-plugin` component. Then, send us a mail to the newsgroup telling us about it.
* Feature Implementations - Even better than both of these is an implementation.  Simply fork our repo, create a branch (named after the JIRA "New Feature" you created earlier), implement it yourself and submit a Pull Request.  Get started with the (light touch) [Architecture Docs](docs/Jenkins-Job-DSL-Architecture.md) and  [How to Build](docs/Building-the-Jenkins-Job-DSL.md) notes and the _Our Git Protocol_ section below

### Bugs
* Bug Reports - Send a mail to [the group](https://groups.google.com/forum/?fromgroups#!forum/job-dsl-plugin) with your request - the more information the better.
* Even better than this is a new "Bug" issue on the [Jenkins JIRA](https://issues.jenkins-ci.org/secure/Dashboard.jspa). Remember to add the `job-dsl-plugin` component. Then, send us a mail to the newsgroup telling us about it.
* Bug Fixes - Even better than both of these is a fix.   Simply fork our repo, create a branch (named after the JIRA "Bug" you created earlier), implement it yourself and submit a Pull Request.  Remember to follow the _Our Git Protocol_ section below.

## Project Developer Docs
_Not required for users of the DSL. And like any developer docs, they're probably out of date the moment they're written._

## Our Git Protocol
If you want to make a change to the code on `jenkinsci/job-dsl-plugin`, here's the protocol we follow (you need a Github account in order to do this):

1. Fork the `jenkinsci/job-dsl-plugin` repository to your account.
2. On your local machine, clone your copy of the `job-dsl-plugin` repo.
3. Again on your local machine, create a branch, ideally named after a JIRA issue you've created for the work.
4. Switch to the local branch and make your changes. Commit them as you go, and when you're happy, push them to your repo branch.
5. Also update the documentation, see below.
6. Then, on the GitHub website, find the branch you created for your work, and submit a Pull Request. This will then poke us and we'll take a look at it. We might ask you to rebase (if the trunk has moved on and there are some conflicts) or we might suggest some more changes.
7. If the all looks good, we'll merge the Pull Request.

Try to focus. It's not required to add all options for a certain plugin to get the pull request merged. In fact, it may
even delay the merge until someone finds time to review a huge change. Only implement the options you really need and
leave room so that the remaining options can be added when needed.

## Our Basic Design Decisions / Conventions
1. Use `javaposse.jobdsl.dsl.Preconditions` for argument validation. E.g. `Preconditions.checkArgument(name, "Channel name for irc channel is required!")`
1. We write tests using [Spock](http://code.google.com/p/spock/), so if (for example) you add a new Helper (e.g. `ScmHelper`), then add a corresponding ScmHelperSpec in the tests directory tree.

## DSL Design
* Every option should have the same defaults as the UI.
* Use method parameters for mandatory options and context closures for optional settings.

```groovy
job {
    publishers {
        foo(String mandatoryA, int mandatoryB) {
            optionalC(String value)
            optionalD(boolean value = true)
        }
    }
}
```

* Use private or protected access modifiers for context and helper methods that should not be exposed to DSL users.
* Add the `@RequiresPlugin` annotation if the feature needs a specific plugin to be installed in Jenkins.

```groovy
@RequiresPlugin(id = 'foo', minimumVersion = '1.2')
void foo(String fooOption) {
    // your implementation goes here
}
```

* Use enum values where appropriate, e.g. when the UI displays a chooser. The enum should be an inner class of the
context which uses the enum. Use conventions for constants for naming enum values. Add the enum to the implicit imports
in `DslScriptLoader.createCompilerConfiguration`.

```groovy
class FooContext {
    FooOptions option = FooOptions.FIRST

    void option(FooOptions option) {
        this.option = option
    }

    enum FooOptions {
      FIRST,
      SECOND
    }
}
```

* Set the default parameter values for boolean options to true, so that a user can write `enableSomeOption()` instead
of `enableSomeOption(true)`.

```groovy
class FooContext {
    boolean foo

    void foo(boolean foo = true) {
        this.foo = foo
    }
}
```

* Offer convenience methods for list or key-value options.

```groovy
class FooContext {
    Map<String, String> jvmOptions = [:]
    List<String> args = []

    void jvmOption(String key, String value) {
        jvmOptions[key] = value
    }

    void jvmOptions(Map<String, String> options) {
        jvmOptions.putAll(options)
    }

    void arg(String arg) {
        args << arg
    }

    void args(String... args) {
        this.args.addAll(args)
    }
}
```

## Code Style
* Indentation: use 4 spaces, no tabs.
* Use a maximum line length of 120 characters.
* We roughly follow the [Java](http://www.oracle.com/technetwork/java/javase/documentation/codeconvtoc-136057.html) and [Groovy](http://groovy.codehaus.org/Groovy+style+and+language+feature+guidelines+for+Java+developers) style guidelines.
* When using IntelliJ IDEA, use the default code style, but disable '*' imports for Java and Groovy.
* Add a CRLF at the end of a file.

## Documentation
* Add an entry to the [Release Notes](docs/Home.md#release-notes).
* Update the [DSL Overview](docs/Job-DSL-Commands.md#dsl-methods) if necessary.
* Make sure that the Job Reference page contains a formal reference, a short description including a link to the plugin, at least one example and the version which added the feature.

```
    ## Foo

    ```groovy
    job {
        wrappers {
            foo(String option) // optional
        }
    }
    ```

    Does some foo. Requires the [Foo Plugin](https://wiki.jenkins-ci.org/display/JENKINS/Foo).

    ```groovy
    job {
        wrappers {
            foo('bar')
        }
    }
    ```

    (Since 1.15)
```


text:
<?php

declare(strict_types=1);

namespace Magmodules\Channable\Model\Config\System;

use Magmodules\Channable\Api\Config\System\ItemupdateInterface;

/**
 * Itemupdate provider class
 */
class ItemupdateRepository extends BaseRepository implements ItemupdateInterface
{

    /**
     * {@inheritDoc}
     */
    public function isItemupdateEnabled(int $storeId = null): bool
    {
        return (bool)$this->getStoreValue(self::XML_PATH_ITEMUPDATE_ENABLE, $storeId);
    }

    /**
     * {@inheritDoc}
     */
    public function getItemupdateWebhookUrl(int $storeId): ?string
    {
        return $this->getStoreValue(self::XML_PATH_ITEMUPDATE_WEBHOOK, $storeId);
    }
}


text:
package com.mcdaniel.serverless;

import java.util.HashMap;

public class APIRequest
{
	public enum PassThrough {NEVER, WHEN_NO_MATCH, WHEN_NO_TEMPLATES};

	protected PassThrough passThrough;
	protected HashMap<String, String> template;
}


text:
class SectionTwo < ActiveRecord::Base
  belongs_to :application
end


text:
@interface LINBaseViewC : UIViewController

@end


text:
package org.codehaus.mojo.appassembler.example.jsw;

import org.mortbay.jetty.Server;
import org.mortbay.jetty.webapp.WebAppContext;

public class MyServer
{
    public static void main( String[] args )
    {
        Server server = new Server(8080);

        String webapp = "/portal-front-web";
        WebAppContext appContext = new WebAppContext("src/main/webapp", webapp);
        server.addHandler(appContext);

        try {
            server.start();
        } catch (Exception e) {
            System.err.println("Error while starting Jetty:");
            e.printStackTrace();
        }
    }
}


text:
describe('angularjs backend', function() {
  var module, httpBackend, requestChain;
  beforeEach(function() {
    requestChain = jasmine.createSpyObj('requestChain', ['respond', 'passThrough', 'fixture']);
    httpBackend = {
      when: jasmine.createSpy('httpBackend.when()').and.returnValue(requestChain)
    };
    module = jasmine.createSpyObj('module', ['run']);
    module.run.and.callFake(function(args) { args[1](httpBackend); });
    smocker.angularjs.angularModule = jasmine.createSpy('angularModule').and.returnValue(module);
  });

  it('should initialise the fixtureResponseMappings as an empty array', function() {
    smocker.angularjs.fixtureResponseMappings = ['test1', 'test2'];

    smocker.angularjs.backend();

    expect(smocker.angularjs.fixtureResponseMappings).toEqual([]);
  });

  describe('forward', function() {
    it('should invoke the passThrough method on $httpBackend', function() {
      smocker.angularjs.backend().forward('test_method', 'test_path');

      expect(module.run).toHaveBeenCalledWith(['$httpBackend', jasmine.any(Function)]);
      expect(httpBackend.when).toHaveBeenCalledWith('TEST_METHOD', 'test_path');
      expect(requestChain.passThrough).toHaveBeenCalled();
    });
  });

  describe('redirect', function() {
    it('should invoke the fixture method on $httpBackend', function() {
      smocker.angularjs.backend().redirect('test_method', 'test_path', 'test_fixture');

      expect(module.run).toHaveBeenCalledWith(['$httpBackend', jasmine.any(Function)]);
      expect(httpBackend.when).toHaveBeenCalledWith('TEST_METHOD', 'test_path');
      expect(requestChain.fixture).toHaveBeenCalledWith('test_fixture');
    });
  });

  describe('process', function() {
    var response, requestHandler;
    beforeEach(function() {
      requestHandler = {
        response: jasmine.createSpy('requestHandler.response()').and.returnValue({
          status: 'response_status',
          content: 'response_content',
          headers: 'response_headers',
          delay: 'response_delay'
        })
      };
      requestChain.respond.and.callFake(function(callback) {
        response = callback('request_method', '/test/request/group/123', 'request_data', 'request_headers');
      });
    });
    it('should invoke the respond method on $httpBackend', function() {
      smocker.angularjs.backend().process('request_method', '/test/request/group/123', requestHandler);

      expect(module.run).toHaveBeenCalledWith(['$httpBackend', jasmine.any(Function)]);
      expect(httpBackend.when).toHaveBeenCalledWith('REQUEST_METHOD', '/test/request/group/123');
      expect(requestChain.respond).toHaveBeenCalledWith(jasmine.any(Function));
    });
    it('should generate the response from the request handler', function() {
      smocker.angularjs.backend().process('request_method', '/test/request/group/123', requestHandler);

      expect(requestHandler.response).toHaveBeenCalledWith('/test/request/group/123', 'request_data', 'request_headers');
      expect(response).toEqual(['response_status', 'response_content', 'response_headers']);
    });
    it('should generate the response from the request handler passing the regexp capture groups', function() {
      smocker.angularjs.backend().process('request_method', /test\/request\/(\w+)\/(\d+)/, requestHandler);

      expect(requestHandler.response).toHaveBeenCalledWith('/test/request/group/123', 'request_data', 'request_headers', 'group', '123');
      expect(response).toEqual(['response_status', 'response_content', 'response_headers']);
    });
    it('should set the response delay property on the $httpBackend', function() {
      smocker.angularjs.backend().process('request_method', '/test/request/group/123', requestHandler);

      expect(httpBackend.responseDelay).toEqual('response_delay');
    });
  });
});