Esempio n. 1
0
 public Enumeration getChildrenInfo() {
   if (nrNeededParams >= 0) {
     return Utils.arrayEnumeration(Utils.arrayConcat(new Object[] {funcOrVal}, getBoundParams()));
   } else {
     return Utils.oneEnumeration(funcOrVal);
   }
 }
  /**
   * Save the downloaded files into the corresponding directories
   *
   * @deprecated
   */
  public synchronized void save() {
    synchronized (this) {
      synchronized (this.isComplete) {
        byte[] data = new byte[0];
        for (int i = 0; i < this.nbPieces; i++) {
          if (this.pieceList[i] == null) {

          } else {
            data = Utils.concat(data, this.pieceList[i].data());
          }
        }
        String saveAs = Constants.SAVEPATH;
        int offset = 0;
        if (this.nbOfFiles > 1) saveAs += this.torrent.saveAs + "/";
        for (int i = 0; i < this.nbOfFiles; i++) {
          try {
            new File(saveAs).mkdirs();
            FileOutputStream fos =
                new FileOutputStream(saveAs + ((String) (this.torrent.name.get(i))));
            fos.write(
                Utils.subArray(data, offset, ((Integer) (this.torrent.length.get(i))).intValue()));
            fos.flush();
            fos.close();
            offset += ((Integer) (this.torrent.length.get(i))).intValue();
          } catch (IOException ioe) {
            ioe.printStackTrace();
            System.err.println(
                "Error when saving the file " + ((String) (this.torrent.name.get(i))));
          }
        }
      }
    }
  }
Esempio n. 3
0
  private String getSingleLineOfChildren(final List children) {
    final StringBuilder result = new StringBuilder();
    final Iterator childrenIt = children.iterator();
    boolean isFirst = true;

    while (childrenIt.hasNext()) {
      final Object child = childrenIt.next();

      if (!(child instanceof ContentNode)) {
        return null;
      } else {
        String content = child.toString();

        // if first item trims it from left
        if (isFirst) {
          content = Utils.ltrim(content);
        }

        // if last item trims it from right
        if (!childrenIt.hasNext()) {
          content = Utils.rtrim(content);
        }

        if (content.indexOf('\n') >= 0 || content.indexOf('\r') >= 0) {
          return null;
        }
        result.append(content);
      }

      isFirst = false;
    }

    return result.toString();
  }
Esempio n. 4
0
  /**
   * Takes a packed-stream InputStream, and writes to a JarOutputStream. Internally the entire
   * buffer must be read, it may be more efficient to read the packed-stream to a file and pass the
   * File object, in the alternate method described below.
   *
   * <p>Closes its input but not its output. (The output can accumulate more elements.)
   *
   * @param in an InputStream.
   * @param out a JarOutputStream.
   * @exception IOException if an error is encountered.
   */
  public void unpack(InputStream in0, JarOutputStream out) throws IOException {
    assert (Utils.currentInstance.get() == null);
    TimeZone tz = (_props.getBoolean(Utils.PACK_DEFAULT_TIMEZONE)) ? null : TimeZone.getDefault();

    try {
      Utils.currentInstance.set(this);
      if (tz != null) TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
      final int verbose = _props.getInteger(Utils.DEBUG_VERBOSE);
      BufferedInputStream in = new BufferedInputStream(in0);
      if (Utils.isJarMagic(Utils.readMagic(in))) {
        if (verbose > 0) Utils.log.info("Copying unpacked JAR file...");
        Utils.copyJarFile(new JarInputStream(in), out);
      } else if (_props.getBoolean(Utils.DEBUG_DISABLE_NATIVE)) {
        (new DoUnpack()).run(in, out);
        in.close();
        Utils.markJarFile(out);
      } else {
        (new NativeUnpack(this)).run(in, out);
        in.close();
        Utils.markJarFile(out);
      }
    } finally {
      _nunp = null;
      Utils.currentInstance.set(null);
      if (tz != null) TimeZone.setDefault(tz);
    }
  }
Esempio n. 5
0
 public String encoded() {
   byte[] raw = Utils.toUtf8(json.toJSONString());
   if (compress) {
     raw = Utils.compress(raw);
   }
   return encodeBase64String(raw);
 }
  /**
   * Refresh the new followers, mentions, number of favorites, and retweeters
   *
   * @return boolean if there was something new
   */
  public boolean refreshActivity() {
    boolean newActivity = false;
    Twitter twitter;

    if (!useSecondAccount) {
      twitter = Utils.getTwitter(context, settings);
    } else {
      twitter = Utils.getSecondTwitter(context);
    }

    if (getMentions(twitter)) {
      newActivity = true;
    }

    if (getFollowers(twitter)) {
      newActivity = true;
    }

    List<Status> myTweets = getMyTweets(twitter);
    if (myTweets != null) {
      if (getRetweets(twitter, myTweets)) {
        newActivity = true;
      }

      if (getFavorites(myTweets)) {
        newActivity = true;
      }
    }

    return newActivity;
  }
 /**
  * Received when a peer request a piece. If the piece is available (which should always be the
  * case according to Bittorrent protocol) and we are able and willing to upload, the send the
  * piece to the peer
  *
  * @param peerID String
  * @param piece int
  * @param begin int
  * @param length int
  */
 public synchronized void peerRequest(String peerID, int piece, int begin, int length) {
   if (this.isPieceComplete(piece)) {
     DownloadTask dt = this.task.get(peerID);
     if (dt != null) {
       dt.ms.addMessageToQueue(
           new Message_PP(
               PeerProtocol.PIECE,
               Utils.concat(
                   Utils.intToByteArray(piece),
                   Utils.concat(
                       Utils.intToByteArray(begin), this.getPieceBlock(piece, begin, length)))));
       dt.peer.setULRate(length);
     }
     dt = null;
     this.pu.updateParameters(0, length, "");
   } else {
     try {
       this.task.get(peerID).end();
     } catch (Exception e) {
     }
     this.task.remove(peerID);
     this.peerList.remove(peerID);
     this.unchoken.remove(peerID);
   }
 }
Esempio n. 8
0
  public static String composeFilterQuery(String fq, CollectionSchemaInfo info) {
    if (Utils.nullOrEmpty(fq)) {
      return null;
    }

    HashMap<String, Set<String>> fqComponents = new HashMap<String, Set<String>>();

    for (String fqComponent : fq.split(FACET_FIELD_REQ_DELIM)) {
      if (Utils.nullOrEmpty(fqComponent)) continue;

      String[] fqComponentArray = fqComponent.split(FACET_VALUES_REQ_DELIM);
      String field = fqComponentArray[0];
      HashSet<String> values = new HashSet<String>();

      for (String value : fqComponentArray[1].split(FACET_VALUE_OPTS_REQ_DELIM)) {
        if (info.fieldTypeIsNumber(field)) {
          values.add(value);
        } else if (info.fieldTypeIsDate(field)) {
          values.add(getFQDateString(value));
        } else {
          values.add(quoteStringIfNotNull(value));
        }
      }
      fqComponents = setFQValues(fqComponents, field, values);
    }

    return composeFQString(fqComponents);
  }
Esempio n. 9
0
  public void draw(BufferedImage buf) {
    WritableRaster dst = buf.getRaster();
    blit(dst, bg.getRaster(), Coord.z);

    alphablit(dst, rmeter(sbars[0].getRaster(), lmax[0], max), mc[0]);
    alphablit(
        dst, lmeter(sbars[1].getRaster(), lmax[1], max), mc[1].sub(bars[1].getWidth() - 1, 0));
    alphablit(
        dst, lmeter(sbars[2].getRaster(), lmax[2], max), mc[2].sub(bars[2].getWidth() - 1, 0));
    alphablit(dst, rmeter(sbars[3].getRaster(), lmax[3], max), mc[3]);

    if (lfood != null) {
      double e = foodeff(lfood);
      alphablit(dst, rgmeter(lfood, e, 0), mc[0]);
      alphablit(dst, lgmeter(lfood, e, 1), mc[1].sub(bars[1].getWidth() - 1, 0));
      alphablit(dst, lgmeter(lfood, e, 2), mc[2].sub(bars[1].getWidth() - 1, 0));
      alphablit(dst, rgmeter(lfood, e, 3), mc[3]);
    }

    alphablit(dst, rmeter(bars[0].getRaster(), lev[0], max), mc[0]);
    alphablit(dst, lmeter(bars[1].getRaster(), lev[1], max), mc[1].sub(bars[1].getWidth() - 1, 0));
    alphablit(dst, lmeter(bars[2].getRaster(), lev[2], max), mc[2].sub(bars[2].getWidth() - 1, 0));
    alphablit(dst, rmeter(bars[3].getRaster(), lev[3], max), mc[3]);

    StringBuilder tbuf = new StringBuilder();
    for (int i = 0; i < 4; i++)
      tbuf.append(
          String.format(
              "%s: %s/%s\n", rnm[i], Utils.fpformat(lev[i], 3, 1), Utils.fpformat(lmax[i], 3, 1)));
    tooltip = RichText.render(tbuf.toString(), 0).tex();
  }
 public static void generateNativeMethodStubs(
     AnnotationProcessorEnvironment env,
     TypeMap type_map,
     PrintWriter writer,
     InterfaceDeclaration d,
     boolean generate_error_checks,
     boolean context_specific) {
   for (MethodDeclaration method : d.getMethods()) {
     Alternate alt_annotation = method.getAnnotation(Alternate.class);
     if (alt_annotation != null && !alt_annotation.nativeAlt()) continue;
     generateMethodStub(
         env,
         type_map,
         writer,
         Utils.getQualifiedClassName(d),
         method,
         Mode.NORMAL,
         generate_error_checks,
         context_specific);
     if (Utils.hasMethodBufferObjectParameter(method))
       generateMethodStub(
           env,
           type_map,
           writer,
           Utils.getQualifiedClassName(d),
           method,
           Mode.BUFFEROBJECT,
           generate_error_checks,
           context_specific);
   }
 }
Esempio n. 11
0
 private static void printJavaNativeStub(
     ProcessingEnvironment env,
     PrintWriter writer,
     ExecutableElement method,
     Mode mode,
     boolean generate_error_checks,
     boolean context_specific) {
   if (Utils.isMethodIndirect(generate_error_checks, context_specific, method)) {
     writer.print("\tstatic native ");
   } else {
     Utils.printDocComment(writer, method, env);
     writer.print("\tpublic static native ");
   }
   writer.print(getResultType(method, true));
   writer.print(
       " " + Utils.getSimpleNativeMethodName(method, generate_error_checks, context_specific));
   if (mode == Mode.BUFFEROBJECT) {
     writer.print(Utils.BUFFER_OBJECT_METHOD_POSTFIX);
   }
   writer.print("(");
   boolean first_parameter =
       generateParametersJava(
           writer, method, TypeInfo.getDefaultTypeInfoMap(method), true, true, mode);
   if (context_specific) {
     if (!first_parameter) {
       writer.print(", ");
     }
     writer.print("long " + Utils.FUNCTION_POINTER_VAR_NAME);
   }
   writer.println(");");
 }
Esempio n. 12
0
 private static void printParameterCaching(
     PrintWriter writer,
     TypeElement interface_decl,
     ExecutableElement method,
     Mode mode,
     boolean context_specific) {
   for (VariableElement param : method.getParameters()) {
     Class java_type = Utils.getJavaType(param.asType());
     CachedReference cachedReference = param.getAnnotation(CachedReference.class);
     if (Buffer.class.isAssignableFrom(java_type)
         && cachedReference != null
         && (mode != Mode.BUFFEROBJECT || param.getAnnotation(BufferObject.class) == null)
         && param.getAnnotation(Result.class) == null) {
       writer.print("\t\tif ( LWJGLUtil.CHECKS ) StateTracker.");
       if (context_specific) {
         writer.print("getReferences(caps).");
       } else {
         writer.print("getTracker().");
       }
       if (cachedReference.name().length() > 0) {
         writer.print(cachedReference.name());
       } else {
         writer.print(Utils.getReferenceName(interface_decl, method, param));
       }
       if (cachedReference.index().length() > 0) {
         writer.print("[" + cachedReference.index() + "]");
       }
       writer.println(" = " + param.getSimpleName() + ";");
     }
   }
 }
Esempio n. 13
0
    public BufferedImage getGridImage() {
      if (rendered) return gridImage;

      if (!loaded) throw new Loading();

      gridImage = TexI.mkbuf(cmaps);

      BufferedImage[] texes = new BufferedImage[256];

      Coord c = new Coord();
      for (c.y = 0; c.y < cmaps.y; c.y++) {
        for (c.x = 0; c.x < cmaps.x; c.x++) {
          int t = gettile(c);
          BufferedImage tex = tileimg(t, texes);
          if (tex != null)
            gridImage.setRGB(
                c.x,
                c.y,
                tex.getRGB(
                    Utils.floormod(c.x, tex.getWidth()), Utils.floormod(c.y, tex.getHeight())));
        }
      }
      for (c.y = 1; c.y < cmaps.y - 1; c.y++) {
        for (c.x = 1; c.x < cmaps.x - 1; c.x++) {
          int t = gettile(c);
          if ((gettile(c.add(-1, 0)) > t)
              || (gettile(c.add(1, 0)) > t)
              || (gettile(c.add(0, -1)) > t)
              || (gettile(c.add(0, 1)) > t)) gridImage.setRGB(c.x, c.y, Color.BLACK.getRGB());
        }
      }
      rendered = true;
      return gridImage;
    }
Esempio n. 14
0
 private void deflate(String tmpDir, String path) {
   String tmpFile = "tmp-" + Utils.timestamp() + ".zip";
   try {
     ZipFile zipFile = new ZipFile(tmpFile);
     ZipParameters parameters = new ZipParameters();
     parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
     parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
     parameters.setIncludeRootFolder(false);
     zipFile.addFolder(tmpDir, parameters);
   } catch (Exception e) {
     e.printStackTrace();
     return;
   }
   File from = null;
   File to = null;
   try {
     File target = new File(path);
     if (target.exists()) FileUtils.forceDelete(target);
     from = new File(tmpFile);
     to = new File(path);
     FileUtils.moveFile(from, to);
   } catch (IOException e) {
     Utils.onError(new Error.FileMove(tmpFile, path));
   }
   try {
     FileUtils.deleteDirectory(new File(tmpDir));
   } catch (IOException e) {
     Utils.log("can't delete temporary folder");
   }
 }
Esempio n. 15
0
 protected boolean checkConfig() {
   String configPath = System.getProperty(Utils.CONFIGPATH);
   if (configPath == null || configPath.equals("")) {
     logger.error("config.path not define, example: -Dconfig.path=/opt/path/config.properties");
     return false;
   }
   try {
     properties.load(new FileInputStream(configPath));
   } catch (IOException e) {
     logger.error("config file not exist :{0}", configPath);
     return false;
   }
   logger.debug(Utils.SIMPLETASKPACKAGE + ":" + properties.getProperty(Utils.SIMPLETASKPACKAGE));
   if (!Utils.checkConfigValue(properties, Utils.SIMPLETASKPACKAGE)) {
     logger.error(
         Utils.SIMPLETASKPACKAGE
             + " not define, example: -D"
             + Utils.SIMPLETASKPACKAGE
             + "=cn.huangchaosuper.steps");
     return false;
   }
   logger.debug(Utils.OPENSTEP + ":" + properties.getProperty(Utils.OPENSTEP));
   if (!Utils.checkConfigValue(properties, Utils.OPENSTEP, "0")) {
     return false;
   }
   logger.debug(Utils.CLOSESTEP + ":" + properties.getProperty(Utils.CLOSESTEP));
   if (!Utils.checkConfigValue(properties, Utils.CLOSESTEP, "9999")) {
     return false;
   }
   return true;
 }
Esempio n. 16
0
 public Enumeration getSuccessors() {
   Object[] params = getBoundParams();
   Object[] succ = params;
   if (funcOrVal instanceof Eval) {
     succ = Utils.arrayCons(funcOrVal, params);
   }
   return Utils.arrayEnumeration(succ);
 }
Esempio n. 17
0
 protected Tex find(List<ItemInfo> info) {
   GItem.NumberInfo ninf = ItemInfo.find(GItem.NumberInfo.class, info);
   if (ninf == null) return (null);
   return (new TexI(
       Utils.outline2(
           Text.render(Integer.toString(ninf.itemnum()), Color.WHITE).img,
           Utils.contrast(Color.WHITE))));
 }
Esempio n. 18
0
 public float getcz(float px, float py) {
   float tw = tilesz.x, th = tilesz.y;
   Coord ul = new Coord(Utils.floordiv(px, tw), Utils.floordiv(py, th));
   float sx = Utils.floormod(px, tw) / tw;
   float sy = Utils.floormod(py, th) / th;
   return (((1.0f - sy) * (((1.0f - sx) * getz(ul)) + (sx * getz(ul.add(1, 0)))))
       + (sy * (((1.0f - sx) * getz(ul.add(0, 1))) + (sx * getz(ul.add(1, 1))))));
 }
Esempio n. 19
0
 private static Color lighter(Color col) {
   int hsl[] = new int[3];
   Utils.rgb2hsl(col.getRed(), col.getGreen(), col.getBlue(), hsl);
   hsl[1] = Math.round(0.7f * hsl[1]);
   hsl[2] = 100;
   int rgb[] = Utils.hsl2rgb(hsl);
   return new Color(rgb[0], rgb[1], rgb[2]);
 }
Esempio n. 20
0
  private int printThreadGroup(OutputSink out, ThreadGroupReference tg, int iThread) {
    out.println("Group " + tg.name() + ":");
    List<ThreadReference> tlist = tg.threads();
    int maxId = 0;
    int maxName = 0;
    for (int i = 0; i < tlist.size(); i++) {
      ThreadReference thr = tlist.get(i);
      int len = Utils.description(thr).length();
      if (len > maxId) {
        maxId = len;
      }
      String name = thr.name();
      int iDot = name.lastIndexOf('.');
      if (iDot >= 0 && name.length() > iDot) {
        name = name.substring(iDot + 1);
      }
      if (name.length() > maxName) {
        maxName = name.length();
      }
    }
    String maxNumString = String.valueOf(iThread + tlist.size());
    int maxNumDigits = maxNumString.length();
    for (int i = 0; i < tlist.size(); i++) {
      ThreadReference thr = tlist.get(i);
      char buf[] = new char[80];
      for (int j = 0; j < 79; j++) {
        buf[j] = ' ';
      }
      buf[79] = '\0';
      StringBuffer sbOut = new StringBuffer();
      sbOut.append(buf);

      // Right-justify the thread number at start of output string
      String numString = String.valueOf(iThread + i + 1);
      sbOut.insert(maxNumDigits - numString.length(), numString);
      sbOut.insert(maxNumDigits, ".");

      int iBuf = maxNumDigits + 2;
      sbOut.insert(iBuf, Utils.description(thr));
      iBuf += maxId + 1;
      String name = thr.name();
      int iDot = name.lastIndexOf('.');
      if (iDot >= 0 && name.length() > iDot) {
        name = name.substring(iDot + 1);
      }
      sbOut.insert(iBuf, name);
      iBuf += maxName + 1;
      sbOut.insert(iBuf, Utils.getStatus(thr));
      sbOut.setLength(79);
      out.println(sbOut.toString());
    }
    for (ThreadGroupReference tg0 : tg.threadGroups()) {
      if (!tg.equals(tg0)) { // TODO ref mgt
        iThread += printThreadGroup(out, tg0, iThread + tlist.size());
      }
    }
    return tlist.size();
  }
  double score(IGMap map, DoubleOrientedPoint p, double[] readings) {
    double s = 0;
    int angleIndex = initialBeamsSkip;
    DoubleOrientedPoint lp = new DoubleOrientedPoint(p.x, p.y, p.theta);
    lp.x += Math.cos(p.theta) * laserPose.x - Math.sin(p.theta) * laserPose.y;
    lp.y += Math.sin(p.theta) * laserPose.x + Math.cos(p.theta) * laserPose.y;
    lp.theta += laserPose.theta;
    int skip = 0;
    double freeDelta = map.getDelta() * freeCellRatio;
    for (int rIndex = initialBeamsSkip; rIndex < readings.length; rIndex++, angleIndex++) {
      skip++;
      skip = skip > likelihoodSkip ? 0 : skip;
      if (skip != 0 || readings[rIndex] > usableRange || readings[rIndex] == 0.0) continue;
      DoublePoint phit = new DoublePoint(lp.x, lp.y);
      phit.x += readings[rIndex] * Math.cos(Utils.theta(lp.theta + laserAngles[angleIndex]));
      phit.y += readings[rIndex] * Math.sin(Utils.theta(lp.theta + laserAngles[angleIndex]));
      IntPoint iphit = map.world2map(phit);
      DoublePoint pfree = new DoublePoint(lp.x, lp.y);
      pfree.x +=
          (readings[rIndex] - map.getDelta() * freeDelta)
              * Math.cos(Utils.theta(lp.theta + laserAngles[angleIndex]));
      pfree.y +=
          (readings[rIndex] - map.getDelta() * freeDelta)
              * Math.sin(Utils.theta(lp.theta + laserAngles[angleIndex]));
      pfree.x = pfree.x - phit.x;
      pfree.y = pfree.y - phit.y;

      IntPoint ipfree = map.world2map(pfree);
      boolean found = false;
      DoublePoint bestMu = new DoublePoint(0., 0.);
      for (int xx = -kernelSize; xx <= kernelSize; xx++) {
        for (int yy = -kernelSize; yy <= kernelSize; yy++) {
          IntPoint pr = new IntPoint(iphit.x + xx, iphit.y + yy);
          IntPoint pf = new IntPoint(pr.x + ipfree.x, pr.y + ipfree.y);
          // int ss = map.getStorage().cellState(pr);
          //                    if ((ss) > 0) {
          PointAccumulator cell = (PointAccumulator) map.cell(pr, true);
          PointAccumulator fcell = (PointAccumulator) map.cell(pf, true);
          if (cell != null && fcell != null) {
            if (cell.doubleValue() > fullnessThreshold && fcell.doubleValue() < fullnessThreshold) {
              DoublePoint mu = DoublePoint.minus(phit, cell.mean());
              if (!found) {
                bestMu = mu;
                found = true;
              } else {
                bestMu = DoublePoint.mulD(mu, mu) < DoublePoint.mulD(bestMu, bestMu) ? mu : bestMu;
              }
            }
          }
          //                    }
        }
      }
      if (found) {
        s += Math.exp(-1. / (gaussianSigma * DoublePoint.mulD(bestMu, bestMu)));
      }
    }
    return s;
  }
Esempio n. 22
0
 private static String getResultType(ExecutableElement method, boolean native_stub) {
   if (native_stub && method.getAnnotation(PointerWrapper.class) != null) {
     return "long";
   } else if (!native_stub && method.getAnnotation(GLreturn.class) != null) {
     return Utils.getMethodReturnType(method, method.getAnnotation(GLreturn.class), false);
   } else {
     return Utils.getJavaType(Utils.getMethodReturnType(method)).getSimpleName();
   }
 }
 /**
  * Parses a given list of options.
  *
  * @param options the list of options as an array of strings
  * @exception Exception if an option is not supported
  */
 public void setOptions(String[] options) throws Exception {
   String optionString = Utils.getOption('A', options);
   if (optionString.length() != 0) setAlphaStar(Double.parseDouble(optionString));
   optionString = Utils.getOption('S', options);
   if (optionString.length() != 0) setSigma(Double.parseDouble(optionString));
   optionString = Utils.getOption('R', options);
   if (optionString.length() != 0) setR(Double.parseDouble(optionString));
   setUseSparseMatrix(Utils.getFlag('M', options));
 }
Esempio n. 24
0
  public void actionPerformed(ActionEvent actionevent) {
    OResource selectedNode = ((OResourceNode) selectedNodes.get(0).getUserObject()).getResource();
    String ns = selectedNode.getONodeID().getNameSpace();
    if (gate.creole.ontology.Utils.hasSystemNameSpace(selectedNode.getONodeID().toString())) {
      ns = ontology.getDefaultNameSpace();
    }
    nameSpace.setText(ns);

    nameSpace.setText(
        ontology.getDefaultNameSpace() == null
            ? "http://gate.ac.uk/example#"
            : ontology.getDefaultNameSpace());
    JOptionPane pane =
        new JOptionPane(
            mainPanel,
            JOptionPane.QUESTION_MESSAGE,
            JOptionPane.OK_CANCEL_OPTION,
            MainFrame.getIcon("ontology-instance")) {
          public void selectInitialValue() {
            instanceName.requestFocusInWindow();
            instanceName.selectAll();
          }
        };
    pane.createDialog(MainFrame.getInstance(), "New Instance").setVisible(true);
    Object selectedValue = pane.getValue();
    if (selectedValue != null
        && selectedValue instanceof Integer
        && (Integer) selectedValue == JOptionPane.OK_OPTION) {
      String s = nameSpace.getText();
      if (!Utils.isValidNameSpace(s)) {
        JOptionPane.showMessageDialog(
            MainFrame.getInstance(),
            "Invalid Name Space: " + s + "\nExample: http://gate.ac.uk/example#");
        return;
      }
      if (!Utils.isValidOntologyResourceName(instanceName.getText())) {
        JOptionPane.showMessageDialog(
            MainFrame.getInstance(), "Invalid Instance: " + instanceName.getText());
        return;
      }
      if (Utils.getOResourceFromMap(ontology, s + instanceName.getText()) != null) {
        JOptionPane.showMessageDialog(
            MainFrame.getInstance(),
            "<html>" + "Resource <b>" + s + instanceName.getText() + "</b> already exists.");
        return;
      }

      for (int i = 0; i < selectedNodes.size(); i++) {
        Object obj = ((OResourceNode) selectedNodes.get(i).getUserObject()).getResource();
        if (obj instanceof OClass) {
          ontology.addOInstance(
              ontology.createOURI(nameSpace.getText() + instanceName.getText()), (OClass) obj);
        }
      }
    }
  }
Esempio n. 25
0
 public void run() {
   try {
     InputStream in;
     OutputStream out;
     try {
       in = sk.getInputStream();
       out = sk.getOutputStream();
     } catch (IOException e) {
       throw (new RuntimeException(e));
     }
     while (true) {
       try {
         int len = Utils.int32d(read(in, 4), 0);
         if (!auth && (len > 256)) return;
         Message msg = new MessageBuf(read(in, len));
         String cmd = msg.string();
         Object[] args = msg.list();
         Object[] reply;
         if (auth) {
           Command cc = commands.get(cmd);
           if (cc != null) reply = cc.run(this, args);
           else reply = new Object[] {"nocmd"};
         } else {
           if (cmd.equals("nonce")) {
             reply = new Object[] {nonce};
           } else if (cmd.equals("auth")) {
             if (Arrays.equals((byte[]) args[0], ckey)) {
               reply = new Object[] {"ok"};
               auth = true;
             } else {
               reply = new Object[] {"no"};
             }
           } else {
             return;
           }
         }
         MessageBuf rb = new MessageBuf();
         rb.addlist(reply);
         byte[] rbuf = new byte[4 + rb.size()];
         Utils.uint32e(rb.size(), rbuf, 0);
         rb.fin(rbuf, 4);
         out.write(rbuf);
       } catch (IOException e) {
         return;
       }
     }
   } catch (InterruptedException e) {
   } finally {
     try {
       sk.close();
     } catch (IOException e) {
       throw (new RuntimeException(e));
     }
   }
 }
Esempio n. 26
0
  private static void recomputeTrainTestSets(TrainAndTestReport r) { // TODO a nicer way? :)
    if (r instanceof TrainAndTestReportCrisp) {
      TrainAndTestReportCrisp rep = (TrainAndTestReportCrisp) r;
      double[] newFittedValues =
          Arrays.copyOfRange(rep.getFittedValues(), 0, rep.getNumTrainingEntries());
      double[] newForecastValsTest =
          Arrays.copyOfRange(
              rep.getFittedValues(), rep.getNumTrainingEntries(), rep.getFittedValues().length);
      rep.setFittedValues(newFittedValues);
      rep.setForecastValuesTest(newForecastValsTest);
      double[] newRealTrain =
          Arrays.copyOfRange(rep.getRealOutputsTrain(), 0, rep.getNumTrainingEntries());
      double[] newRealTest =
          Arrays.copyOfRange(
              rep.getRealOutputsTrain(),
              rep.getNumTrainingEntries(),
              rep.getRealOutputsTrain().length);
      rep.setRealOutputsTrain(newRealTrain);
      rep.setRealOutputsTest(newRealTest);
      rep.setErrorMeasures(
          ErrorMeasuresUtils.computeAllErrorMeasuresCrisp(
              Utils.arrayToList(newRealTrain),
              Utils.arrayToList(newRealTest),
              Utils.arrayToList(newFittedValues),
              Utils.arrayToList(newForecastValsTest),
              0)); // TODO I hope the 0 is not a problem
    } else if (r instanceof TrainAndTestReportInterval) {
      TrainAndTestReportInterval rep = (TrainAndTestReportInterval) r;
      List<Interval> newFittedValues =
          new ArrayList<>(rep.getFittedValues().subList(0, rep.getNumTrainingEntries()));
      List<Interval> newForecastValsTest =
          new ArrayList<>(
              rep.getFittedValues()
                  .subList(rep.getNumTrainingEntries(), rep.getFittedValues().size()));
      rep.setFittedValues(newFittedValues);
      rep.setForecastValuesTest(newForecastValsTest);

      List<Interval> realVals =
          Utils.zipLowerUpperToIntervals(rep.getRealValuesLowers(), rep.getRealValuesUppers());
      List<Interval> realValsTrain =
          new ArrayList<>(realVals.subList(0, rep.getNumTrainingEntries()));
      List<Interval> realValsTest =
          new ArrayList<>(realVals.subList(rep.getNumTrainingEntries(), realVals.size()));

      // TODO somehow add the actual distance and seasonality from params
      rep.setErrorMeasures(
          ErrorMeasuresUtils.computeAllErrorMeasuresInterval(
              realValsTrain,
              realValsTest,
              newFittedValues,
              newForecastValsTest,
              new WeightedEuclideanDistance(0.5),
              0));
    }
  }
Esempio n. 27
0
 public Spec(Indir<Resource> res, Message sdt, int num) {
   this.res = res;
   this.sdt = new MessageBuf(sdt);
   if (num >= 0)
     this.num =
         new TexI(
             Utils.outline2(
                 Text.render(Integer.toString(num), Color.WHITE).img,
                 Utils.contrast(Color.WHITE)));
   else this.num = null;
 }
Esempio n. 28
0
    @Override
    public double getDouble(int i) {
      assert Utils.check(i < size, "bounds check");
      assert Utils.check(i >= 0, "bounds check");

      if (i < excludeIndex) {
        return orig.getDouble(i);
      } else {
        return orig.getDouble(i + 1);
      }
    }
Esempio n. 29
0
 @Override
 protected <N extends RNode> N replaceChild(RNode oldNode, N newNode) {
     assert oldNode != null;
     if (callNode == oldNode) {
         callNode = newNode;
         return adoptInternal(newNode);
     }
     assert Utils.check(oldNode != callableProvider); // this not must not be rewritten
     assert Utils.check(oldNode != xArgProvider);
     assert Utils.check(oldNode != yArgProvider);
     return super.replaceChild(oldNode, newNode);
 }
Esempio n. 30
0
  /*@ helper @*/
  public static Boolean inv_R1(final project.Entrytypes.R2 _r2) {
    Object obj_2 = _r2.t3;
    project.Entrytypes.R4 apply_6 = null;

    if (obj_2 instanceof project.Entrytypes.R3) {
      apply_6 = Utils.copy(((project.Entrytypes.R3) obj_2).r4);
    } else {
      throw new RuntimeException("Missing member: r4");
    }

    return !(Utils.equals(apply_6.x, 1L));
  }