Exemple #1
0
  /**
   * Parse a string value and covert it to its proper data type.
   *
   * @param value
   * @return The parsed value.
   * @throws ParsingException Thrown if not Advisory is available and there was an error parsing.
   */
  @SuppressWarnings("unchecked")
  public static <T> T parseValue(String value) throws ParsingException {
    final T result;

    assert value != null;

    /*
     * todo Restructure the whole class so I've got parse and parseArray as
     * static methods and the share code properly.
     */
    if ("null".equals(value)) {
      result = null;
    } else {
      final List<Object> list = new ArrayList<>();
      final Text t = new Text();
      t.append(value);

      if (any(t, list) && t.isEof()) {
        result = (T) list.get(0);
      } else {
        error("Count not parse value: " + value);
        result = null;
      }
    }

    return result;
  }
Exemple #2
0
  /**
   * Parse a value.
   *
   * @param tb Source.
   * @param type The type of the array, may be any..
   * @param valueList Result added here.
   * @return Return true if a value has been added to the valueList and the cursor advanced or false
   *     and the cursor is as it was.
   */
  private static boolean value(Text t, DataType type, List<Object> valueList) {
    boolean result;

    if (t.isEof()) {
      result = false;
    } else if (t.consume("null")) {
      valueList.add(null);
      result = true;
    } else {
      switch (type) {
        case z:
        case Z:
        case f:
        case F:
          result = number(t, type, valueList);
          break;

        case text:
          result = text(t, valueList);
          break;

        case identifier:
          result = identifier(t, valueList);
          break;

        case path:
          result = path(t, valueList);
          break;

        case datetime:
          result = datetime(t, valueList);
          break;

        case date:
          result = date(t, valueList);
          break;

        case time:
          result = time(t, valueList);
          break;

        case bool:
          result = bool(t, valueList);
          break;

        case cardinality:
          result = cardinality(t, valueList);
          break;

        case any:
          result = any(t, valueList);
          break;

        default:
          throw new UnexpectedException("value: " + type);
      }
    }

    return result;
  }
Exemple #3
0
  private static boolean number(Text t, DataType requiredType, List<Object> valueList) {
    // posNumber
    // : cardinality
    // | '0b' BinaryDigits+ [zZ]?
    // | '0x' HexDigit+ [zZ]?
    // | '-'? Pint? ( '.' Digit+ ) ('e' Pint) [fF]
    // | '-'? Pint [zZfF]?
    // ;
    final boolean result;

    assert !t.isEof() : "Should have been checked by caller";

    if (binary(t, valueList, requiredType) || hex(t, valueList, requiredType)) {
      // ?todo I could allow negatives here
      // ( binary | hex | '0' )
      result = true;
    } else {
      // ( Int DecPart | Int | DecPart ) ( 'e' Int )? [zZfF]?

      final int start = t.cursor();

      if ((t.consumeInt() && (decPart(t) || true) && (exponent(t) || true))
          || (t.consume('-') || true) && decPart(t) && (exponent(t) || true)) {
        final String string = t.getString(start);
        final Object value = deriveType(string, requiredType, t, 10);
        valueList.add(value);
        result = true;
      } else {
        result = false;
      }
    }
    return result;
  }
 @EventHandler(priority = EventPriority.NORMAL)
 public void onEntityDamageByEntity(final EntityDamageByEntityEvent e) {
   Entity ent = e.getEntity();
   Entity entDamager = e.getDamager();
   if ((ent instanceof Player) && (entDamager instanceof Player)) {
     GamePlayer rmp = GamePlayer.getPlayerByName(((Player) ent).getName());
     GamePlayer rmpDamager = GamePlayer.getPlayerByName(((Player) entDamager).getName());
     if ((rmp != null) && (rmpDamager != null)) {
       if ((rmp.isIngame()) && (rmpDamager.isIngame())) {
         GameConfig config = rmp.getGame().getGameConfig();
         Timer pvpTimer = config.getPvpTimer();
         if (!config.getSettingBool(Setting.allowpvp)) {
           e.setCancelled(true);
         } else if (rmp.getTeam() == rmpDamager.getTeam()) {
           if (!config.getSettingBool(Setting.friendlyfire)) {
             e.setCancelled(true);
           }
         } else if ((rmp.isSafe()) || (rmpDamager.isSafe())) {
           e.setCancelled(true);
           rmpDamager.sendMessage(Text.getLabel("game.safezone.pvp"));
         } else if ((pvpTimer.isSet()) && (pvpTimer.isTicking())) {
           e.setCancelled(true);
           // rmpDamager.sendMessage(RMText.getLabelArgs("game.pvp.delay",
           // pvpTimer.getTextTimeRemaining()));
           rmpDamager.sendMessage(Text.getLabelArgs("game.pvp.disabled"));
         }
       }
     }
   }
 }
    // specify input and out keys
    public void map(
        LongWritable key, Text value, OutputCollector<Text, Text> output, Reporter reporter)
        throws IOException {
      String line = value.toString(); // define new variable to be string

      ArrayList<Integer> range = new ArrayList<Integer>();
      for (int i = 2000; i <= 2010; i++) {
        range.add(i);
      }

      // String[] inputs = line.split(",(?=([^\"]*\"[^\"]*\")*[^\"]*$)");
      String[] inputs = line.split(",");

      try {

        int year = Integer.parseInt(inputs[165]);

        if (range.contains(year)) {
          String dur = inputs[3];
          String artist_name = inputs[2];
          String song_title = inputs[1];
          String final_input = artist_name + ',' + dur + ',' + song_title;
          Final_Value.set(final_input);
          output.collect(Final_Value, dummy);
        }
      } catch (NumberFormatException e) {
        // do nothing
      }
    }
 /** Serialize a {@link PermissionStatus} from its base components. */
 public static void write(
     DataOutput out, String username, String groupname, FsPermission permission)
     throws IOException {
   Text.writeString(out, username);
   Text.writeString(out, groupname);
   permission.write(out);
 }
  @Override
  protected void reduce(Text key, Iterable<Text> vals, Context ctx) {
    String name = null;
    String year = null;

    for (Text xx : vals) {
      String[] parts = xx.toString().split("=");

      if (parts[0].equals("name")) {
        name = parts[1];
      }

      if (parts[0].equals("year")) {
        year = parts[1];
      }
    }

    try {
      if (name != null && year != null) {
        ctx.write(new Text(year), new Text(name));
      }
    } catch (Exception ee) {
      ee.printStackTrace(System.err);
      throw new Error("I give up");
    }
  }
Exemple #8
0
  private static AbstractCanvasObject createText(Element elt) {
    int x = Integer.parseInt(elt.getAttribute("x"));
    int y = Integer.parseInt(elt.getAttribute("y"));
    String text = elt.getTextContent();
    Text ret = new Text(x, y, text);

    String fontFamily = elt.getAttribute("font-family");
    String fontStyle = elt.getAttribute("font-style");
    String fontWeight = elt.getAttribute("font-weight");
    String fontSize = elt.getAttribute("font-size");
    int styleFlags = 0;
    if (fontStyle.equals("italic")) styleFlags |= Font.ITALIC;
    if (fontWeight.equals("bold")) styleFlags |= Font.BOLD;
    int size = Integer.parseInt(fontSize);
    ret.setValue(DrawAttr.FONT, new Font(fontFamily, styleFlags, size));

    String alignStr = elt.getAttribute("text-anchor");
    AttributeOption halign;
    if (alignStr.equals("start")) {
      halign = DrawAttr.ALIGN_LEFT;
    } else if (alignStr.equals("end")) {
      halign = DrawAttr.ALIGN_RIGHT;
    } else {
      halign = DrawAttr.ALIGN_CENTER;
    }
    ret.setValue(DrawAttr.ALIGNMENT, halign);

    // fill color is handled after we return
    return ret;
  }
  public void init(
      @NonNull View view, @Nullable AttributeSet attrs, @NonNull TextPaint baseTextPaint) {
    final Context context = view.getContext();
    final int defColor = baseTextPaint.getColor();
    final int defPadding =
        context.getResources().getDimensionPixelSize(R.dimen.drag_direction_text_default_padding);
    final float minTextSize =
        context.getResources().getDimensionPixelSize(R.dimen.drag_direction_text_min_size);

    if (attrs == null) {
      for (DragDirection direction : DragDirection.values()) {
        final Text text = new Text(direction, view, minTextSize);
        text.init(baseTextPaint, null, DEF_SCALE, defColor, DEF_ALPHA, defPadding);
        texts.put(direction, text);
      }
      return;
    }
    final TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.DirectionText);
    final float scale = array.getFloat(R.styleable.DirectionText_directionTextScale, DEF_SCALE);
    final float alpha = array.getFloat(R.styleable.DirectionText_directionTextAlpha, DEF_ALPHA);
    final int color = array.getColor(R.styleable.DirectionText_directionTextColor, defColor);
    final int padding =
        array.getDimensionPixelSize(R.styleable.DirectionText_directionTextPadding, defPadding);
    for (DragDirection direction : DragDirection.values()) {
      final Text text = new Text(direction, view, minTextSize);
      text.init(baseTextPaint, array, scale, color, alpha, padding);
      texts.put(direction, text);
    }
    array.recycle();
  }
 @Override
 public Token tokenizeOnly(Text text, ObjectSupply objectSupply) throws SyntaxErrorException {
   Token leading = this.leader.tokenizeOnly(text, objectSupply);
   if (leading == null) {
     return null;
   }
   TSequence foundTokens = objectSupply.newSequence(this.getMaxSequenceCount());
   foundTokens.addToken(leading);
   if (text.onChar()) {
     int textIndex = text.getIndex();
     for (TFSequence follower : this.followers) {
       foundTokens.resetIndex(1);
       Token result = follower.tokenizeCommon(text, objectSupply, 1, foundTokens, true);
       if (result != null) {
         TokenFactory f0th = follower.getFactory(0);
         Token replaced = f0th.convert(leading);
         foundTokens.set(0, replaced);
         foundTokens.setLength(follower.getSequenceCount());
         return follower.convert(result);
       }
       text.resetIndex(textIndex);
     }
   } else {
     for (TFSequence follower : this.followers) {
       if (follower.validateEnd(0, foundTokens, true)) {
         return follower.convert(foundTokens);
       }
     }
   }
   if (this.singleValid) {
     return this.leader.convert(leading);
   }
   throw new SyntaxErrorException();
 }
 public boolean equals(Object bw) {
   if (bw instanceof BigramWritable) {
     BigramWritable ow = (BigramWritable) bw;
     return leftBigram.equals(ow.leftBigram) && rightBigram.equals(ow.rightBigram);
   }
   return false;
 }
Exemple #12
0
  @Override
  public void renderHUD(Graphics2D g) {
    // TODO Auto-generated method stub
    super.renderHUD(g);

    g.drawImage(HUDBg, 0, 0, null);

    if (player.weapon != null) {

      g.drawImage(player.weapon.getHUDImage(), 123, 121, null);

      float wh = (player.weapon.bulletsLeft / (float) player.weapon.bulletsCapacity);
      drawHealth(g, wh, 121, 137, 36, 4);
    }

    // player health
    drawHealth(g, player.health / (float) player.maxHealth, 3, 137, 36, 4);

    Font f = g.getFont();
    g.setColor(Color.black);
    g.setFont(f.deriveFont(4));
    Text.drawText(g, String.format("%05d", score), 130, 5);

    Text.drawText(
        g, String.format("Day: %d", (int) Math.ceil(realtime / (float) secondsPerDay)), 66, 136);

    if (menu != null) {
      menu.render(g);
    }
  }
Exemple #13
0
  /** Check whether the file list have duplication. */
  private static void checkDuplication(FileSystem fs, Path file, Path sorted, Configuration conf)
      throws IOException {
    SequenceFile.Reader in = null;
    try {
      SequenceFile.Sorter sorter =
          new SequenceFile.Sorter(fs, new Text.Comparator(), Text.class, Text.class, conf);
      sorter.sort(file, sorted);
      in = new SequenceFile.Reader(fs, sorted, conf);

      Text prevdst = null, curdst = new Text();
      Text prevsrc = null, cursrc = new Text();
      for (; in.next(curdst, cursrc); ) {
        if (prevdst != null && curdst.equals(prevdst)) {
          throw new DuplicationException(
              "Invalid input, there are duplicated files in the sources: "
                  + prevsrc
                  + ", "
                  + cursrc);
        }
        prevdst = curdst;
        curdst = new Text();
        prevsrc = cursrc;
        cursrc = new Text();
      }
    } finally {
      checkAndClose(in);
    }
  }
Exemple #14
0
 public boolean overlapsWith(Text t) {
   float tY1 = t.getLocation().getY();
   float tY2 = tY1 + t.getLocation().getHeight();
   float rowY1 = location.getY();
   float rowY2 = rowY1 + location.getHeight();
   return (tY1 <= rowY1 && rowY1 <= tY2) || (rowY1 <= tY1 && tY1 <= rowY2);
 }
  public IReason updateNeeded(IUpdateContext context) {
    // retrieve name from pictogram model
    String pictogramName = null;
    PictogramElement pictogramElement = context.getPictogramElement();
    if (pictogramElement instanceof ContainerShape) {
      ContainerShape cs = (ContainerShape) pictogramElement;
      for (Shape shape : cs.getChildren()) {
        if (shape.getGraphicsAlgorithm() instanceof Text) {
          Text text = (Text) shape.getGraphicsAlgorithm();
          pictogramName = text.getValue();
        }
      }
    }

    // retrieve name from business model
    String businessName = null;
    Object bo = getBusinessObjectForPictogramElement(pictogramElement);
    if (bo instanceof EClass) {
      EClass eClass = (EClass) bo;
      businessName = eClass.getName();
    }

    // update needed, if names are different
    boolean updateNameNeeded =
        ((pictogramName == null && businessName != null)
            || (pictogramName != null && !pictogramName.equals(businessName)));
    if (updateNameNeeded) {
      return Reason.createTrueReason("Name is out of date");
    } else {
      return Reason.createFalseReason();
    }
  }
Exemple #16
0
 /**
 * Initialization
 */
 public void begin(){
   int bx = 0;
   int by = 0;
   int px = 0;
   int py = 0;
   for(int i = 0; i < IMG_NUM; i++){
     
     bx = BOARD_MARGIN_X + SIDE_LENGTH * (i % PIECES_PER_COL);
     by = BOARD_MARGIN_Y + SIDE_LENGTH * (i / PIECES_PER_ROW);
     px = PUZZLE_OFFSET + PUZZLE_SPACING * 
         (i % PIECES_PER_COL + 1) + SIDE_LENGTH * 
         (i % PIECES_PER_COL);
     py = PUZZLE_SPACING * (i / PIECES_PER_ROW + 1) + 
         SIDE_LENGTH * (i / PIECES_PER_ROW);
     //x,y coordination of puzzle & board pieces
     
     img[i] = getImage("p" + i + ".jpg");
     bLocation[i] = new Location(bx, by);
     pLocation[i] = new Location(px, py);
   }
   text = new Text("YOU WIN!!!", TEXT_X,
       bLocation[TEXT_LOCATION].getY(), canvas);
   text.setFontSize(FONT_SIZE);
   text.setBold(true);
   text.setColor(Color.GREEN);
   text.hide();
   
   //pass pieces objects into arrays
   for(int i = 0; i < IMG_NUM; i++){
     bp[i] = new BoardPiece(img[i], i, bLocation[i], canvas);
     pp[i] = getRandomPiece(pLocation[i], canvas);
   }
   
 }
  private final String getTextBestFit(final Context2D context, final String text, final int wide) {
    double pt = LienzoCore.get().getDefaultFontSize();

    String st = LienzoCore.get().getDefaultFontStyle();

    String fm = LienzoCore.get().getDefaultFontFamily();

    String tf = Text.getFontString(pt, TextUnit.PT, st, fm);

    context.save();

    context.setToIdentityTransform();

    while (true) {
      context.setTextFont(tf);

      final TextMetrics tm = context.measureText(text);

      if (tm.getWidth() < wide) {
        break;
      }
      pt = pt - 2;

      if (pt < 6) {
        break;
      }
      tf = Text.getFontString(pt, TextUnit.PT, st, fm);
    }
    context.restore();

    return tf;
  }
Exemple #18
0
    public void map(LongWritable key, Text value, Context context)
        throws IOException, InterruptedException {
      String line = value.toString();
      String[] arr = line.split(",");

      word.set(arr[0]);
      context.write(word, one);
    }
  public void enterNamedAttribute() {
    Text name = Text.empty();
    Text value = Text.empty();
    attList.add(Attribute.of(name, value));

    textObjects.push(value);
    textObjects.push(name);
  }
 @Test
 public void get() throws Exception {
   // vv MapFileSeekTest
   Text value = new Text();
   reader.get(new IntWritable(496), value);
   assertThat(value.toString(), is("One, two, buckle my shoe"));
   // ^^ MapFileSeekTest
 }
 // Identity
 public void reduce(Text key, Iterable<Text> values, Context context)
     throws IOException, InterruptedException {
   System.out.println("I'm in Job1 reduce");
   for (Text val : values) {
     System.out.println("job1:redInp:-" + val.toString());
     context.write(new Text(""), val);
   }
 }
 /**
  * @param text element definition
  * @return pattern element for text
  */
 private ProcPatternElement create(Text text) {
   Scope scope = text.getScope();
   if (scope != null) {
     return new ProcText(text.getName(), createScope(scope), text.isTransparent());
   } else {
     return new ProcText(text.getName(), text.isTransparent());
   }
 }
  /**
   * @param sourceFile File to read from
   * @return List of String objects with the shas
   */
  public static FileRequestFileContent readRequestFile(final File sourceFile) {
    if (!sourceFile.isFile() || !(sourceFile.length() > 0)) {
      return null;
    }
    Document d = null;
    try {
      d = XMLTools.parseXmlFile(sourceFile.getPath());
    } catch (final Throwable t) {
      logger.log(Level.SEVERE, "Exception in readRequestFile, during XML parsing", t);
      return null;
    }

    if (d == null) {
      logger.log(Level.SEVERE, "Could'nt parse the request file");
      return null;
    }

    final Element rootNode = d.getDocumentElement();

    if (rootNode.getTagName().equals(TAG_FrostFileRequestFile) == false) {
      logger.severe(
          "Error: xml request file does not contain the root tag '"
              + TAG_FrostFileRequestFile
              + "'");
      return null;
    }

    final String timeStampStr = XMLTools.getChildElementsTextValue(rootNode, TAG_timestamp);
    if (timeStampStr == null) {
      logger.severe("Error: xml file does not contain the tag '" + TAG_timestamp + "'");
      return null;
    }
    final long timestamp = Long.parseLong(timeStampStr);

    final List<Element> nodelist = XMLTools.getChildElementsByTagName(rootNode, TAG_shaList);
    if (nodelist.size() != 1) {
      logger.severe("Error: xml request files must contain only one element '" + TAG_shaList + "'");
      return null;
    }

    final Element rootShaNode = nodelist.get(0);

    final List<String> shaList = new LinkedList<String>();
    final List<Element> xmlKeys = XMLTools.getChildElementsByTagName(rootShaNode, TAG_sha);
    for (final Element el : xmlKeys) {

      final Text txtname = (Text) el.getFirstChild();
      if (txtname == null) {
        continue;
      }

      final String sha = txtname.getData();
      shaList.add(sha);
    }

    final FileRequestFileContent content = new FileRequestFileContent(timestamp, shaList);
    return content;
  }
Exemple #24
0
  /**
   * Replaces ASCII CRLF's with HTML &lt;br;&gt;'s, first removing &lt;br&gt;'s and &lt;p&gt;'s.
   *
   * @param o text to format
   * @return formatted text or &amp;nbsp; if text is <code>null</code> or empty
   */
  public static String formatLineBreaks(Object o) {
    String s = format(o);

    s = Text.replace(s, "<br>", "");
    s = Text.replace(s, "<p>", "");
    s = Text.replace(s, "\r\n", "<br />");

    return s;
  }
 public void map(LongWritable key, Text value, Context context)
     throws IOException, InterruptedException {
   Text word = new Text();
   StringTokenizer s = new StringTokenizer(value.toString());
   while (s.hasMoreTokens()) {
     word.set(s.nextToken());
     context.write(word, one);
   }
 }
 public void map(LongWritable key, Text value, Context context)
     throws IOException, InterruptedException {
   String line = value.toString();
   StringTokenizer tokenizer = new StringTokenizer(line);
   while (tokenizer.hasMoreTokens()) {
     word.set(tokenizer.nextToken());
     context.write(word, one);
   }
 }
Exemple #27
0
	/**
	 * method that will be called when mouse clicks
	 * @param point , the point mouse click at
	 */
	public void onMouseClick(Location point) {
		if(!isShown){
			mouse = new Deadmau5(point, canvas);
			instr1.hide();
			instr2.hide();
			instr3.hide();
			isShown = true;
		}
	}
Exemple #28
0
  @Override
  public void start(Stage primaryStage) throws Exception {
    GridPane grid = new GridPane();
    grid.setAlignment(Pos.CENTER);
    grid.setVgap(10);
    grid.setHgap(10);
    grid.setPadding(new Insets(25, 25, 25, 25));

    Scene sc = new Scene(grid, 500, 500);

    String css = Main.class.getResource("Login.css").toExternalForm();
    //        System.out.println(css);
    sc.getStylesheets().add(css);

    Text scenetitle = new Text("Welcome");
    //        scenetitle.setFont(Font.font("Tahoma", FontWeight.NORMAL, 20));
    grid.add(scenetitle, 0, 0, 1, 1);

    Label userName = new Label("User Name:");
    grid.add(userName, 0, 1);

    TextField userTextField = new TextField("Мудак");
    grid.add(userTextField, 1, 1);

    Label pw = new Label("Password:"******"Sign in");
    HBox hbBtn = new HBox(10);
    hbBtn.setAlignment(Pos.BOTTOM_RIGHT);
    hbBtn.getChildren().add(btn);
    grid.add(hbBtn, 1, 4);

    final Text actiontarget = new Text();
    grid.add(actiontarget, 1, 6);

    btn.setOnAction(
        new EventHandler<ActionEvent>() {
          @Override
          public void handle(ActionEvent event) {
            //                actiontarget.setFill(Color.FIREBRICK);
            actiontarget.setText("Pressed");
          }
        });

    //        grid.setGridLinesVisible(true);

    scenetitle.setId("welc");
    actiontarget.setId("act");

    primaryStage.setScene(sc);
    primaryStage.setTitle("Hello World");
    primaryStage.show();
  }
 public void map(LongWritable key, Text value, OutputCollector output, Reporter reporter)
     throws IOException {
   String line = value.toString();
   StringTokenizer tokenizer = new StringTokenizer(line);
   while (tokenizer.hasMoreTokens()) {
     word.set(tokenizer.nextToken());
     output.collect(word, one);
   }
 }
Exemple #30
0
  /**
   * Given the parsing context and what numerical data type is expected convert a string to the
   * correct type. Note no attempt is made to let the magnitude of the number influence our choice.
   *
   * @param string The string to convert to a number. E.g. "123.3e2". If it contains a '.' or an 'e'
   *     then the type must either be f or F.
   * @param requiredType Either z, Z, f, F or any.
   * @param tb The source. The cursor will be at the end of the number but any type specifier will
   *     not have been consumed. If there is one then we'll eat it.
   * @return The derived type.
   * @throws ParsingException If there is a clash of types.
   */
  private static Object deriveType(String string, DataType requiredType, Text t, int radix) {
    final Object result;

    // Figure out the correct type...
    final DataType derivedType;
    if (t.isEof()) {
      if (requiredType == DataType.any) {
        if (string.indexOf('.') >= 0 || string.indexOf('e') >= 0) {
          derivedType = DataType.f;
        } else {
          derivedType = DataType.z;
        }
      } else {
        derivedType = requiredType;
      }
    } else {
      final char c = t.peek();
      if (c == 'z' || c == 'Z' || c == 'f' || c == 'F') {
        t.consume(c);
        derivedType = DataType.valueOf(String.valueOf(c));
        if (!(requiredType == DataType.any || requiredType == derivedType)) {
          throw new ParsingException("Incompatible type: " + string + c);
        }
      } else {
        if (requiredType == DataType.any) {
          if (string.indexOf('.') >= 0 || string.indexOf('e') >= 0) {
            derivedType = DataType.f;
          } else {
            derivedType = DataType.z;
          }
        } else {
          derivedType = requiredType;
        }
      }
    }

    switch (derivedType) {
      case z:
        result = new Long(Long.parseLong(string, radix));
        break;
      case Z:
        result = new BigInteger(string, radix);
        break;
      case f:
        result = new Double(string);
        break;
      case F:
        result = new BigDecimal(string);
        break;
        // $CASES-OMITTED$
      default:
        throw new UnexpectedException("toType: " + derivedType);
    }

    return result;
  }