text:
package org.cyclopath.android.items;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.os.Handler;
import android.os.Message;
import android.util.SparseIntArray;

import org.cyclopath.android.G;
import org.cyclopath.android.R;
import org.cyclopath.android.conf.AccessInfer;
import org.cyclopath.android.conf.Constants;
import org.cyclopath.android.conf.ItemType;
import org.cyclopath.android.gwis.GWIS_Checkout;
import org.cyclopath.android.gwis.GWIS_CheckoutCallback;
import org.cyclopath.android.gwis.GWIS_CommitCallback;
import org.cyclopath.android.gwis.GWIS_Commit;
import org.cyclopath.android.gwis.QueryFilters;
import org.cyclopath.android.util.XmlUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;

/**
 * This class represents a track conflation job.
 * @author Fernando
 */
public class ConflationJob extends ItemUserAccess
                           implements GWIS_CommitCallback,
                                      GWIS_CheckoutCallback,
                                      OnCancelListener{

   /** The id of the track to conflate */
   public int track_id;
   /** The conflated ride */
   public Route route;

   /** The job action */
   public String job_act;
   /** Number of stages in this job */
   public int num_stages;
   /** The number of the stage we are in now */
   public int stage_num;
   /** The name of the stage we are in now */
   public String stage_name;
   /** Message describing the current job state */
   public String stage_msg;
   /** The current stage's progress */
   public int stage_progress;
   /** The job's status text */
   public String status_text;
   /** The job's status code */
   public int status_code;
   /** Whether the job has completed */
   public boolean job_finished;

   /** Whether we should continue to send progress requests */
   public boolean get_progress;

   /**
    * This handler receives and handles messages from the thread that
    * communicates with the server.
    */
   protected static ConflationHandler mHandler;

   /**
    * Handler for this class that uses weak references to avoid memory leaks.
    */
   protected static class ConflationHandler extends Handler {

      /** Weak reference to ConflationJob class */
      private WeakReference<ConflationJob> ref;

      /**
       * Constructor
       * @param job
       */
      public ConflationHandler(ConflationJob job) {
         this.ref = new WeakReference<ConflationJob>(job);
      }

      /**
       * Forwards the message to the ConflationJob class, if it exists.
       */
      @Override
      public void handleMessage(Message msg) {
         ConflationJob job = this.ref.get();
         if (job != null) {
            job.handleMessage(msg);
         }
      }
   }

   /**
   * Constructor using XML data.
   * @param root
   */
   public ConflationJob(Node root) {
      super(root);
      this.gmlConsume(root);
   }

   /**
    * Constructor using id of track to be conflated.
    * @param track_id
    */
   public ConflationJob(int track_id) {
      super(null);
      this.track_id = track_id;
      this.job_act = "create";
      this.get_progress = true;
      ConflationJob.mHandler = new ConflationHandler(this);
   }

   /**
    * Returns the type id for this item.
    */
   @Override
   public int getItemTypeId() {
      return ItemType.CONFLATION_JOB;
   }

   /**
    * Returns the access style for this item.
    */
   @Override
   public int getStyleId() {
      return AccessInfer.usr_editor;
   }

   /**
    * Populates this ConflationJob from an XML
    * @param root
    */
   @Override
   public void gmlConsume(Node root) {
      if (root != null) {
         NamedNodeMap atts = root.getAttributes();
         this.stack_id = XmlUtils.getInt(atts, "stid", this.stack_id);
         this.stage_name = XmlUtils.getString(atts, "stage_name", null);
         this.stage_msg = XmlUtils.getString(atts, "job_stage_msg", null);
         this.stage_progress = XmlUtils.getInt(atts, "stage_progress", 0);
         this.status_text = XmlUtils.getString(atts, "status_text", null);
         this.num_stages = XmlUtils.getInt(atts, "num_stages", 0);
         this.stage_num = XmlUtils.getInt(atts, "stage_num", 0);
         this.status_code = XmlUtils.getInt(atts, "status_code", 0);
         this.job_finished = XmlUtils.getInt(atts, "job_finished", 0) == 1;
         if (root.getChildNodes().getLength() > 1) {
            this.route = new Route(root.getChildNodes().item(1));
         }
      }
   }

   /**
    * Returns an XML String representing this ConflationJob.
    */
   @Override
   public Document gmlProduce() {
      Document document = super.gmlProduce();
      Element root = document.getElementById(Integer.toString(this.stack_id));
      document.renameNode(root, null, "conflation_job");
      root.removeAttribute("name");
      root.setAttribute("job_act", this.job_act);
      root.setAttribute("email_on_finish", "0");
      root.setAttribute("track_id", Integer.toString(this.track_id));
      return document;
   }

   /**
    * If progress is complete, download the ride.
    * If we have downloaded the ride, show it.
    * If progress is incomplete, update the progress dialog and schedule
    * another progress request.
    */
   @Override
   public void handleGWIS_CheckoutComplete(ArrayList<ItemUserAccess> feats) {
      if (feats.get(0).getClass().getName().equals(
            ConflationJob.class.getName())) {
         ConflationJob job = (ConflationJob)feats.get(0);
         if (job.job_finished && job.status_code == 2) {
            // We failed. Show error message and dismiss progress dialog.
            G.dismissProgressDialog();
            if (job.stage_msg != null) {
               G.showAlert(job.stage_msg,
                           G.app_context.getResources().getString(
                                 R.string.track_conflate_error));
            }
            return;
         }
         if (job.route != null) {
            G.dismissProgressDialog();
            G.setActiveRoute(job.route);
            // Notify handlers of conflation completion.
            if (G.cyclopath_handler != null) {
               Message msg = Message.obtain();
               msg.what = Constants.CONFLATION_COMPLETE;
               msg.setTarget(G.cyclopath_handler);
               msg.sendToTarget();
            }
            if (G.track_manager_handler != null) {
               Message msg = Message.obtain();
               msg.what = Constants.CONFLATION_COMPLETE;
               msg.setTarget(G.track_manager_handler);
               msg.sendToTarget();
            }
            return;
         }
         // update progress dialog
         if (job.stage_num > 2) {
            // We want to keep the progress at 100% after the conflation stage.
            job.stage_progress = 100;
         }
         if (!job.job_finished) {
            G.updateProgressDialog(
                  G.app_context.getString(
                        R.string.track_conflate_progress_dialog_title),
                  job.stage_name,
                  job.stage_progress);
            if (this.get_progress) {
               new Timer().schedule(new ProgressRequestTask(),
                                    Constants.PROGRESS_REQUEST_WAIT_TIME);
            }
         } else {
            // do download if job is complete
            G.cancel_handler = null;
            QueryFilters qfs = new QueryFilters();
            qfs.only_stack_ids = new int[]{this.stack_id};
            qfs.include_item_aux = true;
            GWIS_Checkout gwis_request =
               new GWIS_Checkout("conflation_job", qfs, this);
            gwis_request.fetch();
         }
      }
   }

   /**
    * Stores the new id for the job and schedules a progress request.
    */
   @Override
   public void handleGWIS_CommitCallback(SparseIntArray id_map) {
      // get job id
      if (id_map != null) {
         this.stack_id = id_map.get(this.stack_id);
         new Timer().schedule(new ProgressRequestTask(),
                              Constants.PROGRESS_REQUEST_WAIT_TIME);
      }
   }

   /**
    * Handles messages from conflation thread.
    * @param msg
    */
   public void handleMessage(Message msg) {
       switch (msg.what) {
          case (Constants.HANDLE_TIMEOUT):
             sendProgressRequest();
             break;
       }
   }

   @Override
   /**
    * Stops sending progress requests if the dialog was canceled.
    */
   public void onCancel(DialogInterface dialog) {
      G.cancel_handler = null;
      this.get_progress = false;
   }

   /**
    * Begins the conflation request.
    */
   public void runJob() {
      // start progress dialog
      G.cancel_handler = this;
      G.showProgressDialog(
            G.app_context.getString(
                  R.string.track_conflate_progress_dialog_title),
            G.app_context.getString(
                  R.string.track_conflate_progress_dialog_content),
            false);
      // send initial request
      ArrayList<ItemUserAccess> items = new ArrayList<ItemUserAccess>();
      items.add(this);
      new GWIS_Commit(items, "", "", this).fetch();
   }

   /**
    * Send a progress request
    */
   public void sendProgressRequest() {
      QueryFilters qfs = new QueryFilters();
      qfs.only_stack_ids = new int[]{this.stack_id};
      GWIS_Checkout gwis_request =
         new GWIS_Checkout("conflation_job", qfs, this);
      gwis_request.fetch();
   }

   /**
    * Task that sends the signal for sending a progress request.
    */
   private class ProgressRequestTask extends TimerTask  {
      @Override
      public void run () {
         Message msg = Message.obtain();
         msg.what = Constants.HANDLE_TIMEOUT;
         msg.setTarget(ConflationJob.mHandler);
         msg.sendToTarget();
      }
    }
}


text:
<?php

namespace Oro\Bundle\NavigationBundle\Tests\Entity;

use Pim\Bundle\UserBundle\Entity\User;
use Pim\Bundle\UserBundle\Entity\UserInterface;
use Oro\Bundle\NavigationBundle\Entity\PageState;

class PageStateTest extends \PHPUnit_Framework_TestCase
{
    public function testUser()
    {
        $item = new PageState();
        $user = new User();

        $this->assertNull($item->getId());
        $this->assertNull($item->getUser());

        $item->setUser($user);

        $this->assertEquals($user, $item->getUser());
    }

    public function testDateTime()
    {
        $item     = new PageState();
        $dateTime = new \DateTime();

        $item->setUpdatedAt($dateTime);
        $item->setCreatedAt($dateTime);

        $this->assertEquals($dateTime, $item->getUpdatedAt());
        $this->assertEquals($dateTime, $item->getCreatedAt());
    }

    public function testPageId()
    {
        $item   = new PageState();
        $pageId = 'SomeId';

        $item->setPageId($pageId);

        $this->assertEquals($pageId, $item->getPageId());
        $this->assertEquals(PageState::generateHash($pageId), $item->getPageHash());
    }

    public function testData()
    {
        $item = new PageState();
        $data = array(
            array('key' => 'val', 'key2' => 'val2'),
        );

        $item->setData($data);

        $this->assertEquals($data, $item->getData());
    }

    public function testDoPrePersist()
    {
        $item = new PageState();

        $item->doPrePersist();

        $this->assertInstanceOf('DateTime', $item->getCreatedAt());
        $this->assertInstanceOf('DateTime', $item->getUpdatedAt());
        $this->assertEquals($item->getCreatedAt(), $item->getUpdatedAt());
    }

    public function testDoPreUpdate()
    {
        $item = new PageState();

        $item->doPreUpdate();

        $this->assertInstanceOf('DateTime', $item->getUpdatedAt());
    }
}

redpajama_set_name: RedPajamaGithub


text:
\documentclass[a4paper,11pt]{article}
\usepackage[dvips]{graphicx}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage[french]{babel}
\usepackage[right=3cm, bottom=4cm]{geometry}
\usepackage{lmodern}
\usepackage{textcomp}
\usepackage{amsmath}
\usepackage{amssymb}
\usepackage{graphicx}
\usepackage{wrapfig}
\usepackage{subcaption}
\usepackage{listings}
\usepackage{setspace}
\usepackage{color}
\usepackage{pdfpages}

\usepackage{fancyvrb} % for verbatim boxes

\usepackage{hyperref}
\hypersetup{
    colorlinks,
    citecolor=black,
    filecolor=black,
    linkcolor=black,
    urlcolor=black
}

\title{\textbf{Contrôleurs dans l'espace: \\Documentation utilisateur}}
\author{https://github.com/HKervadec/mittelwerk}
\date{Juin 2014}
\markright{Contrôleurs dans l'espace}

\begin{document}
\maketitle

\tableofcontents

\setlength{\parskip}{5pt}

\section{Avant-propos}
    \begin{figure}[!h]
                \begin{center}
                    \includegraphics[width=0.7\textwidth]{img/orbiter_logo.png}
                \end{center}
    \end{figure}

    \subsection{Un simulateur en temps réel}
        Orbiter est un simulateur de vol spatial, créé par Dr. Martin Schweiger en 2000 et ce afin de combler le manque de simulateur de vol réaliste disponible sur internet. Gratuit mais non libre, un kit de développement a fait son apparition pour permettre à tout un chacun de développer son propre vaisseau. Fourni avec un lot de scénarios et de vaisseaux, Orbiter permet d'expérimenter et de mieux appréhender les lois de la physique.

        C'est dans cette optique que nous proposons une première démarche d'automatisations des vaisseaux dans Orbiter.

        Le projet est actuellement compatible avec un seul vaisseau: le ShuttleA.

    \subsection{Module lunaire}
        Le ShuttleA est un module lunaire : en effet il est conçu pour permettre aux spationautes de rentrer sur Terre une fois l'alunissage terminé. Ses caractéristiques sont donc plus adaptées à cet environnement. En effet le décollage depuis la Terre est plus diffcile (compte tenu de la gravité, plus forte que sur la Lune) et plus gourmand en carburant. Cependant le ShuttleA a deux avantages :

        \begin{itemize}
            \item Il dispose de nombreux propulseurs, ce qui en facilite la manœuvre
            \item Il est codé en une seule classe C++ : c'est transparent pour l'utilisateur, et dans le cas de notre travail, cela simplifie grandement l'étude.
        \end{itemize}

    \subsection{Théorie du contrôle}
        Pour pouvoir automatiser le pilotage des vaisseau, en particulier du ShuttleA nous disposons de plusieurs outils formels, dont la théorie du contrôle.

        C'est un moyen de formaliser le fait qu'un système, pour se maintenir sur une trajectoire prend des mesures, les compare à des références et adapte ses commandes en fonction. C'est une boucle qui va des capteurs vers le contrôleur, chargé de prendre les décisions pour suivre l'objectif.

        \begin{figure}[!h]
                    \begin{center}
                        \includegraphics[width=0.7\textwidth]{img/boucle_controle.jpg}
                    \end{center}
        \end{figure}

    \subsection{Automates}
        Les automates sont un ensemble d'états et de transitions, qui correspondent à des états d'un système. Par exemple on peut imaginer qu'une lampe soit modélisée par un automate. Elle aurait deux états : allumée, éteinte. Cette lampe peut passer d'un état à l'autre grâce à des transitions.
        Ces transitions définissent sous quelles conditions le système change d'état.
        Pour la lampe, la transition de l'état éteinte vers allumée se fait par exemple si elle est alimentée et vice-versa.

        \begin{figure}[!h]
                    \begin{center}
                        \includegraphics[width=0.7\textwidth]{img/automatelas.png}
                    \end{center}
        \end{figure}

        Pour le vaisseau on peut imaginer une infinité d'états différents, ce qui permet de contrôler le vaisseau à notre guise. Par exemple l'état "Propulsion MAXI" avec une transition sur l'état "Propulsion Gauche seule" en cas de détection d'obstacle.

\section{Langage Mittlewerk}
    \subsection{Introduction}
        Nous avons créé un langage simple permettant de piloter le vaisseau sans maîtriser le C++. En effet, ce langage permet de créer facilement des automates, et donc de créer un contrôleur personnalisé.
        Certains aspects du langage sont proches du C++ mais ce sont des concepts classiques en programmation (affectation, déclaration ...).

    \subsection{Instructions basiques}
        Toutes les instructions se terminent par un ';' pour indiquer au compilateur qu'une instruction est complète.

        \subsubsection{Variables}
            Une variable a un nom et un type, il faut donc les déclarer au compilateur avant de pouvoir les utiliser. Cela se fait très simplement :
            \begin{center}
                \texttt{type nom;}
            \end{center}
            \textit{\textbf{Attention :} les variables doivent être toutes déclarées au début de la fonction avant d'autres instructions.}

            \textit{\textbf{Remarques :}}
            \textit{
                \begin{itemize}
                    \item les variables peuvent être déclarés en groupe si elles sont du même type : \texttt{DOUBLE a, b, c;}
                    \item Des valeurs t, dt et mjd sont accessibles. t correspond au temps écoulé pendant la simulation en secondes, dt est l'intervalle de temps entre deux calculs de simulation : dt est donc le pas de la simulation. Enfin mjd correspond à t mais exprimée dans le calendrier Julien, permettant si la simulation dure très longtemps (aller-retour sur mars) d'exprimer la valeur autrement qu'en secondes !
                \end{itemize}}

            Par exemple, si vous souhaitez définir un double (nombre à virgule à valeur max très élevée) que vous appelez toto, il faudra l'avoir défini avant de l'utiliser :
            \begin{center}
                \texttt{DOUBLE foo;}
            \end{center}
            \textit{\textbf{Attention : }n'utilisez pas de caractères spéciaux, ni accentués, ni espaces dans les noms de fonctions et variables. Ne nommez pas non plus vos variables t, dt ou mjd.}

            Pour affecter une valeur, la démarche est identique à la plupart des langages :
            \begin{center}
                \texttt{foo = 42;}\\
                \texttt{foo = foo + 1;}\\
                \texttt{foo = max(1, foo);}\\
            \end{center}
            On peut affecter à une variable la valeur de retour d'une fonction, d'une autre variable ... Il faut juste vérifier que le type que l'on donne à la variable correspond à celui qu'on lui a donné lors de sa déclaration.
            Les types disponibles sont BOOL (TRUE ou FALSE), INT et DOUBLE.

        \subsubsection{Fonctions}
            Les fonctions peuvent être déclarées, hors du corps d'une fonction, et être appelées, dans le corps d'une fonction ou dans un état de l'automate.

            Pour déclarer une fonction c'est très simple :
            \begin{center}
                \texttt{type nomDeFonction(type1 Param1, type2 Param2 ...) \{ corps de la fonction \}}
            \end{center}

            Si la fonction a un type différent de VOID, elle doit retourner une valeur :
            \begin{center}
                \texttt{RETURN foo;}
            \end{center}

            Pour l'appeler : \texttt{ nomDeFonction(param1, param2, ...)}

        \subsubsection{Commentaires}
            Il est parfois très utile de commenter son code : ce qui est commenté n'est pas interpreté lors de la compilation, ce ne sont que des informations pour les humains.
            Pour encadrer du commentaire il faut mettre /* avant le commentaire, */ à la fin.
            \begin{center}
                \texttt{VOID fonctionInutile() \{ /* cette fonction ne fait rien*/ \}}
            \end{center}

        \subsubsection{Opérateurs de base}
            Sur les \textsc{bool} :
            \begin{itemize}
                \item == teste l'égalité booléenne
                \item != teste la différence booléenne
                \item OR renvoie \textsc{true} si un (au moins) des booléens est vrai
                \item AND renvoie \textsc{true} si les deux booléens sont vrais, \textsc{false} sinon
            \end{itemize}

            Sur les \textsc{double} ou \textsc{int} tous les opérateurs classiques :
            \begin{itemize}
                \item Opérateurs mathématiques : +,*,-,/
                \item Opérateurs de test : ==, !=, <, <=, >, >=
            \end{itemize}

        \subsubsection{Structure de test}
             Là encore, le mécanisme est un grand classique. Pour tester si une condition est vraie et faire une action en conséquence, on utilise une structure \textsc{if} ... \textsc{else} :

            \texttt{\textsc{if} (condition) \{Action si condition vaut TRUE\}}

            \texttt{\textsc{else}  \{Action si condition vaut FALSE\}} \pagebreak

            \textit{\textbf{Remarques : }
            \begin{itemize}
                \item Condtition doit être de type \textsc{bool}.
                \item Pas de ';' après '\}', if et else ne sont pas des intructions. Par contre à l'intérieur des accolades ce sont des instructions, qui terminent donc par un point-virgule.
                \item Il est possible de chainer les IF ELSE de la façon suivante : \newline \texttt{IF () \{ \} ELSE IF () \{ \} ELSE}
            \end{itemize}}

        \subsubsection{Structure de boucle}
            L'implémentation du tantque passe par while dans notre programme. Tantque (condition est vraie) \{ action tant que cond est vraie\} se traduit en :

            \texttt{\textsc{while} (condition) \{ instructions \} }

            \textit{\textbf{Remarques : }
            \begin{itemize}
                \item Condtition doit être de type \textsc{bool}.
                \item Pas de ';' après '\}', while n'est pas une intruction. Par contre à l'intérieur des accolades ce sont des instructions, qui terminent donc par un point-virgule.
            \end{itemize}}

        \subsubsection{Exemple de synthèse:}
            \begin{Verbatim}[frame=single]
DOUBLE bar(INT foo){
    DOUBLE result;

    result = MAX(1, foo) + 5; /* Calcul complexe */

    RETURN result;
}
            \end{Verbatim}

\section{Ecrire un automate}
    Pour définir un  automate, il y a trois grandes étapes : l'initialisation (propre au vaisseau), la définition de fonctions auxiliaires, et la définitions des états/transitions.

    \subsection{Initialisation de l'automate}
        \begin{verbatim}
ShuttleA

main0 : th_main[0]
main1 : th_main[1]
hover0 : th_hover[0]
hover1 : th_hover[1]
pod0 : th_pod[0]
pod1 : th_pod[1]
        \end{verbatim}

        ShuttleA : C'est le nom du vaisseau. C'est la première ligne de l'automate et sert au compilateur : elle est donc indispensable.

        Ensuite le langage permet de définir des alias sur des objets de chaque vaisseau, pour pouvoir les utiliser plus simplement. On choisit un nom et on l'associe à un des objets caractéristiques du vaisseau.
        \texttt{nom : objet\_du\_vaisseau}

        Ce n'est pas une instruction, cela ne nécessite pas de ';'. de plus cela ne fait pas partie d'un corps de fonction ou d'un état.

        \textit{\textbf{Remarque : }Dans le cadre du ShuttleA, th\_main[0] corresponds au réacteur principal gauche.
        Les hover sont des propulseurs verticaux (avant et arrière du vaisseaux) qui provoquent une poussée ascendante. Enfin, les pods sont de tout petits propulseurs, aussi appelés boosters. Ils peuvent s'incliner de -90° à +90°.}

    \subsection{Définition de fonctions}
        Pour s'aider, on peut définir des fonctions que l'on utilisera dans les états de l'automate. Cette étape est déjà détaillée : voir Langage Mittelwerk > Fonctions.

    \subsection{Etats et transitions}
        On arrive au coeur de l'automate.

        \subsubsection{Etat}
            On définit un état par son nom et par son corps, comme ceci :

            \texttt{STATE\_NOM1 \{
                /* Corps de l'automate ici */
            \}}

            \textbf{Remarque :} Le STATE\_ n'est pas un mot-clé : vouys pouvez nommer l'étape comme vous voulez, du moment que le nom ne soit composé que par des nombres, des lettres majuscules non accentuées et des underscore (\_).

        \subsubsection{Transitions}
            Pour les transitions, l'utilisateur dispose du mot-clé GOTOGOTO, pour passer à un autre état. L'appel de GOTOGOTO est une instruction, il faut donc un ';' à la fin.
            Si on veut passer d'un état A a un état on peut faire :
            \newline

            \texttt{STATE\_A \{}

            \texttt{\quad DOUBLE i;}

            \texttt{\quad	IF (i <= 35)\{}

            \texttt{\qquad i = 35;}

            \texttt{\quad \}}

            \texttt{\quad IF (i == 35)\{}

            \texttt{\qquad GOTOGOTO STATE\_B; }

            \texttt{\quad \}}

            \texttt{\}}

            Dans cet exemple, l'état A passera toujours à l'état B.

        \subsubsection{Etat initial/final}

            Il faut bien que votre système ait un état au départ. Il faut donc qu'exactement un automate soit initial, doté du mot-clé START. Ce mot-clé doit être la première chose renseignée dans l'état.
            Généralement c'est le premier état défini, mais ce n'est pas obligatoire. Dans un soucis de clarté cependant, nous vous conseillons de toujours le laisser en premier.

            Un état peut-être FINAL, c'est un automate sans transitions (GOTOGOTO interdits). FINAL s'utilise comme START, mais il peut n'y avoir aucun état FINAL, et il peut y en avoir plusieurs.

    \subsection{API\_GET}
        API\_GET \{ \} est un moyen d'utiliser les fonctions fournies par Orbiter. En effet, certaines de ces fonctions renvoient des valeurs non utilisables dans notre langage, pour des soucis de simplification (pointeurs, vecteurs ...). On récupère donc les valeurs de retours de ces fonctions grâce à API\_GET :

        \begin{figure}[!h]
                    \begin{center}
                        \includegraphics[width=0.7\textwidth]{img/apiget.png}
                    \end{center}
        \end{figure}

        \pagebreak
        \section{Exemple récapitulatif}

        Voici un exemple d'automate, avec quelques explications.
        \begin{center}
            \includegraphics[scale=0.75]{img/otto1.png}
        \end{center}

        Comme prévu, l'initialisation de l'automate des lignes 1 à 8. Ensuite on définit une fonction VOID (qui ne renvoie pas de valeur) takeOff() qui oriente les boosters et met tous les systèmes de propulsion à 100\% de leur capacité (sauf les réacteurs principaux, à poussée horizontale).

        \begin{center}
            \includegraphics[scale=0.75]{img/otto2.png}
        \end{center}
        doubleMain() double la puissance délivrée par les réacteurs principaux, si ils sont à moins de 50\%, les met à 100\% sinon. Elle renvoie faux si le pourcentage de puissance n'a pas pu être doublée : c'est à dire si les réacteurs étaient déjà à plus de 50\% de leur capacité maximale. C'est une fonction illustrative, elle n'est d'ailleurs même pas utilisée.

        Ensuite on définit l'état 1 comme état initial : \texttt{STATE\_1 \{ START [...] \} }
        On définit des variables, et on leur donne des valeurs grâces aux fonctions de l'API.

        \begin{center}
            \includegraphics[scale=0.75]{img/otto3.png}
        \end{center}

        Dans le deuxième état on active les réacteurs principaux à 100\% de leur capacité.
        Lorsque l'on atteint 1500m d'altitude, on passe à l'état 3. Celui ci coupe les booster.

\section{Compilation}
    Voici un récapitulatif des étapes et instructions nécessaires pour rendre votre automate pleinement fonctionnel. Cette partie s'adresse aux utilisateurs qui n'utilisent pas le script python pour tout compiler automatiquement.

    \subsection{Compiler le compilateur}
        \onehalfspacing
        Dans un premier temps, vous devrez compiler le compilateur java. Il s'agira donc de se placer dans le dossier où est placé le compilateur, c'est-à-dire le dossier grammar, pour démarrer la compilation grâce à ant.

        \begin{itemize}
            \item Se placer dans le dossier "grammar" :
            \begin{itemize}
                            \item Démarrer -> Accessoires -> Invite de commande
                            \item Saisir la commande cd et coller l'emplacement du dossier grammar
            \end{itemize}
        \end{itemize}

        Attention les étapes suivantes nécessitent d'avoir javaCC et ant installés, et ajoutés dans le PATH.

        \begin{itemize}
            \item Dans la fenêtre de l'invite de commande, saisir ant grammar
            \item Saisir ant compile
        \end{itemize}

        \begin{center}
            \includegraphics[scale=0.75]{img/cmd.png}
        \end{center}

    \subsection{Compiler un automate}
        La première tâche pour compiler l'automate est bien sûr de l'écrire, puis de le donner en argument au compilateur Mittlewerk.\newline

        \begin{itemize}
            \item Ecrire un automate, par exemple dans un fichier toto.mw (le nom n'a pas dimportance, l'extension non plus, pourvu que le texte soit brut)
            \begin{itemize}
                \item Démarrer -> Accessoires -> Invite de commande
                \item Saisir la commande cd et coller l'emplacement du dossier grammar \newline
            \end{itemize}

            \item Dans la fenêtre de l'invite de commande, saisir : java -cp class Core.Mittelwerk toto.mw <optional\_output.cpp> <optional\_output.h>
            \item <optional\_output.cpp> contient le code de l'automate
            \item <optional\_output.h> contient le code à coller dans le header du vaisseau
        \end{itemize}

    \subsection{Compiler les dll du vaisseau}
        Le code étant généré hors des fichiers du vaisseau, il va falloir l'intégrer dans les fichiers sources de celui-ci.
        On suppose que le code est généré dans "Otto.cpp" et "header.h", (attention : la procédure n'est valide que pour le Shuttle A).\newline
        \begin{itemize}
            \item Ouvrir le projet Visual studio du vaisseau
            \item Ajouter le fichier "Otto.cpp" dedans
            \item Trouver la fonction clbkPostStep dans le code du vaisseau
            \begin{itemize}
                \item Ajouter en toute première ligne de cette fonction :
                \item postStep(simt, simdt, mjd);
            \end{itemize}
            \item Aller dans le header du vaisseau (ShuttleA.h), dans la section privée :
            \begin{itemize}
                \item Coller le contenu de "header.h" (précédemment généré) dedans.
            \end{itemize}

        \end{itemize}

\end{document}


text:
using Content.Shared.Interaction;
using Content.Server.Research.Components;
using Content.Server.Popups;
using Robust.Shared.Player;

namespace Content.Server.Research.Disk
{
    public sealed class ResearchDiskSystem : EntitySystem
    {
        [Dependency] private readonly PopupSystem _popupSystem = default!;
        public override void Initialize()
        {
            base.Initialize();
            SubscribeLocalEvent<ResearchDiskComponent, AfterInteractEvent>(OnAfterInteract);
        }

        private void OnAfterInteract(EntityUid uid, ResearchDiskComponent component, AfterInteractEvent args)
        {
            if (!args.CanReach)
                return;

            if (!TryComp<ResearchServerComponent>(args.Target, out var server))
                return;

            server.Points += component.Points;
            _popupSystem.PopupEntity(Loc.GetString("research-disk-inserted", ("points", component.Points)), args.Target.Value, Filter.Entities(args.User));
            EntityManager.QueueDeleteEntity(uid);
        }
    }
}


text:
module Quantify
  module Mongoid
    VERSION = "0.0.1.alpha"
  end
end


text:
var group__sparse__gpukernels =
[
    [ "GPU kernels for non-symmetric sparse LA", "group__sparse__gegpuk.html", "group__sparse__gegpuk" ],
    [ "GPU kernels for symmetric/Hermitian sparse LA", "group__sparse__sygpuk.html", "group__sparse__sygpuk" ]
];


text:
// This file contains a wrapper class used by the App Invites C++ API.
// See go/firebase-app-invites-cpp for more information.

package com.google.firebase.dynamiclinks.internal.cpp;

import android.app.Activity;
import android.net.Uri;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.app.internal.cpp.Log;
import com.google.firebase.dynamiclinks.FirebaseDynamicLinks;
import com.google.firebase.dynamiclinks.PendingDynamicLinkData;

/**
 * Wrapper class used by the C++ implementation of Dynamic Links. This class wraps the Dynamic Links
 * API in a way that can be easily used by the C++ JNI implementation. It handles talking to the
 * standard Dynamic Links library and handles callbacks back to the C++ code.
 *
 * @hide
 */
public class DynamicLinksNativeWrapper {
  private static final String TAG = "DynamicLinksNW";
  private Activity activity;
  private long nativeInternalPtr;

  // Message that describes the failure to find a native method and a potential resolution.
  private static final String NATIVE_METHOD_MISSING_MESSAGE =
      "Native method not found, unable to send %s message to the application. "
      + "Make sure Firebase was not shut down while a Dynamic Links fetch operation "
      + "was in progress. (%s)";

  public DynamicLinksNativeWrapper(long nativePtr, Activity incomingActivity) {
    nativeInternalPtr = nativePtr;
    // Call our JNI function (passing in 0 as the nativeInternalPtr) so we can verify that
    // they are all hooked up properly.
    //
    // On the C++ side, they will no-op if nativeInternalPtr is 0, so all we are doing is checking
    // that they are registered / named properly. If any of them are not, they will throw an
    // UnsatisfiedLinkError exception that needs to be caught by whatever is constructing us.
    // NOTE: It's fine to use the unsafe native methods here as the constructor of this object is
    // being called from C++.
    receivedDynamicLinkCallback(0, null, 0, null);
    activity = incomingActivity;
  }

  public void discardNativePointer() {
    nativeInternalPtr = 0;
  }

  // Invitation receiving:

  // Fetch Dynamic Links - this function is called from JNI to trigger checking for dynamic links.
  public boolean fetchDynamicLink() {
    try {
      activity.runOnUiThread(new Runnable() {
        @Override
        public void run() {
          FirebaseDynamicLinks.getInstance()
              .getDynamicLink(activity.getIntent())
              .addOnSuccessListener(activity,
                  new OnSuccessListener<PendingDynamicLinkData>() {
                    @Override
                    public void onSuccess(PendingDynamicLinkData pendingDynamicLinkData) {
                      // Get deep link from result (may be null if no link is found)
                      Uri deepLink = null;
                      String deepLinkString = null;
                      if (pendingDynamicLinkData != null) {
                        deepLink = pendingDynamicLinkData.getLink();
                        if (deepLink != null) {
                          deepLinkString = deepLink.toString();
                        }
                      }
                      safeReceivedDynamicLinkCallback(nativeInternalPtr, deepLinkString, 0, "");
                    }
                  })
              .addOnFailureListener(activity, new OnFailureListener() {
                @Override
                public void onFailure(Exception e) {
                  safeReceivedDynamicLinkCallback(
                      nativeInternalPtr, "", Activity.RESULT_CANCELED, e.toString());
                }
              });
        }
      });
      return true;
    } catch (Exception e) {
      // Failed to start fetching invites. The client code will handle this when we return false..
      return false;
    }
  }

  public static void safeReceivedDynamicLinkCallback(
      long nativeInternalPtr, String deepLinkUrl, int resultCode, String errorString) {
    try {
      receivedDynamicLinkCallback(nativeInternalPtr, deepLinkUrl, resultCode, errorString);
    } catch (UnsatisfiedLinkError e) {
      String missingDetails = String.format("received url=%s (code=%d, message=%s)",
          String.valueOf(deepLinkUrl), resultCode, errorString);
      Log.e(TAG, String.format(NATIVE_METHOD_MISSING_MESSAGE, missingDetails, e.toString()));
    }
  }

  public static native void receivedDynamicLinkCallback(
      long nativeInternalPtr, String deepLinkUrl, int resultCode, String errorString);
}


text:
/*global*/

.selectize-control {
    font-size: 12px; /*font-family:Verdana, Arial, Helvetica, sans-serif;*/
    color: #999; /*padding: 8px; 	border: 1px solid #c9c9c9;*/
    display: inline-block !important;
}
.selectize-control.show-checkbox .items .item {
    display: none;
}
.selectize-control.show-checkbox .items .summary {
    display: inline-block;
    margin: 0;
    padding: 0 6px;
    border: none;
    color: #000;
    background: none;
}
.selectize-control.show-checkbox .selectize-dropdown-content div.option {

}
.selectize-control.show-checkbox .selectize-dropdown-content div.option > span {
    background: url('../../../../../../images/checkbox.png') no-repeat 0 center;
    display: inline-block;
    width: 20px;
    height: 23px;
    cursor: pointer;
}
.selectize-control.show-checkbox .selectize-dropdown-content div.option > label {
    display: inline-block;
    height: 23px;
    line-height: 23px;
    vertical-align: top;
    margin-left: 4px;
    cursor: pointer;
}
.selectize-control.show-checkbox .selectize-dropdown-content div.option.selected > span {
    background-position: -51px center;
}

.selectize-control.multi .selectize-input.has-items {
    padding: 8px !important;
}

.dnnFormItem > .selectize-control, .dnnFormItem select {
    width: 47%;
    margin-bottom: 18px;
    max-width: 445px;
}


text:
'use strict';

var paths = {
    'bower': './bower_components/'
};

var Path = {
    get: function(folder) {
        if (typeof paths[folder] === 'undefined') {
            throw new Error('Unknown folder: ' + folder);
        }
        return paths[folder];
    }
};

module.exports = Path;


text:
import argparse

from pipeline.backend.pipeline import PipeLine
from pipeline.component.data_transform import DataTransform
from pipeline.component.homo_nn import HomoNN
from pipeline.component.reader import Reader
from pipeline.interface import Data
from pipeline.utils.tools import load_job_config
from tensorflow.keras import optimizers
from tensorflow.keras.layers import Dense

def main(config="../../config.yaml", namespace=""):
    homo_nn_0 = HomoNN(
        name="homo_nn_0",
        encode_label=True,
        max_iter=15,
        batch_size=-1,
        early_stop={"early_stop": "diff", "eps": 0.0001},
    )
    homo_nn_0.add(Dense(units=5, input_shape=(18,), activation="relu"))
    homo_nn_0.add(Dense(units=4, activation="sigmoid"))
    homo_nn_0.compile(
        optimizer=optimizers.Adam(learning_rate=0.05),
        metrics=["accuracy"],
        loss="categorical_crossentropy",
    )
    run_homo_nn_pipeline(config, namespace, dataset.vehicle, homo_nn_0, 2)

def run_homo_nn_pipeline(config, namespace, data: dict, nn_component, num_host):
    if isinstance(config, str):
        config = load_job_config(config)

    guest_train_data = data["guest"]
    host_train_data = data["host"][:num_host]
    for d in [guest_train_data, *host_train_data]:
        d["namespace"] = f"{d['namespace']}{namespace}"

    hosts = config.parties.host[:num_host]
    pipeline = (
        PipeLine()
        .set_initiator(role="guest", party_id=config.parties.guest[0])
        .set_roles(
            guest=config.parties.guest[0], host=hosts, arbiter=config.parties.arbiter
        )
    )

    reader_0 = Reader(name="reader_0")
    reader_0.get_party_instance(
        role="guest", party_id=config.parties.guest[0]
    ).component_param(table=guest_train_data)
    for i in range(num_host):
        reader_0.get_party_instance(role="host", party_id=hosts[i]).component_param(
            table=host_train_data[i]
        )

    data_transform_0 = DataTransform(name="data_transform_0", with_label=True)
    data_transform_0.get_party_instance(
        role="guest", party_id=config.parties.guest[0]
    ).component_param(with_label=True, output_format="dense")
    data_transform_0.get_party_instance(role="host", party_id=hosts).component_param(
        with_label=True
    )

    pipeline.add_component(reader_0)
    pipeline.add_component(data_transform_0, data=Data(data=reader_0.output.data))
    pipeline.add_component(
        nn_component, data=Data(train_data=data_transform_0.output.data)
    )
    pipeline.compile()
    pipeline.fit()
    print(pipeline.get_component("homo_nn_0").get_summary())
    pipeline.deploy_component([data_transform_0, nn_component])

    # predict
    predict_pipeline = PipeLine()
    predict_pipeline.add_component(reader_0)
    predict_pipeline.add_component(
        pipeline,
        data=Data(
            predict_input={pipeline.data_transform_0.input.data: reader_0.output.data}
        ),
    )
    # run predict model
    predict_pipeline.predict()

# noinspection PyPep8Naming
class dataset_meta(type):
    @property
    def breast(cls):
        return {
            "guest": {"name": "breast_homo_guest", "namespace": "experiment"},
            "host": [
                {"name": "breast_homo_host", "namespace": "experiment"},
                {"name": "breast_homo_host", "namespace": "experiment"},
            ],
        }

    @property
    def vehicle(cls):
        return {
            "guest": {"name": "vehicle_scale_homo_guest", "namespace": "experiment", },
            "host": [
                {"name": "vehicle_scale_homo_host", "namespace": "experiment"},
                {"name": "vehicle_scale_homo_host", "namespace": "experiment"},
            ],
        }

class dataset(metaclass=dataset_meta):
    ...

if __name__ == "__main__":
    parser = argparse.ArgumentParser("PIPELINE DEMO")
    parser.add_argument("-config", type=str, help="config file")
    args = parser.parse_args()
    if args.config is not None:
        main(args.config)
    else:
        main()


text:
namespace Kursach
{
    partial class add_firm
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.button1 = new System.Windows.Forms.Button();
            this.cancelTB = new System.Windows.Forms.Button();
            this.siteTB = new System.Windows.Forms.TextBox();
            this.checkTB = new System.Windows.Forms.TextBox();
            this.bankTB = new System.Windows.Forms.TextBox();
            this.phoneTB = new System.Windows.Forms.TextBox();
            this.addressTB = new System.Windows.Forms.TextBox();
            this.nameTB = new System.Windows.Forms.TextBox();
            this.label5 = new System.Windows.Forms.Label();
            this.label6 = new System.Windows.Forms.Label();
            this.label7 = new System.Windows.Forms.Label();
            this.label4 = new System.Windows.Forms.Label();
            this.label3 = new System.Windows.Forms.Label();
            this.label2 = new System.Windows.Forms.Label();
            this.label1 = new System.Windows.Forms.Label();
            this.pictureBox1 = new System.Windows.Forms.PictureBox();
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
            this.SuspendLayout();
            //
            // button1
            //
            this.button1.FlatStyle = System.Windows.Forms.FlatStyle.System;
            this.button1.Location = new System.Drawing.Point(12, 340);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(169, 33);
            this.button1.TabIndex = 66;
            this.button1.Text = "Добавить фирму";
            this.button1.UseVisualStyleBackColor = true;
            this.button1.Click += new System.EventHandler(this.button1_Click);
            //
            // cancelTB
            //
            this.cancelTB.FlatStyle = System.Windows.Forms.FlatStyle.System;
            this.cancelTB.Location = new System.Drawing.Point(201, 340);
            this.cancelTB.Name = "cancelTB";
            this.cancelTB.Size = new System.Drawing.Size(169, 33);
            this.cancelTB.TabIndex = 65;
            this.cancelTB.Text = "Отмена";
            this.cancelTB.UseVisualStyleBackColor = true;
            this.cancelTB.Click += new System.EventHandler(this.cancelTB_Click);
            //
            // siteTB
            //
            this.siteTB.Font = new System.Drawing.Font("Palatino Linotype", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
            this.siteTB.Location = new System.Drawing.Point(136, 295);
            this.siteTB.Multiline = true;
            this.siteTB.Name = "siteTB";
            this.siteTB.Size = new System.Drawing.Size(231, 35);
            this.siteTB.TabIndex = 64;
            //
            // checkTB
            //
            this.checkTB.Font = new System.Drawing.Font("Palatino Linotype", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
            this.checkTB.Location = new System.Drawing.Point(136, 257);
            this.checkTB.Multiline = true;
            this.checkTB.Name = "checkTB";
            this.checkTB.Size = new System.Drawing.Size(231, 35);
            this.checkTB.TabIndex = 63;
            //
            // bankTB
            //
            this.bankTB.Font = new System.Drawing.Font("Palatino Linotype", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
            this.bankTB.Location = new System.Drawing.Point(136, 219);
            this.bankTB.Multiline = true;
            this.bankTB.Name = "bankTB";
            this.bankTB.Size = new System.Drawing.Size(231, 35);
            this.bankTB.TabIndex = 62;
            //
            // phoneTB
            //
            this.phoneTB.Font = new System.Drawing.Font("Palatino Linotype", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
            this.phoneTB.Location = new System.Drawing.Point(136, 182);
            this.phoneTB.Multiline = true;
            this.phoneTB.Name = "phoneTB";
            this.phoneTB.Size = new System.Drawing.Size(231, 35);
            this.phoneTB.TabIndex = 61;
            //
            // addressTB
            //
            this.addressTB.Font = new System.Drawing.Font("Palatino Linotype", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
            this.addressTB.Location = new System.Drawing.Point(136, 144);
            this.addressTB.Multiline = true;
            this.addressTB.Name = "addressTB";
            this.addressTB.Size = new System.Drawing.Size(231, 35);
            this.addressTB.TabIndex = 60;
            //
            // nameTB
            //
            this.nameTB.Font = new System.Drawing.Font("Palatino Linotype", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
            this.nameTB.Location = new System.Drawing.Point(136, 106);
            this.nameTB.Multiline = true;
            this.nameTB.Name = "nameTB";
            this.nameTB.Size = new System.Drawing.Size(231, 35);
            this.nameTB.TabIndex = 59;
            //
            // label5
            //
            this.label5.AutoSize = true;
            this.label5.Font = new System.Drawing.Font("Gabriola", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
            this.label5.Location = new System.Drawing.Point(6, 257);
            this.label5.Name = "label5";
            this.label5.Size = new System.Drawing.Size(98, 35);
            this.label5.TabIndex = 58;
            this.label5.Text = "Номер счета:";
            //
            // label6
            //
            this.label6.AutoSize = true;
            this.label6.Font = new System.Drawing.Font("Gabriola", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
            this.label6.Location = new System.Drawing.Point(6, 292);
            this.label6.Name = "label6";
            this.label6.Size = new System.Drawing.Size(52, 35);
            this.label6.TabIndex = 57;
            this.label6.Text = "Сайт:";
            //
            // label7
            //
            this.label7.AutoSize = true;
            this.label7.Font = new System.Drawing.Font("Gabriola", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
            this.label7.Location = new System.Drawing.Point(6, 216);
            this.label7.Name = "label7";
            this.label7.Size = new System.Drawing.Size(48, 35);
            this.label7.TabIndex = 56;
            this.label7.Text = "Банк:";
            //
            // label4
            //
            this.label4.AutoSize = true;
            this.label4.Font = new System.Drawing.Font("Gabriola", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
            this.label4.Location = new System.Drawing.Point(6, 141);
            this.label4.Name = "label4";
            this.label4.Size = new System.Drawing.Size(54, 35);
            this.label4.TabIndex = 55;
            this.label4.Text = "Адрес:";
            //
            // label3
            //
            this.label3.AutoSize = true;
            this.label3.Font = new System.Drawing.Font("Gabriola", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
            this.label3.Location = new System.Drawing.Point(6, 179);
            this.label3.Name = "label3";
            this.label3.Size = new System.Drawing.Size(68, 35);
            this.label3.TabIndex = 54;
            this.label3.Text = "Телефон:";
            //
            // label2
            //
            this.label2.AutoSize = true;
            this.label2.Font = new System.Drawing.Font("Gabriola", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
            this.label2.Location = new System.Drawing.Point(6, 106);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(124, 35);
            this.label2.TabIndex = 53;
            this.label2.Text = "Название фирмы:";
            //
            // label1
            //
            this.label1.AutoSize = true;
            this.label1.Font = new System.Drawing.Font("Gabriola", 24F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
            this.label1.ForeColor = System.Drawing.Color.DodgerBlue;
            this.label1.Location = new System.Drawing.Point(126, 35);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(220, 59);
            this.label1.TabIndex = 51;
            this.label1.Text = "Добавить фирму";
            //
            // pictureBox1
            //
            this.pictureBox1.Image = global::Kursach.Properties.Resources.logotype;
            this.pictureBox1.Location = new System.Drawing.Point(12, 12);
            this.pictureBox1.Name = "pictureBox1";
            this.pictureBox1.Size = new System.Drawing.Size(88, 82);
            this.pictureBox1.TabIndex = 52;
            this.pictureBox1.TabStop = false;
            //
            // add_firm
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 28F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.BackColor = System.Drawing.Color.Snow;
            this.ClientSize = new System.Drawing.Size(385, 405);
            this.Controls.Add(this.button1);
            this.Controls.Add(this.cancelTB);
            this.Controls.Add(this.siteTB);
            this.Controls.Add(this.checkTB);
            this.Controls.Add(this.bankTB);
            this.Controls.Add(this.phoneTB);
            this.Controls.Add(this.addressTB);
            this.Controls.Add(this.nameTB);
            this.Controls.Add(this.label5);
            this.Controls.Add(this.label6);
            this.Controls.Add(this.label7);
            this.Controls.Add(this.label4);
            this.Controls.Add(this.label3);
            this.Controls.Add(this.label2);
            this.Controls.Add(this.pictureBox1);
            this.Controls.Add(this.label1);
            this.Font = new System.Drawing.Font("Gabriola", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
            this.Margin = new System.Windows.Forms.Padding(3, 6, 3, 6);
            this.Name = "add_firm";
            this.Text = "Добавить фирму";
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.Button button1;
        private System.Windows.Forms.Button cancelTB;
        private System.Windows.Forms.TextBox siteTB;
        private System.Windows.Forms.TextBox checkTB;
        private System.Windows.Forms.TextBox bankTB;
        private System.Windows.Forms.TextBox phoneTB;
        private System.Windows.Forms.TextBox addressTB;
        private System.Windows.Forms.TextBox nameTB;
        private System.Windows.Forms.Label label5;
        private System.Windows.Forms.Label label6;
        private System.Windows.Forms.Label label7;
        private System.Windows.Forms.Label label4;
        private System.Windows.Forms.Label label3;
        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.PictureBox pictureBox1;
        private System.Windows.Forms.Label label1;
    }
}


text:
package cmd

import (
	"fmt"
	"io/ioutil"
	"reflect"
	"sort"
	"testing"

	kapi "k8s.io/kubernetes/pkg/api"
	kerrors "k8s.io/kubernetes/pkg/api/errors"
	"k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake"
	"k8s.io/kubernetes/pkg/client/testing/core"
	"k8s.io/kubernetes/pkg/runtime"

	tc "github.com/openshift/origin/pkg/client/testclient"
	deployapi "github.com/openshift/origin/pkg/deploy/api"
	deploytest "github.com/openshift/origin/pkg/deploy/api/test"
	deployutil "github.com/openshift/origin/pkg/deploy/util"

	// install all APIs
	_ "github.com/openshift/origin/pkg/api/install"
	_ "k8s.io/kubernetes/pkg/api/install"
)

func deploymentFor(config *deployapi.DeploymentConfig, status deployapi.DeploymentStatus) *kapi.ReplicationController {
	d, err := deployutil.MakeDeployment(config, kapi.Codecs.LegacyCodec(deployapi.SchemeGroupVersion))
	if err != nil {
		panic(err)
	}
	d.Annotations[deployapi.DeploymentStatusAnnotation] = string(status)
	return d
}

// TestCmdDeploy_latestOk ensures that attempts to start a new deployment
// succeeds given an existing deployment in a terminal state.
func TestCmdDeploy_latestOk(t *testing.T) {
	validStatusList := []deployapi.DeploymentStatus{
		deployapi.DeploymentStatusComplete,
		deployapi.DeploymentStatusFailed,
	}
	for _, status := range validStatusList {
		config := deploytest.OkDeploymentConfig(1)
		updatedConfig := config

		osClient := &tc.Fake{}
		osClient.AddReactor("get", "deploymentconfigs", func(action core.Action) (handled bool, ret runtime.Object, err error) {
			return true, config, nil
		})
		osClient.AddReactor("update", "deploymentconfigs/instantiate", func(action core.Action) (handled bool, ret runtime.Object, err error) {
			updatedConfig.Status.LatestVersion++
			return true, updatedConfig, nil
		})

		kubeClient := fake.NewSimpleClientset()
		kubeClient.AddReactor("get", "replicationcontrollers", func(action core.Action) (handled bool, ret runtime.Object, err error) {
			return true, deploymentFor(config, status), nil
		})

		o := &DeployOptions{osClient: osClient, kubeClient: kubeClient, out: ioutil.Discard}
		err := o.deploy(config)
		if err != nil {
			t.Fatalf("unexpected error: %v", err)
		}

		if exp, got := int64(2), updatedConfig.Status.LatestVersion; exp != got {
			t.Fatalf("expected deployment config version: %d, got: %d", exp, got)
		}
	}
}

// TestCmdDeploy_latestConcurrentRejection ensures that attempts to start a
// deployment concurrent with a running deployment are rejected.
func TestCmdDeploy_latestConcurrentRejection(t *testing.T) {
	invalidStatusList := []deployapi.DeploymentStatus{
		deployapi.DeploymentStatusNew,
		deployapi.DeploymentStatusPending,
		deployapi.DeploymentStatusRunning,
	}

	for _, status := range invalidStatusList {
		config := deploytest.OkDeploymentConfig(1)
		existingDeployment := deploymentFor(config, status)
		kubeClient := fake.NewSimpleClientset(existingDeployment)
		o := &DeployOptions{kubeClient: kubeClient, out: ioutil.Discard}

		err := o.deploy(config)
		if err == nil {
			t.Errorf("expected an error starting deployment with existing status %s", status)
		}
	}
}

// TestCmdDeploy_latestLookupError ensures that an error is thrown when
// existing deployments can't be looked up due to some fatal server error.
func TestCmdDeploy_latestLookupError(t *testing.T) {
	kubeClient := fake.NewSimpleClientset()
	kubeClient.PrependReactor("get", "replicationcontrollers", func(action core.Action) (handled bool, ret runtime.Object, err error) {
		return true, nil, kerrors.NewInternalError(fmt.Errorf("internal error"))
	})

	config := deploytest.OkDeploymentConfig(1)
	o := &DeployOptions{kubeClient: kubeClient, out: ioutil.Discard}
	err := o.deploy(config)

	if err == nil {
		t.Fatal("expected an error")
	}
}

// TestCmdDeploy_retryOk ensures that a failed deployment can be retried.
func TestCmdDeploy_retryOk(t *testing.T) {
	deletedPods := []string{}
	config := deploytest.OkDeploymentConfig(1)

	var updatedDeployment *kapi.ReplicationController
	existingDeployment := deploymentFor(config, deployapi.DeploymentStatusFailed)
	existingDeployment.Annotations[deployapi.DeploymentCancelledAnnotation] = deployapi.DeploymentCancelledAnnotationValue
	existingDeployment.Annotations[deployapi.DeploymentStatusReasonAnnotation] = deployapi.DeploymentCancelledByUser

	mkpod := func(name string) kapi.Pod {
		return kapi.Pod{
			ObjectMeta: kapi.ObjectMeta{
				Name: name,
				Labels: map[string]string{
					deployapi.DeployerPodForDeploymentLabel: existingDeployment.Name,
				},
			},
		}
	}
	existingDeployerPods := []kapi.Pod{
		mkpod("hook-pre"), mkpod("hook-post"), mkpod("deployerpod"),
	}

	kubeClient := fake.NewSimpleClientset()
	kubeClient.PrependReactor("get", "replicationcontrollers", func(action core.Action) (handled bool, ret runtime.Object, err error) {
		return true, existingDeployment, nil
	})
	kubeClient.PrependReactor("update", "replicationcontrollers", func(action core.Action) (handled bool, ret runtime.Object, err error) {
		updatedDeployment = action.(core.UpdateAction).GetObject().(*kapi.ReplicationController)
		return true, updatedDeployment, nil
	})
	kubeClient.PrependReactor("list", "pods", func(action core.Action) (handled bool, ret runtime.Object, err error) {
		return true, &kapi.PodList{Items: existingDeployerPods}, nil
	})
	kubeClient.PrependReactor("delete", "pods", func(action core.Action) (handled bool, ret runtime.Object, err error) {
		deletedPods = append(deletedPods, action.(core.DeleteAction).GetName())
		return true, nil, nil
	})

	o := &DeployOptions{kubeClient: kubeClient, out: ioutil.Discard}
	err := o.retry(config)

	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}

	if updatedDeployment == nil {
		t.Fatalf("expected updated config")
	}

	if deployutil.IsDeploymentCancelled(updatedDeployment) {
		t.Fatalf("deployment should not have the cancelled flag set anymore")
	}

	if deployutil.DeploymentStatusReasonFor(updatedDeployment) != "" {
		t.Fatalf("deployment status reason should be empty")
	}

	sort.Strings(deletedPods)
	expectedDeletions := []string{"deployerpod", "hook-post", "hook-pre"}
	if e, a := expectedDeletions, deletedPods; !reflect.DeepEqual(e, a) {
		t.Fatalf("Not all deployer pods for the failed deployment were deleted.\nEXPECTED: %v\nACTUAL: %v", e, a)
	}

	if e, a := deployapi.DeploymentStatusNew, deployutil.DeploymentStatusFor(updatedDeployment); e != a {
		t.Fatalf("expected deployment status %s, got %s", e, a)
	}
}

// TestCmdDeploy_retryRejectNonFailed ensures that attempts to retry a non-
// failed deployment are rejected.
func TestCmdDeploy_retryRejectNonFailed(t *testing.T) {
	invalidStatusList := []deployapi.DeploymentStatus{
		deployapi.DeploymentStatusNew,
		deployapi.DeploymentStatusPending,
		deployapi.DeploymentStatusRunning,
		deployapi.DeploymentStatusComplete,
	}

	for _, status := range invalidStatusList {
		config := deploytest.OkDeploymentConfig(1)
		existingDeployment := deploymentFor(config, status)
		kubeClient := fake.NewSimpleClientset(existingDeployment)
		o := &DeployOptions{kubeClient: kubeClient, out: ioutil.Discard}
		err := o.retry(config)
		if err == nil {
			t.Errorf("expected an error retrying deployment with status %s", status)
		}
	}
}

// TestCmdDeploy_cancelOk ensures that attempts to cancel deployments
// for a config result in cancelling all in-progress deployments
// and none of the completed/faild ones.
func TestCmdDeploy_cancelOk(t *testing.T) {
	type existing struct {
		version      int64
		status       deployapi.DeploymentStatus
		shouldCancel bool
	}
	type scenario struct {
		version  int64
		existing []existing
	}

	scenarios := []scenario{
		// No existing deployments
		{1, []existing{{1, deployapi.DeploymentStatusComplete, false}}},
		// A single existing failed deployment
		{1, []existing{{1, deployapi.DeploymentStatusFailed, false}}},
		// Multiple existing completed/failed deployments
		{2, []existing{{2, deployapi.DeploymentStatusFailed, false}, {1, deployapi.DeploymentStatusComplete, false}}},
		// A single existing new deployment
		{1, []existing{{1, deployapi.DeploymentStatusNew, true}}},
		// A single existing pending deployment
		{1, []existing{{1, deployapi.DeploymentStatusPending, true}}},
		// A single existing running deployment
		{1, []existing{{1, deployapi.DeploymentStatusRunning, true}}},
		// Multiple existing deployments with one in new/pending/running
		{3, []existing{{3, deployapi.DeploymentStatusRunning, true}, {2, deployapi.DeploymentStatusComplete, false}, {1, deployapi.DeploymentStatusFailed, false}}},
		// Multiple existing deployments with more than one in new/pending/running
		{3, []existing{{3, deployapi.DeploymentStatusNew, true}, {2, deployapi.DeploymentStatusRunning, true}, {1, deployapi.DeploymentStatusFailed, false}}},
	}

	for _, scenario := range scenarios {
		updatedDeployments := []kapi.ReplicationController{}
		config := deploytest.OkDeploymentConfig(scenario.version)
		existingDeployments := &kapi.ReplicationControllerList{}
		for _, e := range scenario.existing {
			d, _ := deployutil.MakeDeployment(deploytest.OkDeploymentConfig(e.version), kapi.Codecs.LegacyCodec(deployapi.SchemeGroupVersion))
			d.Annotations[deployapi.DeploymentStatusAnnotation] = string(e.status)
			existingDeployments.Items = append(existingDeployments.Items, *d)
		}

		kubeClient := fake.NewSimpleClientset()
		kubeClient.PrependReactor("update", "replicationcontrollers", func(action core.Action) (handled bool, ret runtime.Object, err error) {
			updated := action.(core.UpdateAction).GetObject().(*kapi.ReplicationController)
			updatedDeployments = append(updatedDeployments, *updated)
			return true, updated, nil
		})
		kubeClient.PrependReactor("list", "replicationcontrollers", func(action core.Action) (handled bool, ret runtime.Object, err error) {
			return true, existingDeployments, nil
		})

		o := &DeployOptions{kubeClient: kubeClient, out: ioutil.Discard}

		err := o.cancel(config)
		if err != nil {
			t.Fatalf("unexpected error: %v", err)
		}

		expectedCancellations := []int64{}
		actualCancellations := []int64{}
		for _, e := range scenario.existing {
			if e.shouldCancel {
				expectedCancellations = append(expectedCancellations, e.version)
			}
		}
		for _, d := range updatedDeployments {
			actualCancellations = append(actualCancellations, deployutil.DeploymentVersionFor(&d))
		}

		sort.Sort(Int64Slice(actualCancellations))
		sort.Sort(Int64Slice(expectedCancellations))
		if !reflect.DeepEqual(actualCancellations, expectedCancellations) {
			t.Fatalf("expected cancellations: %v, actual: %v", expectedCancellations, actualCancellations)
		}
	}
}

type Int64Slice []int64

func (p Int64Slice) Len() int           { return len(p) }
func (p Int64Slice) Less(i, j int) bool { return p[i] < p[j] }
func (p Int64Slice) Swap(i, j int)      { p[i], p[j] = p[j], p[i] }

func TestDeploy_reenableTriggers(t *testing.T) {
	mktrigger := func() deployapi.DeploymentTriggerPolicy {
		t := deploytest.OkImageChangeTrigger()
		t.ImageChangeParams.Automatic = false
		return t
	}

	var updated *deployapi.DeploymentConfig

	osClient := &tc.Fake{}
	osClient.AddReactor("update", "deploymentconfigs", func(action core.Action) (handled bool, ret runtime.Object, err error) {
		updated = action.(core.UpdateAction).GetObject().(*deployapi.DeploymentConfig)
		return true, updated, nil
	})

	config := deploytest.OkDeploymentConfig(1)
	config.Spec.Triggers = []deployapi.DeploymentTriggerPolicy{}
	count := 3
	for i := 0; i < count; i++ {
		config.Spec.Triggers = append(config.Spec.Triggers, mktrigger())
	}

	o := &DeployOptions{osClient: osClient, out: ioutil.Discard}
	err := o.reenableTriggers(config)
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}

	if updated == nil {
		t.Fatalf("expected an updated config")
	}

	if e, a := count, len(config.Spec.Triggers); e != a {
		t.Fatalf("expected %d triggers, got %d", e, a)
	}
	for _, trigger := range config.Spec.Triggers {
		if !trigger.ImageChangeParams.Automatic {
			t.Errorf("expected trigger to be enabled: %#v", trigger.ImageChangeParams)
		}
	}
}


text:
    SPIN_FOR_TIMEDELTA_OR_UNTIL_TRUE(base::TimeDelta::FromSeconds(1), \
                                     (expression))

#define SPIN_FOR_TIMEDELTA_OR_UNTIL_TRUE(delta, expression) do { \
  base::Time start = base::Time::Now(); \
  const base::TimeDelta kTimeout = delta; \
    while(!(expression)) { \
      if (kTimeout < base::Time::Now() - start) { \
      EXPECT_LE((base::Time::Now() - start).InMilliseconds(), \
                kTimeout.InMilliseconds()) << "Timed out"; \
        break; \
      } \
      PlatformThread::Sleep(50); \
    } \
  } \
  while(0)

#endif  // BASE_SPIN_WAIT_H__


text:
package com.voxela.gov.checker;

import java.util.ArrayList;

import com.voxela.gov.utils.FileManager;

public class CheckMandate {

	public static boolean isMandateEnabled(String fed, String mandate) {

		return FileManager.dataFileCfg.getBoolean("federations." + fed + ".mandates." + mandate);

	}

	public static void setMandate(String fed, String mandate, boolean bool) {
		FileManager.dataFileCfg.set("federations." + fed + ".mandates." + mandate, bool);
		FileManager.saveDataFile();
	}

	public static ArrayList<String> getMandates() {

		ArrayList<String> mandates = new ArrayList<String>();
		mandates.add("Transportation Subsidy");
		mandates.add("Universal Healthcare");
		mandates.add("Department of Housing");

		return mandates;

	}

	public static ArrayList<String> getFedMandates(String fed) {

		ArrayList<String> fedMandates = new ArrayList<String>();

		for (String mandate : getMandates()) {
			if (isMandateEnabled(fed, mandate)) {
				fedMandates.add(mandate);
			}
		}
		return fedMandates;

	}

	public static String mandateToPermGroup(String mandate) {

		mandate.replaceAll(" ", "");
		return mandate;
	}

}


text:
@implementation MIHECKeyFactory

- (MIHKeyPair *)pairWithECKey:(EC_KEY *)key {
    if (key == NULL) {
        return nil;
    }

    __auto_type the_key = [[MIHECKey alloc] initWithKey:key];
    __auto_type privateKey = [[MIHECPrivateKey alloc] initWithKey:the_key];
    __auto_type publicKey = [[MIHECPublicKey alloc] initWithKey:the_key];
    __auto_type pair = [[MIHKeyPair alloc] init];
    pair.private = privateKey;
    pair.public = publicKey;
    return pair;
}

- (MIHKeyPair *)generateKeyPair {
    __auto_type group = self.group;
    __auto_type curve = self.curve;

    if (curve != nil) {
        return [self generateKeyPairWithCurve:curve];
    }
    else if (group != nil) {
        return [self generateKeyPairWithGroup:group];
    }
    return nil;
}

- (MIHKeyPair *)generateKeyPairWithCurve:(MIHECCurve *)curve {
    __auto_type identifier = curve.identifier;
    __auto_type ec_key = EC_KEY_new_by_curve_name(identifier.unsignedShortValue);
    EC_KEY_generate_key(ec_key);
    return [self pairWithECKey:ec_key];
}
- (MIHKeyPair *)generateKeyPairWithGroup:(MIHECCurveGroup *)group {
    __auto_type ec_group = group.group;
    __auto_type ec_key = EC_KEY_new();
    EC_KEY_set_group(ec_key, ec_group);
    EC_KEY_generate_key(ec_key);
    return [self pairWithECKey:ec_key];
}

@end


text:
<?php
/**
 * The template for displaying the footer.
 * Contains the closing of the #content div and all content after
 */

?>

<?php
	if(is_active_sidebar( 'zerif-sidebar-footer' ) || is_active_sidebar( 'zerif-sidebar-footer-2' ) || is_active_sidebar( 'zerif-sidebar-footer-3' )):
		echo '

';
		if(is_active_sidebar( 'zerif-sidebar-footer' )):
			echo '
';
			dynamic_sidebar( 'zerif-sidebar-footer' );
			echo '
';
		endif;
		if(is_active_sidebar( 'zerif-sidebar-footer-2' )):
			echo '
';
			dynamic_sidebar( 'zerif-sidebar-footer-2' );
			echo '
';
		endif;
		if(is_active_sidebar( 'zerif-sidebar-footer-3' )):
			echo '
';
			dynamic_sidebar( 'zerif-sidebar-footer-3' );
			echo '
';
		endif;
		echo '

';
	endif;
?>

	<?php
		$footer_sections = 0;
		$zerif_address = get_theme_mod('zerif_address',__('Company address','zerif-lite'));
		$zerif_address_icon = get_theme_mod('zerif_address_icon',get_template_directory_uri().'/images/map25-redish.png');

		$zerif_email = get_theme_mod('zerif_email','contact@site.com');
		$zerif_email_icon = get_theme_mod('zerif_email_icon',get_template_directory_uri().'/images/envelope4-green.png');

		$zerif_phone = get_theme_mod('zerif_phone','0 332 548 954');
		$zerif_phone_icon = get_theme_mod('zerif_phone_icon',get_template_directory_uri().'/images/telephone65-blue.png');

		$zerif_socials_facebook = get_theme_mod('zerif_socials_facebook','#');
		$zerif_socials_twitter = get_theme_mod('zerif_socials_twitter','#');
		$zerif_socials_linkedin = get_theme_mod('zerif_socials_linkedin','#');
		$zerif_socials_behance = get_theme_mod('zerif_socials_behance','#');
		$zerif_socials_dribbble = get_theme_mod('zerif_socials_dribbble','#');
		$zerif_socials_instagram = get_theme_mod('zerif_socials_instagram');

		$zerif_accessibility = get_theme_mod('zerif_accessibility');
		$zerif_copyright = get_theme_mod('zerif_copyright');

		if(!empty($zerif_address) || !empty($zerif_address_icon)):
			$footer_sections++;
		endif;

		if(!empty($zerif_email) || !empty($zerif_email_icon)):
			$footer_sections++;
		endif;

		if(!empty($zerif_phone) || !empty($zerif_phone_icon)):
			$footer_sections++;
		endif;
		if( !empty($zerif_socials_facebook) || !empty($zerif_socials_twitter) || !empty($zerif_socials_linkedin) || !empty($zerif_socials_behance) || !empty($zerif_socials_dribbble) ||
		!empty($zerif_copyright) || !empty($zerif_socials_instagram) ):
			$footer_sections++;
		endif;

		if( $footer_sections == 1 ):
			$footer_class = 'col-md-12';
		elseif( $footer_sections == 2 ):
			$footer_class = 'col-md-6';
		elseif( $footer_sections == 3 ):
			$footer_class = 'col-md-4';
		elseif( $footer_sections == 4 ):
			$footer_class = 'col-md-3';
		else:
			$footer_class = 'col-md-3';
		endif;

		global $wp_customize;

		if( !empty($footer_class) ) {

			/* COMPANY ADDRESS */
			if( !empty($zerif_address_icon) || !empty($zerif_address) ) {
				echo '
';

					if( !empty($zerif_address_icon) ) {
						echo '
';
							 echo '';
						echo '
';
					}

					if( !empty($zerif_address) ) {
						echo '
';
							echo wp_kses_post( $zerif_address );
						echo '
';
					} else if( isset( $wp_customize ) ) {
						echo '

';
					}

				echo '
';
			}

			/* COMPANY EMAIL */
			if( !empty($zerif_email_icon) || !empty($zerif_email) ) {
				echo '
';

					if( !empty($zerif_email_icon) ) {
						echo '
';
							echo '';
						echo '
';
					}
					if( !empty($zerif_email) ) {
						echo '
';
							echo wp_kses_post( $zerif_email );
						echo '
';
					} else if( isset( $wp_customize ) ) {
						echo '

';
					}

				echo '
';
			}

			/* COMPANY PHONE NUMBER */
			if( !empty($zerif_phone_icon) || !empty($zerif_phone) ) {
				echo '
';
					if( !empty($zerif_phone_icon) ) {
						echo '
';
							echo '';
						echo '
';
					}
					if( !empty($zerif_phone) ) {
						echo '
';
							echo wp_kses_post( $zerif_phone );
						echo '
';
					} else if( isset( $wp_customize ) ) {
						echo '

';
					}
				echo '
';
			}
		}

		// open link in a new tab when checkbox "accessibility" is not ticked
		$attribut_new_tab = (isset($zerif_accessibility) && ($zerif_accessibility != 1) ? ' target="_blank"' : '' );

		if( !empty($zerif_socials_facebook) || !empty($zerif_socials_twitter) || !empty($zerif_socials_linkedin) || !empty($zerif_socials_behance) || !empty($zerif_socials_dribbble) ||
		!empty($zerif_copyright) || !empty($zerif_socials_instagram) ):

					echo '
';
					if(!empty($zerif_socials_facebook) || !empty($zerif_socials_twitter) || !empty($zerif_socials_linkedin) || !empty($zerif_socials_behance) || !empty($zerif_socials_dribbble)):
						echo '
';

						/* facebook */
						if( !empty($zerif_socials_facebook) ):
							echo '

';
						endif;
						/* twitter */
						if( !empty($zerif_socials_twitter) ):
							echo '

';
						endif;
						/* linkedin */
						if( !empty($zerif_socials_linkedin) ):
							echo '

';
						endif;
						/* behance */
						if( !empty($zerif_socials_behance) ):
							echo '

';
						endif;
						/* dribbble */
						if( !empty($zerif_socials_dribbble) ):
							echo '

';
						endif;
						/* instagram */
						if( !empty($zerif_socials_instagram) ):
							echo '

';
						endif;
						echo '
';
					endif;

					if( !empty($zerif_copyright) ):
						echo '
'.wp_kses_post($zerif_copyright).'
';
					elseif( isset( $wp_customize ) ):
						echo '

';
					endif;

					echo '
Zerif Lite '.__('powered by','zerif-lite').' WordPress
';

					echo '
';

		endif;
	?>

<?php wp_footer(); ?>


text:
tumblrcl
========

Tool for interacting with Tumblr from the command line.

It really doesn't add any pretty printing of information, and is just a wrapper around
[pytumblr](https://github.com/tumblr/pytumblr).

Installation
------------

First clone or download the repo.  Then you will need to use PIP to first install my tumblrtokens package
found at https://github.com/mkell43/tumblrtokens.

Then you can run the following to install the rest of the requirements.

`pip install -r requirements.txt`

Using
-----

First you will need to register the application with Tumblr at
[http://www.tumblr.com/oauth/apps](http://www.tumblr.com/oauth/apps).

Then you'll need to run with tumblrcl is `./tumblrcl.py auth-create`, which will guide you through creating
the authentication file used by tumblrcl for connecting to Tumblr.

I may add a `first-run` option that will guide through the process of creating an application on Tumblr as well.

For right now all the data output is json.  I don't think I'll change that, so if you would like prettier output please
fork and just shoot me back a message so I can check it out.  If you'd like to send a pull request please feel free as
well.  If someone can find a way of nicely printing the output I'd reallyt like to see it.

TODO
----

1.  Need to add the post and tagged methods from pytumblr still.

2.  Add support for the additional params on the client.posts method.


text:
<!DOCTYPE html>

<meta charset="UTF-8">

<title>RDoc Documentation</title>

<link href="./css/fonts.css" rel="stylesheet">
<link href="./css/rdoc.css" rel="stylesheet">

    Home

    Pages
    Classes
    Methods

  <form action="#" method="get" accept-charset="utf-8">

      <input id="search-field" role="combobox" aria-label="Search"
             aria-autocomplete="list" aria-controls="search-results"
             type="text" name="search" placeholder="Search" spellcheck="false"
             title="Type to search, Up and Down to navigate, Enter to load">

  </form>

Pages

README

Class and Module Index

UmtsCustomMatchers

UmtsCustomMatchers::RedirectBack

UmtsCustomMatchers¶ ↑

Custom RSpec Rails-related matchers, used for UMass Transit's internal Rails development process.

Much of the inspiration for these solutions came from inspection of the rspec-rails source code, so thanks to the rspec-rails team for making their source code public.

Installation¶ ↑

Add this line to your application's Gemfile:

gem 'umts-custom-matchers'

And then execute:

$ bundle

Or install it yourself as:

$ gem install umts-custom-matchers

Usage¶ ↑

Require the matchers in your RSpec configuration file:

require 'umts_custom_matchers'

And include them:

RSpec.configure do |config|
  # ...
  config.include UmtsCustomMatchers
end

Development¶ ↑

After checking out the repo, run bin/setup to install dependencies. Then, run rake spec to run the tests. You can also run bin/console for an interactive prompt that will allow you to experiment.

To install this gem onto your local machine, run bundle exec rake install. To release a new version, update the version number in version.rb, and then run bundle exec rake release, which will create a git tag for the version, push git commits and tags, and push the .gem file to rubygems.org.

Contributing¶ ↑

Bug reports and pull requests are welcome on GitHub at github.com/umts/custom-matchers.

License¶ ↑

The gem is available as open source under the terms of the MIT License.

Validate

Generated by RDoc 6.1.2.

Based on Darkfish by Michael Granger.


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

  <title>Qt 4.8: Carnet d'adresses 3 - Navigation entre les éléments</title>
  <link rel="stylesheet" type="text/css" href="style/style.css" />

  <link rel="stylesheet" type="text/css" href="style/superfish.css" />
  <link rel="stylesheet" type="text/css" href="style/narrow.css" />

      Home

    Qt Reference Documentation

Qt HOME

DEV

          DOC

BLOG

Qt 4.8

ALL VERSIONS

API Lookup

Class index

Function index

Modules

Namespaces

Global Declarations

QML elements

Qt Topics

Programming with Qt

Device UIs & Qt Quick

UI Design with Qt

Supported Platforms

Qt and Key Technologies

How-To's and Best Practices

Examples

Examples

Tutorials

Demos

QML Examples

          Search index:

          <form id="qtdocsearch" action="" onsubmit="return false;">
            <fieldset>
              <input type="text" name="searchstring" id="pageType" value="" />

 Close

All | API | Articles | Examples

 results:

            </fieldset>
          </form>

            API Lookup

Class index

Function index

Modules

Namespaces

Global Declarations

QML elements

            Qt Topics

Programming with Qt

Device UIs & Qt Quick

UI Design with Qt

Supported Platforms

Qt and Key Technologies

How-To's and Best Practices

            Examples

Examples

Tutorials

Demos

QML Examples

Home

Examples

Carnet d'adresses 3 - Navigation entre les éléments

A

A

A

                Print

Contents

Définition de la classe AddressBook

Implémentation de la classe AddressBook

Carnet d'adresses 3 - Navigation entre les éléments

Files:

tutorials/addressbook-fr/part3/addressbook.cpp

tutorials/addressbook-fr/part3/addressbook.h

tutorials/addressbook-fr/part3/main.cpp

tutorials/addressbook-fr/part3/part3.pro

L'application "Carnet d'adresses" est maintenant à moitié terminée. Il nous faut maintenant ajouter quelques fonctions pour naviguer entre les contacts. Avant de commencer, il faut se décider sur le type de structure de données le plus approprié pour stocker les contacts.

Dans le chapitre 2, nous avons utilisé un QMap utilisant des paires clé-valeur, avec le nom du contact comme clé, et l'adresse du contact comme valeur. Cela fonctionnait bien jusqu'ici, mais pour ajouter la navigation entre les entrées, quelques améliorations sont nécessaires.

Nous améliorerons le QMap en le faisant ressembler à une structure de données similaire à une liste liée, où tous les éléments sont connectés, y compris le premier et le dernier élément. La figure ci-dessous illustre cette structure de donnée.

Définition de la classe AddressBook

Pour ajouter les fonctions de navigation au carnet d'adresses, nous avons besoin de deux slots supplémentaires dans notre classe <tt>AddressBook</tt>: <tt>next()</tt> et <tt>previous()</tt>. Ceux-ci sont ajoutés au fichier addressbook.h:

     void next();
     void previous();

Nous avons aussi besoin de deux nouveaux objets QPushButton, nous ajoutons donc les variables privées <tt>nextButton</tt> et <tt>previousButton</tt>.

     QPushButton *nextButton;
     QPushButton *previousButton;

Implémentation de la classe AddressBook

A l'intérieur du constructeur de <tt>AddressBook</tt>, dans <tt>addressbook.cpp</tt>, nous instancions <tt>nextButton</tt> et <tt>previousButton</tt> et nous les désactivons par défaut. Nous faisons ceci car la navigation ne doit être activée que lorsqu'il y a plus d'un contact dans le carnet d'adresses.

     nextButton = new QPushButton(tr("&Next"));
     nextButton->setEnabled(false);
     previousButton = new QPushButton(tr("&Previous"));
     previousButton->setEnabled(false);

Nous connectons alors ces boutons à leur slots respectifs:

     connect(nextButton, SIGNAL(clicked()), this, SLOT(next()));
     connect(previousButton, SIGNAL(clicked()), this, SLOT(previous()));

L'image ci-dessous montre l'interface utilisateur que nous allons créer. Remarquez que cela ressemble de plus en plus à l'interface du programme complet.

Nous suivons les conventions pour les fonctions <tt>next()</tt> et <tt>previous()</tt> en plaçant <tt>nextButton</tt> à droite et <tt>previousButton</tt> à gauche. Pour faire cette mise en page intuitive, nous utilisons un QHBoxLayout pour placer les widgets côte à côte:

     QHBoxLayout *buttonLayout2 = new QHBoxLayout;
     buttonLayout2->addWidget(previousButton);
     buttonLayout2->addWidget(nextButton);

L'objet QHBoxLayout, <tt>buttonLayout2</tt>, est ensuite ajouté à <tt>mainLayout</tt>.

     mainLayout->addLayout(buttonLayout2, 2, 1);

La figure ci-dessous montre les systèmes de coordonnées pour les widgets du <tt>mainLayout</tt>.

Dans notre méthode <tt>addContact()</tt>, nous avons desactivé ces boutons pour être sûr que l'utilisateur n'utilise pas la navigation lors de l'ajout d'un contact.

     nextButton->setEnabled(false);
     previousButton->setEnabled(false);

Dans notre méthode <tt>submitContact()</tt>, nous activons les boutons de navigation, <tt>nextButton</tt> et <tt>previousButton</tt>, en fonction de la taille de <tt>contacts</tt>. Commen mentionné plus tôt, la navigation n'est activée que si il y a plus d'un contact dans le carnet d'adresses. Les lignes suivantes montrent comment faire cela:

     int number = contacts.size();
     nextButton->setEnabled(number > 1);
     previousButton->setEnabled(number > 1);

Nous incluons aussi ces lignes de code dans le bouton <tt>cancel()</tt>.

Souvenez vous que nous voulons émuler une liste-liée ciruculaire à l'aide de l'objet QMap, <tt>contacts</tt>. Pour faire cela, nous obtenons un itérateur sur <tt>contact</tt> dans la méthode <tt>next()</tt>, et ensuite:

Si l'itérateur n'est pas à la fin de <tt>contacts</tt>, nous l'incrémentons

Si l'itérateur est à la fin de <tt>contacts</tt>, nous changeons sa position jusqu'au début de <tt>contacts</tt>. Cela donne l'illusion que notre QMap fonctionne comme une liste circulaire.

 void AddressBook::next()
 {
     QString name = nameLine->text();
     QMap<QString, QString>::iterator i = contacts.find(name);

     if (i != contacts.end())
         i++;

     if (i == contacts.end())
         i = contacts.begin();

     nameLine->setText(i.key());
     addressText->setText(i.value());
 }

Une fois que nous avons itéré jusqu'à l'objet recherché dans <tt>contacts</tt>, nous affichons son contenu sur <tt>nameLine</tt> et <tt>addressText</tt>.

De la même façon, pour la méthode <tt>previous()</tt>, nous obtenons un itérateur sur <tt>contacts</tt> et ensuite:

Si l'itérateur est à la fin de <tt>contacts</tt>, on réinitialise l'affichage et on retourne.

Si l'itérateur est au début de <tt>contacts</tt>, on change sa position jusqu'à la fin

Ensuite, on décrémente l'itérateur

 void AddressBook::previous()
 {
     QString name = nameLine->text();
     QMap<QString, QString>::iterator i = contacts.find(name);

     if (i == contacts.end()){
         nameLine->clear();
         addressText->clear();
         return;
     }

     if (i == contacts.begin())
         i = contacts.end();

     i--;
     nameLine->setText(i.key());
     addressText->setText(i.value());
 }

à nouveau, nous affichons le contenu de l'objet courant dans <tt>contacts</tt>.

      <acronym title="Copyright">©</acronym> 2013 Digia Plc and/or its
      subsidiaries. Documentation contributions included herein are the copyrights of
      their respective owners.

      The documentation provided herein is licensed under the terms of the
      GNU Free Documentation
      License version 1.3 as published by the Free Software Foundation.

      Documentation sources may be obtained from
      www.qt-project.org.

      Digia, Qt and their respective logos are trademarks of Digia Plc
      in Finland and/or other countries worldwide. All other trademarks are property
      of their respective owners. Privacy Policy


text:
#ifndef LOOKAT_H
#define LOOKAT_H

// Includes
#include "pandabase.h"
#include "cmath.h"
#include "coordinateSystem.h"
#include "luse.h"

#include "fltnames.h"
#include "look_at_src.h"

#include "dblnames.h"
#include "look_at_src.h"

#endif


text:
<!--

-->
<!DOCTYPE struts PUBLIC
          "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
          "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
    <package name="default" extends="struts-default">
        <action name="hello" class="com.opensymphony.xwork2.ActionSupport">
            <result name="success">hello.jsp</result>
            <result name="tutorial" type="redirect">/tutorial/test.action</result>
        </action>
    </package>

    <package name="tutorial" namespace="/tutorial" extends="struts-default">
        <result-types>
            <result-type name="freemarker" default="true"
                         class="org.apache.struts2.views.freemarker.FreemarkerResult"/>
        </result-types>

        <action name="test" class="com.opensymphony.xwork2.ActionSupport">
            <result name="input">sitegraph/guess-input.ftl</result>
        </action>

        <action name="test2" class="com.opensymphony.xwork2.ActionSupport">
            <result type="freemarker">
                <param name="location">org/apache/struts2/views/freemarker/callActionFreeMarker.ftl</param>
            </result>
        </action>

        <action name="test3" class="com.opensymphony.xwork2.ActionSupport">
            <result type="freemarker">org/apache/struts2/views/freemarker/nested.ftl</result>
        </action>

        <action name="test4" class="org.apache.struts2.TestAction" method="executeThrowsException">
            <result type="freemarker">
                <param name="location">org/apache/struts2/views/freemarker/nested.ftl</param>
            </result>
        </action>

         <action name="test5" class="com.opensymphony.xwork2.ActionSupport">
            <result type="freemarker">
                <param name="location">org/apache/struts2/views/freemarker/callActionFreeMarker2.ftl</param>
            </result>
        </action>

    </package>

    <package name="sitegraph" namespace="/tutorial/sitegraph" extends="struts-default">
        <result-types>
            <result-type name="freemarker" default="true"
                         class="org.apache.struts2.views.freemarker.FreemarkerResult"/>
        </result-types>

        <action name="guess" class="com.opensymphony.xwork2.ActionSupport">
            <result name="success" type="redirect">guess-success.jsp</result>
            <result name="input">guess-input.ftl</result>
            <result name="error">guess-error.ftl</result>
        </action>
    </package>
</struts>


text:
// Code generated by goagen v1.2.0, DO NOT EDIT.
//
// API "comics": hero Resource Client
//
// Command:
// $ goagen
// --design=github.com/ottogiron/goa-heroes/design
// --out=$(GOPATH)/src/github.com/ottogiron/goa-heroes
// --version=v1.2.0

package client

import (
	"bytes"
	"context"
	"fmt"
	"net/http"
	"net/url"
	"strconv"
)

// CreateHeroPayload is the hero create action payload.
type CreateHeroPayload struct {
	Name string `form:"name" json:"name" xml:"name"`
}

// CreateHeroPath computes a request path to the create action of hero.
func CreateHeroPath() string {

	return fmt.Sprintf("/heroes")
}

// Create new hero
func (c *Client) CreateHero(ctx context.Context, path string, payload *CreateHeroPayload, contentType string) (*http.Response, error) {
	req, err := c.NewCreateHeroRequest(ctx, path, payload, contentType)
	if err != nil {
		return nil, err
	}
	return c.Client.Do(ctx, req)
}

// NewCreateHeroRequest create the request corresponding to the create action endpoint of the hero resource.
func (c *Client) NewCreateHeroRequest(ctx context.Context, path string, payload *CreateHeroPayload, contentType string) (*http.Request, error) {
	var body bytes.Buffer
	if contentType == "" {
		contentType = "*/*" // Use default encoder
	}
	err := c.Encoder.Encode(payload, &body, contentType)
	if err != nil {
		return nil, fmt.Errorf("failed to encode body: %s", err)
	}
	scheme := c.Scheme
	if scheme == "" {
		scheme = "http"
	}
	u := url.URL{Host: c.Host, Scheme: scheme, Path: path}
	req, err := http.NewRequest("POST", u.String(), &body)
	if err != nil {
		return nil, err
	}
	header := req.Header
	if contentType == "*/*" {
		header.Set("Content-Type", "application/json")
	} else {
		header.Set("Content-Type", contentType)
	}
	return req, nil
}

// ListHeroPath computes a request path to the list action of hero.
func ListHeroPath() string {

	return fmt.Sprintf("/heroes")
}

// Retrieve all heroes
func (c *Client) ListHero(ctx context.Context, path string) (*http.Response, error) {
	req, err := c.NewListHeroRequest(ctx, path)
	if err != nil {
		return nil, err
	}
	return c.Client.Do(ctx, req)
}

// NewListHeroRequest create the request corresponding to the list action endpoint of the hero resource.
func (c *Client) NewListHeroRequest(ctx context.Context, path string) (*http.Request, error) {
	scheme := c.Scheme
	if scheme == "" {
		scheme = "http"
	}
	u := url.URL{Host: c.Host, Scheme: scheme, Path: path}
	req, err := http.NewRequest("GET", u.String(), nil)
	if err != nil {
		return nil, err
	}
	return req, nil
}

// ShowHeroPath computes a request path to the show action of hero.
func ShowHeroPath(heroID int) string {
	param0 := strconv.Itoa(heroID)

	return fmt.Sprintf("/heroes/%s", param0)
}

// Get hero by id
func (c *Client) ShowHero(ctx context.Context, path string) (*http.Response, error) {
	req, err := c.NewShowHeroRequest(ctx, path)
	if err != nil {
		return nil, err
	}
	return c.Client.Do(ctx, req)
}

// NewShowHeroRequest create the request corresponding to the show action endpoint of the hero resource.
func (c *Client) NewShowHeroRequest(ctx context.Context, path string) (*http.Request, error) {
	scheme := c.Scheme
	if scheme == "" {
		scheme = "http"
	}
	u := url.URL{Host: c.Host, Scheme: scheme, Path: path}
	req, err := http.NewRequest("GET", u.String(), nil)
	if err != nil {
		return nil, err
	}
	return req, nil
}


text:
module Chargeover
  class ChargeoverException < StandardError

    attr_accessor :status

    def initialize(status, message = nil)
      @status = status
      @message = message
      @default_message = 'There was an error with chargeover'
    end

    def to_s
      @message || @default_message
    end
  end
end


text:
// This file defines helpers useful when creating or manipulating lhlo/hlo.

#ifndef TENSORFLOW_COMPILER_MLIR_XLA_HLO_UTILS_H_
#define TENSORFLOW_COMPILER_MLIR_XLA_HLO_UTILS_H_

#include "mlir/IR/Attributes.h"  // TF:llvm-project
#include "mlir/IR/Builders.h"  // TF:llvm-project
#include "mlir/IR/StandardTypes.h"  // TF:llvm-project
#include "tensorflow/compiler/mlir/xla/convert_op_folder.h"
#include "tensorflow/compiler/xla/service/hlo_instruction.h"

namespace xla {

StatusOr<mlir::DenseElementsAttr> CreateDenseElementsAttrFromLiteral(
    const Literal& literal, mlir::Builder builder);

mlir::DenseIntElementsAttr CreateDenseIntElementsAttrFromVector(
    const llvm::ArrayRef<int64> vector, mlir::Builder builder);

template <typename TypeT>
static StatusOr<TypeT> ConvertTensorShapeToType(const Shape& shape,
                                                mlir::Builder builder) {
  auto dimensions = shape.dimensions();
  llvm::SmallVector<int64_t, 4> array(dimensions.begin(), dimensions.end());

  switch (shape.element_type()) {
    case PrimitiveType::PRED:
      return TypeT::get(array, builder.getI1Type());
    case PrimitiveType::F16:
      return TypeT::get(array, builder.getF16Type());
    case PrimitiveType::F32:
      return TypeT::get(array, builder.getF32Type());
    case PrimitiveType::F64:
      return TypeT::get(array, builder.getF64Type());
    case PrimitiveType::S8:
      return TypeT::get(array, builder.getIntegerType(8));
    case PrimitiveType::S16:
      return TypeT::get(array, builder.getIntegerType(16));
    case PrimitiveType::S32:
      return TypeT::get(array, builder.getIntegerType(32));
    case PrimitiveType::S64:
      return TypeT::get(array, builder.getIntegerType(64));
    default:
      return tensorflow::errors::Internal(absl::StrCat(
          "Unsupported type: ", PrimitiveType_Name(shape.element_type())));
  }
}

StatusOr<mlir::MemRefType> ConvertTensorShapeToMemRefType(
    const Shape& shape, mlir::Builder builder);

template <>
inline StatusOr<mlir::MemRefType> ConvertTensorShapeToType(
    const Shape& shape, mlir::Builder builder) {
  return ConvertTensorShapeToMemRefType(shape, builder);
}

template <typename TypeT>
static StatusOr<mlir::Type> ConvertShapeToType(const Shape& shape,
                                               mlir::Builder builder) {
  if (shape.IsTuple()) {
    llvm::SmallVector<mlir::Type, 4> contents;
    contents.reserve(shape.tuple_shapes_size());
    for (const auto& subtype : shape.tuple_shapes()) {
      TF_ASSIGN_OR_RETURN(auto mlir_subtype,
                          ConvertShapeToType<TypeT>(subtype, builder));
      contents.push_back(mlir_subtype);
    }
    return builder.getTupleType(contents);
  }
  return ConvertTensorShapeToType<TypeT>(shape, builder);
}

}  // namespace xla

#endif  // TENSORFLOW_COMPILER_MLIR_XLA_HLO_UTILS_H_


text:
name: Fernando Moreira - Jekyll theme
date: 2015-11-08
online: true
thumbnail: /images/uploads/nandomoreira-jekyll-theme.png
url: https://github.com/nandomoreirame/nandomoreira-jekyll-theme
description: Esse é o projeto do meu antigo blog feito com Jekyll, está totalmente open source e hospedado no Github pages.
tags:
- Jekyll
- FreeTheme
- Blogging
- GithubPages
- OpenSource
---


text:
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.compressedimage">

    <application android:allowBackup="true" android:label="@string/app_name"
        android:supportsRtl="true">

    </application>

</manifest>


text:
import fs from 'fs';
import { remote, ipcRenderer } from 'electron';
import constants from './helpers/constants';
import tail from './helpers/node-tail';

let getParameterByName = (name, url) => {
    if (!url) url = window.location.href;
    name = name.replace(/[\[\]]/g, "\\$&");
    let regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, " "));
}

let calcSize = (file) => {
    let sizeInBytes = fs.statSync(file)["size"]
    return sizeInBytes && sizeInBytes <= 500 ? 0 : Math.round(sizeInBytes/1000);
};

document.addEventListener('DOMContentLoaded', () => {
   window.et = {
       id: getParameterByName('id'),
       file: {
           name: getParameterByName('file'),
           lines: 0,
           sizeInKB: 0.0
       },
       tail: {
           fromBeginning: getParameterByName('fromBeginning')
       }
   }

   let tl = new tail.Tail(window.et.file.name, { separator: /[\r]{0,1}\n/, fromBeginning: window.et.tail.fromBeginning });
   tl.on('line', (data) => {
       window.et.file.lines++;
       if(window.et.file.lines && (window.et.file.lines == 0 || window.et.file.lines % 10 == 0)){
           window.et.file.sizeInKB = calcSize(window.et.file.name);
       }
       document.dispatchEvent(new CustomEvent('line', { 'detail': {
           file: window.et.file,
           line: data
       }}));
       console.log(`Line ${window.et.file.lines} and Size ${window.et.file.sizeInKB} KB`, data);
   });

    document.addEventListener('line', (evt) => {
        ipcRenderer.send(constants.events.passthrough, {
            scope: window.et.id,
            topic: constants.events.file.newLine,
            payload: evt.detail
        })
    })

});