Esempio n. 1
0
 public static String syntax(Element element) {
   StringBuffer stringBuffer = new StringBuffer();
   int tab = 4, indent = 0;
   while (element != null) {
     String token = element.getToken();
     String description = token + ' ' + element.description() + '\n';
     int splitIdx = description.indexOf('\n');
     int spaces = indent * tab;
     while (splitIdx >= 0) {
       for (int idx = 0; idx < spaces; idx++) {
         stringBuffer.append(' ');
       }
       stringBuffer.append(description.substring(0, splitIdx));
       stringBuffer.append('\n');
       spaces = indent * tab + token.length() + 1;
       description = description.substring(splitIdx + 1);
       splitIdx = description.indexOf('\n');
     }
     if (element.getChild() != null) {
       indent = indent + 1;
       element = element.getChild();
     } else if (element.getSibling() != null) {
       element = element.getSibling();
     } else {
       while (element != null && element.getSibling() == null) {
         indent = indent - 1;
         element = element.getParent();
       }
       if (element != null) {
         element = element.getSibling();
       }
     }
   }
   return stringBuffer.toString();
 }
Esempio n. 2
0
 /**
  * Process Message from server
  *
  * @param doc
  */
 private void _message(Document doc) {
   Element root = doc.getRootElement();
   Element message = root.getChild("message");
   String sender = message.getChild("sender").getText();
   String mesg = message.getChild("mesg").getText();
   sendMessage(NORMAL, sender + ": " + mesg);
 }
Esempio n. 3
0
 /**
  * Process kick from server
  *
  * @param doc
  */
 private void _kick(Document doc) {
   Element root = doc.getRootElement();
   Element kick = root.getChild("kick");
   String user = kick.getChild("user").getText();
   String answer = kick.getChild("answer").getText();
   if (answer.equals("OK") == true) sendMessage(SERVER, user + " was kicked from " + _group);
 }
Esempio n. 4
0
	public boolean read(String strRoute, String strElement, int flag) {
		//SAXBuilder builder=new SAXBuilder();
		strText = null;
		try {
			String[] route = new String[4];

			String str = null;
			Document doc = builder.build(xmlFileName);
			Element root = doc.getRootElement();
			Element element = root;

			//创建一个拆分字符串内容的对象,每次返回一项
			StringTokenizer st = new StringTokenizer(strRoute, ":");
			str = st.nextToken();

			while (st.hasMoreTokens()) {
				str = st.nextToken();
				element = element.getChild(str);
			}

			//mypage.FcfeMain.wR(mypage.FcfeMain.SIM_APP_ERP,str);
			element = (Element) element.getParent();
			/*
			 * while(flag!=1) { if(element.removeChild(str))
			 * mypage.FcfeMain.wR(mypage.FcfeMain.SIM_APP_ERP,"deleted "+str);
			 * else mypage.FcfeMain.wR(mypage.FcfeMain.SIM_APP_ERP,"not
			 * deleted");
			 * 
			 * flag--; }
			 */
			//	mypage.FcfeMain.wR(mypage.FcfeMain.SIM_APP_ERP,element.getName());
			strText = element.getChild(str).getChild(strElement).getText();

		} catch (JDOMException jdome) {
			mypage.FcfeMain.wR(mypage.FcfeMain.SIM_APP_ERP, xmlFileName
					+ " is not well-formed");

		} catch (IOException ioe) {
			mypage.FcfeMain.wR(mypage.FcfeMain.SIM_APP_ERP, ioe);

		} catch (NullPointerException nullpe) {
			mypage.FcfeMain.wR(mypage.FcfeMain.SIM_APP_ERP, "not founded"
					+ "\n" + nullpe);

		} catch (Exception e) {
			mypage.FcfeMain.wR(mypage.FcfeMain.SIM_APP_ERP, "read no succeed"
					+ "\n" + e);

		}

		if (strText == null) {
			mypage.FcfeMain.wR(mypage.FcfeMain.SIM_APP_ERP, "not founded");
			return false;
		} else {
			//	mypage.FcfeMain.wR(mypage.FcfeMain.SIM_APP_ERP,"strText="+strText);
			return true;
		}

	}
Esempio n. 5
0
 private static boolean comparerTripletObjet(Element triplet1, Element triplet2) {
   Element o1 = triplet1.getChild("o");
   Element o2 = triplet2.getChild("o");
   if (!comparerObjet(o1, o2)) {
     return false;
   }
   return true;
 }
Esempio n. 6
0
 private static boolean comparerTripletSujet(Element triplet1, Element triplet2) {
   String s1 = triplet1.getChild("s").getChildText("uri");
   String s2 = triplet2.getChild("s").getChildText("uri");
   if (!s1.equals(s2)) {
     return false;
   }
   return true;
 }
  /**
   * 1) Performs re-ranking using a linear function, which takes into account only three features:
   * newRank = 1 * oldRank + 10 * underconstrained_query + 10 * incosistent_tense; <br>
   * 2) Takes the hypothesis which is smallest in (new) rank as the best one. <br>
   * 3) Computes the semantic error rate (SER) as follows: -- a recognition is considered as
   * semantically correct if the dialogue move representation it produces is both a) non-null and b)
   * the same as the one that would have been produced from a perfect recognition result. -- if
   * dialogue move is not the same: then counts the number of deletions/insertions required in order
   * to obtain the perfect dialogue move.
   *
   * @deprecated Use instead the linear re-ranking with more than 3 feat and SER manually defined
   *     (available in xml file)
   * @param xmlFileName - input xml file containing both the n-best hypothesis and the reference
   *     transcription.
   * @return
   * @throws Exception
   */
  public float[] getER4LinearReranking3Feat(String xmlFileName) throws Exception {
    // read the xml file in order to get the utterance transcripts
    try {
      Document d =
          new org.jdom.input.SAXBuilder().build(new File(xmlFileName)); // PARSE THE XML FILE
      java.util.List nbestList = d.getRootElement().getChildren("nbest_data");
      float[] serArray = new float[nbestList.size()];
      int noUtt = 0;
      int minNewRankID = 1;

      for (int i = 0; i < nbestList.size(); i++) {
        Element nbestElem = (Element) nbestList.get(i);
        noUtt++;

        // In order to COMPUTE SEMANTIC ERROR RATE (ser),
        // get the dialogue_move feature value for the correct transcription
        // dialogue_move
        Element dmElem = nbestElem.getChild("dialogue_move");
        String refDM = "";
        if (dmElem != null) if (!dmElem.getValue().equalsIgnoreCase("")) refDM = dmElem.getValue();

        // In the xml tree: find hyp_transcription,
        // i.e. the transcription corresponding to the 1-rank predicted hypothesis
        java.util.List recList = nbestElem.getChildren("recognition");

        // PERFORM LINEAR RE-RANKING
        int minNewRank = 100;
        for (int j = 1; j < recList.size(); j++) {
          Element recElem = (Element) recList.get(j);
          int rank = new Integer(recElem.getChild("rank").getValue()).intValue();
          int uq = new Integer(recElem.getChild("underconstrained_query").getValue()).intValue();
          int it = new Integer(recElem.getChild("inconsistent_tense").getValue()).intValue();

          int newRank = rank + 10 * uq + 10 * it;
          if (newRank < minNewRank) {
            minNewRank = newRank;
            minNewRankID = j;
          }
        }

        Element recElem = (Element) recList.get(minNewRankID);
        Element dm4recElem = recElem.getChild("dialogue_move");
        String dm4rec = "";
        if (dm4recElem != null)
          if (!dm4recElem.getValue().equalsIgnoreCase("")) dm4rec = dm4recElem.getValue();

        WordErrorRate wer = new WordErrorRate(refDM, dm4rec, this.wordDeliminator);
        serArray[i] = wer.computeNumerator();
      }

      return serArray;
    } catch (IOException eIO) {
      eIO.printStackTrace();
    } catch (JDOMException eJDOM) {
      eJDOM.printStackTrace();
    }
    return null;
  }
  private QueryResult gatherResultInfoForSelectQuery(
      String queryString, int queryNr, boolean sorted, Document doc, String[] rows) {
    Element root = doc.getRootElement();

    // Get head information
    Element child =
        root.getChild("head", Namespace.getNamespace("http://www.w3.org/2005/sparql-results#"));

    // Get result rows (<head>)
    List headChildren =
        child.getChildren(
            "variable", Namespace.getNamespace("http://www.w3.org/2005/sparql-results#"));

    Iterator it = headChildren.iterator();
    ArrayList<String> headList = new ArrayList<String>();
    while (it.hasNext()) {
      headList.add(((Element) it.next()).getAttributeValue("name"));
    }

    List resultChildren =
        root.getChild("results", Namespace.getNamespace("http://www.w3.org/2005/sparql-results#"))
            .getChildren(
                "result", Namespace.getNamespace("http://www.w3.org/2005/sparql-results#"));
    int nrResults = resultChildren.size();

    QueryResult queryResult = new QueryResult(queryNr, queryString, nrResults, sorted, headList);

    it = resultChildren.iterator();
    while (it.hasNext()) {
      Element resultElement = (Element) it.next();
      String result = "";

      // get the row values and paste it together to one String
      for (int i = 0; i < rows.length; i++) {
        List bindings =
            resultElement.getChildren(
                "binding", Namespace.getNamespace("http://www.w3.org/2005/sparql-results#"));
        String rowName = rows[i];
        for (int j = 0; j < bindings.size(); j++) {
          Element binding = (Element) bindings.get(j);
          if (binding.getAttributeValue("name").equals(rowName))
            if (result.equals(""))
              result +=
                  rowName + ": " + ((Element) binding.getChildren().get(0)).getTextNormalize();
            else
              result +=
                  "\n"
                      + rowName
                      + ": "
                      + ((Element) binding.getChildren().get(0)).getTextNormalize();
        }
      }

      queryResult.addResult(result);
    }
    return queryResult;
  }
Esempio n. 9
0
 /**
  * Process Partgroup from server
  *
  * @param doc
  */
 private void _partgroup(Document doc) {
   Element root = doc.getRootElement();
   Element part = root.getChild("partgroup");
   String group = part.getChild("group").getText();
   String answer = part.getChild("answer").getText();
   if (group.equals(_group) == true) {
     sendMessage(SERVER, group + ": " + answer);
   }
 }
Esempio n. 10
0
 /**
  * Process Groupmessage from server
  *
  * @param doc
  */
 private void _groupmessage(Document doc) {
   Element root = doc.getRootElement();
   Element message = root.getChild("groupmessage");
   String group = message.getChild("group").getText();
   String sender = message.getChild("sender").getText();
   String mesg = message.getChild("mesg").getText();
   if (group.equals(_group) == true) {
     sendMessage(NORMAL, group + "(" + sender + "): " + mesg);
   }
 }
Esempio n. 11
0
 /**
  * Process Joingroup from server
  *
  * @param doc
  */
 private void _joingroup(Document doc) {
   Element root = doc.getRootElement();
   Element join = root.getChild("joingroup");
   String group = join.getChild("group").getText();
   String answer = join.getChild("answer").getText();
   sendMessage(SERVER, "JoinGroup: " + answer);
   if (answer.equals("OK") == true) {
     sendMessage(SERVER, "Group " + group + " joined.");
     _group = group;
   }
 }
Esempio n. 12
0
 /**
  * Process Creategroup from server
  *
  * @param doc
  */
 private void _creategroup(Document doc) {
   Element root = doc.getRootElement();
   Element create = root.getChild("creategroup");
   String group = create.getChild("group").getText();
   String answer = create.getChild("answer").getText();
   sendMessage(SERVER, "Group creation is: " + answer);
   if (answer.equals("OK") == true) {
     sendMessage(SERVER, "Group " + group + " joined.");
     _group = group;
   }
 }
Esempio n. 13
0
  public void addVariables(Element inRoot) throws org.jdom2.DataConversionException {
    Element vs = inRoot.getChild("decoder").getChild("variables");

    Element segment = new Element("segment");
    segment.setAttribute("space", "253");
    root.addContent(segment);

    Iterator it = vs.getDescendants();
    while (it.hasNext()) {
      Object o = it.next();
      if (o instanceof Element) {
        Element e = (Element) o;
        if (e.getName().equals("variable")) {
          // get common attributes
          String comment = e.getAttributeValue("comment");
          for (Object oc : e.getChildren("comment")) {
            Element ec = (Element) oc;
            if (ec.getAttributeValue("lang", "xml").equals("")) comment = ec.getText();
          }
          String name = e.getAttributeValue("label");
          if (name.equals("")) name = e.getAttributeValue("item");
          for (Object on : e.getChildren("label")) {
            Element en = (Element) on;
            if (en.getAttributeValue("lang", "xml").equals("")) name = en.getText();
          }

          long cv = e.getAttribute("CV").getIntValue();

          // find subtype and process
          Element type;
          type = e.getChild("decVal");
          if (type != null) {
            segment.addContent(handleDecVal(type, cv, name, comment, e.getAttributeValue("mask")));
            continue;
          }
          type = e.getChild("enumVal");
          if (type != null) {
            segment.addContent(handleEnumVal(type, cv, name, comment, e.getAttributeValue("mask")));
            continue;
          }
          type = e.getChild("shortAddressVal");
          if (type != null) {
            segment.addContent(handleShortAddressVal(type, cv, name, comment));
            continue;
          }
          type = e.getChild("longAddressVal");
          if (type != null) {
            segment.addContent(handleLongAddressVal(type, cv, name, comment));
            continue;
          }
        }
      }
    }
  }
  public DataColumn(Element xml) {
    // These two things are required.
    // index = Integer.valueOf(xml.getAttributeValue("index"));
    type = xml.getChild(COLUMN_TYPE_TAG).getText().trim();

    if (type.trim().equals(DATA_COLUMN_TYPE)) {
      templateValue = new ValueObject(xml.getChild(ValueObject.METADATA_TAG));
    } else {
      templateValue = new ValueObject();
    }
  }
Esempio n. 15
0
  /**
   * Método public static void leerArchivoXML(ListaUsuarios listaDeUsuarios): Este método permite
   * leer un archivo XML que contiene los datos de los usuarios a través de jdom
   */
  public static void leerArchivoXML(ListaUsuario listaDeUsuarios) {
    try {
      SAXBuilder builder = new SAXBuilder();

      /* Se crea un documento nuevo con el nombre del archivo */
      Document doc = builder.build(nombreArchivo);

      /* Se obtiene la raíz del archivo (la etiqueta inicial) */
      Element raiz = doc.getRootElement();

      /* Se puede obtener el atributo de la raíz (de la etiqueta) */
      System.out.println(raiz.getAttributeValue("tipo"));

      /* Se obtienen todos los hijos cuya etiqueta esa "usuario"  */
      /* y se asignan esos hijos a un List                        */
      List listaUsuarios = raiz.getChildren("usuario");

      System.out.println("Formada por:" + listaUsuarios.size() + " usuarios");
      System.out.println("------------------");

      /* Se genera un iterador para recorrer el List que se generó */
      Iterator i = listaUsuarios.iterator();

      /* Se recorre el List */
      while (i.hasNext()) {
        /* Se obtiene cada uno y se asigna a un objeto de tipo Element */
        Element e = (Element) i.next();

        /* Se obtiene el nombre, apellido y cargo de cada una de las etiquetas  */
        /* hijas de usuario, es decir, nombre, apellido y cargo                 */
        Element nick = e.getChild("nick");
        Element clave = e.getChild("clave");
        Element nombre = e.getChild("nombre");
        Element apellido = e.getChild("apellido");
        Element fechanac = e.getChild("fechanac");
        Element avatar = e.getChild("avatar");

        /* Se crea un nodo nuevo con la información y se agrega a la lista de usuarios */
        Usuario elUsuario =
            new Usuario(
                nick.getText(),
                clave.getText(),
                nombre.getText(),
                apellido.getText(),
                fechanac.getText(),
                avatar.getText());

        listaDeUsuarios.AgregarElemento(elUsuario);
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Esempio n. 16
0
  public void readDOMElement(Element element) {
    String label = element.getAttribute("name").getValue();
    m_name = label;
    Attribute idelement = element.getAttribute("id");
    if (idelement != null) {
      setId(idelement.getValue());
    }
    Element datasetselements = (Element) element.getChild(IDataSets.class.getName());
    readDOMDataElement(datasetselements, getDataSets());

    Element exportselements = (Element) element.getChild(IExportItem.class.getName());
    if (exportselements != null) {}
  }
Esempio n. 17
0
  /**
   * Process listgroup from server
   *
   * @param doc
   */
  private void _listgroup(Document doc) {
    StringBuffer grouplist = new StringBuffer();

    Element root = doc.getRootElement();
    Element list = root.getChild("listgroup");
    List groups = list.getChildren("group");
    Iterator i = groups.iterator();
    while (i.hasNext()) {
      Element temp = (Element) i.next();
      grouplist.append(temp.getChild("name").getText());
      grouplist.append("\t");
      grouplist.append(temp.getChild("description").getText());
      grouplist.append("\n");
    }
    sendMessage(SERVER, "Groups: \n" + grouplist);
  }
Esempio n. 18
0
  // Empieza La Carga de la Partida
  public static void leerArchivoXML(ListaPartida listaDePartidas) {
    try {
      SAXBuilder builder = new SAXBuilder();

      /* Se crea un documento nuevo con el nombre del archivo */
      Document doc = builder.build(nombreArchivoPartida);

      /* Se obtiene la raíz del archivo (la etiqueta inicial) */
      Element raiz = doc.getRootElement();

      /* Se puede obtener el atributo de la raíz (de la etiqueta) */
      System.out.println(raiz.getAttributeValue("tipo"));

      /* Se obtienen todos los hijos cuya etiqueta esa "usuario"  */
      /* y se asignan esos hijos a un List                        */
      List listaPartida = raiz.getChildren("partida");

      System.out.println("Formada por:" + listaPartida.size() + " Partidas");
      System.out.println("------------------");

      /* Se genera un iterador para recorrer el List que se generó */
      Iterator i = listaPartida.iterator();

      /* Se recorre el List */
      while (i.hasNext()) {
        /* Se obtiene cada uno y se asigna a un objeto de tipo Element */
        Element e = (Element) i.next();

        /* Se obtiene el nombre, apellido y cargo de cada una de las etiquetas  */
        /* hijas de usuario, es decir, nombre, apellido y cargo                 */
        Element nick = e.getChild("Usuario");
        Element ID = e.getChild("ID");
        Element fechaactual = e.getChild("fechaacual");
        Element fechainicio = e.getChild("fechainicio");
        /* Se crea un nodo nuevo con la información y se agrega a la lista de usuarios */
        Partida laPartida =
            new Partida(
                nick.getText(), ID.getContentSize(), fechaactual.getText(), fechainicio.getText());
        listaDePartidas.AgregarElemento(laPartida);
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Esempio n. 19
0
 private static void checkCRC(Element element) throws CRCMismatchException {
   Element CRCElement = element.getChild(CRC_ELEMENT);
   if (CRCElement != null) {
     String crc = CRCElement.getText();
     // the length in bytes is the number of characters divided by 2
     int crcLength = crc.length() / 2;
     if (!crc.equals(element.getHash(crcLength, CRC_ELEMENT))) {
       throw new CRCMismatchException();
     }
   }
 }
Esempio n. 20
0
  private static boolean comparerObjet(Element triplet1, Element triplet2) {
    Element uri1 = triplet1.getChild("uri");
    Element uri2 = triplet2.getChild("uri");
    Element literal1 = triplet1.getChild("literal");
    Element literal2 = triplet1.getChild("literal");
    if ((uri1 == null && uri2 != null) || (uri2 == null && uri1 != null)) {
      return false;
    } else if (uri1 != null && uri2 != null) {
      String uri1text = uri1.getText();
      String uri2text = uri2.getText();
      if (!(uri1text.equals(uri2text))) {
        return false;
      }
    } else if (literal1 != null && literal2 != null) {
      String lang1 = literal1.getAttributeValue("lang", Namespace.XML_NAMESPACE);
      String lang2 = literal2.getAttributeValue("lang", Namespace.XML_NAMESPACE);
      String datatype1 = literal1.getAttributeValue("datatype");
      String datatype2 = literal2.getAttributeValue("datatype");
      String literal1Text = literal1.getText();
      String literal2Text = literal2.getText();

      if (lang1 != null && lang2 != null) {

        if (!lang1.equals(lang2)) {
          return false;
        } else if (!literal1Text.equals(literal2Text)) {

          return false;
        }
      } else if (datatype1 != null && datatype2 != null) {
        if (!datatype1.equals(datatype2)) {
          return false;
        } else if (!literal1Text.equals(literal2Text)) {
          return false;
        }
      }
    }
    return true;
  }
Esempio n. 21
0
  /**
   * Process listuser from server
   *
   * @param doc
   */
  private void _listuser(Document doc) {
    StringBuffer userlist = new StringBuffer();

    Element root = doc.getRootElement();
    Element list = root.getChild("listuser");
    List users = list.getChildren("user");
    Iterator i = users.iterator();
    while (i.hasNext()) {
      userlist.append(((Element) i.next()).getText());
      userlist.append("\n");
    }
    sendMessage(SERVER, "Users: \n" + userlist);
  }
Esempio n. 22
0
 /**
  * See if the dropdown already has a group of that name, else create it
  *
  * @param select the select element
  * @param name the name of the group
  * @return the optgroup or null
  */
 HTMLOptGroup getGroup(Element select, String name) {
   for (int i = 0; i < select.numChildren(); i++) {
     try {
       Element e = select.getChild(i);
       if (e instanceof HTMLOptGroup) {
         String label = e.getAttribute(HTMLNames.LABEL);
         if (label != null && label.equals(name)) return (HTMLOptGroup) e;
       }
     } catch (AeseException he) {
       System.out.println(he.getMessage());
     }
   }
   return null;
 }
Esempio n. 23
0
  public void addHeader(Element inRoot) {
    Element id = new Element("identification");

    String mfg = inRoot.getChild("decoder").getChild("family").getAttributeValue("mfg");
    id.addContent(new Element("manufacturer").addContent(mfg));

    String name = inRoot.getChild("decoder").getChild("family").getAttributeValue("name");
    id.addContent(new Element("model").addContent(name));
    id.addContent(new Element("hardwareVersion"));
    id.addContent(new Element("softwareVersion"));

    // add models in map, if any
    Element map = new Element("map");
    for (Object o : inRoot.getChild("decoder").getChild("family").getChildren("model")) {
      Element e = (Element) o;
      Element relation = new Element("relation");
      relation.addContent(new Element("property").addContent("Model"));
      relation.addContent(new Element("value").addContent(e.getAttributeValue("model")));
      map.addContent(relation);
    }
    id.addContent(map);

    root.addContent(id);
  }
Esempio n. 24
0
  public static void saveCourseCreerToXml(Evenement event) {
    Element elementEvent = JDomOperations.getElementActuel_();
    Element listCourses = elementEvent.getChild("listcourses");

    Iterator itListCoursesInEvent = event.getIteratorCollectionEssaiCourse_();
    while (itListCoursesInEvent.hasNext()) {
      EssaiOrCourse course = (EssaiOrCourse) itListCoursesInEvent.next();
      Element elementCourse = new Element("course");
      elementCourse.setAttribute(new Attribute("nomEssaiOrCourse", course.getNomEssaiOrCourse_()));
      elementCourse.setAttribute(
          new Attribute("typeEssaiOrCourse", course.getTypeEssaiOrCourse_().toString()));

      listCourses.addContent(elementCourse);
    }

    JDomOperations.enregistre(elementEvent.getDocument(), xmlDefaultPath);
  }
Esempio n. 25
0
  /**
   * Compute the best semantic error rate that can be achieved starting from n-best hypothesis.
   *
   * @param xmlFileName
   * @return a list of error rates corresponding to each utterance
   * @throws Exception
   */
  public float[] getBestERCanBeAchieved(String xmlFileName) throws Exception {
    // read the xml file in order to get the utterance transcripts
    try {
      Document d =
          new org.jdom.input.SAXBuilder().build(new File(xmlFileName)); // PARSE THE XML FILE
      java.util.List nbestList = d.getRootElement().getChildren("nbest_data");
      float[] serArray = new float[nbestList.size()];
      int noUtt = 0;
      for (int i = 0; i < nbestList.size(); i++) {
        Element nbestElem = (Element) nbestList.get(i);
        noUtt++;

        // In order to COMPUTE SEMANTIC ERROR RATE (SER)

        java.util.List recList = nbestElem.getChildren("recognition");

        float bestSER = 10000;
        // (start with k=1 since we skip first value in recList which corresponds to the correct
        // transcription)
        for (int k = 1; k < recList.size(); k++) {
          Element recElem = (Element) recList.get(k);

          Element semCorrectElem = recElem.getChild("semantically_correct");
          String semCorrect = semCorrectElem.getValue();
          int ser;
          if (semCorrect.equalsIgnoreCase("good")) ser = 0;
          else ser = 1;

          if (bestSER > ser) {
            bestSER = ser;
          }
        } // end for k
        serArray[i] = bestSER;
      }
      return serArray;
    } catch (IOException eIO) {
      eIO.printStackTrace();
    } catch (JDOMException eJDOM) {
      eJDOM.printStackTrace();
    }
    return null;
  }
Esempio n. 26
0
 public void parse(String s) throws JDOMException, IOException {
   docIn = new StringReader(s);
   System.out.println(s);
   SAXBuilder builder = new SAXBuilder();
   Document doc = builder.build(docIn);
   Element root = doc.getRootElement();
   // getting channel descriptor and rebuilding it
   Element chDesc = root;
   // .getChild("desc");
   // getting Channel Name
   // FIXME: there's a bug ...this a workaround.
   Element chName = chDesc.getChild("name");
   if (chName == null) {
     chDesc = root.getChild("desc");
     chName = chDesc.getChild("name");
   }
   channelName = new String(chName.getText());
   // getting channel topic
   Element chTopic = chDesc.getChild("topic");
   Element pipeUri = chDesc.getChild("pipeID");
   pipeURI = new String(pipeUri.getText());
   channelTopic = new String(chTopic.getText());
   Element chDateTime = chDesc.getChild("timestamp");
   nanotime = Long.parseLong(chDateTime.getText().trim());
   Element chFounder = chDesc.getChild("founder");
   if (chFounder == null) return;
   founderName = chFounder.getChildText("name");
   founderAddress = chFounder.getChildText("email");
   founderPeerID = chFounder.getChildText("peerid");
   Element userListItem = root.getChild("userlist");
   if (userListItem == null) return;
   List userList = userListItem.getChildren();
   for (Object o : userList) {
     Element e = (Element) o;
     UserInfo infoItem = mkUserInfo(e);
     chUsers.put(infoItem.getAddress(), infoItem);
   }
 }
Esempio n. 27
0
 private static boolean comparerTripletEntier(Element triplet1, Element triplet2) {
   String s1 = triplet1.getChild("s").getChildText("uri");
   String s2 = triplet2.getChild("s").getChildText("uri");
   String p1 = triplet1.getChild("p").getChildText("uri");
   String p2 = triplet2.getChild("p").getChildText("uri");
   Element o1 = triplet1.getChild("o");
   Element o2 = triplet2.getChild("o");
   if (!s1.equals(s2)) {
     return false;
   } else if (!p1.equals(p2)) {
     return false;
   } else if (!comparerObjet(o1, o2)) {
     return false;
   }
   return true;
 }
Esempio n. 28
0
  /**
   * Gets the SER for a naive algorithm which does random re-ranking.
   *
   * @param xmlFileName
   * @param svmPredFileName
   * @return
   * @throws Exception
   */
  public float[] getER4RandomHyp(String xmlFileName) throws Exception {
    // read the xml file in order to get the utterance transcripts
    try {

      Document d =
          new org.jdom.input.SAXBuilder().build(new File(xmlFileName)); // PARSE THE XML FILE
      java.util.List nbestList = d.getRootElement().getChildren("nbest_data");
      float[] serArray = new float[nbestList.size()];
      int noUtt = 0;
      java.util.Random rand = new java.util.Random();

      for (int i = 0; i < nbestList.size(); i++) {
        Element nbestElem = (Element) nbestList.get(i);
        noUtt++;
        java.util.List recList = nbestElem.getChildren("recognition");

        int bestRankIdx = rand.nextInt(recList.size() - 1) + 1;

        // System.out.println("best rank = " + bestRankIdx);
        if (recList.size() < bestRankIdx)
          System.out.println("Less than " + bestRankIdx + " recognitions !!! ");

        Element recElem = (Element) recList.get(bestRankIdx);

        Element semCorrectElem = recElem.getChild("semantically_correct");
        String semCorrect = semCorrectElem.getValue();
        if (semCorrect.equalsIgnoreCase("good")) serArray[i] = 0;
        else serArray[i] = 1;
      }
      return serArray;
    } catch (IOException eIO) {
      eIO.printStackTrace();
    } catch (JDOMException eJDOM) {
      eJDOM.printStackTrace();
    } catch (NullPointerException nullE) {
      nullE.printStackTrace();
    }
    return null;
  }
Esempio n. 29
0
  private void collectSourceDataFromDOM(Element code, IDataSets dataset) throws Exception {
    // get code fragment
    CodeFragment.TYPE type = CodeFragment.TYPE.valueOf(code.getAttributeValue("type"));
    if (type == CodeFragment.TYPE.SOURCE) {
      String dataname = code.getAttributeValue("name");
      String dataid = code.getAttributeValue("dataid");
      // check import method and reader
      Element importelement = code.getChild(IImport.class.getName());
      Element readerelement = code.getChild(IReader.class.getName());
      // get URI
      String URI = importelement.getAttributeValue("URI");
      String scheme = (new URI(URI)).getScheme();
      // look for a suitable import method
      IImports allimports = WorkFlowManager.getInstance().getImports();
      IImportMethod importmethod = allimports.findImport(scheme);
      if (importmethod == null) {
        Util.errorMessage("Could not find suitable import for scheme '" + scheme + "'");
        return;
      }
      IImport method = importmethod.getImport();
      method.setURI(URI);
      // get reader
      String readername = readerelement.getAttributeValue("name");
      String format = readerelement.getAttributeValue("format");
      String readertype = readerelement.getAttributeValue("datatype");
      IReaders allreaders = WorkFlowManager.getInstance().getReaders();
      IReader reader = allreaders.findReaderWithName(readername);
      if (reader == null) {
        Util.errorMessage("Could not find reader " + readername);
        return;
      }
      reader.setType(readertype);
      reader.setDataFormat(format);
      reader.setType(readertype);

      dataset.importDataContent(method, reader, dataname, dataid);
    }
  }
Esempio n. 30
0
 private StructureType assignStructureType(Element structure) throws VisualizerLoadException {
   String name = structure.getName().toLowerCase();
   if (name.compareTo("graph") == 0) {
     if (structure.getAttributeValue("weighted").compareTo("true") == 0)
       return new Graph_Network("NETWORK");
     else return new Graph_Network("GRAPH");
   } else if (name.equals("array")) return new MD_Array();
   else if (name.equals("no3darray")) return new No3darray();
   else if (name.equals("linkedlist")) return new VisLinkedList();
   else if (name.equals("no3dlinkedlist")) return new No3dLinkedList();
   else if (name.equals("linkedlistnonull")) return new VisLinkedListNoNull();
   else if (name.equals("bargraph")) return new BarScat("BAR");
   else if (name.equals("scattergraph"))
     return new BarScat(
         "SCAT"); // not implemented in xml dtd, and does not have a load-from-xml method defined
   else if (name.equals("stack")) return new Stack();
   else if (name.equals("queue")) return new Queue();
   else if (name.equals("tree")) {
     if (structure.getChild("binary_node") != null) return new BinaryTree();
     else return new GeneralTree();
   } else if (name.equals("text")) return new TextStructure();
   // if the XML element name is different from your structure's name, you can do something like
   // this:
   // 	else if( name.equalsIgnoreCase("node"))
   // 	    return new Node();
   else if (name.equals("legend")) return new LegendofColors();
   else {
     // try dynamic typing
     try {
       return assignStructureType(name);
     } catch (Exception e) {
       throw new VisualizerLoadException(
           "Unable to instantiate class \"" + name + "\":\n" + e.getMessage());
     }
   }
 }