@Override
 public int corpusDocFrequencyByTerm(String term) {
   String indexFile = _options._indexPrefix + "/merge.txt";
   try {
     BufferedReader reader = new BufferedReader(new FileReader(indexFile));
     String line;
     while ((line = reader.readLine()) != null) {
       int termDocFren = 0;
       String title = "";
       String data = "";
       Scanner s = new Scanner(line).useDelimiter("\t");
       while (s.hasNext()) {
         title = s.next();
         data = s.next();
       }
       if (title.equals(term)) {
         String[] docs = data.split("\\|");
         termDocFren = docs.length;
       }
       reader.close();
       return termDocFren;
     }
     reader.close();
   } catch (Exception e) {
     e.printStackTrace();
   }
   return 0;
 }
  // open up an audio stream
  private static void init() {
    try {
      // 44,100 samples per second, 16-bit audio, mono, signed PCM, little
      // Endian
      AudioFormat format = new AudioFormat((float) SAMPLE_RATE, BITS_PER_SAMPLE, 1, true, false);
      DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);

      line = (SourceDataLine) AudioSystem.getLine(info);
      line.open(format, SAMPLE_BUFFER_SIZE * BYTES_PER_SAMPLE);

      // the internal buffer is a fraction of the actual buffer size, this
      // choice is arbitrary
      // it gets divided because we can't expect the buffered data to line
      // up exactly with when
      // the sound card decides to push out its samples.
      buffer = new byte[SAMPLE_BUFFER_SIZE * BYTES_PER_SAMPLE / 3];
      listeners = new HashSet<AudioEventListener>();
    } catch (Exception e) {
      System.err.println("Error initializing StdAudio audio system:");
      e.printStackTrace();
      System.exit(1);
    }

    // no sound gets made before this call
    line.start();
  }
  public void unrelateAcrossR1013From(MessageArgument_c target, boolean notifyChanges) {
    if (target == null) return;

    if (IsSupertypeMessageArgument == null) return; // already unrelated

    if (target != IsSupertypeMessageArgument) {
      Exception e = new Exception();
      e.fillInStackTrace();
      CorePlugin.logError("Tried to unrelate from non-related instance across R1013", e);
      return;
    }

    if (target != null) {
      target.clearBackPointerR1013To(this);
    }

    if (IsSupertypeMessageArgument != null) {

      m_arg_id = IsSupertypeMessageArgument.getArg_id();
      IsSupertypeMessageArgument = null;
      target.removeRef();
      if (notifyChanges) {
        RelationshipChangeModelDelta change =
            new RelationshipChangeModelDelta(
                Modeleventnotification_c.DELTA_ELEMENT_UNRELATED, this, target, "1013", "");
        Ooaofooa.getDefaultInstance().fireModelElementRelationChanged(change);
      }
    }
  }
Exemple #4
0
  @Override
  protected synchronized Class<?> loadClass(String className, boolean resolve)
      throws ClassNotFoundException {
    Class<?> c = null;
    try {
      try {
        ClassLoader cl = getParent();
        c = cl.loadClass(className);
        if (c != null) return c;
      } catch (ClassNotFoundException e) {
        /* let the next one handle this */
      }

      try {
        c = findJarClass(className);
        if (c != null) return c;
      } catch (Exception e) {
        System.out.println(
            "Error loading class ["
                + className
                + "] from jars in war file ["
                + outerFile.getName()
                + "]: "
                + e.toString());
        e.printStackTrace();
      }

      throw new ClassNotFoundException("Class [" + className + "] not found");
    } finally {
      if (c != null && resolve) {
        resolveClass(c);
      }
    }
  }
 private static void printHelp(OptionParser parser) {
   try {
     parser.printHelpOn(System.out);
   } catch (Exception exception) {
     exception.printStackTrace();
   }
 }
 private void setHPubAccessHandleString(String encodedHandleWithSpaces) {
   String encodedHandle = removeSpaceCharacters(encodedHandleWithSpaces);
   if ((encodedHandle == null) || (encodedHandle.length() < 5)) {
     return;
   }
   try {
     byte[] handleByteArray = null;
     sun.misc.BASE64Decoder dec = new sun.misc.BASE64Decoder();
     try {
       handleByteArray = dec.decodeBuffer(encodedHandle);
     } catch (Exception e) {
       System.out.println("AccessEJBTemplate::setHPubAccessHandleString()  decoding buffer");
     }
     ;
     ByteArrayInputStream bais = new ByteArrayInputStream(handleByteArray);
     javax.ejb.Handle h1 = null;
     try {
       ObjectInputStream ois = new ObjectInputStream(bais);
       hPubAccessHandle = (javax.ejb.Handle) ois.readObject();
     } catch (Exception ioe) {
       System.out.println("Exception reading handle object");
     }
   } catch (Exception e) {
     e.printStackTrace(System.err);
     System.out.println("Exception AccessEJBTemplate::setHPubAccessHandleString()");
   }
   return;
 }
 static {
   try {
     properties[0] = new PropertyDescriptor("dataQuality", DQ.class, "getDataQuality", null);
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
  public boolean delete() {
    boolean result = super.delete();
    boolean delete_error = false;
    String errorMsg =
        "The following relationships were not torn down by the GraphNode.dispose call: ";
    Graphelement_c testR301Inst1 = Graphelement_c.getOneDIM_GEOnR301(this, false);

    if (testR301Inst1 != null) {
      delete_error = true;
      errorMsg = errorMsg + "301 ";
    }
    Shape_c testR19Inst1 = Shape_c.getOneGD_SHPOnR19(this, false);

    if (testR19Inst1 != null) {
      delete_error = true;
      errorMsg = errorMsg + "19 ";
    }
    FloatingText_c testR19Inst2 = FloatingText_c.getOneGD_CTXTOnR19(this, false);

    if (testR19Inst2 != null) {
      delete_error = true;
      errorMsg = errorMsg + "19 ";
    }
    if (delete_error == true) {

      if (CanvasPlugin.getDefault().isDebugging()) {
        Ooaofgraphics.log.println(ILogger.DELETE, "GraphNode", errorMsg);
      } else {
        Exception e = new Exception();
        e.fillInStackTrace();
        CanvasPlugin.logError(errorMsg, e);
      }
    }
    return result;
  }
  static void writeNewData(String datafile) {

    try {
      BufferedReader bufr = new BufferedReader(new FileReader(datafile));
      BufferedWriter bufw = new BufferedWriter(new FileWriter(datafile + ".nzf"));

      String line;
      String[] tokens;

      while ((line = bufr.readLine()) != null) {

        tokens = line.split(" ");
        bufw.write(tokens[0]);
        for (int i = 1; i < tokens.length; i++) {

          Integer index = Integer.valueOf(tokens[i].split(":")[0]);
          if (nnzFeas.contains(index)) {
            bufw.write(" " + tokens[i]);
          }
        }
        bufw.newLine();
      }
      bufw.close();
      bufr.close();

    } catch (Exception e) {
      e.printStackTrace();
      System.exit(0);
    }
  }
  /**
   * Establishes a connection to a registry.
   *
   * @param queryUrl the URL of the query registry
   * @param publishUrl the URL of the publish registry
   */
  public void makeConnection(String queryUrl, String publishUrl) {

    Context context = null;
    ConnectionFactory factory = null;

    /*
     * Define connection configuration properties.
     * To publish, you need both the query URL and the
     * publish URL.
     */
    Properties props = new Properties();
    props.setProperty("javax.xml.registry.queryManagerURL", queryUrl);
    props.setProperty("javax.xml.registry.lifeCycleManagerURL", publishUrl);

    try {
      // Create the connection, passing it the
      // configuration properties
      context = new InitialContext();
      factory = (ConnectionFactory) context.lookup("java:comp/env/eis/JAXR");
      factory.setProperties(props);
      connection = factory.createConnection();
      System.out.println("Created connection to registry");
    } catch (Exception e) {
      e.printStackTrace();
      if (connection != null) {
        try {
          connection.close();
        } catch (JAXRException je) {
        }
      }
    }
  }
  public void unrelateAcrossR301From(Graphelement_c target, boolean notifyChanges) {
    if (target == null) return;

    if (IsSupertypeGraphelement == null) return; // already unrelated

    if (target != IsSupertypeGraphelement) {
      Exception e = new Exception();
      e.fillInStackTrace();
      CanvasPlugin.logError("Tried to unrelate from non-related instance across R301", e);
      return;
    }

    if (target != null) {
      target.clearBackPointerR301To(this);
    }

    if (IsSupertypeGraphelement != null) {

      m_elementid = IsSupertypeGraphelement.getElementid();
      if (IdAssigner.NULL_UUID.equals(m_elementid)) {
        m_elementid = IsSupertypeGraphelement.getElementidCachedValue();
      }
      IsSupertypeGraphelement = null;
      target.removeRef();
      if (notifyChanges) {
        RelationshipChangeModelDelta change =
            new RelationshipChangeModelDelta(
                Modeleventnotification_c.DELTA_ELEMENT_UNRELATED, this, target, "301", "");
        Ooaofgraphics.getDefaultInstance().fireModelElementRelationChanged(change);
      }
    }
  }
  public boolean delete() {
    boolean result = super.delete();
    boolean delete_error = false;
    String errorMsg =
        "The following relationships were not torn down by the Data Type in Package.dispose call: ";
    DataType_c testR39Inst = DataType_c.getOneS_DTOnR39(this, false);

    if (testR39Inst != null) {
      delete_error = true;
      errorMsg = errorMsg + "39 ";
    }

    DataTypePackage_c testR39InstOth = DataTypePackage_c.getOneS_DPKOnR39(this, false);

    if (testR39InstOth != null) {
      delete_error = true;
      errorMsg = errorMsg + "39 ";
    }
    if (delete_error == true) {

      if (CorePlugin.getDefault().isDebugging()) {
        Ooaofooa.log.println(ILogger.DELETE, "Data Type in Package", errorMsg);
      } else {
        Exception e = new Exception();
        e.fillInStackTrace();
        CorePlugin.logError(errorMsg, e);
      }
    }
    return result;
  }
  public void unrelateAcrossR39From(DataType_c target, boolean notifyChanges) {
    if (target == null) return;

    if (ContainsDataType == null) return; // already unrelated

    if (target != ContainsDataType) {
      Exception e = new Exception();
      e.fillInStackTrace();
      CorePlugin.logError("Tried to unrelate from non-related instance across R39", e);
      return;
    }

    if (target != null) {
      target.clearBackPointerR39To(this);
    }

    if (ContainsDataType != null) {

      m_dt_id = ContainsDataType.getDt_id();
      if (IdAssigner.NULL_UUID.equals(m_dt_id)) {
        m_dt_id = ContainsDataType.getDt_idCachedValue();
      }
      ContainsDataType = null;
      target.removeRef();
      if (notifyChanges) {
        RelationshipChangeModelDelta change =
            new RelationshipChangeModelDelta(
                Modeleventnotification_c.DELTA_ELEMENT_UNRELATED, this, target, "39", "");
        Ooaofooa.getDefaultInstance().fireModelElementRelationChanged(change);
      }
    }
  }
 @Override
 public int documentTermFrequency(String term, String url) {
   String docpath = "" + url;
   int result;
   try {
     BufferedReader reader =
         new BufferedReader(new FileReader(_options._indexPrefix + "/" + docpath));
     String line;
     int count = 0;
     while ((line = reader.readLine()) != null) {
       count++;
       if (count > 2) {
         String[] terms = line.split("\t");
         if (terms[0].equals(term)) {
           result = Integer.parseInt(terms[1]);
           reader.close();
           return result;
         }
       }
     }
     reader.close();
   } catch (Exception e) {
     e.printStackTrace();
   }
   return 0;
 }
Exemple #15
0
 /**
  * Adds <code>AttributeValue</code> to the Attribute.
  *
  * @param value A String representing <code>AttributeValue</code>.
  * @exception SAMLException
  */
 public void addAttributeValue(String value) throws SAMLException {
   if (value == null || value.length() == 0) {
     if (SAMLUtilsCommon.debug.messageEnabled()) {
       SAMLUtilsCommon.debug.message("addAttributeValue: Input is null");
     }
     throw new SAMLRequesterException(SAMLUtilsCommon.bundle.getString("nullInput"));
   }
   StringBuffer sb = new StringBuffer(300);
   sb.append("<")
       .append(SAMLConstants.ASSERTION_PREFIX)
       .append("AttributeValue")
       .append(SAMLConstants.assertionDeclareStr)
       .append(">")
       .append(value)
       .append("</")
       .append(SAMLConstants.ASSERTION_PREFIX)
       .append("AttributeValue>");
   try {
     Element ele =
         XMLUtils.toDOMDocument(sb.toString().trim(), SAMLUtilsCommon.debug).getDocumentElement();
     if (_attributeValue == null) {
       _attributeValue = new ArrayList();
     }
     if (!(_attributeValue.add(ele))) {
       if (SAMLUtilsCommon.debug.messageEnabled()) {
         SAMLUtilsCommon.debug.message(
             "Attribute: failed to " + "add to the attribute value list.");
       }
       throw new SAMLRequesterException(SAMLUtilsCommon.bundle.getString("addListError"));
     }
   } catch (Exception e) {
     SAMLUtilsCommon.debug.error("addAttributeValue error", e);
     throw new SAMLRequesterException("Exception in addAttributeValue" + e.getMessage());
   }
 }
Exemple #16
0
  public static String getAddressByIP(String ip) {
    try {
      String js = visitWeb("http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js&ip=" + ip);
      JsonParser jsonParser = new JsonParser();
      js = js.trim();
      JsonObject jo = jsonParser.parse(js.substring(21, js.length() - 1)).getAsJsonObject();
      String province = "";
      String city = "";
      try {
        // 获取 省、市
        province =
            jo.get("province") == null
                ? ""
                : URLDecoder.decode(jo.get("province").toString(), "UTF-8");
        city = jo.get("city") == null ? "" : URLDecoder.decode(jo.get("city").toString(), "UTF-8");
        // 省为空用国家代替
        if (StringUtils.isEmpty(province)) {
          province =
              jo.get("country") == null
                  ? ""
                  : URLDecoder.decode(jo.get("country").toString(), "UTF-8");
        }

      } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
      }

      return (province.equals("") || province.equals(city)) ? city : province + " " + city;
    } catch (Exception e) {
      e.printStackTrace();
      return "";
    }
  }
Exemple #17
0
  /**
   * Adds <code>AttributeValue</code> to the Attribute.
   *
   * @param element An Element object representing <code>AttributeValue</code>.
   * @exception SAMLException
   */
  public void addAttributeValue(Element element) throws SAMLException {
    if (element == null) {
      if (SAMLUtilsCommon.debug.messageEnabled()) {
        SAMLUtilsCommon.debug.message("addAttributeValue: input  is null.");
      }
      throw new SAMLRequesterException(SAMLUtilsCommon.bundle.getString("nullInput"));
    }

    String tag = element.getLocalName();
    if ((tag == null) || (!tag.equals("AttributeValue"))) {
      if (SAMLUtilsCommon.debug.messageEnabled()) {
        SAMLUtilsCommon.debug.message("AttributeValue: wrong input.");
      }
      throw new SAMLRequesterException(SAMLUtilsCommon.bundle.getString("wrongInput"));
    }
    try {
      if (_attributeValue == null) {
        _attributeValue = new ArrayList();
      }
      if (!(_attributeValue.add(element))) {
        if (SAMLUtilsCommon.debug.messageEnabled()) {
          SAMLUtilsCommon.debug.message(
              "Attribute: failed to " + "add to the attribute value list.");
        }
        throw new SAMLRequesterException(SAMLUtilsCommon.bundle.getString("addListError"));
      }
    } catch (Exception e) {
      SAMLUtilsCommon.debug.error("addAttributeValue error", e);
      throw new SAMLRequesterException("Exception in addAttributeValue" + e.getMessage());
    }
  }
Exemple #18
0
 public static String visitWeb(String urlStr) {
   URL url = null;
   HttpURLConnection httpConn = null;
   InputStream in = null;
   try {
     url = new URL(urlStr);
     httpConn = (HttpURLConnection) url.openConnection();
     HttpURLConnection.setFollowRedirects(true);
     httpConn.setRequestMethod("GET");
     httpConn.setRequestProperty("User-Agent", "Mozilla/4.0(compatible;MSIE 6.0;Windows 2000)");
     in = httpConn.getInputStream();
     return convertStreamToString(in);
   } catch (MalformedURLException e) {
     e.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   } finally {
     try {
       in.close();
       httpConn.disconnect();
     } catch (Exception ex) {
       ex.printStackTrace();
     }
   }
   return null;
 }
Exemple #19
0
  /**
   * caution: no authentication so far
   *
   * @return
   * @throws Exception
   */
  public String export() throws Exception {
    project = projectMgr.getProject(projectId);
    velocityEngine.init();
    VelocityContext context = new VelocityContext();
    context.put("project", project);
    Template template = null;
    try {
      template = velocityEngine.getTemplate("resource/export.vm", "UTF8");
    } catch (ResourceNotFoundException rnfe) {
      rnfe.printStackTrace();
    } catch (ParseErrorException pee) {
      pee.printStackTrace();
    } catch (MethodInvocationException mie) {
      mie.printStackTrace();
    } catch (Exception e) {
      e.printStackTrace();
    }
    StringWriter sw = new StringWriter();
    template.merge(context, sw);
    fileInputStream = new ByteArrayInputStream(sw.toString().getBytes("UTF8"));

    // 记录操作日志
    RapLog log = new RapLog();
    log.setIp(org.apache.struts2.ServletActionContext.getRequest().getRemoteAddr());
    log.setOperation("导出接口文档.项目名称:" + project.getName());
    log.setUserName(getAccountMgr().getUser(getCurUserId()).getName());
    logMgr.createLog(log);

    return SUCCESS;
  }
Exemple #20
0
 // User defined finders/Buscadores definidos por el usuario
 public static Size findById(int id) throws javax.ejb.ObjectNotFoundException {
   if (XavaPreferences.getInstance().isJPAPersistence()) {
     javax.persistence.Query query =
         org.openxava.jpa.XPersistence.getManager()
             .createQuery("from Size as o where o.id = :arg0");
     query.setParameter("arg0", new Integer(id));
     try {
       return (Size) query.getSingleResult();
     } catch (Exception ex) {
       // In this way in order to work with Java pre 5
       if (ex.getClass().getName().equals("javax.persistence.NoResultException")) {
         throw new javax.ejb.ObjectNotFoundException(
             XavaResources.getString("object_not_found", "Size"));
       } else {
         ex.printStackTrace();
         throw new RuntimeException(ex.getMessage());
       }
     }
   } else {
     org.hibernate.Query query =
         org.openxava.hibernate.XHibernate.getSession()
             .createQuery("from Size as o where o.id = :arg0");
     query.setParameter("arg0", new Integer(id));
     Size r = (Size) query.uniqueResult();
     if (r == null) {
       throw new javax.ejb.ObjectNotFoundException(
           XavaResources.getString("object_not_found", "Size"));
     }
     return r;
   }
 }
Exemple #21
0
    public void run() {
      // run this first, ie shutdown the container before closing jarFiles to avoid errors with
      // classes missing
      if (callMethod != null) {
        try {
          callMethod.invoke(callObject);
        } catch (Exception e) {
          System.out.println("Error in shutdown: " + e.toString());
        }
      }

      // give things a couple seconds to destroy; this way of running is mostly for dev/test where
      // this should be sufficient
      try {
        synchronized (this) {
          this.wait(2000);
        }
      } catch (Exception e) {
        System.out.println("Shutdown wait interrupted");
      }
      System.out.println(
          "========== Shutting down Moqui Executable (closing jars, etc) ==========");

      // close all jarFiles so they will "deleteOnExit"
      for (JarFile jarFile : jarFileList) {
        try {
          jarFile.close();
        } catch (IOException e) {
          System.out.println("Error closing jar [" + jarFile + "]: " + e.toString());
        }
      }
    }
Exemple #22
0
 public void run() throws Exception {
   Thread[] threads = new Thread[THREADS];
   for (int i = 0; i < THREADS; i++) {
     try {
       threads[i] = new Thread(peerFactory.newClient(this), "Client " + i);
     } catch (Exception e) {
       e.printStackTrace();
       return;
     }
     threads[i].start();
   }
   try {
     for (int i = 0; i < THREADS; i++) {
       threads[i].join();
     }
   } catch (InterruptedException e) {
     setFailed();
     e.printStackTrace();
   }
   if (failed) {
     throw new Exception("*** Test '" + peerFactory.getName() + "' failed ***");
   } else {
     System.out.println("Test '" + peerFactory.getName() + "' completed successfully");
   }
 }
 private void checkDialog(DlgResource dialog) {
   List<StructEntry> flatList = dialog.getFlatList();
   for (int i = 0; i < flatList.size(); i++) {
     if (flatList.get(i) instanceof StringRef) {
       StringRef ref = (StringRef) flatList.get(i);
       if (ref.getValue() >= 0 && ref.getValue() < strUsed.length) strUsed[ref.getValue()] = true;
     } else if (flatList.get(i) instanceof AbstractCode) {
       AbstractCode code = (AbstractCode) flatList.get(i);
       try {
         String compiled =
             infinity.resource.bcs.Compiler.getInstance()
                 .compileDialogCode(code.toString(), code instanceof Action);
         if (code instanceof Action) Decompiler.decompileDialogAction(compiled, true);
         else Decompiler.decompileDialogTrigger(compiled, true);
         Set<Integer> used = Decompiler.getStringRefsUsed();
         for (final Integer stringRef : used) {
           int u = stringRef.intValue();
           if (u >= 0 && u < strUsed.length) strUsed[u] = true;
         }
       } catch (Exception e) {
         e.printStackTrace();
       }
     }
   }
 }
Exemple #24
0
    protected void buildPanel(String strPath) {
      BufferedReader reader = WFileUtil.openReadFile(strPath);
      String strLine;

      if (reader == null) return;

      try {
        while ((strLine = reader.readLine()) != null) {
          if (strLine.startsWith("#") || strLine.startsWith("%") || strLine.startsWith("@"))
            continue;

          StringTokenizer sTokLine = new StringTokenizer(strLine, ":");

          // first token is the label e.g. Password Length
          if (sTokLine.hasMoreTokens()) {
            createLabel(sTokLine.nextToken(), this);
          }

          // second token is the value
          String strValue = sTokLine.hasMoreTokens() ? sTokLine.nextToken() : "";
          if (strValue.equalsIgnoreCase("yes") || strValue.equalsIgnoreCase("no"))
            createChkBox(strValue, this);
          else createTxf(strValue, this);
        }
      } catch (Exception e) {
        Messages.writeStackTrace(e);
        // e.printStackTrace();
        Messages.postDebug(e.toString());
      }
    }
Exemple #25
0
  public static void RetrieveTrainMatrix() {
    try {
      BufferedReader flrdr =
          new BufferedReader(
              new FileReader("D:\\IR\\Assignment7\\Pytest\\part2\\output\\train_matrix.txt"));
      String line = "";
      int doc_count = 0;

      while ((line = flrdr.readLine()) != null) {
        SortedSet<Integer> word_ids = new TreeSet<Integer>();
        int val_count = 0;

        String[] key_value = line.split(" :: ");
        key_value[1] = key_value[1].substring(1, key_value[1].length() - 2);
        String[] values = key_value[1].split(",");

        FeatureNode[] node = new FeatureNode[values.length];

        for (String val : values) word_ids.add(Integer.parseInt(val.trim()));

        for (int val : word_ids) node[val_count++] = new FeatureNode(val, 1);

        if (spam_docs.contains(key_value[0].trim())) ylable[doc_count] = 1;
        else ylable[doc_count] = 0;

        train_matrix[doc_count++] = node;
      }
      flrdr.close();
    } catch (Exception e) {
      e.printStackTrace();
      System.exit(0);
    }
  }
  /**
   * This method builds a decision tree model
   *
   * @param sparkContext JavaSparkContext initialized with the application
   * @param modelID Model ID
   * @param trainingData Training data as a JavaRDD of LabeledPoints
   * @param testingData Testing data as a JavaRDD of LabeledPoints
   * @param workflow Machine learning workflow
   * @param mlModel Deployable machine learning model
   * @throws MLModelBuilderException
   */
  private ModelSummary buildDecisionTreeModel(
      JavaSparkContext sparkContext,
      long modelID,
      JavaRDD<LabeledPoint> trainingData,
      JavaRDD<LabeledPoint> testingData,
      Workflow workflow,
      MLModel mlModel,
      SortedMap<Integer, String> includedFeatures,
      Map<Integer, Integer> categoricalFeatureInfo)
      throws MLModelBuilderException {
    try {
      Map<String, String> hyperParameters = workflow.getHyperParameters();
      DecisionTree decisionTree = new DecisionTree();
      DecisionTreeModel decisionTreeModel =
          decisionTree.train(
              trainingData,
              getNoOfClasses(mlModel),
              categoricalFeatureInfo,
              hyperParameters.get(MLConstants.IMPURITY),
              Integer.parseInt(hyperParameters.get(MLConstants.MAX_DEPTH)),
              Integer.parseInt(hyperParameters.get(MLConstants.MAX_BINS)));

      // remove from cache
      trainingData.unpersist();
      // add test data to cache
      testingData.cache();

      JavaPairRDD<Double, Double> predictionsAndLabels =
          decisionTree.test(decisionTreeModel, testingData).cache();
      ClassClassificationAndRegressionModelSummary classClassificationAndRegressionModelSummary =
          SparkModelUtils.getClassClassificationModelSummary(
              sparkContext, testingData, predictionsAndLabels);

      // remove from cache
      testingData.unpersist();

      mlModel.setModel(new MLDecisionTreeModel(decisionTreeModel));

      classClassificationAndRegressionModelSummary.setFeatures(
          includedFeatures.values().toArray(new String[0]));
      classClassificationAndRegressionModelSummary.setAlgorithm(
          SUPERVISED_ALGORITHM.DECISION_TREE.toString());

      MulticlassMetrics multiclassMetrics =
          getMulticlassMetrics(sparkContext, predictionsAndLabels);

      predictionsAndLabels.unpersist();

      classClassificationAndRegressionModelSummary.setMulticlassConfusionMatrix(
          getMulticlassConfusionMatrix(multiclassMetrics, mlModel));
      Double modelAccuracy = getModelAccuracy(multiclassMetrics);
      classClassificationAndRegressionModelSummary.setModelAccuracy(modelAccuracy);
      classClassificationAndRegressionModelSummary.setDatasetVersion(workflow.getDatasetVersion());

      return classClassificationAndRegressionModelSummary;
    } catch (Exception e) {
      throw new MLModelBuilderException(
          "An error occurred while building decision tree model: " + e.getMessage(), e);
    }
  }
Exemple #27
0
  /*
   * Return data as a byte array.
   */
  private static byte[] readByte(String filename) {
    byte[] data = null;
    AudioInputStream ais = null;
    try {

      // try to read from file
      File file = new File(filename);
      if (file.exists()) {
        ais = AudioSystem.getAudioInputStream(file);
        data = new byte[ais.available()];
        ais.read(data);
      }

      // try to read from URL
      else {
        URL url = StdAudio.class.getResource(filename);
        ais = AudioSystem.getAudioInputStream(url);
        data = new byte[ais.available()];
        ais.read(data);
      }
    } catch (Exception e) {
      System.out.println(e.getMessage());
      throw new RuntimeException("Could not read " + filename);
    }

    return data;
  }
Exemple #28
0
  /**
   * returns list of output lines
   *
   * @param userId user id
   * @return sessionId session id object
   */
  public static List<SessionOutput> getOutput(Connection con, Long userId) {
    List<SessionOutput> outputList = new ArrayList<SessionOutput>();

    UserSessionsOutput userSessionsOutput = userSessionsOutputMap.get(userId);
    if (userSessionsOutput != null) {

      for (Long key : userSessionsOutput.getSessionOutputMap().keySet()) {

        // get output chars and set to output
        try {
          SessionOutput sessionOutput =
              (SessionOutput)
                  BeanUtils.cloneBean(userSessionsOutput.getSessionOutputMap().get(key));

          outputList.add(sessionOutput);

          SessionAuditDB.insertTerminalLog(con, sessionOutput);

          userSessionsOutput.getSessionOutputMap().get(key).setOutput("");
        } catch (Exception ex) {
          ex.printStackTrace();
        }
      }
    }

    return outputList;
  }
Exemple #29
0
  /*
   * 备注:平台编写规则类
   * 接口执行类
   */
  public Object runComClass(PfParameterVO vo) throws BusinessException {
    try {
      super.m_tmpVo = vo;
      // ####本脚本必须含有返回值,返回DLG和PNL的组件不允许有返回值####
      Object retObj = null;
      // ####该组件为单动作弃审处理开始...不能进行修改####
      boolean isFinishToGoing = procUnApproveFlow(vo);
      // ###返回值:true-审批流程由完成态返回到运行态;false-其他情况
      // ####该组件为单动作弃审处理结束...不能进行修改####

      if (isFinishToGoing) {
        // 审批流程由完成态返回到运行态,需要进行的业务补偿
      }

      // ####重要说明:生成的业务组件方法尽量不要进行修改####
      // 方法说明:反查单据主表VO的ts属性
      retObj =
          runClass(
              "nc.bs.trade.business.HYPubBO",
              "setBillTs",
              "nc.vo.pub.AggregatedValueObject:01",
              vo,
              m_keyHas,
              m_methodReturnHas);
      // ##################################################
      return getVo();
    } catch (Exception ex) {
      if (ex instanceof BusinessException) throw (BusinessException) ex;
      else throw new PFBusinessException(ex.getMessage(), ex);
    }
  }
Exemple #30
0
 // constructors
 public Rearrange() throws IOException {
   try {
     // spellchecker checker = new spellchecker();
   } catch (Exception e) {
     e.printStackTrace();
   }
 }