text:
<?php
namespace FB\groupeBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Doctrine\DBAL\DBALException;
use FB\groupeBundle\Entity\Utilisateur;
use FB\groupeBundle\Entity\MembreGroupe;
use FB\groupeBundle\Entity\Post;
use FB\groupeBundle\Entity\Commentaire;
use FB\groupeBundle\Entity\Historique;
use FB\groupeBundle\Entity\PersistProgressionMb;
use FB\groupeBundle\Entity\PersistProgressPst;
use FOS\FacebookBundle\Facebook\FacebookSessionPersistence;

class ImportDataController extends Controller {

     /**
     *Une constante qui désigne l'mportation de tous les post
     */
    const IMPORT_TOUT = 1;
    /**
     *Une constante qui désigne l'mportation depuis une date donnée de mise à jour
     * en fonction du nombre limite de post à importer
     */
    const IMPORT_DEPUIS = 2; //date de mise à jour
    /**
     *Une constante qui désigne l'mportation jusqu'a une date donnée de mise à jour
     * en fonction du nombre limite de post à importer
     */
    const IMPORT_JUSQUA = 3; //date de mise à jour
    /**
     *Une constante qui désigne l'mportation entre deux date de mise à jour
     *
     */
    const IMPORT_DEP_JUSQ = 4;
    /**
     *Une constante qui désigne l'mportation entre deux date de publication
     *
     */
    const IMPORT_DEP_JUSQ_DATE_CREAT = 5;
    /**
     *Une constante qui désigne l'mportation depuis une date donnée de publication
     * en fonction du nombre limite de post à importer
     */
    const IMPORT_DEP_DATE_CREAT = 6;
    /**
     *Une constante qui désigne l'mportation jusqu'a une date donnée de publication
     * en fonction du nombre limite de post à importer
     */
    const IMPORT_JUSQ_DATE_CREAT = 7;

    /**
     * @var FacebookSessionPersistence C'est l'instance qui permet d'intéragir avec le serveur facebook,
     * on le déclare privé que si on l'initialise au moins une fois
     * on va pouvoir l'utliser sur les méthodes privé
     */
    private $facebook;

    /**
     * @var AbstractManagerRegistry c'est l'objet entityManager mais on utilise
     * le manager car l'entity manager est deprecié
     * dans les recentess version
     */
    private $manager;

    /**
     * @var Groupe c'est l'objet groupe courant dont on fait l'importation
     *
     */
    private $groupe;

    /**
     * @var Utilisateur c'est l'utilisateur nouveau qui change à chaque
     * importation d'un membre qui a posé, aimé ou commenté
     * chaque itération sur le boucle d'importation
     */

    private $new_usr;

    /**
     * @var Post
     * c'est le post courant,cahangé à
     * chaque itération sur le boucle d'importation
     */
    private $new_post;

    /**
     *@var integer Nombre designant la progression en cours une fois l'importation est fini
     */
    private $progression;

    /**
     *@var integer Nombre de poste importé une fois l'importation est fini
     */
    private $nPostImporté;

    /**
     *@var integer  la date depuis laquelle on va importer les post
     * il est exprimé en tempstime qui est le temps unix a compté
     * depuis le 1e Janvier 1970 à minuit.
     * L'importation se fait depuis cette date jusqu'a une date plus proche
     */
    private $tempstime_depuis;

    /**
     *@var integer  la date juqu'a laquelle on va importer les posts
     *il est exprimé en tempstime qui est le temps unix a compté
     *depuis le 1e Janvier 1970 à minuit.
     * L'importation se fait depuis la limite ou la date depuis
     * jusqu'a cette date.
     */
    private $tempstime_jusqua;

    /**
     * @var PersistProgressionMb   L'objet qui permet le suivi en temps réel de
     * la progression  de l'importation des membres
     * la session est vérouillé par le thread en cours
     */
    private $progressMbPersistance;

    /**
     * @var PersistProgressPst  L'objet qui permet le suivi en temps réel de
     * la progression  de l'importation des membres
     * la session est vérouillé par le thread en cours
     */
    private $progressPstPersistance;

    //private $fluxWebSoket;
    /**
     * L'action qui permet de récupérer les membres d'un groupe facebook vers notre base de données
     *
     * @param integer $id_groupe l'id du groupe
     * @param integer $nbrmembre nombre des membre d'un groupe
     * @param integer $limit la limite d'un bloc de requette
     *
     * @Route("/importmembres/{id_groupe}&{nbrmembre}&{limit}", name="import_membres")
     *
     *@return Response
     */
    public function importMembresAction($id_groupe, $nbrmembre, $limit=40) {

        $this->facebook = $this->get('fos_facebook.api');

        if ($this->facebook->getUser() == 0) {
            return $this->forward("FBgroupeBundle:Accueil:index");
        }

        $this->manager = $this->getDoctrine()->getManager();

        $this->groupe = $this->manager->find("FBgroupeBundle:Groupe", $id_groupe);

        $this->progressMbPersistance=$this->manager->find("FBgroupeBundle:PersistProgressionMb", $id_groupe);

        //CODE POUR LE SUIVI DE LA PROGRESSION
        if(!$this->progressMbPersistance){
        $this->progressMbPersistance=new PersistProgressionMb();
        $this->progressMbPersistance->setIdGroupe($id_groupe);
        $this->manager->persist($this->progressMbPersistance);
        $this->manager->flush();

        }

        if (!$this->groupe) {
            $this->get('session')->getFlashBag()->add(
                    'note', "Il y a des erreurs le groupe avec id: $id_groupe  n'existe pas"
            );
            return $this->redirect($this->generateUrl("_security_check"), 301);
        }

        $requete = "/$id_groupe?fields=owner";
        $CreateurGb = $this->facebook->api($requete);
        $id_createur_gp = $CreateurGb["owner"]["id"];

        if (isset($id_createur_gp)) {

            $requete = "/$id_createur_gp?fields=id,name,first_name,last_name,username,gender,email";

            //Il faut toujours s'assurer que le token n'est pas encore expiré au moin
            //pour la première requette sur facebook
       try {

            $usr = $this->facebook->api($requete);

           } catch (\FacebookApiException $e){

             return $this->redirect($this->facebook->getLoginUrl());
          }
            $this->new_usr = (new Utilisateur($usr['id']))
                                    ->setNomEntier($usr['name'])
                                    ->setNom(isset($usr['last_name']) ? $usr['last_name'] : "")
                                    ->setPrenom(isset($usr['first_name']) ? $usr['first_name'] : "")
                                    ->setUsername(isset($usr['username']) ? $usr['username'] : "")
                                    ->setSexe(isset($usr['gender']) ? (($usr['gender'] == 'male') ? "M" : "F") : "")
                                    ->setEmail(isset($usr['email']) ? $usr['email'] : "");

            try {

                $this->manager->persist($this->new_usr);
                $this->manager->flush();

            } catch (DBALException $e) {
                //Si le  Manager est férmé

                    $this->container->get('doctrine')->resetManager();
                    $this->manager = $this->getDoctrine()->getManager();
                    $this->groupe  = $this->manager->merge($this->groupe);
                    $this->new_usr = $this->manager->merge($this->new_usr);
                    $this->progressMbPersistance=$this->manager->merge($this->progressMbPersistance);
            }

            if (!$this->groupe->getCreateur()) {
                $this->groupe->setCreateur($this->new_usr);
                $this->manager->flush();
            }
        } else {
            if (isset($CreateurGb[id])) {
                return new Response("Le createur du groupe ne fait plus parti des memebres, possible qu'il a quitté le groupe");
            } else {
                return new Response("Pas de recupération d'information de profile depuis facebook");
            }
        }

        $nbrImporte = 0;
        $offset = 0;
        $id_dernier_importé = "";
        $this->progression=0;
        $nbrAdmin=0;

    while (($offset <= $nbrmembre) ) {

        $requete = "/$id_groupe?fields=members.offset($offset).limit($limit).fields" .
                "(id,name,first_name,last_name,username,gender,email,administrator)";

        $Resultat = $this->facebook->api($requete);
        if(empty($Resultat['members']['data'])||!isset($Resultat['members']['data']))break;

        foreach ($Resultat['members']['data'] as &$membre) {

            if (isset($membre['id'])) {

            $this->new_usr = (new Utilisateur($membre['id']))
                                    ->setNomEntier($membre['name'])
                                    ->setNom(isset($membre['last_name']) ? $membre['last_name'] : "")
                                    ->setPrenom(isset($membre['first_name']) ? $membre['first_name'] : "")
                                    ->setUsername(isset($membre['username']) ? $membre['username'] : "")
                                    ->setSexe(isset($membre['gender']) ? (($membre['gender'] == 'male') ? "M" : "F") : "")
                                    ->setEmail(isset($membre['email']) ? $membre['email'] : "");

                    $this->manager->persist($this->new_usr);

                    try {

                        $this->manager->flush();
                    } catch (DBALException $e) {

                            $this->container->get('doctrine')->resetManager();
                            $this->manager = $this->getDoctrine()->getManager();
                            $this->groupe = $this->manager->merge($this->groupe);
                            $this->new_usr = $this->manager->merge($this->new_usr);
                            $this->progressMbPersistance=$this->manager->merge($this->progressMbPersistance);
                    }

                    $membre_gpoupe = (new MembreGroupe($this->groupe, $this->new_usr))->setEstAdmin($membre['administrator']);

                    try {

                        $this->manager->persist($membre_gpoupe);
                        $this->manager->flush();
                        //CODE POUR LE SUIVI DE LA PROGRESSION
                        $nbrImporte++;
                        if ($membre['administrator']) $nbrAdmin++;
                        $id_dernier_importé = $this->new_usr->getId();

                    } catch (DBALException $e) {

                            $this->container->get('doctrine')->resetManager();
                            $this->manager = $this->getDoctrine()->getManager();
                            $this->groupe = $this->manager->merge($this->groupe);

                            //CODE POUR LE SUIVI DE LA PROGRESSION
                            $this->progressMbPersistance=$this->manager->merge($this->progressMbPersistance);

                    }
                }

                //CODE POUR LE SUIVI DE LA PROGRESSION
                $this->progression++;
                $this->progressMbPersistance->setNbrProgress($this->progression);
                $this->progressMbPersistance->setNbrMembre($nbrImporte);
                $this->progressMbPersistance->setNbrAdmin($nbrAdmin);
                $this->manager->flush();
            }//END foreach

            $offset+=$limit;

        }//END while

        if($nbrImporte!=0){
        $thisuser = $this->get('session')->get('utilisateur');

        $HistoUser = $this->manager->find("FBgroupeBundle:Historique",
           array('idUtilisateur' => $thisuser['id'],
            'idGroupe' => $id_groupe));

        if (isset($HistoUser)) {

             $HistoUser->setDernierMembreImport($id_dernier_importé);
             $this->manager->flush();
        } else {

            $HistoUser = new Historique($thisuser['id'], $id_groupe);
            $HistoUser->setDernierMembreImport($id_dernier_importé);
            $this->manager->persist($HistoUser);
            $this->manager->flush();
        }
        }

        $objetJSON=  json_encode($this->progressMbPersistance);

        $response = new Response($objetJSON);

        //LIBRATION DES DONNEES DE SUIVIS POUR LES PROCHAINES REQUETES
        $this->progressMbPersistance->setNbrProgress(0)
                                            ->setNbrMembre(0)
                                            ->setNbrAdmin(0);

                $this->manager->flush();
                $response->headers->set('Content-Type', 'application/json');
        return $response;
    }

    /**
     *L'action qui permet de récupérer les postes vers notre base données selon différents type de mode 'importation
     *Le mode d'importation nous permettra de connaitre la requete à executer
     *
     *
     * @Route("/importposts/{id_groupe}&{MODE_IMPORT}&{limit}&{date_depuis}&{date_jusqua}",  name="importPost")
     * @Route("/importposts/{id_groupe}&{MODE_IMPORT}&{limit}", defaults={"MODE_IMPORT" = 1}, name="importTout")
     *
     * @param integer $id_groupe l'id du groupe
     * @param string $date_depuis une date antérieur vers des posts à date postérieur , un string au format date
     * @param string $date_jusqua une date postérieur vers des posts à date antérieur , un string au format date
     * @param integer $limit la limite d'un bloc de requette
     * @param const $MODE_IMPORT Mode d'importation de post
     *
     * @return PersistProgressPst au format json
     *
     */
    public function importPostsAction($id_groupe, $MODE_IMPORT, $limit, $date_depuis = null, $date_jusqua = null) {

         $this->facebook = $this->get('fos_facebook.api');

       if($this->facebook->getUser()==0)
           return $this->forward ("FBgroupeBundle:Accueil:index");

        $this->manager = $this->getDoctrine()->getManager();

        $this->groupe = ($this->manager->find("FBgroupeBundle:Groupe", $id_groupe));

        $this->progressPstPersistance=$this->manager->find("FBgroupeBundle:PersistProgressPst", $id_groupe);

        if(!$this->progressPstPersistance){
        $this->progressPstPersistance=new PersistProgressPst();
        $this->progressPstPersistance->setIdGroupe($id_groupe);
        $this->manager->persist($this->progressPstPersistance);
        $this->manager->flush();
        }
        $this->nPostImporté = 0;
        $this->progression=0;

        if($MODE_IMPORT==self::IMPORT_TOUT)
            {
            /**
            *Pour le mode d'importation Import tout on va fixer la date au temps actuel
            * pour boucler jusqu'au dernier post
            */

            $this->tempstime_jusqua=  strtotime(date("c"));
            $this->tempstime_depuis=  strtotime(date("c"))-30; //On recule de 30 secondes juste pour créer la difference

       while($this->tempstime_jusqua!=$this->tempstime_depuis){

           $this->tempstime_jusqua--;
           $requete = "/$id_groupe?fields=feed.until($this->tempstime_jusqua).limit($limit)" .
                        ".fields(id,type,message,link,full_picture,source," .
                        "name,description,created_time,updated_time,from)";

           try{

            $Resultat = $this->facebook->api($requete);

           } catch (\FacebookApiException $e){

             return $this->redirect($this->facebook->getLoginUrl());
            }
            if(!isset($Resultat['feed']['data']))break;

            foreach($Resultat['feed']['data'] as $post){

                $this->importPost($post);

            }

            $url_precedant=$Resultat['feed']['paging']['previous'];
            $url_suivant=$Resultat['feed']['paging']['next'];

            $this->tempstime_depuis=  intval(Outils::paramDansURL('since', $url_precedant));
            $this->tempstime_jusqua=  intval(Outils::paramDansURL('until',$url_suivant));

        };//FIN WHILE

        }//FIN SI MODE_IMPORT=1

        else  //IMPORTATION SELON LA DATE DE MISE A JOUR
               if(in_array($MODE_IMPORT, array(2,3,4))) {

            if (isset($date_depuis) && $date_depuis != 'null') {
                $this->tempstime_depuis = strtotime($date_depuis);
            }
            if (isset($date_jusqua) && $date_jusqua != 'null') {
                $this->tempstime_jusqua = strtotime($date_jusqua);
            }

            switch ($MODE_IMPORT) {

            //Cette requette va boucler en fonction du pas
            case self::IMPORT_JUSQUA : $requete = "/$id_groupe?fields=feed.until($this->tempstime_jusqua).limit" .
                                            "($limit).fields(id,type,message,link,full_picture,source," .
                                            "name,description,created_time,updated_time,from)";
                                             break;

            case self::IMPORT_DEPUIS : $requete = "/$id_groupe?fields=feed.since($this->tempstime_depuis).limit" .
                                            "($limit).fields(id,type,message,link,full_picture,source," .
                                            "name,description,created_time,updated_time,from)";
                                             break;

            case self::IMPORT_DEP_JUSQ : $requete = "/$id_groupe?fields=feed.since($this->tempstime_depuis)" .
                                                ".until($this->tempstime_jusqua).limit(5000).fields" .
                                                "(id,type,message,link,full_picture,source," .
                                                "name,created_time,updated_time,from)";
                                              break;
        }

           try{

            $Resultat = $this->facebook->api($requete);

           } catch (\FacebookApiException $e){

             return $this->redirect($this->facebook->getLoginUrl());
            }

           $nbrTotPost=count($Resultat['feed']['data']);
           $this->progressPstPersistance->setNbrTotPost($nbrTotPost)->setNbrPostImport(0);
           $this->manager->flush();

            foreach($Resultat['feed']['data'] as $post){

                $this->importPost($post);

            }
        } //FIN SI in_array($MODE_IMPORT, array(2,3,4))

        else

                //IMPORTATION SELON LA DATE DE CREATION
       /**==================!!!!!!ATTENTION!!!!=========================/**
        *  																																																								 *
        *  L'importation selon la date de creation reconnait un bug sur   *
        *  facebook quand vous fournissez une date de creation de post que*
        *  vous voulez selectioner les postes dont leurs date de creation *
        *  sont inférieus ou supérieus alors si la date de mise à jour de *
        *  ne l'est pas ne sera pas sélectioné.                           *
        *                                                                 *
        *=================================================================*/

            if(in_array($MODE_IMPORT, array(5,6,7))){

        $this->tempstime_depuis = strtotime($date_depuis);
        $this->tempstime_jusqua = strtotime($date_jusqua);

        switch ($MODE_IMPORT) {
            //On selectione les id des posts et on boucle dessus.
            case self::IMPORT_DEP_JUSQ_DATE_CREAT :
                        $requetFQL = "SELECT post_id FROM  stream  WHERE source_id=$id_groupe" .
                        " AND created_time<=$this->tempstime_jusqua ".
                        " AND created_time>=$this->tempstime_depuis LIMIT 5000";
                        break;

            case self::IMPORT_DEP_DATE_CREAT :
                         $requetFQL = "SELECT post_id FROM  stream  WHERE source_id=$id_groupe" .
                        " AND created_time>=$this->tempstime_depuis LIMIT $limit";
                        break;

            case self::IMPORT_JUSQ_DATE_CREAT :
                        $requetFQL = "SELECT post_id FROM  stream  WHERE source_id=$id_groupe" .
                        " AND created_time<=$this->tempstime_jusqua LIMIT $limit";
                        break;
        }
       try{

        $lesIdPosts = $this->facebook->api(array(
            'method' => 'fql.query',
            'query' => $requetFQL
        ));

           } catch (\FacebookApiException $e){

             return $this->redirect($this->facebook->getLoginUrl());
            }
        $nbrTotPosts = count($lesIdPosts);
        $this->progressPstPersistance->setNbrTotPost($nbrTotPosts)->setNbrPostImport(0);
        $this->manager->flush();

        foreach ($lesIdPosts as &$objet_post_id) {

              $id_post=$objet_post_id['post_id'];
              $requete = "/$id_post?fields=type,message,link,full_picture,".
                         "source,name,created_time,updated_time,from";

              $post= $this->facebook->api($requete);

              $this->importPost($post);
        }//fin foreach sur les id des postes
        }

        $objetJSON=  json_encode($this->progressPstPersistance);

        //LIBERATION DES DONNEES DE SUIVI
        $this->progressPstPersistance->setNbrComImport(0)
                                            ->setNbrTotPost(0)
                                            ->setNbrProgress(0)
                                            ->setIdPost("")
                                            ->setNbrPostImport(0)
                                            ->setNbrTotComment(0)
                                            ->setNbrToJaime(0)
                                            ->setNbrJaimeImport(0);
        $this->manager->flush();
        $response=new Response($objetJSON);
        $response->headers->set('Content-Type', 'application/json');
        return $response;
    }

    /**
     * Cette méthode cherche un utilisateur dans la base donnée avec son id, s'il ne le trouve pas il le crée
     * en récupérant ses information de facebook
     *
     * @param bigint id_utilisateur
     * @return Utilisateur
     *
     */
    private function findOuCreatMembre($id_utilisateur) {

        $this->new_usr = $this->manager->find("FBgroupeBundle:Utilisateur", $id_utilisateur);

        if ($this->new_usr) {
            $membre_groupe = $this->manager->find("FBgroupeBundle:MembreGroupe", array('utilisateur' => $this->new_usr->getId(), 'groupe' => $this->groupe->getId()));
            if (!$membre_groupe) {

                $Resultat = $this->facebook->api(array(
                    'method' => 'fql.query',
                    'query' => "select administrator FROM group_member WHERE gid=".$this->groupe->getId()." AND uid=$id_utilisateur"
                ));
                $membre_gpoupe = (new MembreGroupe($this->groupe, $this->new_usr))->setEstAdmin($Resultat[0]['administrator']);
                $this->manager->persist($membre_gpoupe);
                $this->manager->flush();
            }

        }else {

            $requete = "/$id_utilisateur?fields=id,name,first_name,last_name,username,gender,email,updated_time";

            $usr = $this->facebook->api($requete);
            $this->new_usr = (new Utilisateur($id_utilisateur))
                                ->setNomEntier($usr['name'])
                                ->setNom(isset($usr['last_name']) ? $usr['last_name'] : "")
                                ->setPrenom(isset($usr['first_name']) ? $usr['first_name'] : "")
                                ->setUsername(isset($usr['username']) ? $usr['username'] : "")
                                ->setSexe(($usr['gender'] == 'male') ? "M" : "F")
                                ->setEmail(isset($usr['email']) ? $usr['email'] : "");

            $Resultat = $this->facebook->api(array(
                'method' => 'fql.query',
                'query' => "select administrator FROM group_member WHERE gid=".$this->groupe->getId()." AND uid=$id_utilisateur"
            ));

            $membre_gpoupe = (new MembreGroupe($this->groupe, $this->new_usr))->setEstAdmin($Resultat[0]['administrator']);

            $this->manager->persist($this->new_usr);
            $this->manager->persist($membre_gpoupe);
            $this->manager->flush();
   }
    }

    /**
     * Cette méthode récupère un enregistrement dans un tableau représentant un post provenant de facebook
     * et l'enregistre dans la base de données, elle accède au propretés privés du contrôleur
     * @param array(stream) $post une ligne d'enregistrement d'un post récupéré depuis facebook
     *
     *@return void
     */
    private function importPost($post){

              $this->new_post = new Post($post['id']);
              $this->new_post->setType($post['type'])//Obligatoire et existe toujour si le new_post exist
                                ->setMessage(isset($post['message']) ? $post['message'] : "")
                                ->setLien(isset($post['link']) ? $post['link'] : "")
                                ->setSource(isset($post['source']) ? $post['source'] : "")
                                ->setNom(isset($post['name']) ? $post['name'] : "")
                                ->setDescription(isset($post['description']) ? $post['description'] : "")
                                ->setDateHeurCreation(new \DateTime($post['created_time']))//Obligatoire et existe toujour si le new_post exist
                                ->setDateHeurUpdate(new \DateTime($post['updated_time']));
            //Pour les photos on va remplacer just celles de type XXXXXXX_s.jpg par XXXXXXX_n.jpg pour une meilleur qualité
            if(isset($post['full_picture'])){

                $picture=$post['full_picture'];
                $photo = (substr_count($picture, "s.jpg") ? str_replace("s.jpg", "n.jpg", $picture) : $picture);
                $this->new_post->setPhoto($photo);

            }

            $this->new_post->setGroupe($this->groupe);

            $id_publicateur = $post['from']['id'];
            $this->findOuCreatMembre($id_publicateur);
            $this->new_post->setPublicateur($this->new_usr);

            $this->progressPstPersistance->setIdPost($this->new_post->getId());

           //On persiste le post avant ses commentaires car il faut que le post existe en BD
           try{

            $this->manager->persist($this->new_post);

            $this->progression++;
            $this->nPostImporté++;
            $this->progressPstPersistance->setIdPost($this->new_post->getId())
                                         ->setNbrProgress($this->progression)
                                         ->setNbrPostImport($this->nPostImporté)
                                         ->setNbrToJaime(0)
                                         ->setNbrTotComment(0);
            $this->manager->flush();

            //RECUPERATION DES JAIMES
            $this->importJaimes();

            } catch (DBALException $e) {
                //Si l'entity Manager est férmé
                if (!$this->getDoctrine()->getEntityManager()->isOpen()) {

                    $this->container->get('doctrine')->resetManager();
                    $this->manager = $this->getDoctrine()->getManager();
                    $this->groupe = $this->manager->merge($this->groupe);
                    $this->new_post = $this->manager->merge($this->new_post);
                    $this->progressPstPersistance=$this->manager->merge($this->progressPstPersistance);
                    $this->nPostImporté--;
                    $this->progressPstPersistance->setNbrPostImport($this->nPostImporté);
                    $this->manager->flush();
                    }
            }
       //RECUPERATION DES COMMENTAIRES DU POST
       $this->importCommentaires();
    }

    /**
     * A appeler àprès l'intialisation d'un post
     * Cette méthode accède au proprietés privés du controlleur
     *
     * @return void
     */
    private function importJaimes(){

            $requete = "/". $this->new_post->getId()."?fields=likes.limit(5000).fields(id)";
            $ResultJaimes = $this->facebook->api($requete);

            //Si il y a des personnes qui aiment la publication
            if(isset($ResultJaimes['likes'])){

            $nbrTotJaime = count($ResultJaimes['likes']['data']);
            $nbrJaimesImport=0;
            $this->progressPstPersistance->setNbrToJaime($nbrTotJaime);
            $this->manager->flush();

            foreach ($ResultJaimes['likes']['data'] as &$usr_passioné) {

                $this->findOuCreatMembre($usr_passioné['id']);
                $this->new_post->addJaime($this->new_usr);
                $nbrJaimesImport++;
                $this->progressPstPersistance->setNbrJaimeImport($nbrJaimesImport);
                $this->manager->flush();
            }
            }     $this->progressPstPersistance->setNbrToJaime(-1);
            $this->manager->flush();
    }

   /**
    * A appeler àprès l'intialisation d'un post et importation des commentaires
    * Cette méthode accède au proprietés privés du controlleur
    *
    * @return void
    */
    private function importCommentaires(){

            $requete = "/".$this->new_post->getId()."?fields=comments.limit(5000).fields(id,message,like_count,created_time,from)";
            $ResultComments = $this->facebook->api($requete);

            if(isset($ResultComments['comments'])){
            $nbrComment = count($ResultComments['comments']['data']);
            $this->progressPstPersistance->setNbrTotComment($nbrComment);

            $nbrCommentImport = 0;
            //On boucle sur les jaimes
            foreach ($ResultComments['comments']['data'] as &$comment) {

                $commentaire=new Commentaire($comment['id']);
                $commentaire->setMessage($comment['message'])
                               ->setDateCreation(new \DateTime($comment['created_time']))
                               ->setNbrJaime($comment['like_count']);

                $id_commentateur=$comment['from']['id'];

                $this->findOuCreatMembre($id_commentateur);

                $commentaire->setCommentateur($this->new_usr);

                $commentaire->setPost($this->new_post);

            try{

            $this->manager->persist($commentaire);
            $nbrCommentImport++;
            $this->progressPstPersistance->setNbrComImport($nbrCommentImport);
            $this->manager->flush();

            } catch (DBALException $e) {
                //Si l'entity Manager est férmé
                if (!$this->getDoctrine()->getEntityManager()->isOpen()) {

                    $this->container->get('doctrine')->resetManager();
                    $this->manager = $this->getDoctrine()->getManager();
                    $this->groupe = $this->manager->merge($this->groupe);
                    $this->new_post = $this->manager->merge($this->new_post);
                    $this->progressPstPersistance=$this->manager->merge($this->progressPstPersistance);
                    $nbrCommentImport--;
                }
            }              }
            }$this->progressPstPersistance->setNbrTotComment(-1);
    }

/**
     * Cette méthode nous pertmet de suivre la progression de l"importation des posts
     * A chaque ajout on persiste un objet de PersistProgressPst
     *
     * @Route("/importposts/progress/{id_gp}" , name="postsProgress")
     *
     *
     * @param long $id_gp l'id du groupe
     * @return Response PersistProgressPst au formatat JSON
     */

    public function progressPostsAction($id_gp){

        $em=$this->getDoctrine()->getManager();
        $this->progressPstPersistance=$em->find("FBgroupeBundle:PersistProgressPst", $id_gp);

        $objetJSON=  json_encode($this->progressPstPersistance);
        $response=new Response($objetJSON);
        $response->headers->set('Content-Type', 'application/json');
        return $response;
    }
    /**
     * Cette méthode nous permet de suivre la progression de l'importation des membres
     * A chaque ajout on persiste un objet de PersistProgressionMb
     *
     * @Route("/importmembres/progress/{id_gp}" ,  name="membresProgress")
     *
     *
     * @param long $id_gp l'id du groupe
     *
     * @return Response PersistProgressionMb au formatat JSON
     */

    public function progressMembresAction($id_gp){

        $em=$this->getDoctrine()->getManager();
        $this->progressMbPersistance=$em->find("FBgroupeBundle:PersistProgressionMb", $id_gp);

        $objetJSON=  json_encode($this->progressMbPersistance);
       $response=new Response($objetJSON);
        $response->headers->set('Content-Type', 'application/json');
        return $response;
    }

    /**
     * Cette méthode nous permet d'importer le formulaire d'importation de groupe
     *
     * @Route("/importposts/vues", name="vues_importpost")
     *
     *@return Response une vue twig contenant un formaulaire
     */

    public function sendVuesImportPostAction() {
    $this->facebook = $this->get('fos_facebook.api');

    if($this->facebook->getUser() == 0) {
            return $this->forward("FBgroupeBundle:Accueil:index");
        }

        return $this->render('FBgroupeBundle:FbGroupeViews:VuesImportPost.html.twig');
    }

}


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace Podcasts.Dom
{
    public interface IUriResolution : IDisposable
    {
        Task<Stream> GetStreamAsync(Uri uri);
    }

    public class HttpUriResolution : IUriResolution
    {
        private HttpClient _client = new HttpClient();

        public void Dispose()
        {
            _client.Dispose();
        }

        public Task<Stream> GetStreamAsync(Uri location)
        {
            if (location.Scheme != "http" && location.Scheme != "https")
            {
                throw new ArgumentOutOfRangeException($"{nameof(location)} must be an http or https URI");
            }

            return _client.GetStreamAsync(location);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
require 'spec_helper'

module Watir
  describe FileField do
    describe '#field_value' do
      subject { FileField.new('', id: '') }

      context 'no path is set' do
        it 'returns empty string' do
          allow(subject).to receive(:value).and_return(nil)
          expect(subject.field_value).to eq('')
        end
      end

      context 'a path is set' do
        it 'returns string with file name' do
          allow(subject).to receive(:value).and_return('form.html')
          expect(subject.field_value).to eq('form.html')
        end
      end
    end
  end
end


text:
import sys
import time
import Log
import MemPool
import ChainDb
import cStringIO

from bitcoin.coredefs import NETWORKS
from bitcoin.core import CBlock
from bitcoin.serialize import ser_uint256
from bitcoin.scripteval import VerifySignature

NET_SETTINGS = {
	'mainnet' : {
		'log' : '/spare/tmp/testscript.log',
		'db' : '/spare/tmp/chaindb'
	},
	'testnet3' : {
		'log' : '/spare/tmp/testtestscript.log',
		'db' : '/spare/tmp/chaintest'
	}
}

MY_NETWORK = 'mainnet'

SETTINGS = NET_SETTINGS[MY_NETWORK]

start_height = 0
end_height = -1
if len(sys.argv) > 1:
	start_height = int(sys.argv[1])
if len(sys.argv) > 2:
	end_height = int(sys.argv[2])
if len(sys.argv) > 3:
	SETTINGS['log'] = sys.argv[3]

log = Log.Log(SETTINGS['log'])
mempool = MemPool.MemPool(log)
chaindb = ChainDb.ChainDb(SETTINGS['db'], log, mempool,
			  NETWORKS[MY_NETWORK], True)
chaindb.blk_cache.max = 500

if end_height < 0 or end_height > chaindb.getheight():
	end_height = chaindb.getheight()

scanned = 0
scanned_tx = 0
failures = 0
opcount = {}

SKIP_TX = {
}

def scan_tx(tx):
	tx.calc_sha256()

	if tx.sha256 in SKIP_TX:
		return True

#	log.write("...Scanning TX %064x" % (tx.sha256,))
	for i in xrange(len(tx.vin)):
		txin = tx.vin[i]
		txfrom = chaindb.gettx(txin.prevout.hash)
		if not VerifySignature(txfrom, tx, i, 0):
			log.write("TX %064x/%d failed" % (tx.sha256, i))
			log.write("FROMTX %064x" % (txfrom.sha256,))
			log.write(txfrom.__repr__())
			log.write("TOTX %064x" % (tx.sha256,))
			log.write(tx.__repr__())
			return False
	return True

for height in xrange(end_height):
	if height < start_height:
		continue
	heightidx = ChainDb.HeightIdx()
	heightidx.deserialize(chaindb.height[str(height)])

	blkhash = heightidx.blocks[0]
	ser_hash = ser_uint256(blkhash)

	f = cStringIO.StringIO(chaindb.blocks[ser_hash])
	block = CBlock()
	block.deserialize(f)

	start_time = time.time()

	for tx_tmp in block.vtx:
		if tx_tmp.is_coinbase():
			continue

		scanned_tx += 1

		if not scan_tx(tx_tmp):
			failures += 1
			sys.exit(1)

	end_time = time.time()

	scanned += 1
#	if (scanned % 1000) == 0:
	log.write("Scanned %d tx, height %d (%d failures), %.2f sec" % (
		scanned_tx, height, failures, end_time - start_time))

log.write("Scanned %d tx, %d blocks (%d failures)" % (
	scanned_tx, scanned, failures))

#for k,v in opcount.iteritems():
#	print k, v


text:
aboutme
=======

From frontend JS course code in related repo (github.com/richierichrawr/frontend-nanodegree-resume).  Code is modified for jQuery to slidetoggle on divs.  Intended to hold resume material.


text:
namespace Logger.Entites.Layouts.Factory
{
    using System;
    using System.Linq;
    using System.Reflection;
    using Interfaces;

    public class LayoutFactory
    {
        public ILayout CreateLayout(string layoutName)
        {
            Type layoutType = Assembly
                .GetExecutingAssembly()
                .GetTypes()
                .FirstOrDefault(t => t.Name == layoutName);
            return (ILayout) Activator.CreateInstance(layoutType);
        }
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">

<title>Forms :: legend : margin-bottom</title>

<form action="">
	<fieldset>
		<legend>x</legend>
		x
		</fieldset>
</form>

Ahem font required for this test

you should see a yellow square

yellow square should be located inside the blue area,
	not outside of it

the bottom and left edges of the yellow square should be
	aligned with the bottom and left edges of the blue area,
	respectively.


text:
using Content.Shared.Damage.Prototypes;
using Robust.Shared.Serialization.TypeSerializers.Implementations.Custom.Prototype.List;

namespace Content.Server.Xenoarchaeology.XenoArtifacts.Triggers.Components;

/// <summary>
/// Triggers when a certain threshold of damage of certain types is reached
/// </summary>
[RegisterComponent]
public sealed class ArtifactDamageTriggerComponent : Component
{
    /// <summary>
    /// What damage types are accumulated for the trigger?
    /// </summary>
    [DataField("damageTypes", customTypeSerializer: typeof(PrototypeIdListSerializer<DamageTypePrototype>))]
    public List<string>? DamageTypes;

    /// <summary>
    /// What threshold has to be reached before it is activated?
    /// </summary>
    [DataField("damageThreshold", required: true)]
    public float DamageThreshold;

    /// <summary>
    /// How much damage has been accumulated on the artifact so far
    /// </summary>
    [ViewVariables(VVAccess.ReadWrite)]
    public float AccumulatedDamage = 0;
}


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

namespace Application.Web.Areas.Administration.Models.ViewModels
{
    public class TagViewModel
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
}


text:
from collections import deque

import rospy
import numpy
import tf
import actionlib
import yaml
from math import sqrt, cos
from collections import *
from sklearn.cluster import KMeans

from std_msgs.msg import *
from geometry_msgs.msg import *
from move_base_msgs.msg import *
from nav_msgs.msg import OccupancyGrid, Odometry, MapMetaData

class PathPlanner:
    UP = Quaternion(0, 0, 0.7071, 0.7071)
    DOWN = Quaternion(0, 0, -0.7071, 0.7071)
    LEFT = Quaternion(0, 0, 1, 0)
    RIGHT = Quaternion(0, 0, 0, 1)

    def __init__(self):
        self.goals = deque()
        self.offset = (0, 0)
        self.resolution = 0
        self.map = None
        self.listener = None
        self.client = actionlib.SimpleActionClient('move_base', MoveBaseAction)
        self.seq = -1
        self.step = 0.2

    def extract_points(self, ogrid):
        points = []
        #print numpy.asarray(ogrid.data)
        for i in xrange(len(ogrid.data)):
            #if there is contamination in an empty space, add point to list
            if ogrid.data[i] > 0 and self.map[i] == 0:
                newp = [j*ogrid.info.resolution for j in divmod(i, ogrid.info.width)]
                newp.reverse()
                points.append(newp)
        return numpy.asarray(points)

    def bounding_box(self, points):
        min_x, min_y = numpy.min(points, axis=0)
        max_x, max_y = numpy.max(points, axis=0)
        min_x += self.offset[0]
        max_x += self.offset[0]
        min_y += self.offset[1]
        max_y += self.offset[1]
        center = ((min_x + max_x)/2, (min_y+max_y)/2)
        #print min_x, min_y, max_x, max_y, center
        return [min_x, min_y, max_x, max_y, center]

    def _set_map(self, new_map, costmap):
        #0.177 = robot radius - parameterize so it can source from same place as cleanerbot?
        self.offset = (new_map.info.origin.position.x, new_map.info.origin.position.y)
        self.resolution = new_map.info.resolution
        m = []
        for i in xrange(len(new_map.data)):
            if new_map.data[i] > -1 and new_map.data[i] < costmap.data[i] and costmap.data[i] >= 40: m.append(costmap.data[i])
            else: m.append(new_map.data[i])
        self.map = m

    def _set_goal(self, header, x, y, orientation):
        pose = PoseStamped(header, Pose(Point(x, y, 0), orientation))
        goal = MoveBaseGoal()
        goal.target_pose = pose
        return goal

    def _set_cluster_goals(self, points, data, corner):
        #data format: (min_x, min_y, max_x, max_y, center)
        #print data
        vert, horiz = corner.split()
        g = []
        if vert == 'top': #start from top
            goal_range = numpy.arange(data[3], data[1], 0-self.step)
        elif vert == 'bottom': #start from bottom
            goal_range = numpy.arange(data[1], data[3], self.step)
        for y in goal_range:
            point_slice = []
            for p in points:
                if abs(y-p[1]) <= self.step: point_slice.append(p)
            try:
                min_x, min_y = numpy.min(point_slice, axis=0)
                max_x, max_y = numpy.max(point_slice, axis=0)
            except ValueError:
                continue
            header = Header(self.seq, rospy.Time.now(), '/map')
            if horiz == 'left':
                g.append(self._set_goal(header, min_x, y, self.RIGHT))
                g.append(self._set_goal(header, max_x, y, self.LEFT))
            elif horiz == 'right': #start from right
                g.append(self._set_goal(header, max_x, y, self.LEFT))
                g.append(self._set_goal(header, min_x, y, self.RIGHT))
        return g

    def _dist(self, a, b):
        #print a, b
        return sqrt((a[0]-b[0])**2 + (a[1]-b[1])**2)

    #pass it points in order: brute force (recursive?) nearest-neighbor
    #point format: [(point_id, (x, y))]
    def _nearest_neighbor(self, base_point, points):
        if len(points) == 0:
            return []
        else:
            temp = numpy.inf
            index = -1
            for p in xrange(len(points)):
                dist = self._dist(base_point[1], points[p][1])
                #print 'robot_loc: {0} >> cluster{1} loc: {2}: {3}'.format(base_point[1], p, points[p][1], dist)
                if dist < temp:
                    temp = dist
                    index = p
            next_point = points.pop(index)
            direction = None
            if base_point[1][0] < next_point[1][0]:
                if base_point[1][1] < next_point[1][1]:
                    direction = "bottom left"
                else: direction = "top left"
            elif base_point[1][1] < next_point[1][1]: direction = "bottom right"
            else: direction = "top right"
            x = [(next_point[0], direction)]
            x.extend(self._nearest_neighbor(next_point, points))
            return x

    def _get_order(self, centers):
        #determine order of clusters to publish points for
        #centers should be a list of (x, y) tuples
        robot = rospy.wait_for_message("amcl_pose", PoseWithCovarianceStamped)
        robot_loc = robot.pose.pose.position
        points = zip(range(len(centers)), centers)
        #print points
        path = self._nearest_neighbor((None, (robot_loc.x, robot_loc.y)), points)
        #print path
        #point_order, directions = zip(*path)
        return path

    def set_path(self, ogrid):
        #group contam_points into boxes, prioritizing less dirty areas first
        points = self.extract_points(ogrid)
        if points.size==0:
            rospy.signal_shutdown("Cleaning complete. Program will now exit.")
            return
        else:
            n_clusters = int(round(points.size/2*(self.resolution**2))) #1 cluster ~= 1 sq. meter
        print n_clusters
        cluster_data = []
        if n_clusters >= 1:
            kmeans = KMeans(n_clusters).fit(points)
            for n in xrange(n_clusters):
                xy = points[kmeans.labels_==n]
                #print "point {0}".format(n)
                cluster_data.append(self.bounding_box(xy))
            order = self._get_order([x[4] for x in cluster_data])
            self.seq += 1
            self.goals.extend(self._set_cluster_goals(points[kmeans.labels_==order[0][0]].tolist(), cluster_data[order[0][0]], order[0][1]))
            # for o in order:
            #     self.goals.extend(self._set_cluster_goals(cluster_data[o[0]], o[1]))
            #     self.seq += 1
        # elif n_clusters == 0 and -1 in db.labels_:
        #     xy = points[db.labels_== -1]
        #     for point in xy:
        #         header = Header(self.seq, rospy.Time.now(), '/map')
        #         self.seq += 1
        #         pose = PoseStamped(header, Pose(Point(point[0], point[1], 0), RIGHT))
        #         goal = MoveBaseGoal()
        #         goal.target_pose = pose
        #         self.goals.append(goal)
        else:
            rospy.signal_shutdown("Cleaning complete. Program will now exit.")

#send next goal if previous one has completed/terminated
    def send_goal(self):
        self.client.wait_for_server()
        goal = self.goals.popleft()
        try:
            print "Sending Goal"
            self.client.send_goal(goal)
        except IndexError:
            print "Oops! No more goals!"
            return
        self.client.wait_for_result()
        state = self.client.get_state()
        count = 0
        while state == 4 and count < 3: #if server rejects goal, try another goal a little closer
            print "Goal failed. Trying again."
            pose = goal.target_pose.pose
            if pose.orientation == self.LEFT: pose.position.x -= self.step
            elif pose.orientation == self.RIGHT: pose.position.x += self.step
            goal.target_pose.pose = pose
            self.client.send_goal(goal)
            self.client.wait_for_result()
            state = self.client.get_state()
            count+=1

    def setup(self):
        rospy.init_node('path_planner', anonymous=True)
        base_map = rospy.wait_for_message("map", OccupancyGrid)
        costmap = rospy.wait_for_message("/move_base/global_costmap/costmap", OccupancyGrid)
        self._set_map(base_map,costmap)
        r = rospy.Rate(5)
        while not rospy.is_shutdown():
            if self.goals: self.send_goal() #if there is a goal, send something
            else:
                msg = rospy.wait_for_message("contamination_grid", OccupancyGrid)
                self.set_path(msg)
            #print "Looping"
            r.sleep()

if __name__ == '__main__':
    node = PathPlanner()
    try:
        node.setup()
    except rospy.ROSInterruptException:
        pass


text:
<?php
return array (
  'Calvin Klein – Between love and madness lies obsession.' => 'Mně se hodně líbilo to přirovnání, že je Bůh jako náš otec. Myslím, že kdo má děti, dokáže si dobře představit, co to znamená.',
  'Create Admin Account' => 'Vytvořit účet administrátora',
  'Nike – Just buy it. ;Wink;' => 'Asi nejvíc vývojová psychologie dítěte. Měl dobré postřehy.',
  'We\'re looking for great slogans of famous brands. Maybe you can come up with some samples?' => 'Kdo jste dneska byli na tom semináři v aule - co vás nejvíc zaujalo?',
  'Welcome Space' => 'Uvítací prostor',
  'Yay! I\'ve just installed HumHub ;Cool;' => 'Jupí, právě jsme nainstalovali HumHub ;Cool;',
  'Your first sample space to discover the platform.' => 'Toto je první prostor, ve kterém vítáme nové uživatele.',
);


text:
package fiddle.android.droidz.model.components;

public class Speed {

    public static final int DIRECTION_RIGHT	= 1;
    public static final int DIRECTION_LEFT	= -1;
    public static final int DIRECTION_UP	= -1;
    public static final int DIRECTION_DOWN	= 1;

    private float xv = 1;	// velocity value on the X axis
    private float yv = 1;	// velocity value on the Y axis

    private int xDirection = DIRECTION_RIGHT;
    private int yDirection = DIRECTION_DOWN;

    public Speed() {
        this.xv = 5;
        this.yv = 5;
    }

    public Speed(float xv, float yv) {
        this.xv = xv;
        this.yv = yv;
    }

    public float getXv() {
        return xv;
    }
    public void setXv(float xv) {
        this.xv = xv;
    }
    public float getYv() {
        return yv;
    }
    public void setYv(float yv) {
        this.yv = yv;
    }

    public int getxDirection() {
        return xDirection;
    }
    public void setxDirection(int xDirection) {
        this.xDirection = xDirection;
    }
    public int getyDirection() {
        return yDirection;
    }
    public void setyDirection(int yDirection) {
        this.yDirection = yDirection;
    }

    // changes the direction on the X axis
    public void toggleXDirection() {
        xDirection = xDirection * -1;
    }

    // changes the direction on the Y axis
    public void toggleYDirection() {
        yDirection = yDirection * -1;
    }

}


text:
#include <aws/ds/model/EnableSsoResult.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/UnreferencedParam.h>

#include <utility>

using namespace Aws::DirectoryService::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws;

EnableSsoResult::EnableSsoResult()
{
}

EnableSsoResult::EnableSsoResult(const AmazonWebServiceResult<JsonValue>& result)
{
  *this = result;
}

EnableSsoResult& EnableSsoResult::operator =(const AmazonWebServiceResult<JsonValue>& result)
{
  AWS_UNREFERENCED_PARAM(result);

  return *this;
}


text:
ytcenter = ytcenter || {};
ytcenter.io = ytcenter.io || {};
(function(self, ytcenter){
  /* Blob.js
   * A Blob implementation.
   * 2013-06-20
   *
   * By Eli Grey, http://eligrey.com
   * By Devin Samarin, https://github.com/eboyjr
   * License: X11/MIT
   *   See LICENSE.md
   */
  /*! @source http://purl.eligrey.com/github/Blob.js/blob/master/Blob.js */
  try {ytcenter.io.Blob = Blob;} catch (e) {}
  if (typeof Blob !== "function" || typeof URL === "undefined")
  if (typeof Blob === "function" && typeof webkitURL !== "undefined") self.URL = webkitURL;
  else ytcenter.io.Blob = (function (view) {
    "use strict";

    var BlobBuilder = (function(){
      var a = false;
      try {
        a = view.BlobBuilder || view.WebKitBlobBuilder || view.MozBlobBuilder || view.MSBlobBuilder;
      } catch (e) {
        try {
          a = view.WebKitBlobBuilder || view.MozBlobBuilder || view.MSBlobBuilder;
        } catch (e) {
          try {
            a = view.MozBlobBuilder || view.MSBlobBuilder;
          } catch (e) {
            try {
              a = view.MSBlobBuilder;
            } catch (e) {
            }
          }
        }
      }
      return a;
    })() || (function(view) {
      var
          get_class = function(object) {
          return Object.prototype.toString.call(object).match(/^\[object\s(.*)\]$/)[1];
        }
        , FakeBlobBuilder = function BlobBuilder() {
          this.data = [];
        }
        , FakeBlob = function(data, type, encoding) {
          this.data = data;
          this.size = data.length;
          this.type = type;
          this.encoding = encoding;
        }
        , FBB_proto = FakeBlobBuilder.prototype
        , FB_proto = FakeBlob.prototype
        , FileReaderSync = view.FileReaderSync
        , FileException = function(type) {
          this.code = this[this.name = type];
        }
        , file_ex_codes = (
            "NOT_FOUND_ERR SECURITY_ERR ABORT_ERR NOT_READABLE_ERR ENCODING_ERR "
          + "NO_MODIFICATION_ALLOWED_ERR INVALID_STATE_ERR SYNTAX_ERR"
        ).split(" ")
        , file_ex_code = file_ex_codes.length
        , real_URL = view.URL || view.webkitURL || view
        , real_create_object_URL = real_URL.createObjectURL
        , real_revoke_object_URL = real_URL.revokeObjectURL
        , URL = real_URL
        , btoa = view.btoa
        , atob = view.atob

        , ArrayBuffer = view.ArrayBuffer
        , Uint8Array = view.Uint8Array
      ;
      FakeBlob.fake = FB_proto.fake = true;
      while (file_ex_code--) {
        FileException.prototype[file_ex_codes[file_ex_code]] = file_ex_code + 1;
      }
      if (!real_URL.createObjectURL) {
        URL = view.URL = {};
      }
      URL.createObjectURL = function(blob) {
        var
            type = blob.type
          , data_URI_header
        ;
        if (type === null) {
          type = "application/octet-stream";
        }
        if (blob instanceof FakeBlob) {
          data_URI_header = "data:" + type;
          if (blob.encoding === "base64") {
            return data_URI_header + ";base64," + blob.data;
          } else if (blob.encoding === "URI") {
            return data_URI_header + "," + decodeURIComponent(blob.data);
          } if (btoa) {
            return data_URI_header + ";base64," + btoa(blob.data);
          } else {
            return data_URI_header + "," + encodeURIComponent(blob.data);
          }
        } else if (real_create_object_URL) {
          return real_create_object_URL.call(real_URL, blob);
        }
      };
      URL.revokeObjectURL = function(object_URL) {
        if (object_URL.substring(0, 5) !== "data:" && real_revoke_object_URL) {
          real_revoke_object_URL.call(real_URL, object_URL);
        }
      };
      FBB_proto.append = function(data/*, endings*/) {
        var bb = this.data;
        // decode data to a binary string
        if (Uint8Array && (data instanceof ArrayBuffer || data instanceof Uint8Array)) {
          var
              str = ""
            , buf = new Uint8Array(data)
            , i = 0
            , buf_len = buf.length
          ;
          for (; i < buf_len; i++) {
            str += String.fromCharCode(buf[i]);
          }
          bb.push(str);
        } else if (get_class(data) === "Blob" || get_class(data) === "File") {
          if (FileReaderSync) {
            var fr = new FileReaderSync;
            bb.push(fr.readAsBinaryString(data));
          } else {
            // async FileReader won't work as BlobBuilder is sync
            throw new FileException("NOT_READABLE_ERR");
          }
        } else if (data instanceof FakeBlob) {
          if (data.encoding === "base64" && atob) {
            bb.push(atob(data.data));
          } else if (data.encoding === "URI") {
            bb.push(decodeURIComponent(data.data));
          } else if (data.encoding === "raw") {
            bb.push(data.data);
          }
        } else {
          if (typeof data !== "string") {
            data += ""; // convert unsupported types to strings
          }
          // decode UTF-16 to binary string
          bb.push(unescape(encodeURIComponent(data)));
        }
      };
      FBB_proto.getBlob = function(type) {
        if (!arguments.length) {
          type = null;
        }
        return new FakeBlob(this.data.join(""), type, "raw");
      };
      FBB_proto.toString = function() {
        return "[object BlobBuilder]";
      };
      FB_proto.slice = function(start, end, type) {
        var args = arguments.length;
        if (args < 3) {
          type = null;
        }
        return new FakeBlob(
            this.data.slice(start, args > 1 ? end : this.data.length)
          , type
          , this.encoding
        );
      };
      FB_proto.toString = function() {
        return "[object Blob]";
      };
      return FakeBlobBuilder;
    }(view));

    return function(blobParts, options) {
      var type = options ? (options.type || "") : "";
      var builder = new BlobBuilder();
      if (blobParts) {
        for (var i = 0, len = blobParts.length; i < len; i++) {
          builder.append(blobParts[i]);
        }
      }
      return builder.getBlob(type);
    };
  }(self));

  /* FileSaver.js
  * A saveAs() FileSaver implementation.
  * 2013-01-23
  *
  * By Eli Grey, http://eligrey.com
  * License: X11/MIT
  *   See LICENSE.md
  */
  /*! @source http://purl.eligrey.com/github/FileSaver.js/blob/master/FileSaver.js */
  ytcenter.io.saveAs = (self && self.saveAs)
    || (navigator && navigator.msSaveOrOpenBlob && navigator.msSaveOrOpenBlob.bind(navigator))
    || (function(view) {
    "use strict";
    var
        doc = view.document
        // only get URL when necessary in case BlobBuilder.js hasn't overridden it yet
      , get_URL = function() {
        var a;
        try {
          a = view.URL || view.webkitURL || view;
        } catch (e) {
          try {
            a = view.URL || view.webkitURL || view;
          } catch (e) {
            try {
              a = view.webkitURL || view;
            } catch (e) {
              try {
                a = view;
              } catch (e) {

              }
            }
          }
        }
        return a;
      }
      , URL = get_URL()
      , save_link = doc.createElementNS("http://www.w3.org/1999/xhtml", "a")
      , can_use_save_link =  !view.externalHost && "download" in save_link
      , click = function(node) {
        var event = doc.createEvent("MouseEvents");
        event.initMouseEvent(
          "click", true, false, view, 0, 0, 0, 0, 0
          , false, false, false, false, 0, null
        );
        node.dispatchEvent(event);
      }
      , webkit_req_fs = view.webkitRequestFileSystem
      , req_fs = view.requestFileSystem || webkit_req_fs || view.mozRequestFileSystem
      , throw_outside = function (ex) {
        (view.setImmediate || view.setTimeout)(function() {
          throw ex;
        }, 0);
      }
      , force_saveable_type = "application/octet-stream"
      , fs_min_size = 0
      , deletion_queue = []
      , process_deletion_queue = function() {
        var i = deletion_queue.length;
        while (i--) {
          var file = deletion_queue[i];
          if (typeof file === "string") { // file is an object URL
            URL.revokeObjectURL(file);
          } else { // file is a File
            file.remove();
          }
        }
        deletion_queue.length = 0; // clear queue
      }
      , dispatch = function(filesaver, event_types, event) {
        event_types = [].concat(event_types);
        var i = event_types.length;
        while (i--) {
          var listener = filesaver["on" + event_types[i]];
          if (typeof listener === "function") {
            try {
              listener.call(filesaver, event || filesaver);
            } catch (ex) {
              throw_outside(ex);
            }
          }
        }
      }
      , FileSaver = function(blob, name) {
        // First try a.download, then web filesystem, then object URLs
        var
            filesaver = this
          , type = blob.type
          , blob_changed = false
          , object_url
          , target_view
          , get_object_url = function() {
            var object_url = get_URL().createObjectURL(blob);
            deletion_queue.push(object_url);
            return object_url;
          }
          , dispatch_all = function() {
            dispatch(filesaver, "writestart progress write writeend".split(" "));
          }
          // on any filesys errors revert to saving with object URLs
          , fs_error = function() {
            // don't create more object URLs than needed
            if (blob_changed || !object_url) {
              object_url = get_object_url(blob);
            }
            if (target_view) {
              target_view.location.href = object_url;
            } else {
                          window.open(object_url, "_blank");
                      }
            filesaver.readyState = filesaver.DONE;
            dispatch_all();
          }
          , abortable = function(func) {
            return function() {
              if (filesaver.readyState !== filesaver.DONE) {
                return func.apply(this, arguments);
              }
            };
          }
          , create_if_not_found = {create: true, exclusive: false}
          , slice
        ;
        filesaver.readyState = filesaver.INIT;
        if (!name) {
          name = "download";
        }
        if (can_use_save_link) {
          object_url = get_object_url(blob);
          save_link.href = object_url;
          save_link.download = name;
          click(save_link);
          filesaver.readyState = filesaver.DONE;
          dispatch_all();
          return;
        }
        // Object and web filesystem URLs have a problem saving in Google Chrome when
        // viewed in a tab, so I force save with application/octet-stream
        // http://code.google.com/p/chromium/issues/detail?id=91158
        if (view.chrome && type && type !== force_saveable_type) {
          slice = blob.slice || blob.webkitSlice;
          blob = slice.call(blob, 0, blob.size, force_saveable_type);
          blob_changed = true;
        }
        // Since I can't be sure that the guessed media type will trigger a download
        // in WebKit, I append .download to the filename.
        // https://bugs.webkit.org/show_bug.cgi?id=65440
        if (webkit_req_fs && name !== "download") {
          name += ".download";
        }
        if (type === force_saveable_type || webkit_req_fs) {
          target_view = view;
        }
        if (!req_fs) {
          fs_error();
          return;
        }
        fs_min_size += blob.size;
        req_fs(view.TEMPORARY, fs_min_size, abortable(function(fs) {
          fs.root.getDirectory("saved", create_if_not_found, abortable(function(dir) {
            var save = function() {
              dir.getFile(name, create_if_not_found, abortable(function(file) {
                file.createWriter(abortable(function(writer) {
                  writer.onwriteend = function(event) {
                    target_view.location.href = file.toURL();
                    deletion_queue.push(file);
                    filesaver.readyState = filesaver.DONE;
                    dispatch(filesaver, "writeend", event);
                  };
                  writer.onerror = function() {
                    var error = writer.error;
                    if (error.code !== error.ABORT_ERR) {
                      fs_error();
                    }
                  };
                  "writestart progress write abort".split(" ").forEach(function(event) {
                    writer["on" + event] = filesaver["on" + event];
                  });
                  writer.write(blob);
                  filesaver.abort = function() {
                    writer.abort();
                    filesaver.readyState = filesaver.DONE;
                  };
                  filesaver.readyState = filesaver.WRITING;
                }), fs_error);
              }), fs_error);
            };
            dir.getFile(name, {create: false}, abortable(function(file) {
              // delete file if it already exists
              file.remove();
              save();
            }), abortable(function(ex) {
              if (ex.code === ex.NOT_FOUND_ERR) {
                save();
              } else {
                fs_error();
              }
            }));
          }), fs_error);
        }), fs_error);
      }
      , FS_proto = FileSaver.prototype
      , saveAs = function(blob, name) {
        return new FileSaver(blob, name);
      }
    ;
    FS_proto.abort = function() {
      var filesaver = this;
      filesaver.readyState = filesaver.DONE;
      dispatch(filesaver, "abort");
    };
    FS_proto.readyState = FS_proto.INIT = 0;
    FS_proto.WRITING = 1;
    FS_proto.DONE = 2;

    FS_proto.error =
    FS_proto.onwritestart =
    FS_proto.onprogress =
    FS_proto.onwrite =
    FS_proto.onabort =
    FS_proto.onerror =
    FS_proto.onwriteend =
      null;

    view.addEventListener("unload", process_deletion_queue, false);
    return saveAs;
  }(self));
})(self, ytcenter);


text:
#include "vice.h"

#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
#include <ctype.h>
#include <dir.h>
#include <errno.h>
#include <io.h>
#include <process.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <unistd.h>

#include <allegro.h>

#include <dos.h>

#include "archdep.h"
#include "fcntl.h"
#include "lib.h"
#include "log.h"
#include "machine.h"
#include "platform.h"
#include "util.h"
#include "video.h"

static char *orig_workdir;
static char *argv0;

int archdep_network_init(void)
{
    return 0;
}

void archdep_network_shutdown(void)
{
}

static void restore_workdir(void)
{
    if (orig_workdir) {
        chdir(orig_workdir);
    }
}

int archdep_init(int *argc, char **argv)
{
    allegro_init();

    _fmode = O_BINARY;

    argv0 = lib_stralloc(argv[0]);

    orig_workdir = getcwd(NULL, PATH_MAX);
    atexit(restore_workdir);

    return 0;
}

char *archdep_program_name(void)
{
    static char *program_name = NULL;

    if (program_name == NULL) {
        char *s, *e;
        int len;

        s = strrchr(argv0, '/');
        if (s == NULL) {
            s = argv0;
        } else {
            s++;
        }
        e = strchr(s, '.');
        if (e == NULL) {
            e = argv0 + strlen(argv0);
        }

        len = e - s + 1;
        program_name = lib_malloc(len);
        memcpy(program_name, s, len - 1);
        program_name[len - 1] = 0;
    }

    return program_name;
}

const char *archdep_boot_path(void)
{
    static char *boot_path;

    if (boot_path == NULL) {
        util_fname_split(argv0, &boot_path, NULL);

        /* This should not happen, but you never know...  */
        if (boot_path == NULL) {
            boot_path = lib_stralloc("./");
        }
    }

    return boot_path;
}

char *archdep_default_sysfile_pathlist(const char *emu_id)
{
    static char *default_path;

    if (default_path == NULL) {
        const char *boot_path = archdep_boot_path();

        default_path = util_concat(boot_path, "/", emu_id,
                                   ARCHDEP_FINDPATH_SEPARATOR_STRING,
                                   boot_path, "/", "DRIVES",
                                   ARCHDEP_FINDPATH_SEPARATOR_STRING,
                                   boot_path, "/", "PRINTER",
                                   NULL);
    }

    return default_path;
}

/* Return a malloc'ed backup file name for file `fname'.  */
char *archdep_make_backup_filename(const char *fname)
{
    static char backup_name[MAXPATH];
    char drive[MAXDRIVE];
    char dir[MAXDIR];
    char name[MAXFILE];
    char ext[MAXEXT];

    fnsplit(fname, drive, dir, name, ext);
    fnmerge(backup_name, drive, dir, name, "BAK");

    return lib_stralloc(backup_name);
}

char *archdep_default_save_resource_file_name(void)
{
    return archdep_default_resource_file_name();
}

char *archdep_default_resource_file_name(void)
{
    return util_concat(archdep_boot_path(), "\\vicerc", NULL);
}

char *archdep_default_fliplist_file_name(void)
{
    return util_concat(archdep_boot_path(), "\\",
                       machine_get_name(), ".vfl", NULL);
}

char *archdep_default_autostart_disk_image_file_name(void)
{
    const char *home;

    home = archdep_boot_path();
    return util_concat(home, "\\auto-", machine_get_name(), ".d64", NULL);
}

FILE *archdep_open_default_log_file(void)
{
    char *fname;
    FILE *f;

    fname = util_concat(archdep_boot_path(), "\\vice.log", NULL);
    f = fopen(fname, "wt");
    lib_free(fname);

    return f;
}

int archdep_num_text_lines(void)
{
    struct text_info text_mode_info;

    gettextinfo(&text_mode_info);
    return text_mode_info.screenheight;
}

int archdep_num_text_columns(void)
{
    struct text_info text_mode_info;

    gettextinfo(&text_mode_info);
    return text_mode_info.screenwidth;
}

int archdep_default_logger(const char *level_string, const char *txt)
{
    return 0;
}

int archdep_path_is_relative(const char *path)
{
    if (path == NULL) {
        return 0;
    }

    /* `c:\foo', `c:/foo', `c:foo', `\foo' and `/foo' are absolute.  */

    return !((isalpha(path[0]) && path[1] == ':') || path[0] == '/' || path[0] == '\\');
}

int archdep_spawn(const char *name, char **argv, char **pstdout_redir, const char *stderr_redir)
{
    int new_stdout, new_stderr;
    int old_stdout_mode, old_stderr_mode;
    int old_stdout, old_stderr;
    int retval;
    char *stdout_redir = NULL;

    if (pstdout_redir != NULL) {
        if (*pstdout_redir == NULL) {
            *pstdout_redir = archdep_tmpnam();
        }
        stdout_redir = *pstdout_redir;
    }

    new_stdout = new_stderr = old_stdout = old_stderr = -1;

    /* Make sure we are in binary mode.  */
    old_stdout_mode = setmode(STDOUT_FILENO, O_BINARY);
    old_stderr_mode = setmode(STDERR_FILENO, O_BINARY);

    /* Redirect stdout and stderr as requested, saving the old
       descriptors.  */
    if (stdout_redir != NULL) {
        old_stdout = dup(STDOUT_FILENO);
        new_stdout = open(stdout_redir, O_WRONLY | O_TRUNC | O_CREAT, 0666);
        if (new_stdout == -1) {
            log_error(LOG_DEFAULT, "open(\"%s\") failed: %s.", stdout_redir, strerror(errno));
            retval = -1;
            goto cleanup;
        }
        dup2(new_stdout, STDOUT_FILENO);
    }
    if (stderr_redir != NULL) {
        old_stderr = dup(STDERR_FILENO);
        new_stderr = open(stderr_redir, O_WRONLY | O_TRUNC | O_CREAT, 0666);
        if (new_stderr == -1) {
            log_error(LOG_DEFAULT, "open(\"%s\") failed: %s.", stderr_redir, strerror(errno));
            retval = -1;
            goto cleanup;
        }
        dup2(new_stderr, STDERR_FILENO);
    }

    /* Spawn the child process.  */
    retval = spawnvp(P_WAIT, name, argv);

cleanup:
    if (old_stdout >= 0) {
        dup2(old_stdout, STDOUT_FILENO);
        close(old_stdout);
    }
    if (old_stderr >= 0) {
        dup2(old_stderr, STDERR_FILENO);
        close(old_stderr);
    }
    if (old_stdout_mode >= 0) {
        setmode(STDOUT_FILENO, old_stdout_mode);
    }
    if (old_stderr_mode >= 0) {
        setmode(STDERR_FILENO, old_stderr_mode);
    }
    if (new_stdout >= 0) {
        close(new_stdout);
    }
    if (new_stderr >= 0) {
        close(new_stderr);
    }

    return retval;
}

/* return malloc´d version of full pathname of orig_name */
int archdep_expand_path(char **return_path, const char *orig_name)
{
    /* MS-DOS version.  */
    char *full_path = _truename(orig_name, NULL);

    if (full_path == NULL) {
        log_error(LOG_ERR, "zfile_list_add: warning, illegal file name `%s'.", orig_name);
        *return_path = lib_stralloc(orig_name);
    }
    *return_path = lib_stralloc(full_path);
    free(full_path); /* not lib_free() */
    return 0;
}

void archdep_startup_log_error(const char *format, ...)
{
    va_list ap;

    va_start(ap, format);
    vfprintf(stderr, format, ap);
    va_end(ap);
}

char *archdep_filename_parameter(const char *name)
{
    /* nothing special(?) */
    return lib_stralloc(name);
}

char *archdep_quote_parameter(const char *name)
{
    /*not needed(?) */
    return lib_stralloc(name);
}

char *archdep_tmpnam(void)
{
    if (getenv("temp")) {
        return util_concat(getenv("temp"), tmpnam(NULL), NULL);
    } else if (getenv("tmp")) {
        return util_concat(getenv("tmp"), tmpnam(NULL), NULL);
    } else {
        return lib_stralloc(tmpnam(NULL));
    }
}

FILE *archdep_mkstemp_fd(char **filename, const char *mode)
{
    char *tmp;
    FILE *fd;

    if (getenv("temp")) {
        tmp = util_concat(getenv("temp"), tmpnam(NULL), NULL);
    } else if (getenv("tmp")) {
        tmp = util_concat(getenv("tmp"), tmpnam(NULL), NULL);
    } else {
        tmp = lib_stralloc(tmpnam(NULL));
    }

    fd = fopen(tmp, mode);

    if (fd == NULL) {
        return NULL;
    }

    *filename = tmp;

    return fd;
}

int archdep_file_is_gzip(const char *name)
{
    size_t l = strlen(name);

    if ((l < 4 || strcasecmp(name + l - 3, ".gz")) && (l < 3 || strcasecmp(name + l - 2, ".z")) && (l < 4 || toupper(name[l - 1]) != 'Z' || name[l - 4] != '.')) {
        return 0;
    }
    return 1;
}

int archdep_file_set_gzip(const char *name)
{
    return 0;
}

int archdep_mkdir(const char *pathname, int mode)
{
    return mkdir(pathname, (mode_t)mode);
}

int archdep_stat(const char *file_name, unsigned int *len, unsigned int *isdir)
{
    struct stat statbuf;

    if (stat(file_name, &statbuf) < 0) {
        return -1;
    }

    *len = statbuf.st_size;
    *isdir = S_ISDIR(statbuf.st_mode);

    return 0;
}

/* set permissions of given file to rw, respecting current umask */
int archdep_fix_permissions(const char *file_name)
{
    return _chmod(file_name, 1, 0);
}

int archdep_file_is_blockdev(const char *name)
{
    return 0;
}

int archdep_file_is_chardev(const char *name)
{
    return 0;
}

void archdep_shutdown(void)
{
}

static char archdep_os_version[128];

char *archdep_get_runtime_os(void)
{
    unsigned short real_version = _get_dos_version(1);

    sprintf(archdep_os_version, "%s v%d.%d", _os_flavor, real_version >> 8, real_version & 0xff);

    return archdep_os_version;
}

char *archdep_get_runtime_cpu(void)
{
    return platform_get_x86_runtime_cpu();
}


text:
#pragma once

#include "MainPage.g.h"
#include "SplitContainer.xaml.h"
#include "RulerContainer.xaml.h"
#include "SettingsDialog.xaml.h"
#include "TabbableTextBox.h"
#include "AppSettings.h"

namespace XamlCruncher
{
    public ref class MainPage sealed
    {
    private:
        Windows::UI::Xaml::Media::Brush^ textBlockBrush;
        Windows::UI::Xaml::Media::Brush^ textBoxBrush;
        Windows::UI::Xaml::Media::Brush^ errorBrush;
        XamlCruncher::AppSettings^ appSettings;
        Windows::Storage::StorageFile^ loadedStorageFile;

    public:
        MainPage();

    private:
        void OnLoaded(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ args);
        void FinishInitialization();
        void OnApplicationSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ args);
        Concurrency::task<void> SetDefaultXamlFile();
        void OnRefreshAppBarButtonClick(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ args);
        void OnSettingsAppBarButtonClick(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ args);

        // File I/O events
        void OnAddAppBarButtonClick(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ args);
        void OnOpenAppBarButtonClick(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ args);
        Concurrency::task<void> CheckIfOkToTrashFile(Concurrency::task<void> (MainPage::*commandAction)(void));
        Concurrency::task<void> LoadFileFromOpenPicker();
        void OnSaveAsAppBarButtonClick(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ args);
        void OnSaveAppBarButtonClick(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ args);
        Concurrency::task<Windows::Storage::StorageFile^> GetFileFromSavePicker();
        Concurrency::task<void> SaveXamlToFile(Windows::Storage::StorageFile^ storageFile);

        // TextBox events
        void OnEditBoxSelectionChanged(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ args);
        void DisplayLineAndColumn();
        void OnEditBoxTextChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::TextChangedEventArgs^ args);
        void ParseText();
        void SetErrorText(Platform::String^ text);
        void SetOkText();
        void SetStatusText(Platform::String^ text, Windows::UI::Xaml::Media::Brush^ statusBrush, Windows::UI::Xaml::Media::Brush^ textBoxBrush);
    };
}