text:
import java.io.*;

import java.net.*;
import java.util.*;

class DGPI {
// note : \u03C9 = caractˆre unicode pour omega
// note : pas d'affichage possibli dans
  String STR_OMEGA = "\u03C9"; // pour le mode graphique
  //String STR_OMEGA = "w"; // pour le mode texte HTML

  public static final int OUTPUT_TYPE_HTML = 0;
  public static final int OUTPUT_TYPE_TEXT_ONLY = 1;
//add gff output for multifasta on Dec 7th 2016 by Eduardo Alves
//TRINITY_DN1006_c0_g1_i1|m.4045  DGPI     gpi-anchor  603       26      0.469   .       .       YES
  public static final int OUTPUT_TYPE_GFF = 2;

  boolean quiet_mode = false;

  String dgpi_result, dgpi_result_text_only,  dgpi_result_gff; // résultats de l'analyse par DGPI, sous forme HTML et text only

  Hashtable ht_parametres = new Hashtable(); // table contenant les paramètres de la ligne de commande. Chaque paramètre est sur la ligne de commande comme -<nom_param>=<valeur>
                                             // <nom_param> est la clé de la hashtable et <valeur> est la valeur qui correspond à la clé. Si un paramètre n'a pas de valeur, il est mis dans la table avec la valeur "" (chaine vide).
                                             // un paramètre n'est mis dans la table que si il commence par '-'

  // variables DGPI
  // g‰n‰ration de la page HTML qui sera donn‰e € l'utilisateur. il est possible d'utiliser ce soft en local en entrant :
  //         java DGPI <access_number> > result.html
  // et de lire la page HTML result.html (seule diff‰rence : le header DGPI avec le logo)
  public static Hydrophobicite hy =null;
  public static AncreGPI ancre = null;
  //public static Signal si = null;

//  public static String sequence = null;
//  public static String access_number = null;

  public static int position_w_sp = 0;
  public static boolean keyword_GPI = false;
  public static int nbr_Sequences;
  private String serveur = "";
  private String resultat_get_sequence;

  public String database_name = "-";
  private boolean is_eukariote = true; //par d‰faut, on considˆre la prot‰ine comme eukariote (dans le cas o· on a que la s‰quence)

  INIFile init_file = null;

  public DGPI(String[] argv) {

    // choix du serveur depuis le fichier .ini

    try {
      // on essaie de lire le fichier .ini s'il existe
      init_file = new INIFile("dgpi.ini");

      // serveur
      serveur = init_file.getValue("server", "server_url");

      // position de la fenŠtre
      int x = Integer.parseInt(init_file.getValue("window", "x"));
      int y = Integer.parseInt(init_file.getValue("window", "y"));
      int width = Integer.parseInt(init_file.getValue("window", "width"));
      int height = Integer.parseInt(init_file.getValue("window", "height"));

    }
    catch (IOException e) {
      // le fichier n'existe pas => on cr‰e un nouveau fichier
      init_file = new INIFile("dgpi.ini", true);

      serveur = "http://www.expasy.ch/cgi-bin/sprot-search-ac";
    }

    // extraction des paramètres
    for (int i=0; i<argv.length; i++) {
      if (argv[i].charAt(0)=='-') {
        // le paramètre commence par '-' => on le met dans la table
        int index_egal = argv[i].indexOf('=',1);
        String nom_param; // le nom du paramètre (clé de la table)
        String valeur; // valeur associée au nom du paramètre

        if (index_egal>0) {
          // il y a un égal dans le paramètre => on calcule le nom du paramètre
          nom_param = argv[i].substring(1, index_egal);
          valeur = argv[i].substring(index_egal+1);
        } else {
          // pas de égal => pas de valeur
          nom_param = argv[i].substring(1);
          valeur = "";
        }//end if

        // ajout du paramètre dans la table
        //System.out.println(nom_param+"   "+valeur);
        ht_parametres.put(nom_param, valeur);
      }//end if
    }//end for

    // traitement des paramètres
    String valeur_param_quiet=(String)ht_parametres.get("q");
    if (valeur_param_quiet!=null) {
      // pas de paramètre -q => pas de quiet mode quiet mode
      quiet_mode = true;
    }//end if

    String valeur_param_help=(String)ht_parametres.get("h");
    if (valeur_param_help!=null) {
      // paramètre -h => display help
      System.out.println("DGPI v2.04 - Prediction of GPI-anchor from a protein sequence");
      System.out.println("Syntax : ");
      System.out.println("     dgpi [-file=<file_name> [-output=HTML|text|gff]] [-h] [-q]\n");
      System.out.println("     -file=<file_name>    : tell DGPI which file contain the protein to analyze");
      System.out.println("                            <file_name> contains :");
      System.out.println("                                        an access unmber  OR");
      System.out.println("                                        an entry name     OR");
      System.out.println("                                        a sequence        OR");
      System.out.println("                                        a protein in fasta format");
      System.out.println("     -output=HTML|text|gff    : tell DGPI on which format need to be writed");
      System.out.println("                            Default output type is HTML");
      System.out.println("     -h                   : display this help");
      System.out.println("     -q                   : quiet mode (does not display any messages)");
      System.out.println("\n     DGPI start in graphical if no file is specified from the command line");
      System.out.println("\n     DGPI results are stored in HTML|text|gff format in file <file_name>.html|txt|gff");
      System.out.println("\n     web : dgpi.pathbot.com       email : dgpi@bigfoot.com");
      System.exit(0);
    } else {
      // pas d'aide demandée => on la propose
      if (!quiet_mode) System.out.println("DGPI v2.04 -      (use flag -h for help)");
    }//end if

    String copyright = "

Generated by DGPI v.2.04   (free version for educational purpose only)
"+(new Date()).toString()+"";
    String valeur_param_output = (String)ht_parametres.get("output");
    String valeur_param_file=(String)ht_parametres.get("file");
    String file_name_extension = "html";
    String reponse = "";
    if (valeur_param_file!=null) {
// for gff output, read each protein and call getResult on Protein.set(sequence)
       if (valeur_param_output.equals("gff")) {
    BufferedReader in = null;
    try {
      // ouvrir le fichier
      in = new BufferedReader(new FileReader(valeur_param_file));
      String sequence="";
      Protein prot = new Protein();
      // lire la première ligne
      String ligne = in.readLine();
      while (ligne != null) {

      	if (ligne.charAt(0)=='>') {
		prot.fasta_id=ligne.split(" ")[0].substring(1);
		sequence="";
		ligne = in.readLine();
        } else {
	boolean keepReading = true;

	do{
          sequence +=ligne;
	  ligne = in.readLine();
	  if(ligne == null){
	    keepReading = false;
      	    prot.set(sequence);
      	    reponse += getResponse(prot, OUTPUT_TYPE_GFF);
	    }else if((ligne.charAt(0) == '>')){
		keepReading = false;
      		prot.set(sequence);
      		reponse += getResponse(prot, OUTPUT_TYPE_GFF);
		}
	  }while(keepReading);
       }//end if
     }
//add gff output for multifasta on Dec 7th 2016 by Eduardo Alves
          if (!quiet_mode) System.out.println("  output type = gff");
          file_name_extension = "gff";
          copyright = "";

    }
    catch (IOException e) {
      //e.printStackTrace();
      System.out.println("DGPI error : cannot read file "+valeur_param_file);
      System.exit(-1);
    }
}//end gff output

      // lecture de la protéine for non gff output (does not support multi-fasta)

      Protein prot = new Protein();
      prot.read_from_file(valeur_param_file);
      //System.out.println(prot);

      STR_OMEGA = "w"; // pour le mode texte HTML sinon la page HTML de résultat n'afficha pas les omégas correctement.
      prot.serveur = this.serveur;

      if (valeur_param_output!=null) {
        if (valeur_param_output.equals("HTML")) {
          if (!quiet_mode) System.out.println("  output type = HTML");

          reponse = getResponse(prot, OUTPUT_TYPE_HTML);
        } else if (valeur_param_output.equals("text")) {
          if (!quiet_mode) System.out.println("  output type = text");
          file_name_extension = "txt";
          copyright = "";
          reponse = getResponse(prot, OUTPUT_TYPE_TEXT_ONLY);

        } else if (!valeur_param_output.equals("gff")){
          // type de fichier inconnu => erreur
          System.out.println("DGPI error : output parameter is wrong : "+valeur_param_output+" (valid option are : HTML or text)");
          System.exit(-1);
        }//end if
      } else if (!valeur_param_output.equals("gff")){
        // pas de paramètre de sortie => format par défaut
        reponse = getResponse(prot);
      }//end if

      // sauver dans un fichier HTML
      String out_file_name = valeur_param_file+"."+file_name_extension;
      try {
        PrintWriter pw = new PrintWriter(new FileWriter(out_file_name));
        pw.println(reponse);
        pw.println(copyright);
        pw.close();
        System.exit(0);
      }
      catch (IOException e) {
        //e.printStackTrace();
        System.out.println("DGPI error : cannot write to file "+out_file_name);
        System.exit(-1);
      }
      if (!quiet_mode) System.out.println("Done! (result saved in "+out_file_name+")");

}

  }//end constructeur

public String getResponse(Protein prot) {
    // par défaut, on retourne une page HTML
    return getResponse(prot, OUTPUT_TYPE_HTML);
  }//end getResponse

  public String getResponse(Protein prot, int output_type) {
    String result = "";

    result += "

<BIG><big>DGPI Result</BIG></big>

";
    result += "

Protein	"+prot.name_HTML()+"
";

    if (prot.sequence==null) {
      // la séquence est inconnue => il faut aller la chercher sur le serveur
      if (!quiet_mode) System.out.println("Retrieving protein from server...");
      prot.sequence = getSequence(prot.name());
      if (!quiet_mode) System.out.println("Scanning protein...");
      if (prot.sequence.length()==0) {
      	result += "<big>ERROR : </big>the protein "+prot.name_HTML()+" does not exist!";
        return result;
      }//end if
      result += resultat_get_sequence;
    }//end if

    // traitement de la protéine par DGPI
    result += "
Sequence
";
    for (int i=0; i<prot.sequence.length(); i+=100) {
      int b_sup = i+100;

      if (b_sup>=prot.sequence.length()) b_sup=prot.sequence.length();
      result += prot.sequence.substring(i,b_sup)+"
";
    }
    result += "

";
    result += "
Length	"+prot.sequence.length()+"
";

    traite(prot);

    result += dgpi_result;
    result += "

";

    switch (output_type) {

      case OUTPUT_TYPE_HTML: return result;
      case OUTPUT_TYPE_TEXT_ONLY: return dgpi_result_text_only;
      case OUTPUT_TYPE_GFF: return dgpi_result_gff;
      default :
        System.out.println("DGPI Error : unknow output type");
        System.exit(-1);
    }//end switch
    return null;
  }// end getResponse

  public String getSequence(String access_number) {
    resultat_get_sequence = "";
    String str_PSORT = "";
    String val_sequence = "";

        // connexion au serveur web expasy et r‰cup‰ration de la prot‰ine
        BufferedReader donneesHTML = null;
        try {
          URL u;
          u = new URL(serveur+"?"+access_number);
          donneesHTML = new BufferedReader(new InputStreamReader(u.openStream()));
        }
        catch (Exception e){
          System.out.println("Error while connecting to server '"+serveur+"'");
        }

        try {
	  String ligneCourante = null;
	  while ((ligneCourante = donneesHTML.readLine()) != null) {
            str_PSORT += ligneCourante;
	  }
	}
	catch (Exception e) {
	  System.out.println("DGPI error : cannot read data from server "+serveur);
	  //e.printStackTrace();
	  System.exit(-1);
	}

	//try {

        // recherche du nom de la base de donn‰e d'o· provient la prot‰ine
        // le format HTML est :
NiceProt View of TrEMBL:
        String database_name_str_debut = "
NiceProt View of ";
        if (str_PSORT.indexOf(database_name_str_debut)==-1) {
          return "";// s‰quence vide
        } else {
          int index_database_name_debut = str_PSORT.indexOf(database_name_str_debut) + database_name_str_debut.length();
          int index_database_name_fin = str_PSORT.indexOf(':', index_database_name_debut);
          database_name = str_PSORT.substring(index_database_name_debut, index_database_name_fin);
          resultat_get_sequence += "
Data from "+database_name+"	";

          String str_access_number = "Primary accession number	";
          int index_AC_debut = str_PSORT.indexOf(str_access_number, index_database_name_fin)+str_access_number.length();
          int index_AC_fin   = str_PSORT.indexOf("", index_AC_debut);
          access_number      = str_PSORT.substring(index_AC_debut, index_AC_fin);

          //recherche de la feature PROPEP (partie entre le site w et le C-terminal)
          String str_PROPEP = "
PROPEP";
          int index_PROPEP_debut = str_PSORT.indexOf(str_PROPEP);
          if (index_PROPEP_debut!=-1) resultat_get_sequence += "Found the feature PROPEP in "+database_name+" entry
";
          index_PROPEP_debut += str_PROPEP.length();
          int index_PROPEP_fin   = str_PSORT.indexOf("
", index_PROPEP_debut);
          String str_PROPEP_GPI  = str_PSORT.substring(index_PROPEP_debut, index_PROPEP_fin);

          //extraction de la feature LIPID (ancre GPI)
          String str_LIPID     = "
LIPID";
          String str_LIPID_GPI = "";
          String position_w    = "0";
          int index_LIPID_debut = str_PSORT.indexOf(str_LIPID);
          if (index_LIPID_debut!=-1) {
            // LIPID trouv‰e
            resultat_get_sequence += "Found the feature LIPID in "+database_name+" entry
";
            index_LIPID_debut +=str_LIPID.length();
            int index_LIPID_fin   = str_PSORT.indexOf("
", index_LIPID_debut);
            str_LIPID_GPI         = str_PSORT.substring(index_LIPID_debut, index_LIPID_fin);

            //recherche de la position de l'ancre
            String str_position_GPI = "\">";
            int index_position_GPI_debut = str_LIPID_GPI.indexOf(str_position_GPI)+str_position_GPI.length();
            int index_position_GPI_fin   = str_LIPID_GPI.indexOf("  ", index_position_GPI_debut);
            position_w                   = str_LIPID_GPI.substring(index_position_GPI_debut, index_position_GPI_fin);
            position_w_sp = new Integer(position_w).intValue();
            if (position_w_sp!=0) resultat_get_sequence += "cleavage site at "+position_w_sp+".
";
          }//end if

          //extraction de la taxonomie
          String str_taxonomy = "Taxonomy	";
          int index_taxonomy_debut = str_PSORT.indexOf(str_taxonomy)+str_taxonomy.length();
          //int index_taxonomy_fin   = str_PSORT.indexOf("	", index_taxonomy_debut);
          int index_taxonomy_fin   = str_PSORT.indexOf("; ", index_taxonomy_debut);
          String str_taxonomy_2      = str_PSORT.substring(index_taxonomy_debut, index_taxonomy_fin);
          int index_taxonomy_point   = str_taxonomy_2.indexOf(". ");
          if (index_taxonomy_point!=-1) str_taxonomy_2 = str_taxonomy_2.substring(0, index_taxonomy_point);
          //taxonomie = str_taxonomy_2;*/
          if (!str_taxonomy_2.equals("Eukaryota")) {
            resultat_get_sequence += "WARNING : this protein is not from an Eukaryota.
";
            is_eukariote = false;
          } else {
            is_eukariote = true;
          }//end if

          //extraction des mots-cl‰s
          String str_Keyword = "Keywords	";
          int index_Keyword_debut = str_PSORT.indexOf(str_Keyword)+str_Keyword.length();
          int index_Keyword_fin   = str_PSORT.indexOf("	", index_Keyword_debut);
          String str_Keyword_GPI  = str_PSORT.substring(index_Keyword_debut, index_Keyword_fin);

          //r‰cup‰ration de la s‰quence
          String str_sequence = "
";
          int index_sequence_debut = str_PSORT.indexOf(str_sequence)+str_sequence.length();
          int index_sequence_fin   = str_PSORT.indexOf("
", index_sequence_debut);
          for (int j=index_sequence_debut; j<index_sequence_fin; j++) {
            char chr = str_PSORT.charAt(j);
            if ((chr>='A') && (chr<='Z')) val_sequence += chr;
          }//end for

          // calcul des propri‰t‰s selon swiss-prot.
/*          String val_keyword_gpi = "0";
          String val_propep      = "0";
          String val_propep_p    = "0";
          String val_propep_bs   = "0";
          String val_lipid       = "0";
          String val_lipid_p     = "0";
          String val_lipid_bs    = "0";*/
          if (str_Keyword_GPI.indexOf("GPI-anchor"            )!=-1) {keyword_GPI = true; resultat_get_sequence += "Found the keyword 'gpi-anchor' in "+database_name+" entry
";}
          if (str_PROPEP_GPI.indexOf ("REMOVED IN MATURE FORM")!=-1) resultat_get_sequence += "the PROPEP is removed in mature form
";
          if (str_PROPEP_GPI.indexOf ("POTENTIAL"             )!=-1) resultat_get_sequence += "the PROPEP is potential
";
          if (str_PROPEP_GPI.indexOf ("BY SIMILARITY"         )!=-1) resultat_get_sequence += "the PROPEP is by similarity
";
          if (str_LIPID_GPI.indexOf  ("GPI-ANCHOR"            )!=-1) resultat_get_sequence += "the LIPID is a GPI-anchor
";
          if (str_LIPID_GPI.indexOf  ("POTENTIAL"             )!=-1) resultat_get_sequence += "the LIPID is potential
";
          if (str_LIPID_GPI.indexOf  ("BY SIMILARITY"         )!=-1) resultat_get_sequence += "the LIPID is by similarity
";

          resultat_get_sequence += "
";

          }//end if (protein found)

//        }//end if (error)
/*      }//end try
      catch (Exception e) {
         resultat_get_sequence += "impossible de faire la requete!!! (proteine "+access_number+")";
         resultat_get_sequence += e.getMessage();
         resultat_get_sequence += str_PSORT;
      }*/
      return val_sequence;

  }//end getSequence

	public void traite(Protein prot) {
	  String result ="";
	  String result_text_only = "";
	  String result_gff = ""; //add gff output for multifasta on Dec 7th 2016 by Eduardo Alves

          boolean critere1, critere2, critere3;
	  char Caract;

          String is_GPI_anchored = null;
          String comment = null;
          String position_GPI_anchor = null;

          int nbr_gpi_anchor_ok = 0;
          int nbr_ancres_sp = 0;
          int nbr_proteines_gpi_ok = 0;
          int nbr_proteines_gpi_ok_phobe_phile = 0;
          int nbr_proteine_signal = 0;

          result += "
Data from DGPI	";
          result_text_only += "";

          float longueur_hydrophobe = 0;
          float longueur_hydrophile = 0;
          float position_GPI_probable = 0;
          position_GPI_anchor = "0";

//                     if (prot.sequence[i].length()>=47) {

          // SIGNAL
          result += "N-term Signal :
";
          result_text_only += "N-term Signal :\n";
          sigs si2 = new sigs(prot.sequence, is_eukariote);
          if (si2.has_Nterm_signal) {
            result += "  there is a N-term signal   (1.."+si2.pos_site_clivage+" in violet)
";
            result_text_only += "  there is a N-term signal   (1.."+si2.pos_site_clivage+")\n";
          } else {
            result += "  there ISN'T a N-term signal
";
            result_text_only += "  there ISN'T a N-term signal\n";
          }
          result += "  maximal score="+si2.score_max+"

";
          result_text_only += "  maximal score="+si2.score_max+"\n\n";

          // HYDROPHOBICITE
          result += "C-term Hydrophobicity profile :
";
          result_text_only += "C-term Hydrophobicity profile :\n";
          try {
            hy = new Hydrophobicite(prot.sequence, "median passe-bas");
          }
          catch (Exception e) {
            result += "Exception while computing C-term Hydrophobicity profile";
          }
	  result += "  hydrophobe length (low-pass filter)="+hy.hydrophobe_length+"
";
	  result += "  hydrophile length (low-pass filter)="+hy.hydrophile_length+"
";
	  result += "  hydrophobe length (median filter)="+hy.hydrophobe_median_length+"
";
	  result += "  hydrophile length (median filter)="+hy.hydrophile_median_length+"
";
	  result_text_only += "  hydrophobe length (low-pass filter)="+hy.hydrophobe_length+"\n";
	  result_text_only += "  hydrophile length (low-pass filter)="+hy.hydrophile_length+"\n";
	  result_text_only += "  hydrophobe length (median filter)="+hy.hydrophobe_median_length+"\n";
	  result_text_only += "  hydrophile length (median filter)="+hy.hydrophile_median_length+"\n";

          float POIDS_MEDIAN_PHOBE = (float)0.5;//meilleur = 0.7 (en tous cas pour les 172 mais pas pour les 23)
          float POIDS_MEDIAN_PHILE = (float)0.5;//meilleur = 0.7
          longueur_hydrophobe = POIDS_MEDIAN_PHOBE * hy.hydrophobe_median_length + (1-POIDS_MEDIAN_PHOBE) * hy.hydrophobe_length /*+ hy.hydrophobe_eisenberg_length*/;
          longueur_hydrophile = POIDS_MEDIAN_PHILE * hy.hydrophile_median_length + (1-POIDS_MEDIAN_PHILE) * hy.hydrophile_length /*+ hy.hydrophile_eisenberg_length*/;
          result += "  average hydrophobe length = "+longueur_hydrophobe+" (in blue)
";
          result += "  average hydrophile length = "+longueur_hydrophile+"

";
          result_text_only += "  average hydrophobe length = "+longueur_hydrophobe+"\n";
          result_text_only += "  average hydrophile length = "+longueur_hydrophile+"\n\n";
          position_GPI_probable = longueur_hydrophobe + 7;

//          System.out.println("  position_GPI_probable="+position_GPI_probable);

          result += "Cleavage site ("+STR_OMEGA+") :
";
          result_text_only += "Cleavage site (w) :\n";

          try {
            ancre = new AncreGPI(prot.sequence, 13);
          }
          catch (Exception e) {
            result += "Exception AncreGPI : proteine = "+prot.access_number;
            result += "  seq="+prot.sequence;
            result_text_only += "Exception AncreGPI : proteine = "+prot.access_number;
            result_text_only += "  seq="+prot.sequence;
          }

/*                        try {
                          si = new Signal(prot.sequence[i], "");
                        }
                        catch (Exception e) {
                          System.out.println("Exception Signal : proteine = "+access_number[i]);
                          System.out.println("  seq="+sequence[i]);
                        }
*/
/*                        System.out.println("  phile1="+si.hydrophile1_length);
                        System.out.println("  phobe ="+si.hydrophobe_length);
                        System.out.println("  phile2="+si.hydrophile2_length);
                        System.out.println("  median_phile1="+si.hydrophile1_median_length);
                        System.out.println("  median_phobe ="+si.hydrophobe_median_length);
                        System.out.println("  median_phile2="+si.hydrophile2_median_length);
*/

                        float valeur_max=1000;
                        int index_max=-1;
                        int num_ancre;
//System.out.println(ancre.nbr_ancres+ " ancres trouves");
                        for (num_ancre=0; num_ancre<ancre.nbr_ancres; num_ancre++) {
                          if ((ancre.position[num_ancre]-position_GPI_probable)<valeur_max) {
                            valeur_max = Math.abs(ancre.position[num_ancre]-position_GPI_probable);
                            index_max = num_ancre;
                          }
                        }

                        int index_max_pourcent=index_max;

                        if (index_max==-1) {
                          result += "  no cleavage site detected ("+STR_OMEGA+", "+STR_OMEGA+"+2 rule not respected).
";
                          result_text_only += "  no cleavage site detected (w, w+2 rule not respected).\n";
                          position_GPI_anchor = "0";
                        } else {
                          result += "  There's a GPI-anchor near "+(prot.sequence.length()-ancre.position[index_max])+"  (7 aa after hydrophobic tail)";
                          result_text_only += "  There's a GPI-anchor near "+(prot.sequence.length()-ancre.position[index_max])+"  (7 aa after hydrophobic tail)";
                          if (position_w_sp!=0) {
                            result += " ("+position_w_sp+" say "+database_name+", "+prot.sequence.substring(position_w_sp-1, position_w_sp+2)+")";
                            result_text_only += " ("+position_w_sp+" say "+database_name+", "+prot.sequence.substring(position_w_sp-1, position_w_sp+2)+")";
                          }//end if
                          result += "
";
                          result_text_only += "\n";

                          int NBR_GAUCHE = 1;
                          int NBR_DROITE = 1;
                          float valeur_max_pourcent=ancre.position_pourcent[index_max];
 //System.out.println("pos_max="+index_max_pourcent + "   pourcent="+ancre.position_pourcent[index_max]);
                          for (num_ancre=index_max-NBR_GAUCHE; num_ancre<=index_max+NBR_DROITE; num_ancre++) {// modif <=
                            if ((num_ancre>=0) &&
                                (num_ancre<ancre.nbr_ancres) &&
                                (ancre.position_pourcent[num_ancre]>valeur_max_pourcent)) {
                              valeur_max_pourcent = ancre.position_pourcent[num_ancre];
                              index_max_pourcent = num_ancre;
                            }
                          }

                          for (num_ancre=0; num_ancre<ancre.nbr_ancres; num_ancre++) {
                            result += "  There's a potential cleavage site at "+(prot.sequence.length()-ancre.position[num_ancre])+" (score="+ancre.position_pourcent[num_ancre]+") detected by "+STR_OMEGA+","+STR_OMEGA+"+2 rule.
";
                            result_text_only += "  There's a potential cleavage site at "+(prot.sequence.length()-ancre.position[num_ancre])+" (score="+ancre.position_pourcent[num_ancre]+") detected by w, w+2 rule.\n";
                          }

                          result += "  The best cleavage site is "+(prot.sequence.length()-ancre.position[index_max_pourcent])+"
";
                          result_text_only += "  The best cleavage site is "+(prot.sequence.length()-ancre.position[index_max_pourcent])+"\n";
                          position_GPI_anchor = new Integer(prot.sequence.length()-ancre.position[index_max_pourcent]).toString();

                          //ancre.position[index_max_pourcent] = Math.round((float)0.8 * ancre.position[index_max_pourcent] + (float)0.2 * ancre.position[index_max]);

                          if ((prot.sequence.length()-ancre.position[index_max_pourcent]==position_w_sp) && (keyword_GPI==true) ) {
                            //mŠme r‰sultat que swissprot
                            nbr_gpi_anchor_ok++;
                          }

                          }//end if (ancre d‰tect‰e)

                          if (position_w_sp!=0) {
                            if (nbr_gpi_anchor_ok>0) {
                              result += "  "+database_name+" indicate the same cleavage site.
";
                              result_text_only += "  "+database_name+" indicate the same cleavage site.\n";
                            } else {
                              result += "  "+database_name+" indicate a different cleavage site.
";
                              result_text_only += "  "+database_name+" indicate a different cleavage site.\n";
                            }
                          }
                          result += "
";
                          result_text_only += "\n";

                        // CONCLUSION
                        result += "Conclusion :
";
                        result_text_only += "Conclusion :\n";
                        // calcul du nombre de prot‰ines gpi selon nous (349 selon swiss-prot)
                        result += "  This protein ";
                        result_text_only += "  This protein ";
                        is_GPI_anchored = "0";
                        if (/*si.score_max>=0*/ si2.has_Nterm_signal) {//signal
                          nbr_proteine_signal++;
                          if (longueur_hydrophobe>12) {//partie hydrophobe   <<<< meilleurs resultats avec >15 >>>>
                            nbr_proteines_gpi_ok++;
                            if (longueur_hydrophile>2) {//partie hydrophile <<<< meilleurs resultats avec >2 >>>>
                              nbr_proteines_gpi_ok_phobe_phile++;
                              is_GPI_anchored = "1";
                              result += "is GPI-anchored (signal, hydrophobic & hydrophilic tail present).
";
                              result_text_only += "is GPI-anchored (signal, hydrophobic & hydrophilic tail present).\n";
	  		      result_gff=prot.fasta_id+"\tDGPI\tgpi-anchor\t"+si2.pos_site_clivage+"\t"+prot.sequence.length()+"\t"+si2.score_max+"\t.\t.\tYES\n";//add gff output for multifasta on Dec 7th 2016 by Eduardo Alves
                              //comment = "is GPI-anchored.";
                            } else {
                              result += "is not GPI-anchored (C-terminal hydrophobic area but C-terminal hydrophilic area is too short).
";
                              result_text_only += "is not GPI-anchored (C-terminal hydrophobic area but C-terminal hydrophilic area is too short).\n";
                              //comment = "is not GPI-anchored (C-terminal hydrophobic area but C-terminal hydrophilic area is too short).";
                            }
                          }else {
                            result += "is not GPI-anchored (C-terminal hydrophobic area is too short).
";
                            result_text_only += "is not GPI-anchored (C-terminal hydrophobic area is too short).\n";
                            //comment = "is not GPI-anchored (C-terminal hydrophobic area is too short).";
                          }
                        } else {
                          result += "is not GPI-anchored (no signal).
";
                          result_text_only += "is not GPI-anchored (no signal).\n";
                          //comment = "is not GPI-anchored (no signal).";
                        }

                        if (index_max==-1) {
                          result += "  No cleavage site detected.
";
                          result_text_only += "  No cleavage site detected.\n";
                        } else {
                          result += "  There is a potential cleavage site at "+(prot.sequence.length()-ancre.position[index_max_pourcent])+" ("+STR_OMEGA+", "+STR_OMEGA+"+1, "+STR_OMEGA+"+2 in red)
";
                          result_text_only += "  There is a potential cleavage site at "+(prot.sequence.length()-ancre.position[index_max_pourcent])+" (w, w+1, w+2)\n";
                        }

                        // calcul du nombre d'ancres GPI selon swiss-prot
                        if ((position_w_sp!=0) && (keyword_GPI==true)) {
                          nbr_ancres_sp++;
                        }

                result += "

";
                result_text_only += "";
//font face=courier size=-1
          result += "
Sequence annotated by DGPI
";
          String str_sequence = "";
          for (int i=0; i<prot.sequence.length(); i++) {
            if (i+1==si2.pos_site_clivage) str_sequence += "";
            str_sequence += prot.sequence.charAt(i);
            if ((i+1) % 100 == 0) str_sequence +="\n";//"

";
            if ((i+1)==prot.sequence.length()-(new Float(longueur_hydrophobe).intValue())) str_sequence += "";
            if (index_max!=-1) {
              if ((i+1)==(prot.sequence.length()-ancre.position[index_max_pourcent]-1)) str_sequence += "";
              if ((i+1)==(prot.sequence.length()-ancre.position[index_max_pourcent]-1+3)) str_sequence += "";
            }
          }
          str_sequence += "";
          result += str_sequence;

          result += "

";

/*
                int NBR_VARSPLIC = 5;
                int NBR_FRAGMENT = 3;
                if (nbr_ancres_sp==0) {
                  System.out.println(nbr_gpi_anchor_ok+" ancres trouvees sur 0 (- %)");
                } else {
                  System.out.println(nbr_gpi_anchor_ok+" ancres trouvees sur "+nbr_ancres_sp+" ("+nbr_gpi_anchor_ok*100/nbr_ancres_sp+"%)");
                }
                System.out.println(nbr_proteine_signal+" proteines trouvees sur "+(nbr_Sequences-NBR_VARSPLIC-NBR_FRAGMENT)+" ("+nbr_proteine_signal*100/(nbr_Sequences-NBR_VARSPLIC-NBR_FRAGMENT)+"%) avec signal");
                System.out.println(nbr_proteines_gpi_ok+" proteines trouvees sur "+(nbr_Sequences-NBR_VARSPLIC-NBR_FRAGMENT)+" ("+nbr_proteines_gpi_ok*100/(nbr_Sequences-NBR_VARSPLIC-NBR_FRAGMENT)+"%) avec signal+phobe");
                System.out.println(nbr_proteines_gpi_ok_phobe_phile+" proteines trouvees sur "+(nbr_Sequences-NBR_VARSPLIC-NBR_FRAGMENT)+" ("+nbr_proteines_gpi_ok_phobe_phile*100/(nbr_Sequences-NBR_VARSPLIC-NBR_FRAGMENT)+"%) avec signal+phobe+phile");*/
          dgpi_result = result;
          dgpi_result_text_only = result_text_only;
 	  dgpi_result_gff = result_gff;//add gff output for multifasta on Dec 7th 2016 by Eduardo Alves

	}//end traite

/*  public static void main(String[] argv) {
    if (argv.length==0) {
      System.out.println("Erreur : il faut donner l'access number ou la s‰quence de la prot‰ine");
    } else {
      DGPI prot = new DGPI(argv[0]);
    }//end if
  }//end main
*/

  public static void main(String[] argv) {
    new DGPI(argv);
  }//end main
}//end


text:
package treeton.prosody.lomonosov;

import org.apache.log4j.Logger;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import treeton.core.*;
import treeton.core.model.TreetonModelException;
import treeton.core.model.TrnType;
import treeton.core.model.TrnTypeStorage;
import treeton.core.scape.ParseException;
import treeton.core.scape.trnmapper.TrnMapperRule;
import treeton.core.scape.trnmapper.TrnMapperRuleStorage;

import java.io.IOException;
import java.util.*;

public class MarkupHandler extends DefaultHandler {
    private TrnMapperRuleStorage trnMapperRuleStorage;

    private Logger logger = Logger.getLogger(MarkupHandler.class);
    private StringBuffer text = new StringBuffer();
    private TreenotationStorage tStorage;
    private BlackBoard localBoard = TreetonFactory.newBlackBoard(100,false);
    private List<Map<String,String>> glossList = new ArrayList<Map<String, String>>();

    private TrnType atomicType;
    private TrnType sentenceType;
    private TrnType tokenType;
    private TrnType glossType;
    private int kindFeature;
    private TString punctuationValue = TreetonFactory.newTString("punctuation");

    private Token beforeLastWordStart;
    private Token beforeLastSentenceStart;

    public MarkupHandler(TreenotationStorage tStorage, String mapperPath) {
        this.tStorage = tStorage;
        TrnTypeStorage types = tStorage.getTypes();
        try {
            atomicType = types.get("Atom");
            tokenType = types.get("Token");
            kindFeature = tokenType.getFeatureIndex("kind");
            sentenceType = types.get("Sentence");
            glossType = types.get("gloss");
        } catch (TreetonModelException e) {
            logger.error(e);
        }

        if (mapperPath != null) {
            trnMapperRuleStorage = new TrnMapperRuleStorage(types,types);
            try {
                trnMapperRuleStorage.readInFromFile(mapperPath);
            } catch (ParseException e) {
                trnMapperRuleStorage = null;
                logger.error("Unable to read in mapping rules. Working without mapping rules.",e);
            } catch (IOException e) {
                logger.error("Unable to read in mapping rules. Working without mapping rules.",e);
                logger.error("Unable to read in mapping rules. Working without mapping rules.",e);
            }
        }
    }

    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        super.startElement(uri, localName, qName, attributes);

        try {
            if (qName.equals("se")) {
                beforeLastSentenceStart = tStorage.lastToken();
            } else if (qName.equals("c") || qName.equals("w")) {
                beforeLastWordStart = tStorage.lastToken();
            } else if (qName.equals("gloss")) {
                String lem = attributes.getValue("lem");
                String lex = attributes.getValue("lex");
                String gram = attributes.getValue("gram");
                String flex = attributes.getValue("flex");

                List<Map<String,String>> lexVariants = new ArrayList<Map<String, String>>();
                parseAttrs(lex,lexVariants);
                Set<Map<String,String>> variants;
                if (gram != null) {
                    List<Map<String,String>> gramVariants = new ArrayList<Map<String, String>>();
                    parseAttrs(gram,gramVariants);

                    variants = multiply(lexVariants,gramVariants);
                } else {
                    variants = new HashSet<Map<String, String>>(lexVariants);
                }

                for (Map<String, String> variant : variants) {
                    variant.put("lem",lem);
                    variant.put("flex",flex);
                }

                glossList.addAll(variants);
            }
        } catch (Exception e) {
            logger.warn("Error when trying to process " + qName, e);
        }

    }

    private Set<Map<String, String>> multiply(List<Map<String, String>> vars1, List<Map<String, String>> vars2) {
        Set<Map<String,String>> result = new HashSet<Map<String, String>>();

        for (Map<String, String> map1 : vars1) {
            for (Map<String, String> map2 : vars2) {
                Map<String,String> nmap = new HashMap<String, String>(map1);
                nmap.putAll(map2);
                result.add(nmap);
            }
        }

        return result;
    }

    public void endElement(String uri, String localName, String qName) throws SAXException {
        super.endElement(uri, localName, qName);
        try {
            if (qName.equals("se")) {
                Token s = beforeLastSentenceStart == null ? tStorage.firstToken() : beforeLastSentenceStart.getNextToken();
                Token e = tStorage.lastToken();
                tStorage.add(TreetonFactory.newTreenotation(s,e,sentenceType));
            } else if (qName.equals("br")||qName.equals("br ")) {
                text.append(" ");
                tStorage.addToken(1,1,atomicType,localBoard," ");
            } else if (qName.equals("c")) {
                Token s = beforeLastWordStart == null ? tStorage.firstToken() : beforeLastWordStart.getNextToken();
                while (s != null) {
                    if (s.getText().trim().length()>0)
                        break;
                    s = s.getNextToken();
                }

                if (s!=null) {
                    Token e = tStorage.lastToken();
                    while (e != null) {
                        if (e.getText().trim().length()>0)
                            break;
                        e = e.getPreviousToken();
                    }

                    if (e != null) {
                        localBoard.put(kindFeature,punctuationValue);
                        tStorage.add(TreetonFactory.newTreenotation(s,e,tokenType,localBoard));
                    }
                }
            } else if (qName.equals("w")) {
                Token s = beforeLastWordStart == null ? tStorage.firstToken() : beforeLastWordStart.getNextToken();
                Token e = tStorage.lastToken();
                for (Map<String,String> map : glossList) {
                    for (Map.Entry<String,String> entry : map.entrySet()) {
                        String key = entry.getKey().replace('-','_');
                        int feature = glossType.getFeatureIndex(key);
                        if (feature < 0) {
                            throw new MarkupHandlerException("Undefined feature "+key+"(type "+glossType.getName()+")");
                        }
                        localBoard.put(feature,glossType,entry.getValue());
                    }
                    Treenotation trn = TreetonFactory.newTreenotation(s, e, glossType, localBoard);

                    if (trnMapperRuleStorage != null) {
                        TrnMapperRule mapperRule = trnMapperRuleStorage.getRule(trn);
                        if (mapperRule != null) {
                            mapperRule.bind(trn);
                            mapperRule.assign(localBoard);
                            trn.removeAll();
                            if (!mapperRule.getType().equals(trn.getType())) {
                                tStorage.changeType(trn,mapperRule.getType());
                            }
                            trn.put(localBoard);
                        }
                    }

                    tStorage.add(trn);
                }

                glossList.clear();
            } else if (qName.equals("gloss")) {
            }
        } catch (Exception e) {
            logger.warn("Error when trying to process " + qName, e);
        } finally {
            localBoard.clean();
        }
    }

    public void characters(char ch[], int start, int length) throws SAXException {
        String s = new String(ch, start, length);
        text.append(s);
        int i=0;
        while (i<s.length() && s.charAt(i)==' ') i++;

        if (i>0) {
            tStorage.addToken(i,1,atomicType,localBoard,s.substring(0,i));
            s = s.substring(i);
        }

        if (s.length()>0) {
            i=s.length()-1;
            while (i>=0 && s.charAt(i)==' ') i--;

            tStorage.addToken(i+1,1,atomicType,localBoard,s.substring(0,i+1));
            if (i < s.length() - 1) {
                s = s.substring(i+1);
                tStorage.addToken(s.length(),1,atomicType,localBoard,s);
            }
        }

    }

    private void parseAttrs(String s, List<Map<String,String>> variants) {
        StringTokenizer tok = new StringTokenizer(s,"¦");
        while (tok.hasMoreTokens()) {
            String variant = tok.nextToken();
            StringTokenizer tok1 = new StringTokenizer(variant,",");
            List<Map<String,String>> attrs = new ArrayList<Map<String, String>>();
            while (tok1.hasMoreTokens()) {
                String pair = tok1.nextToken().trim();
                int idx = pair.indexOf(":");
                if (idx>=0) {
                    String key = pair.substring(0,idx).trim();
                    String value = pair.substring(idx+1).trim();

                    List<String> values = new ArrayList<String>();

                    StringTokenizer tok2 = new StringTokenizer(value,"/");
                    while (tok2.hasMoreTokens()) {
                        values.add(tok2.nextToken().trim());
                    }

                    if (attrs.size()==0) {
                        attrs.add(new HashMap<String, String>());
                    }

                    String first = values.get(0);

                    for (Map<String, String> attr : attrs) {
                        attr.put(key,first);
                    }

                    int sz = attrs.size();

                    for (int i=1;i<values.size();i++) {
                        for (int j=0;j<sz;j++) {
                            Map<String, String> nmap = new HashMap<String, String>(attrs.get(j));
                            nmap.put(key,values.get(i));
                            attrs.add(nmap);
                        }
                    }
                } else {
                    logger.warn("Found unary attr: "+pair);
                }
            }
            variants.addAll(attrs);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.eigenbase.test;

import java.util.*;
import java.util.regex.*;

import junit.framework.*;

import org.eigenbase.runtime.*;

public abstract class EigenbaseTestCase
    extends TestCase
{
    //~ Static fields/initializers ---------------------------------------------

    protected static final String nl = System.getProperty("line.separator");
    protected static final String [] emptyStringArray = new String[0];

    //~ Constructors -----------------------------------------------------------

    protected EigenbaseTestCase(String s)
        throws Exception
    {
        super(s);
    }

    //~ Methods ----------------------------------------------------------------

    protected static void assertEqualsDeep(
        Object o,
        Object o2)
    {
        if ((o instanceof Object []) && (o2 instanceof Object [])) {
            Object [] a = (Object []) o;
            Object [] a2 = (Object []) o2;
            assertEquals(a.length, a2.length);
            for (int i = 0; i < a.length; i++) {
                assertEqualsDeep(a[i], a2[i]);
            }
            return;
        }
        if ((o != null)
            && (o2 != null)
            && o.getClass().isArray()
            && (o.getClass() == o2.getClass()))
        {
            boolean eq;
            if (o instanceof boolean []) {
                eq = Arrays.equals((boolean []) o, (boolean []) o2);
            } else if (o instanceof byte []) {
                eq = Arrays.equals((byte []) o, (byte []) o2);
            } else if (o instanceof char []) {
                eq = Arrays.equals((char []) o, (char []) o2);
            } else if (o instanceof short []) {
                eq = Arrays.equals((short []) o, (short []) o2);
            } else if (o instanceof int []) {
                eq = Arrays.equals((int []) o, (int []) o2);
            } else if (o instanceof long []) {
                eq = Arrays.equals((long []) o, (long []) o2);
            } else if (o instanceof float []) {
                eq = Arrays.equals((float []) o, (float []) o2);
            } else if (o instanceof double []) {
                eq = Arrays.equals((double []) o, (double []) o2);
            } else {
                eq = false;
            }
            if (!eq) {
                fail("arrays not equal");
            }
        } else {
            // will handle the case 'o instanceof int[]' ok, because
            // shallow comparison is ok for ints
            assertEquals(o, o2);
        }
    }

    /**
     * Fails if throwable is null, or if its message does not
     * contain the string pattern.
     */
    protected void assertThrowableContains(
        Throwable throwable,
        String pattern)
    {
        if (throwable == null) {
            fail(
                "expected exception containing pattern <" + pattern
                + "> but got none");
        }
        String message = throwable.getMessage();
        if ((message == null) || (message.indexOf(pattern) < 0)) {
            fail(
                "expected pattern <" + pattern + "> in exception <"
                + throwable + ">");
        }
    }

    /**
     * Returns an iterator over the elements of an array.
     */
    public static Iterator makeIterator(Object [] a)
    {
        return Arrays.asList(a).iterator();
    }

    /**
     * Returns a TupleIter over the elements of an array.
     */
    public static TupleIter makeTupleIter(final Object [] a)
    {
        return new AbstractTupleIter() {
            private List data = Arrays.asList(a);
            private Iterator iter = data.iterator();

            public Object fetchNext()
            {
                if (iter.hasNext()) {
                    return iter.next();
                }

                return NoDataReason.END_OF_DATA;
            }

            public void restart()
            {
                iter = data.iterator();
            }

            public void closeAllocation()
            {
                iter = null;
                data = null;
            }
        };
    }

    /**
     * Converts an iterator to a list.
     */
    protected static List toList(Iterator iterator)
    {
        ArrayList list = new ArrayList();
        while (iterator.hasNext()) {
            list.add(iterator.next());
        }
        return list;
    }

    /**
     * Converts a TupleIter to a list.
     */
    protected static List toList(TupleIter tupleIter)
    {
        ArrayList list = new ArrayList();
        while (true) {
            Object o = tupleIter.fetchNext();
            if (o == TupleIter.NoDataReason.END_OF_DATA) {
                return list;
            } else if (o == TupleIter.NoDataReason.UNDERFLOW) {
                // Busy loops.
                continue;
            }

            list.add(o);
        }
    }

    /**
     * Converts an enumeration to a list.
     */
    protected static List toList(Enumeration enumeration)
    {
        ArrayList list = new ArrayList();
        while (enumeration.hasMoreElements()) {
            list.add(enumeration.nextElement());
        }
        return list;
    }

    /**
     * Checks that an iterator returns the same objects as the contents of an
     * array.
     */
    protected void assertEquals(
        Iterator iterator,
        Object [] a)
    {
        ArrayList list = new ArrayList();
        while (iterator.hasNext()) {
            list.add(iterator.next());
        }
        assertEquals(list, a);
    }

    /**
     * Checks that a TupleIter returns the same objects as the contents of an
     * array.
     */
    protected void assertEquals(
        TupleIter iterator,
        Object [] a)
    {
        ArrayList list = new ArrayList();
        while (true) {
            Object next = iterator.fetchNext();
            if (next == TupleIter.NoDataReason.END_OF_DATA) {
                break;
            }
            list.add(next);
        }
        assertEquals(list, a);
    }

    /**
     * Checks that a list has the same contents as an array.
     */
    protected void assertEquals(
        List list,
        Object [] a)
    {
        Object [] b = list.toArray();
        assertEquals(a, b);
    }

    /**
     * Checks that two arrays are equal.
     */
    protected void assertEquals(
        Object [] expected,
        Object [] actual)
    {
        assertTrue(expected.length == actual.length);
        for (int i = 0; i < expected.length; i++) {
            assertEquals(expected[i], actual[i]);
        }
    }

    protected void assertEquals(
        Object [] expected,
        Object actual)
    {
        if (actual instanceof Object []) {
            assertEquals(expected, (Object []) actual);
        } else {
            // They're different. Let assertEquals(Object,Object) give the
            // error.
            assertEquals((Object) expected, actual);
        }
    }

    /**
     * Copies all of the tests in a suite whose names match a given pattern.
     */
    public static TestSuite copySuite(
        TestSuite suite,
        Pattern testPattern)
    {
        TestSuite newSuite = new TestSuite();
        Enumeration tests = suite.tests();
        while (tests.hasMoreElements()) {
            Test test = (Test) tests.nextElement();
            if (test instanceof TestCase) {
                TestCase testCase = (TestCase) test;
                final String testName = testCase.getName();
                if (testPattern.matcher(testName).matches()) {
                    newSuite.addTest(test);
                }
            } else if (test instanceof TestSuite) {
                TestSuite subSuite = copySuite((TestSuite) test, testPattern);
                if (subSuite.countTestCases() > 0) {
                    newSuite.addTest(subSuite);
                }
            } else {
                // some other kind of test
                newSuite.addTest(test);
            }
        }
        return newSuite;
    }
}

// End EigenbaseTestCase.java


text:
This guide explains how to install TensorFlow on Ubuntu Linux. While these
instructions may work on other Linux variants, they are tested and supported
with the following system requirements:

*   64-bit desktops or laptops
*   Ubuntu 16.04 or higher

## Choose which TensorFlow to install

The following TensorFlow variants are available for installation:

*   __TensorFlow with CPU support only__. If your system does not have a
    NVIDIA® GPU, you must install this version. This version of TensorFlow
    is usually easier to install, so even if you have an NVIDIA GPU, we
    recommend installing this version first.
*   __TensorFlow with GPU support__. TensorFlow programs usually run much faster
    on a GPU instead of a CPU. If you run performance-critical applications and
    your system has an NVIDIA® GPU that meets the prerequisites, you should
    install this version. See [TensorFlow GPU support](#NVIDIARequirements) for
    details.

## How to install TensorFlow

There are a few options to install TensorFlow on your machine:

*   [Use pip in a virtual environment](#InstallingVirtualenv) *(recommended)*
*   [Use pip in your system environment](#InstallingNativePip)
*   [Configure a Docker container](#InstallingDocker)
*   [Use pip in Anaconda](#InstallingAnaconda)
*   [Install TensorFlow from source](/install/install_sources)

### Use `pip` in a virtual environment

Key Point: Using a virtual environment is the recommended install method.

The [Virtualenv](https://virtualenv.pypa.io/en/stable/) tool creates virtual
Python environments that are isolated from other Python development on the same
machine. In this scenario, you install TensorFlow and its dependencies within a
virtual environment that is available when *activated*. Virtualenv provides a
reliable way to install and run TensorFlow while avoiding conflicts with the
rest of the system.

##### 1. Install Python, `pip`, and `virtualenv`.

On Ubuntu, Python is automatically installed and `pip` is *usually* installed.
Confirm the `python` and `pip` versions:

  python -V  # or: python3 -V
  pip -V     # or: pip3 -V

To install these packages on Ubuntu:

  sudo apt-get install python-pip python-dev python-virtualenv   # for Python 2.7
  sudo apt-get install python3-pip python3-dev python-virtualenv # for Python 3.n

We *recommend* using `pip` version 8.1 or higher. If using a release before
version 8.1, upgrade `pip`:

  pip install --upgrade pip

If not using Ubuntu and [setuptools](https://pypi.org/project/setuptools/) is
installed, use `easy_install` to install `pip`:

  easy_install -U pip

##### 2. Create a directory for the virtual environment and choose a Python interpreter.

  mkdir ~/tensorflow  # somewhere to work out of
  cd ~/tensorflow
  # Choose one of the following Python environments for the ./venv directory:
  virtualenv --system-site-packages <var>venv</var>            # Use python default (Python 2.7)
  virtualenv --system-site-packages -p python3 <var>venv</var> # Use Python 3.n

##### 3. Activate the Virtualenv environment.

Use one of these shell-specific commands to activate the virtual environment:

  source ~/tensorflow/<var>venv</var>/bin/activate      # bash, sh, ksh, or zsh
  source ~/tensorflow/<var>venv</var>/bin/activate.csh  # csh or tcsh
  . ~/tensorflow/<var>venv</var>/bin/activate.fish      # fish

When the Virtualenv is activated, the shell prompt displays as `(venv) $`.

##### 4. Upgrade `pip` in the virtual environment.

Within the active virtual environment, upgrade `pip`:

(venv)$ pip install --upgrade pip

You can install other Python packages within the virtual environment without
affecting packages outside the `virtualenv`.

##### 5. Install TensorFlow in the virtual environment.

Choose one of the available TensorFlow packages for installation:

*   `tensorflow` —Current release for CPU
*   `tensorflow-gpu` —Current release with GPU support
*   `tf-nightly` —Nightly build for CPU
*   `tf-nightly-gpu` —Nightly build with GPU support

Within an active Virtualenv environment, use `pip` to install the package:

  pip install --upgrade tensorflow

Use `pip list` to show the packages installed in the virtual environment.
[Validate the install](#ValidateYourInstallation) and test the version:

(venv)$ python -c "import tensorflow as tf; print(tf.__version__)"

Success: TensorFlow is now installed.

Use the `deactivate` command to stop the Python virtual environment.

#### Problems

If the above steps failed, try installing the TensorFlow binary using the remote
URL of the `pip` package:

(venv)$ pip install --upgrade <var>remote-pkg-URL</var>   # Python 2.7
(venv)$ pip3 install --upgrade <var>remote-pkg-URL</var>  # Python 3.n

The <var>remote-pkg-URL</var> depends on the operating system, Python version,
and GPU support. See [here](#the_url_of_the_tensorflow_python_package) for the
URL naming scheme and location.

See [Common Installation Problems](#common_installation_problems) if you
encounter problems.

#### Uninstall TensorFlow

To uninstall TensorFlow, remove the Virtualenv directory you created in step 2:

  deactivate  # stop the virtualenv
  rm -r ~/tensorflow/<var>venv</var>

### Use `pip` in your system environment

Use `pip` to install the TensorFlow package directly on your system without
using a container or virtual environment for isolation. This method is
recommended for system administrators that want a TensorFlow installation that
is available to everyone on a multi-user system.

Since a system install is not isolated, it could interfere with other
Python-based installations. But if you understand `pip` and your Python
environment, a system `pip` install is straightforward.

See the
[REQUIRED_PACKAGES section of setup.py](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/tools/pip_package/setup.py)
for a list of packages that TensorFlow installs.

##### 1. Install Python, `pip`, and `virtualenv`.

On Ubuntu, Python is automatically installed and `pip` is *usually* installed.
Confirm the `python` and `pip` versions:

  python -V  # or: python3 -V
  pip -V     # or: pip3 -V

To install these packages on Ubuntu:

  sudo apt-get install python-pip python-dev   # for Python 2.7
  sudo apt-get install python3-pip python3-dev # for Python 3.n

We *recommend* using `pip` version 8.1 or higher. If using a release before
version 8.1, upgrade `pip`:

  pip install --upgrade pip

If not using Ubuntu and [setuptools](https://pypi.org/project/setuptools/) is
installed, use `easy_install` to install `pip`:

  easy_install -U pip

##### 2. Install TensorFlow on system.

Choose one of the available TensorFlow packages for installation:

*   `tensorflow` —Current release for CPU
*   `tensorflow-gpu` —Current release with GPU support
*   `tf-nightly` —Nightly build for CPU
*   `tf-nightly-gpu` —Nightly build with GPU support

And use `pip` to install the package for Python 2 or 3:

  pip install --upgrade --user tensorflow   # Python 2.7
  pip3 install --upgrade --user tensorflow  # Python 3.n

Use `pip list` to show the packages installed on the system.
[Validate the install](#ValidateYourInstallation) and test the version:

  python -c "import tensorflow as tf; print(tf.__version__)"

Success: TensorFlow is now installed.

#### Problems

If the above steps failed, try installing the TensorFlow binary using the remote
URL of the `pip` package:

  pip install --user --upgrade <var>remote-pkg-URL</var>   # Python 2.7
  pip3 install --user --upgrade <var>remote-pkg-URL</var>  # Python 3.n

The <var>remote-pkg-URL</var> depends on the operating system, Python version,
and GPU support. See [here](#the_url_of_the_tensorflow_python_package) for the
URL naming scheme and location.

See [Common Installation Problems](#common_installation_problems) if you
encounter problems.

#### Uninstall TensorFlow

To uninstall TensorFlow on your system, use one of following commands:

  pip uninstall tensorflow   # for Python 2.7
  pip3 uninstall tensorflow  # for Python 3.n

### Configure a Docker container

Docker completely isolates the TensorFlow installation from pre-existing
packages on your machine. The Docker container contains TensorFlow and all its
dependencies. Note that the Docker image can be quite large (hundreds of MBs).
You might choose the Docker installation if you are incorporating TensorFlow
into a larger application architecture that already uses Docker.

Take the following steps to install TensorFlow through Docker:

1.  Install Docker on your machine as described in the
    [Docker documentation](http://docs.docker.com/engine/installation/).
2.  Optionally, create a Linux group called docker to allow
    launching containers without sudo as described in the
    [Docker documentation](https://docs.docker.com/engine/installation/linux/linux-postinstall/).
    (If you don't do this step, you'll have to use sudo each time you invoke
    Docker.)
3.  To install a version of TensorFlow that supports GPUs, you must first
    install [nvidia-docker](https://github.com/NVIDIA/nvidia-docker), which is
    stored in github.
4.  Launch a Docker container that contains one of the
    [TensorFlow binary images](https://hub.docker.com/r/tensorflow/tensorflow/tags/).

The remainder of this section explains how to launch a Docker container.

#### CPU-only

To launch a Docker container with CPU-only support (that is, without GPU
support), enter a command of the following format:

$ docker run -it -p hostPort:containerPort TensorFlowCPUImage

where:

*   <tt>-p hostPort:containerPort</tt> is optional. If you plan to run
    TensorFlow programs from the shell, omit this option. If you plan to run
    TensorFlow programs as Jupyter notebooks, set both <tt>hostPort</tt>
    and <tt>containerPort</tt> to <tt>8888</tt>. If you'd like to run
    TensorBoard inside the container, add a second `-p` flag, setting both
    hostPort and containerPort to 6006.
*   <tt>TensorFlowCPUImage</tt> is required. It identifies the Docker
    container. Specify one of the following values:

    *   <tt>tensorflow/tensorflow</tt>, which is the TensorFlow CPU binary
        image.
    *   <tt>tensorflow/tensorflow:latest-devel</tt>, which is the latest
        TensorFlow CPU Binary image plus source code.
    *   <tt>tensorflow/tensorflow:version</tt>, which is the specified
        version (for example, 1.1.0rc1) of TensorFlow CPU binary image.
    *   <tt>tensorflow/tensorflow:version-devel</tt>, which is the
        specified version (for example, 1.1.0rc1) of the TensorFlow GPU binary
        image plus source code.

    TensorFlow images are available at
    [dockerhub](https://hub.docker.com/r/tensorflow/tensorflow/).

For example, the following command launches the latest TensorFlow CPU binary
image in a Docker container from which you can run TensorFlow programs in a
shell:

$ docker run -it tensorflow/tensorflow bash

The following command also launches the latest TensorFlow CPU binary image in a
Docker container. However, in this Docker container, you can run TensorFlow
programs in a Jupyter notebook:

$ docker run -it -p 8888:8888 tensorflow/tensorflow

Docker will download the TensorFlow binary image the first time you launch it.

#### GPU support

To launch a Docker container with NVidia GPU support, enter a command of the
following format (this
[does not require any local CUDA installation](https://github.com/nvidia/nvidia-docker/wiki/CUDA#requirements)):

$ nvidia-docker run -it -p hostPort:containerPort TensorFlowGPUImage

where:

*   <tt>-p hostPort:containerPort</tt> is optional. If you plan to run
    TensorFlow programs from the shell, omit this option. If you plan to run
    TensorFlow programs as Jupyter notebooks, set both <tt>hostPort</tt>
    and containerPort to `8888`.
*   TensorFlowGPUImage specifies the Docker container. You must specify
    one of the following values:
    *   <tt>tensorflow/tensorflow:latest-gpu</tt>, which is the latest
        TensorFlow GPU binary image.
    *   <tt>tensorflow/tensorflow:latest-devel-gpu</tt>, which is the latest
        TensorFlow GPU Binary image plus source code.
    *   <tt>tensorflow/tensorflow:version-gpu</tt>, which is the
        specified version (for example, 0.12.1) of the TensorFlow GPU binary
        image.
    *   <tt>tensorflow/tensorflow:version-devel-gpu</tt>, which is the
        specified version (for example, 0.12.1) of the TensorFlow GPU binary
        image plus source code.

We recommend installing one of the `latest` versions. For example, the following
command launches the latest TensorFlow GPU binary image in a Docker container
from which you can run TensorFlow programs in a shell:

$ nvidia-docker run -it tensorflow/tensorflow:latest-gpu bash

The following command also launches the latest TensorFlow GPU binary image in a
Docker container. In this Docker container, you can run TensorFlow programs in a
Jupyter notebook:

$ nvidia-docker run -it -p 8888:8888 tensorflow/tensorflow:latest-gpu

The following command installs an older TensorFlow version (0.12.1):

$ nvidia-docker run -it -p 8888:8888 tensorflow/tensorflow:0.12.1-gpu

Docker will download the TensorFlow binary image the first time you launch it.
For more details see the
[TensorFlow docker readme](https://github.com/tensorflow/tensorflow/tree/master/tensorflow/tools/docker).

#### Next Steps

You should now [validate your installation](#ValidateYourInstallation).

### Use `pip` in Anaconda

Anaconda provides the `conda` utility to create a virtual environment. However,
within Anaconda, we recommend installing TensorFlow using the `pip install`
command and *not* with the `conda install` command.

Caution: `conda` is a community supported package this is not officially
maintained by the TensorFlow team. Use this package at your own risk since it is
not tested on new TensorFlow releases.

Take the following steps to install TensorFlow in an Anaconda environment:

1.  Follow the instructions on the
    [Anaconda download site](https://www.continuum.io/downloads) to download and
    install Anaconda.

2.  Create a conda environment named <tt>tensorflow</tt> to run a version of
    Python by invoking the following command:

$ conda create -n tensorflow pip python=2.7 # or python=3.3, etc.

3.  Activate the conda environment by issuing the following command:

$ source activate tensorflow
     (tensorflow)$  # Your prompt should change

4.  Issue a command of the following format to install TensorFlow inside your
    conda environment:

(tensorflow)$ pip install --ignore-installed --upgrade tfBinaryURL

    where tfBinaryURL is the
    [URL of the TensorFlow Python package](#the_url_of_the_tensorflow_python_package).
    For example, the following command installs the CPU-only version of
    TensorFlow for Python 3.4:

     (tensorflow)$ pip install --ignore-installed --upgrade \
     https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-1.10.0-cp34-cp34m-linux_x86_64.whl

## Validate your installation

To validate your TensorFlow installation, do the following:

1.  Ensure that your environment is prepared to run TensorFlow programs.
2.  Run a short TensorFlow program.

### Prepare your environment

If you installed on native pip, Virtualenv, or Anaconda, then do the following:

1.  Start a terminal.
2.  If you installed with Virtualenv or Anaconda, activate your container.
3.  If you installed TensorFlow source code, navigate to any directory *except*
    one containing TensorFlow source code.

If you installed through Docker, start a Docker container from which you can run
bash. For example:

$ docker run -it tensorflow/tensorflow bash

### Run a short TensorFlow program

Invoke python from your shell as follows:

$ python

Enter the following short program inside the python interactive shell:

```python
# Python
import tensorflow as tf
hello = tf.constant('Hello, TensorFlow!')
sess = tf.Session()
print(sess.run(hello))
```

If the system outputs the following, then you are ready to begin writing
TensorFlow programs:

Hello, TensorFlow!

If the system outputs an error message instead of a greeting, see
[Common installation problems](#common_installation_problems).

To learn more, see the [TensorFlow tutorials](../tutorials/).

## TensorFlow GPU support

Note: Due to the number of libraries required, using [Docker](#InstallingDocker)
is recommended over installing directly on the host system.

The following NVIDIA® hardware must be installed on your system:

*   GPU card with CUDA Compute Capability 3.5 or higher. See
    [NVIDIA documentation](https://developer.nvidia.com/cuda-gpus) for a list of
    supported GPU cards.

The following NVIDIA® software must be installed on your system:

*   [GPU drivers](http://nvidia.com/driver). CUDA 9.0 requires 384.x or higher.
*   [CUDA Toolkit 9.0](http://nvidia.com/cuda).
*   [cuDNN SDK](http://developer.nvidia.com/cudnn) (>= 7.0). Version 7.1 is
    recommended.
*   [CUPTI](http://docs.nvidia.com/cuda/cupti/) ships with the CUDA Toolkit, but
    you also need to append its path to the `LD_LIBRARY_PATH` environment
    variable: `export
    LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/cuda/extras/CUPTI/lib64`
*   *OPTIONAL*: [NCCL 2.2](https://developer.nvidia.com/nccl) to use TensorFlow
    with multiple GPUs.
*   *OPTIONAL*:
    [TensorRT](http://docs.nvidia.com/deeplearning/sdk/tensorrt-install-guide/index.html)
    which can improve latency and throughput for inference for some models.

To use a GPU with CUDA Compute Capability 3.0, or different versions of the
preceding NVIDIA libraries see
@{$install_sources$installing TensorFlow from Sources}. If using Ubuntu 16.04
and possibly other Debian based linux distros, `apt-get` can be used with the
NVIDIA repository to simplify installation.

```bash
# Adds NVIDIA package repository.
sudo apt-key adv --fetch-keys http://developer.download.nvidia.com/compute/cuda/repos/ubuntu1604/x86_64/7fa2af80.pub
wget http://developer.download.nvidia.com/compute/cuda/repos/ubuntu1604/x86_64/cuda-repo-ubuntu1604_9.1.85-1_amd64.deb
wget http://developer.download.nvidia.com/compute/machine-learning/repos/ubuntu1604/x86_64/nvidia-machine-learning-repo-ubuntu1604_1.0.0-1_amd64.deb
sudo dpkg -i cuda-repo-ubuntu1604_9.1.85-1_amd64.deb
sudo dpkg -i nvidia-machine-learning-repo-ubuntu1604_1.0.0-1_amd64.deb
sudo apt-get update
# Includes optional NCCL 2.x.
sudo apt-get install cuda9.0 cuda-cublas-9-0 cuda-cufft-9-0 cuda-curand-9-0 \
  cuda-cusolver-9-0 cuda-cusparse-9-0 libcudnn7=7.1.4.18-1+cuda9.0 \
   libnccl2=2.2.13-1+cuda9.0 cuda-command-line-tools-9-0
# Optionally install TensorRT runtime, must be done after above cuda install.
sudo apt-get update
sudo apt-get install libnvinfer4=4.1.2-1+cuda9.0
```

## Common installation problems

We are relying on Stack Overflow to document TensorFlow installation problems
and their remedies. The following table contains links to Stack Overflow answers
for some common installation problems. If you encounter an error message or
other installation problem not listed in the following table, search for it on
Stack Overflow. If Stack Overflow doesn't show the error message, ask a new
question about it on Stack Overflow and specify the `tensorflow` tag.

 Link to GitHub or Stack Overflow	 Error Message

  36159194

ImportError: libcudart.so.Version: cannot open shared object file:
  No such file or directory

  41991101

ImportError: libcudnn.Version: cannot open shared object file:
  No such file or directory

  36371137 and
  here

libprotobuf ERROR google/protobuf/src/google/protobuf/io/coded_stream.cc:207] A
  protocol message was rejected because it was too big (more than 67108864 bytes).
  To increase the limit (or to disable these warnings), see
  CodedInputStream::SetTotalBytesLimit() in google/protobuf/io/coded_stream.h.

  35252888

Error importing tensorflow. Unless you are using bazel, you should
  not try to import tensorflow from its source directory; please exit the
  tensorflow source tree, and relaunch your python interpreter from
  there.

  33623453

IOError: [Errno 2] No such file or directory:
  '/tmp/pip-o6Tpui-build/setup.py'</tt>

  42006320

ImportError: Traceback (most recent call last):
  File ".../tensorflow/core/framework/graph_pb2.py", line 6, in <module>
  from google.protobuf import descriptor as _descriptor
  ImportError: cannot import name 'descriptor'

  35190574

SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify
  failed

  42009190

  Installing collected packages: setuptools, protobuf, wheel, numpy, tensorflow
  Found existing installation: setuptools 1.1.6
  Uninstalling setuptools-1.1.6:
  Exception:
  ...
  [Errno 1] Operation not permitted:
  '/tmp/pip-a1DXRT-uninstall/.../lib/python/_markerlib'

  36933958

  ...
  Installing collected packages: setuptools, protobuf, wheel, numpy, tensorflow
  Found existing installation: setuptools 1.1.6
  Uninstalling setuptools-1.1.6:
  Exception:
  ...
  [Errno 1] Operation not permitted:
  '/tmp/pip-a1DXRT-uninstall/System/Library/Frameworks/Python.framework/
   Versions/2.7/Extras/lib/python/_markerlib'

## The URL of the TensorFlow Python package

A few installation mechanisms require the URL of the TensorFlow Python package.
The value you specify depends on three factors:

*   operating system
*   Python version
*   CPU only vs. GPU support

This section documents the relevant values for Linux installations.

### Python 2.7

CPU only:

https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-1.10.0-cp27-none-linux_x86_64.whl

GPU support:

https://storage.googleapis.com/tensorflow/linux/gpu/tensorflow_gpu-1.10.0-cp27-none-linux_x86_64.whl

Note that GPU support requires the NVIDIA hardware and software described in
[NVIDIA requirements to run TensorFlow with GPU support](#NVIDIARequirements).

### Python 3.4

CPU only:

https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-1.10.0-cp34-cp34m-linux_x86_64.whl

GPU support:

https://storage.googleapis.com/tensorflow/linux/gpu/tensorflow_gpu-1.10.0-cp34-cp34m-linux_x86_64.whl

Note that GPU support requires the NVIDIA hardware and software described in
[NVIDIA requirements to run TensorFlow with GPU support](#NVIDIARequirements).

### Python 3.5

CPU only:

https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-1.10.0-cp35-cp35m-linux_x86_64.whl

GPU support:

https://storage.googleapis.com/tensorflow/linux/gpu/tensorflow_gpu-1.10.0-cp35-cp35m-linux_x86_64.whl

Note that GPU support requires the NVIDIA hardware and software described in
[NVIDIA requirements to run TensorFlow with GPU support](#NVIDIARequirements).

### Python 3.6

CPU only:

https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-1.10.0-cp36-cp36m-linux_x86_64.whl

GPU support:

https://storage.googleapis.com/tensorflow/linux/gpu/tensorflow_gpu-1.10.0-cp36-cp36m-linux_x86_64.whl

Note that GPU support requires the NVIDIA hardware and software described in
[NVIDIA requirements to run TensorFlow with GPU support](#NVIDIARequirements).


text:
 /*
  *   LOCATION:    see http://www.boost.org for most recent version.
  *   FILE         test_regex_replace.hpp
  *   VERSION      see <boost/version.hpp>
  *   DESCRIPTION: Declares tests for regex search and replace.
  */

#ifndef BOOST_REGEX_REGRESS_REGEX_REPLACE_HPP
#define BOOST_REGEX_REGRESS_REGEX_REPLACE_HPP
#include "info.hpp"

template<class charT, class traits>
void test_regex_replace(boost::basic_regex<charT, traits>& r)
{
   typedef std::basic_string<charT> string_type;
   const string_type& search_text = test_info<charT>::search_text();
   boost::regex_constants::match_flag_type opts = test_info<charT>::match_options();
   const string_type& format_string = test_info<charT>::format_string();
   const string_type& result_string = test_info<charT>::result_string();

   string_type result = boost::regex_replace(search_text, r, format_string, opts);
   if(result != result_string)
   {
      BOOST_REGEX_TEST_ERROR("regex_replace generated an incorrect string result", charT);
   }
}

struct test_regex_replace_tag{};

template<class charT, class traits>
void test(boost::basic_regex<charT, traits>& r, const test_regex_replace_tag&)
{
   const std::basic_string<charT>& expression = test_info<charT>::expression();
   boost::regex_constants::syntax_option_type syntax_options = test_info<charT>::syntax_options();
   try{
      r.assign(expression, syntax_options);
      if(r.status())
      {
         BOOST_REGEX_TEST_ERROR("Expression did not compile when it should have done, error code = " << r.status(), charT);
      }
      test_regex_replace(r);
   }
   catch(const boost::bad_expression& e)
   {
      BOOST_REGEX_TEST_ERROR("Expression did not compile when it should have done: " << e.what(), charT);
   }
   catch(const std::runtime_error& e)
   {
      BOOST_REGEX_TEST_ERROR("Received an unexpected std::runtime_error: " << e.what(), charT);
   }
   catch(const std::exception& e)
   {
      BOOST_REGEX_TEST_ERROR("Received an unexpected std::exception: " << e.what(), charT);
   }
   catch(...)
   {
      BOOST_REGEX_TEST_ERROR("Received an unexpected exception of unknown type", charT);
   }

}

#endif


text:
/**
 * DO NOT EDIT
 *
 * This file was automatically generated by
 *   https://github.com/Polymer/gen-typescript-declarations
 *
 * To modify these typings, edit the source file(s):
 *   iron-button-state.html
 */

/// <reference path="../polymer/types/polymer.d.ts" />
/// <reference path="../iron-a11y-keys-behavior/iron-a11y-keys-behavior.d.ts" />
/// <reference path="iron-control-state.d.ts" />

declare namespace Polymer {

  interface IronButtonState extends Polymer.IronA11yKeysBehavior {
    keyBindings: object;

    /**
     * If true, the user is currently holding down the button.
     */
    readonly pressed: boolean|null|undefined;

    /**
     * If true, the button toggles the active state with each tap or press
     * of the spacebar.
     */
    toggles: boolean|null|undefined;

    /**
     * If true, the button is a toggle and is currently in the active state.
     */
    active: boolean|null|undefined;

    /**
     * True if the element is currently being pressed by a "pointer," which
     * is loosely defined as mouse or touch input (but specifically excluding
     * keyboard input).
     */
    readonly pointerDown: boolean|null|undefined;

    /**
     * True if the input device that caused the element to receive focus
     * was a keyboard.
     */
    readonly receivedFocusFromKeyboard: boolean|null|undefined;

    /**
     * The aria attribute to be set if the button is a toggle and in the
     * active state.
     */
    ariaActiveAttribute: string|null|undefined;
    _mouseEventRe: RegExp|null;
    _tapHandler(): void;
    _focusChanged(focused: any): void;
    _detectKeyboardFocus(focused: any): void;

    /**
     * 'change' events
     */
    _userActivate(active: any): void;
    _downHandler(event: any): void;
    _upHandler(): void;

    /**
     * @param event .
     */
    _spaceKeyDownHandler(event: KeyboardEvent): void;

    /**
     * @param event .
     */
    _spaceKeyUpHandler(event: KeyboardEvent): void;

    /**
     * event handler to unwind before triggering another event
     */
    _asyncClick(): void;
    _pressedChanged(pressed: any): void;
    _ariaActiveAttributeChanged(value: any, oldValue: any): void;
    _activeChanged(active: any, ariaActiveAttribute: any): void;
    _controlStateChanged(): void;
    _changedButtonState(): void;
  }

  const IronButtonState: object;
}


text:
namespace Account
{
    using System;
    using System.Web.Security;
    using System.Web.UI;
    using BlogEngine.Core;
    using Resources;

    /// <summary>
    /// The account change password.
    /// </summary>
    public partial class ChangePassword : System.Web.UI.Page
    {
        #region Methods

        /// <summary>
        /// Handles the Click event of the ChangePasswordPushButton control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void ChangePasswordPushButton_Click(object sender, EventArgs e)
        {
            Master.SetStatus("warning", Resources.labels.passwordNotChanged);
        }

        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            hdnPassLength.Value = Membership.MinRequiredPasswordLength.ToString();
            ChangeUserPassword.SuccessPageUrl = Utils.RelativeWebRoot + "Account/change-password-success.aspx";
        }

        #endregion
    }
}


text:
import uuid, os
from django.db import models
from django.utils import timezone
from django.core.urlresolvers import reverse
from django.utils.text import slugify
from django.contrib.auth import models as authModels

# Create your models here.
from django.db import models

def get_file_path(instance, filename):
    ext = filename.split('.')[-1]
    filename = "%s.%s" % (uuid.uuid4(), ext)
    return os.path.join('books/img', filename)

def getProfilePath(instance, filename):
    ext = filename.split('.')[-1]
    filename = "%s.%s" % (uuid.uuid4(), ext)
    return os.path.join('profiles/img', filename)

def get_slug(instance, *argv):
    slug = ''
    for arg in argv:
        slug += slugify(arg)
    return slug

class Publisher(models.Model):
    name = models.CharField(max_length=30)
    address = models.CharField(max_length=50)
    city = models.CharField(max_length=60)
    state_province = models.CharField(max_length=30)
    country = models.CharField(max_length=50)
    website = models.URLField()
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.name

class Author(models.Model):
    first_name = models.CharField(max_length=30, db_index=True)
    middle_name = models.CharField(max_length=40, blank=True, null=True)
    last_name = models.CharField(max_length=40, db_index=True)
    slug = models.SlugField(max_length=200, db_index=True)
    email = models.EmailField()
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)

    def __str__(self):
        return u'%s %s'%(self.first_name, self.last_name)

    class Meta:
        ordering = ('first_name', 'last_name')
        index_together = (('id', 'slug'),)

class Book(models.Model):
    title = models.CharField(max_length=200, db_index=True)
    slug = models.SlugField(max_length=200, db_index=True)
    authors = models.ManyToManyField(Author)
    publisher = models.ForeignKey(Publisher)
    publication_date = models.DateField()
    image = models.ImageField(upload_to=get_file_path, blank=True, null=True)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    description = models.TextField(blank=True)
    price = models.DecimalField(max_digits=10, decimal_places=2)
    discount_percent = models.DecimalField(max_digits=5, decimal_places=2)
    stock = models.PositiveIntegerField(default=0)
    available = models.BooleanField(default=True)

    class Meta:
        ordering = ('title',)
        index_together = (('id', 'slug'),)

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('book_detail', args=[self.id, self.slug])

class Subscription(models.Model):
    email = models.EmailField()
    created = models.DateTimeField(auto_now_add=True)
    subscribed = models.BooleanField(default=True)

    def __str__(self):
        return self.email

#Extending User model
class Profile(models.Model):
    user = models.OneToOneField(authModels.User)
    dob = models.DateField(blank=True, null=True)
    photo = models.ImageField(upload_to=getProfilePath, blank=True)

    def __str__(self):
        return 'Profile: {}'.format(self.user.username)


text:
package org.simpleflatmapper.util;

public class PredicatedEnumerable<T> implements Enumerable<T> {

    private final Enumerable<? extends T> delegate;
    private final Predicate<? super T> predicate;

    public PredicatedEnumerable(Enumerable<? extends T> delegate, Predicate<? super T> predicate) {
        if (delegate instanceof PredicatedEnumerable) {
            PredicatedEnumerable<T> pe = (PredicatedEnumerable<T>) delegate;
            this.delegate = pe.delegate;
            this.predicate = new AndPredicate<T>(pe.predicate, predicate);
        } else {
            this.delegate = delegate;
            this.predicate = predicate;
        }
    }

    @Override
    public boolean next() {
        while (delegate.next()) {
            if (predicate.test(delegate.currentValue())) {
                return true;
            }
        }
        return false;
    }

    @Override
    public T currentValue() {
        return delegate.currentValue();
    }
}


text:
<?php

/***
Description: File to generate unique nonce
Author: Sneha Inguva
Date: 7-30-2014
**/

require_once('../../config.php');
require_once('../../db/mysqldb.php');

$client_id = "";
$request_method = $_SERVER['REQUEST_METHOD'];

/*Receive GET request*/
/*Iterate through the relevant http request headers and obtain client id*/
$headers = getallheaders();
if ($headers){
	foreach($headers as $header => $value){
		if ($header =='Client-Id'){
			$client_id = $value;
		}
	}
}

/*Ensure that the client id is correct and a get method is being called*/
if ($client_id == "13adfewasdf432dae" && $request_method == "GET"){

	/*Create database connection*/
	$con = new mysqldb($db_settings,false);

	/*Generate uuid which is nonce*/
	$nonce_exists = true;

	/*Generate uuid which is nonce*/
	$uid = $con->query('Select uuid()')->fetch();
	$nonce = $uid['uuid()'];
	$nonce_hash = md5($nonce); //hash nonce value using md5 to store in db
	$expiry_date = date('Y-m-d H:i:s', strtotime('+1 day')); //nonce value expires 24 hours after creation

	/*Set up statement,bind values, and insert into db*/
	$stmt = 'Insert Into nonce_values (nonce_value,expiry_time) Values (:nonce,:expiry_time)';
	$parameters = array(':nonce' => PDO::PARAM_STR,':expiry_time' => PDO::PARAM_STR);
	$values = array(':nonce' => $nonce_hash,':expiry_time' => $expiry_date);

	$result = $con->insert($stmt,$values,$parameters,false,'Nonce');

	/*Set response header and return nonce*/
	if ($result){ //if nonce successfully added to the db

		http_response_code(200);
		echo json_encode(array('nonce' => $nonce));

	}else{ //if nonce not successfully added to the db

		http_response_code(500);

	}

}else{ //send back authentication failure or incorrect request error

	http_response_code(400);

}

?>


text:
* Needs to start/load quickly
* Needs to support fast reloading of code, after changes
* Cannot change or impact existing CMR dev-system at all


text:
package com.jaxio.celerio.configuration.entity;

import com.jaxio.celerio.configuration.MetaAttribute;
import lombok.Getter;
import lombok.Setter;

import java.util.List;

import static com.google.common.collect.Lists.newArrayList;
import static org.apache.commons.lang.StringUtils.isNotBlank;
import static org.springframework.util.StringUtils.hasLength;

@Setter
public class ManyToOneConfig implements CascadeGetter, CacheConfigGetter, FetchTypeGetter, AssociationActionGetter, LabelGetter, TargetEntityNameGetter {
    private String var;
    private FetchType fetch;
    private String targetEntityName;
    private List<Label> labels;
    private List<Cascade> cascades;
    private CacheConfig cacheConfig;
    private AssociationAction associationAction;
    private List<MetaAttribute> metaAttributes;

    /*
     * The variable name for association. It should be singular, for example: 'parent'.
     */
    public String getVar() {
        return var;
    }

    public boolean hasVar() {
        return hasLength(getVar());
    }

    /*
     * The JPA fetch type for this association. Use NONE if you do not want any fetchType to be set.
     */
    public FetchType getFetch() {
        return fetch;
    }

    /*
     * If the target entity is part of a SINGLE_TABLE inheritance hierarchy, you must set name of the target entity as Celerio cannot guess it.
     */
    public String getTargetEntityName() {
        return targetEntityName;
    }

    public boolean hasTargetEntityName() {
        return isNotBlank(targetEntityName);
    }

    /*
     * The labels for this association.
     */
    public List<Label> getLabels() {
        return labels;
    }

    /*
     * The list of JPA cascade types for the this association.
     */
    public List<Cascade> getCascades() {
        return cascades;
    }

    /*
     * Convenient for hbm2celerio to avoid dead tags.
     */
    public void forceCascadesToNullIfEmpty() {
        if (cascades != null && cascades.isEmpty()) {
            cascades = null;
        }
    }

    /*
     * The 2d level cache configuration for this association.
     */
    public CacheConfig getCacheConfig() {
        return cacheConfig;
    }

    /*
     * Configure which actions should or should not be generated for this association in the front end layer.
     */
    public AssociationAction getAssociationAction() {
        return associationAction;
    }

    /**
     * Meta attributes are free form key value pairs.
     */
    public List<MetaAttribute> getMetaAttributes() {
        return metaAttributes;
    }

    public boolean hasMetaAttributes() {
        return metaAttributes != null && !metaAttributes.isEmpty();
    }
}


text:
<?php declare(strict_types=1);
/**
 * XArray
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
namespace modethirteen\XArray\Tests\XArrayBase;

use modethirteen\XArray\ArrayInterface;
use modethirteen\XArray\SchemaBuilder;
use modethirteen\XArray\Tests\UnitTestCaseBase;

abstract class XArrayUnitTestCaseBase extends UnitTestCaseBase  {

    /**
     * @var string
     */
    protected static string $class;

    /**
     * @param array $array
     * @param SchemaBuilder|null $schemaBuilder - default schema builder will be inferred from source array
     * @return ArrayInterface
     */
    final protected static function newArray(array $array, SchemaBuilder $schemaBuilder = null) : ArrayInterface {
        return self::newArrayFromClass(static::$class, $array, $schemaBuilder);
    }
}