id
stringlengths
36
36
text
stringlengths
1
1.25M
40df9d24-9569-4536-93fb-4a080b60ff0b
public Color getCurrentLineForeground() { return currentLineForeground == null ? getForeground() : currentLineForeground; }
1d921d89-5f33-4c2b-9ab1-64c95a58aa08
public void setCurrentLineForeground(Color currentLineForeground) { this.currentLineForeground = currentLineForeground; }
b0f5cb12-17e3-41e9-b20a-70dd426fd1e3
public float getDigitAlignment() { return digitAlignment; }
69580155-8741-4787-adca-e93a2e8bc32b
public void setDigitAlignment(float digitAlignment) { this.digitAlignment = digitAlignment > 1.0f ? 1.0f : digitAlignment < 0.0f ? -1.0f : digitAlignment; }
5e516a91-c59a-4648-a317-f94dada65b4a
public int getMinimumDisplayDigits() { return minimumDisplayDigits; }
558e77ef-a4d9-422d-ae98-6a254e3a7202
public void setMinimumDisplayDigits(int minimumDisplayDigits) { this.minimumDisplayDigits = minimumDisplayDigits; setPreferredWidth(); }
b2a1dec9-38c0-4f17-98de-1008c76366fc
private void setPreferredWidth() { Element root = component.getDocument().getDefaultRootElement(); int lines = root.getElementCount(); int digits = Math.max(String.valueOf(lines).length(), minimumDisplayDigits); // Update sizes when number of digits in the line number changes if (lastDigits != digits) { lastDigits = digits; FontMetrics fontMetrics = getFontMetrics(getFont()); int width = fontMetrics.charWidth('0') * digits; Insets insets = getInsets(); int preferredWidth = insets.left + insets.right + width; Dimension d = getPreferredSize(); d.setSize(preferredWidth, HEIGHT); setPreferredSize(d); setSize(d); } }
0a62e3cb-f5fa-40ab-9e6c-4a5a40a508c4
@Override public void paintComponent(Graphics g) { super.paintComponent(g); // Determine the width of the space available to draw the line number FontMetrics fontMetrics = component.getFontMetrics(component.getFont()); Insets insets = getInsets(); int availableWidth = getSize().width - insets.left - insets.right; // Determine the rows to draw within the clipped bounds. Rectangle clip = g.getClipBounds(); int rowStartOffset = component.viewToModel(new Point(0, clip.y)); int endOffset = component.viewToModel(new Point(0, clip.y + clip.height)); while (rowStartOffset <= endOffset) { try { if (isCurrentLine(rowStartOffset)) g.setColor(getCurrentLineForeground()); else g.setColor(getForeground()); // Get the line number as a string and then determine the // "X" and "Y" offsets for drawing the string. String lineNumber = getTextLineNumber(rowStartOffset); int stringWidth = fontMetrics.stringWidth(lineNumber); int x = getOffsetX(availableWidth, stringWidth) + insets.left; int y = getOffsetY(rowStartOffset, fontMetrics); g.drawString(lineNumber, x, y); // Move to the next row rowStartOffset = Utilities.getRowEnd(component, rowStartOffset) + 1; } catch (Exception e) { break; } } }
bfa019db-5bbb-41df-b4b3-89c39bc744bd
private boolean isCurrentLine(int rowStartOffset) { int caretPosition = component.getCaretPosition(); Element root = component.getDocument().getDefaultRootElement(); if (root.getElementIndex(rowStartOffset) == root.getElementIndex(caretPosition)) { return true; } else { return false; } }
fe11c0e9-6901-4eef-b953-78dfa92615de
protected String getTextLineNumber(int rowStartOffset) { Element root = component.getDocument().getDefaultRootElement(); int index = root.getElementIndex(rowStartOffset); Element line = root.getElement(index); if (line.getStartOffset() == rowStartOffset) return String.valueOf(index + 1); else return ""; }
776c0611-3569-45e9-9a9a-c640b72bf433
private int getOffsetX(int availableWidth, int stringWidth) { return (int) ((availableWidth - stringWidth) * digitAlignment); }
70464fdb-0568-45d1-8537-2603eb81b320
private int getOffsetY(int rowStartOffset, FontMetrics fontMetrics) throws BadLocationException { // Get the bounding rectangle of the row Rectangle r = component.modelToView(rowStartOffset); int lineHeight = fontMetrics.getHeight(); int y = r.y + r.height; int descent = 0; // The text needs to be positioned above the bottom of the bounding // rectangle based on the descent of the font(s) contained on the row. if (r.height == lineHeight) // default font is being used { descent = fontMetrics.getDescent(); } else // We need to check all the attributes for font changes { if (fonts == null) fonts = new HashMap<>(); Element root = component.getDocument().getDefaultRootElement(); int index = root.getElementIndex(rowStartOffset); Element line = root.getElement(index); for (int i = 0; i < line.getElementCount(); i++) { Element child = line.getElement(i); AttributeSet as = child.getAttributes(); String fontFamily = (String) as.getAttribute(StyleConstants.FontFamily); Integer fontSize = (Integer) as.getAttribute(StyleConstants.FontSize); String key = fontFamily + fontSize; FontMetrics fm = fonts.get(key); if (fm == null) { Font font = new Font(fontFamily, Font.PLAIN, fontSize); fm = component.getFontMetrics(font); fonts.put(key, fm); } descent = Math.max(descent, fm.getDescent()); } } return y - descent; }
3de06fed-c634-49eb-86cf-ff4b62813695
@Override public void caretUpdate(CaretEvent e) { // Get the line the caret is positioned on int caretPosition = component.getCaretPosition(); Element root = component.getDocument().getDefaultRootElement(); int currentLine = root.getElementIndex(caretPosition); // Need to repaint so the correct line number can be highlighted if (lastLine != currentLine) { repaint(); lastLine = currentLine; } }
2b9d08a3-11b9-4921-a295-ee69200efbb8
@Override public void changedUpdate(DocumentEvent e) { documentChanged(); }
07883043-c09d-4662-9a0d-6d51d7dc6c11
@Override public void insertUpdate(DocumentEvent e) { documentChanged(); }
4250d959-311d-4cfb-b996-08547e40e7d0
@Override public void removeUpdate(DocumentEvent e) { documentChanged(); }
e79a4c66-ff1e-450b-8f86-fdd7058bf234
private void documentChanged() { // View of the component has not been updated at the time // the DocumentEvent is fired SwingUtilities.invokeLater(() -> { try { int endPos = component.getDocument().getLength(); Rectangle rect = component.modelToView(endPos); if (rect != null && rect.y != lastHeight) { setPreferredWidth(); repaint(); lastHeight = rect.y; } } catch (BadLocationException ex) { /* nothing to do */ } }); }
63dd066f-a5bc-4ab0-91f3-b04e9fa251f3
@Override public void propertyChange(PropertyChangeEvent evt) { if (evt.getNewValue() instanceof Font) { if (updateFont) { Font newFont = (Font) evt.getNewValue(); setFont(newFont); lastDigits = 0; setPreferredWidth(); } else { repaint(); } } }
b9ce637f-62ff-4c97-bbdc-bedd64f4a1cf
public HeadGiveCommand(TrophyHeads plugin) { this.plugin = plugin; }
dff191cc-0557-4427-99f7-25fa54ae506f
@Override public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { if (sender.hasPermission("trophyheads.give")) { if (args.length >= 2) { Player player = null; String pName = args[1]; for (Player pl : plugin.getServer().getOnlinePlayers()) { if (args[0].equalsIgnoreCase(pl.getName())) { player = pl; } } if (player == null) { sender.sendMessage(ChatColor.RED + "Player " + ChatColor.WHITE + args[0] + ChatColor.RED + " not found!"); return true; } int count = 1; if (args.length == 3) { if (args[1].matches("\\d+")) { count = Integer.parseInt(args[1]); } } List<String> lore = new ArrayList<>(); if (args.length >= 4) { String m = ""; for (int i = 3; i < args.length; i++) { m = m + " " + args[i]; } lore.add(ChatColor.translateAlternateColorCodes('&', m.substring(1))); } ItemStack item = new ItemStack(Material.SKULL_ITEM, count, (byte) 3); Location loc = player.getLocation().clone(); World world = loc.getWorld(); ItemMeta itemMeta = item.getItemMeta(); ((SkullMeta) itemMeta).setOwner(pName); if (!lore.isEmpty()) { ((SkullMeta) itemMeta).setLore(lore); } item.setItemMeta(itemMeta); plugin.logDebug("Skull: " + item.toString()); if (player.getInventory().firstEmpty() > -1) { player.sendMessage("Placed " + ChatColor.GOLD + pName + "'s head " + ChatColor.RESET + " in your inventory."); player.getInventory().setItem(player.getInventory().firstEmpty(), item); } else { player.sendMessage("Dropped " + ChatColor.GOLD + pName + "'s head" + ChatColor.RESET + " on the ground because your inventory was full."); world.dropItemNaturally(loc, item); } } else { sender.sendMessage("Usage: /headgive <player> <skull name> <count> <lore>"); } } else { sender.sendMessage(ChatColor.RED + "You do not have permission to use this command."); } return true; }
1d9a5f3c-6823-4341-8519-1868940e1568
public ReloadCommand(TrophyHeads plugin) { this.plugin = plugin; }
c5a7509d-7b2a-416a-8d6f-2028ec9e7146
@Override public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { if (sender.hasPermission("trophyheads.reload")) { plugin.loadTrophyConfig(sender); } else { sender.sendMessage(ChatColor.RED + "You do not have permission to run this command."); } return true; }
e0ff57c6-1f8b-4b7e-938b-2997dcc95e99
@Override public void onEnable() { LOG_HEADER = "[" + this.getName() + "]"; randomGenerator = new Random(); pluginFolder = getDataFolder(); configFile = new File(pluginFolder, "config.yml"); this.saveDefaultConfig(); loadTrophyConfig(this.getServer().getConsoleSender()); getServer().getPluginManager().registerEvents(this, this); getCommand("headspawn").setExecutor(new HeadSpawnCommand(this)); getCommand("headgive").setExecutor(new HeadGiveCommand(this)); getCommand("trophyreload").setExecutor(new ReloadCommand(this)); if (renameEnabled) { ItemStack resultHead = new ItemStack(Material.SKULL_ITEM, 1, (byte) 3); ShapelessRecipe shapelessRecipe = new ShapelessRecipe(resultHead); shapelessRecipe.addIngredient(1, Material.SKULL_ITEM); shapelessRecipe.addIngredient(1, renameItem); getServer().addRecipe(shapelessRecipe); } }
95aa1d09-6952-48ea-8368-602bf91a9454
public String getCustomSkullType(String name) { for (String key : CUSTOM_SKINS.keySet()) { if (CUSTOM_SKINS.get(key).equalsIgnoreCase(name)) { return key; } } return EntityType.UNKNOWN.toString(); }
2b41f29d-f5d9-4a79-b98a-260c55d8e216
public String getCustomSkullName(String type) { if (SKULL_NAMES.containsKey(type)) { return SKULL_NAMES.get(type); } return type; }
a791ab22-5beb-409b-950d-8d91ee49a041
@EventHandler public void onPrepareItemCraftEvent(PrepareItemCraftEvent event) { if (!renameEnabled) { return; } if (event.getRecipe() instanceof Recipe) { CraftingInventory ci = event.getInventory(); ItemStack result = ci.getResult(); if (result == null) { return; } if (result.getType().equals(Material.SKULL_ITEM)) { for (ItemStack i : ci.getContents()) { if (i.getType().equals(Material.SKULL_ITEM)) { if (i.getData().getData() != (byte) 3) { ci.setResult(new ItemStack(Material.AIR)); return; } } } for (ItemStack i : ci.getContents()) { if (i.hasItemMeta() && i.getType().equals(renameItem)) { ItemMeta im = i.getItemMeta(); if (im.hasDisplayName()) { ItemStack res = new ItemStack(Material.SKULL_ITEM, 1, (byte) 3); ItemMeta itemMeta = res.getItemMeta(); ((SkullMeta) itemMeta).setOwner(im.getDisplayName()); res.setItemMeta(itemMeta); ci.setResult(res); break; } } } } } }
41f22bc5-0461-4fc1-a477-6ab7616d928e
@EventHandler public void onPlayerInteractEvent(PlayerInteractEvent event) { Action action = event.getAction(); Player player = event.getPlayer(); if (!player.hasPermission("trophyheads.info")) { logDebug("Player does not have permission: trophyheads.info"); return; } if (action.equals(Action.RIGHT_CLICK_BLOCK)) { org.bukkit.block.Block block = event.getClickedBlock(); logDebug(action.name() + ": " + block.getType().name()); if (block.getType().equals(Material.SKULL)) { BlockState bs = block.getState(); org.bukkit.block.Skull skull = (org.bukkit.block.Skull) bs; String pName = "Unknown"; String message = ""; logDebug("Skull type: " + skull.getSkullType().name()); if (skull.getSkullType().equals(SkullType.PLAYER)) { if (skull.hasOwner()) { pName = skull.getOwner(); logDebug("Skull owner: " + pName); if (pName == null) { if (!nonTropyHeadMessage.isEmpty()) { if (rightClickCoolDowns.containsKey(player.getUniqueId())) { if (rightClickCoolDowns.get(player.getUniqueId()) >= System.currentTimeMillis()) { return; } } player.sendMessage(nonTropyHeadMessage); rightClickCoolDowns.put(player.getUniqueId(), System.currentTimeMillis() + cooldown); return; } } else if (CUSTOM_SKINS.containsValue(pName)) { message = SKULL_MESSAGES.get(getCustomSkullType(pName)); } else { message = SKULL_MESSAGES.get(EntityType.PLAYER.name()); } } else { message = SKULL_MESSAGES.get(EntityType.PLAYER.toString()); } } else if (skull.getSkullType().name().equalsIgnoreCase("Dragon")) { message = SKULL_MESSAGES.get(EntityType.ENDER_DRAGON.toString()); } else if (skull.getSkullType().toString().equals(SkullType.CREEPER.toString())) { message = SKULL_MESSAGES.get(EntityType.CREEPER.toString()); } else if (skull.getSkullType().toString().equals(SkullType.SKELETON.toString())) { message = SKULL_MESSAGES.get(EntityType.SKELETON.toString()); } else if (skull.getSkullType().toString().equals(SkullType.WITHER.toString())) { message = SKULL_MESSAGES.get("WITHER_SKELETON"); } else if (skull.getSkullType().toString().equals(SkullType.ZOMBIE.toString())) { message = SKULL_MESSAGES.get(EntityType.ZOMBIE.toString()); } else { message = SKULL_MESSAGES.get(EntityType.PLAYER.toString()); } if (pName == null) { pName = "Unknown"; } if (message == null) { message = ""; } if (INFO_BLACKLIST.contains(pName.toLowerCase())) { logDebug("Ignoring: " + pName); return; } if (rightClickCoolDowns.containsKey(player.getUniqueId())) { if (rightClickCoolDowns.get(player.getUniqueId()) >= System.currentTimeMillis()) { return; } } message = message.replace("%%NAME%%", pName); message = ChatColor.translateAlternateColorCodes('&', message); logDebug(message); player.sendMessage(message); rightClickCoolDowns.put(player.getUniqueId(), System.currentTimeMillis() + cooldown); } } }
0c3c1580-48e8-4f36-a908-4e22b4eba44a
public boolean isValidItem(EntityType et, Material mat) { if (et == null || mat == null) { return false; } try { if (ITEMS_REQUIRED.containsKey(et.name())) { if (ITEMS_REQUIRED.get(et.name()).contains("ANY")) { return true; } if (ITEMS_REQUIRED.get(et.name()).contains(String.valueOf(mat.getId()))) { return true; } else { for (String s : ITEMS_REQUIRED.get(et.name())) { if (s.toUpperCase().equals(mat.toString())) { return true; } } } } } catch (Exception ex) { logDebug("isValidItem: Catching exception: " + ex.getMessage() + " [: " + et.name() + "] [" + mat.name() + "] [" + ITEMS_REQUIRED.size() + "]"); return false; } return false; }
1d5aae56-7368-449a-8518-6e9ff9919ad2
@EventHandler public void onPlayerDeathEvent(PlayerDeathEvent event) { Player player = (Player) event.getEntity(); if (!player.hasPermission("trophyheads.drop")) { return; } if (randomGenerator.nextInt(100) >= DROP_CHANCES.get(EntityType.PLAYER.toString())) { return; } boolean dropOkay = false; DamageCause dc; if (player.getLastDamageCause() != null) { dc = player.getLastDamageCause().getCause(); logDebug("DamageCause: " + dc.toString()); } else { logDebug("DamageCause: NULL"); return; } if (DEATH_TYPES.contains(dc.toString())) { dropOkay = true; } if (DEATH_TYPES.contains("ALL")) { dropOkay = true; } if (player.getKiller() instanceof Player) { logDebug("Player " + player.getName() + " killed by another player. Checking if PVP is valid death type."); if (DEATH_TYPES.contains("PVP")) { dropOkay = isValidItem(EntityType.PLAYER, player.getKiller().getItemInHand().getType()); logDebug("PVP is a valid death type. Killer's item in hand is valid? " + dropOkay); } else { logDebug("PVP is not a valid death type."); } } if (dropOkay) { logDebug("Match: true"); Location loc = player.getLocation().clone(); World world = loc.getWorld(); String pName = player.getName(); ItemStack item = new ItemStack(Material.SKULL_ITEM, 1, (byte) 3); ItemMeta itemMeta = item.getItemMeta(); ArrayList<String> itemDesc = new ArrayList<>(); itemMeta.setDisplayName("Head of " + pName); itemDesc.add(event.getDeathMessage()); itemMeta.setLore(itemDesc); if (playerSkin) { ((SkullMeta) itemMeta).setOwner(pName); } item.setItemMeta(itemMeta); world.dropItemNaturally(loc, item); } else { logDebug("Match: false"); } }
915e9bf3-f5cb-4483-a51d-fe9464bc764d
@EventHandler(priority = EventPriority.MONITOR) public void onBlockBreakEvent(BlockBreakEvent event) { if (event.isCancelled()) { logDebug("TH: Block break cancel detected."); return; } logDebug("TH: No cancel detected."); org.bukkit.block.Block block = event.getBlock(); if (event.getPlayer() instanceof Player) { if (event.getPlayer().getGameMode().equals(GameMode.CREATIVE)) { return; } } if (block.getType() == Material.SKULL) { org.bukkit.block.Skull skull = (org.bukkit.block.Skull) block.getState(); if (skull.getSkullType().equals(SkullType.PLAYER)) { if (skull.hasOwner()) { String pName = skull.getOwner(); if (pName == null) { return; } if (CUSTOM_SKINS.containsValue(pName)) { Location loc = block.getLocation().clone(); event.setCancelled(true); block.setType(Material.AIR); ItemStack item = new ItemStack(Material.SKULL_ITEM, 1, (byte) 3); ItemMeta itemMeta = item.getItemMeta(); ((SkullMeta) itemMeta).setOwner(pName); itemMeta.setDisplayName(ChatColor.GREEN + getCustomSkullName(getCustomSkullType(pName)) + " Head"); item.setItemMeta(itemMeta); World world = loc.getWorld(); world.dropItemNaturally(loc, item); } } } } }
381a14b2-ce16-4a14-98a6-2f9cb3cb7700
@EventHandler public void onEntityDeathEvent(EntityDeathEvent event) { Player player; EntityType entityType = event.getEntityType(); Entity entity = event.getEntity(); String entityName = entity.getName(); String entityTypeName = entity.getType().name(); int skullType; boolean dropOkay; if (entityType.equals(EntityType.PLAYER)) { return; } Material material = Material.AIR; if (((LivingEntity) entity).getKiller() instanceof Player) { player = (Player) ((LivingEntity) entity).getKiller(); material = player.getItemInHand().getType(); } dropOkay = isValidItem(entityType, material); if (entityType.equals(EntityType.SKELETON)) { switch (((Skeleton) entity).getSkeletonType()) { case NORMAL: if (randomGenerator.nextInt(100) >= DROP_CHANCES.get(entityType.name())) { return; } skullType = 0; break; case WITHER: if (randomGenerator.nextInt(100) >= DROP_CHANCES.get(entityType.name())) { return; } entityName = "Wither Skeleton"; entityTypeName = "WITHER_SKELETON"; skullType = 1; break; default: return; } } else if (entityType.equals(EntityType.ZOMBIE)) { if (randomGenerator.nextInt(100) >= DROP_CHANCES.get(entityType.name())) { return; } skullType = 2; } else if (entityType.equals(EntityType.CREEPER)) { if (randomGenerator.nextInt(100) >= DROP_CHANCES.get(entityType.name())) { return; } skullType = 4; } else if (entityType.equals(EntityType.ENDER_DRAGON)) { if (randomGenerator.nextInt(100) >= DROP_CHANCES.get(entityType.name())) { return; } skullType = 5; } else if (DROP_CHANCES.containsKey(entityType.name())) { if (randomGenerator.nextInt(100) >= DROP_CHANCES.get(entityType.name())) { return; } skullType = 3; } else { return; } if (!dropOkay) { return; } ItemStack item = new ItemStack(Material.SKULL_ITEM, 1, (byte) skullType); if (entityType.equals(EntityType.GUARDIAN)) { if (((Guardian) entity).isElder()) { entityName = "Elder Guardian"; entityTypeName = "ELDER_GUARDIAN"; } } if (skullType == 3 || CUSTOM_SKINS.containsKey(entityName)) { logDebug("Dropping: [skin: " + CUSTOM_SKINS.get(entityTypeName) + "] [etName: " + entityName + "] [etType: " + entityTypeName + "]"); if (CUSTOM_SKINS.containsKey(entityTypeName)) { if (!CUSTOM_SKINS.get(entityTypeName).equalsIgnoreCase("@default")) { ItemMeta itemMeta = item.getItemMeta(); ((SkullMeta) itemMeta).setOwner(CUSTOM_SKINS.get(entityTypeName)); itemMeta.setDisplayName(entityName + " Head"); item.setItemMeta(itemMeta); } } else { logDebug("Entity not in config: " + entityName); } } Location loc = entity.getLocation().clone(); World world = loc.getWorld(); world.dropItemNaturally(loc, item); }
1c5e0ea7-fd50-4a41-98c7-39d0feb3d702
protected void loadTrophyConfig(CommandSender sender) { if (!configLoaded) { sender.sendMessage(ChatColor.GOLD + LOG_HEADER + " Configuration loaded."); } else { reloadConfig(); sender.sendMessage(ChatColor.GOLD + LOG_HEADER + " Configuration reloaded."); } configLoaded = true; debugEnabled = getConfig().getBoolean("debug-enabled"); logDebug("Debug enabled"); cooldown = getConfig().getLong("right-click-cooldown", 40L); logDebug("Cooldown: " + cooldown); DROP_CHANCES.put(EntityType.PLAYER.toString(), getConfig().getInt("drop-chance")); logDebug("Chance to drop head: " + DROP_CHANCES.get(EntityType.PLAYER.toString()) + "%"); playerSkin = getConfig().getBoolean("player-skin"); logDebug("Player skins: " + playerSkin); nonTropyHeadMessage = ChatColor.translateAlternateColorCodes('&', (getConfig().getString("non-th-message", "&eThat is a Custom head!"))); logDebug("Non TH message: " + nonTropyHeadMessage); List<String> pItems = getConfig().getStringList("items-required"); if (pItems.isEmpty()) { pItems.add("ANY"); pItems.add("276"); } ITEMS_REQUIRED.put(EntityType.PLAYER.toString(), pItems); logDebug("Player items required: " + ITEMS_REQUIRED.get(EntityType.PLAYER.toString())); for (String monsterName : getConfig().getConfigurationSection("custom-heads").getKeys(false)) { logDebug("Entity Name: " + monsterName); String entityTypeName; if (monsterName.equalsIgnoreCase("CaveSpider")) { entityTypeName = "CAVE_SPIDER"; } else if (monsterName.equalsIgnoreCase("Golem") || monsterName.equalsIgnoreCase("IronGolem")) { entityTypeName = "IRON_GOLEM"; } else if (monsterName.equalsIgnoreCase("MushroomCow") || monsterName.equalsIgnoreCase("Mooshroom")) { entityTypeName = "MUSHROOM_COW"; } else if (monsterName.equalsIgnoreCase("PigZombie") || monsterName.equalsIgnoreCase("ZombiePigman")) { entityTypeName = "PIG_ZOMBIE"; } else if (monsterName.equalsIgnoreCase("LavaSlime") || monsterName.equalsIgnoreCase("MagmaCube")) { entityTypeName = "MAGMA_CUBE"; } else if (monsterName.equalsIgnoreCase("EnderDragon") || monsterName.equalsIgnoreCase("Dragon")) { entityTypeName = "ENDER_DRAGON"; } else if (monsterName.equalsIgnoreCase("ElderGuardian")) { entityTypeName = "ELDER_GUARDIAN"; } else if (monsterName.equalsIgnoreCase("SnowMan") || monsterName.equalsIgnoreCase("SnowGolem")) { entityTypeName = "SNOWMAN"; } else if (monsterName.equalsIgnoreCase("WitherSkeleton")) { entityTypeName = "WITHER_SKELETON"; } else { entityTypeName = monsterName; } logDebug(" Type: " + entityTypeName); int dropChance = getConfig().getInt("custom-heads." + monsterName + ".drop-chance", 0); List<String> items = getConfig().getStringList("custom-heads." + monsterName + ".items-required"); if (items.isEmpty()) { items.add("ANY"); items.add("276"); } String skin = getConfig().getString("custom-heads." + monsterName + ".skin", "MHF_" + monsterName); String message = getConfig().getString("custom-heads." + monsterName + ".message", "&eThis head once belonged to a &e" + monsterName + "&e."); DROP_CHANCES.put(entityTypeName, dropChance); logDebug(" Chance to drop head: " + DROP_CHANCES.get(entityTypeName) + "%"); ITEMS_REQUIRED.put(entityTypeName, items); logDebug(" Items required: " + ITEMS_REQUIRED.get(entityTypeName)); CUSTOM_SKINS.put(entityTypeName, skin); logDebug(" Skin: " + CUSTOM_SKINS.get(entityTypeName)); SKULL_MESSAGES.put(entityTypeName, message); logDebug(" Message: " + SKULL_MESSAGES.get(entityTypeName)); SKULL_NAMES.put(entityTypeName, monsterName); logDebug(" Name: " + SKULL_NAMES.get(monsterName)); } SKULL_MESSAGES.put(EntityType.PLAYER.toString(), getConfig().getString("message")); renameEnabled = getConfig().getBoolean("rename-enabled"); if (renameEnabled) { try { renameItem = Material.getMaterial(getConfig().getInt("rename-item")); } catch (Exception e) { renameItem = Material.PAPER; } logDebug("Rename recipe enabled: head + " + renameItem.toString()); } DEATH_TYPES.addAll(getConfig().getStringList("death-types")); INFO_BLACKLIST.clear(); for (String name : getConfig().getStringList("info-blacklist")) { INFO_BLACKLIST.add(name.toLowerCase()); logDebug("Blacklisting: " + name.toLowerCase()); } }
bd265b52-71a8-481e-9c02-c8f00a95cc90
public void logInfo(String _message) { LOG.log(Level.INFO, String.format("%s %s", LOG_HEADER, _message)); }
0975c818-1832-4917-8f2e-d09827a8b319
public void logError(String _message) { LOG.log(Level.SEVERE, String.format("%s %s", LOG_HEADER, _message)); }
672562e1-d599-4272-96ac-d194f28aebf3
public void logDebug(String _message) { if (debugEnabled) { LOG.log(Level.INFO, String.format("%s [DEBUG] %s", LOG_HEADER, _message)); } }
55898815-2128-4437-ab60-396e04977372
public HeadSpawnCommand(TrophyHeads plugin) { this.plugin = plugin; }
b365ec1f-6888-451b-b3f9-473491e7d242
@Override public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { if (sender instanceof Player) { Player player = (Player) sender; if (player.hasPermission("trophyheads.spawn")) { String pName = player.getName(); int count = 1; if (args.length >= 1) { pName = args[0]; if (args.length == 2) { if (args[1].matches("\\d+")) { count = Integer.parseInt(args[1]); } } } ItemStack item = new ItemStack(Material.SKULL_ITEM, count, (byte) 3); Location loc = player.getLocation().clone(); World world = loc.getWorld(); ItemMeta itemMeta = item.getItemMeta(); ((SkullMeta) itemMeta).setOwner(pName); item.setItemMeta(itemMeta); plugin.logDebug("Skull: " + item.toString()); if (player.getInventory().firstEmpty() > -1) { player.sendMessage("Placed " + ChatColor.GOLD + pName + "'s head " + ChatColor.RESET + " in your inventory."); player.getInventory().setItem(player.getInventory().firstEmpty(), item); } else { player.sendMessage("Dropped " + ChatColor.GOLD + pName + "'s head" + ChatColor.RESET + " on the ground because your inventory was full."); world.dropItemNaturally(loc, item); } } else { player.sendMessage(ChatColor.RED + "You do not have permission to use this command."); } } else { sender.sendMessage(ChatColor.RED + "Only a player can use this command! Try the headgive command instead."); } return true; }
eac439b7-14d2-4433-a203-01c0a1c84c9c
public KeySetIterator(Iterator<CaseInsensitiveKey> iterator) { this.iterator = iterator; }
a4174702-6df7-45d7-8e89-8049c8f2419f
@Override public boolean hasNext() { return this.iterator.hasNext(); }
0ea4c2c7-98f8-4499-86d2-07182ae89930
@Override public String next() { return this.iterator.next().toString(); }
0672eecc-2b75-4b55-a14f-37a3f3616111
@Override public void remove() { this.iterator.remove(); }
c99c5734-10d6-4ddb-a1ec-e90045792ce2
public KeySet(Set<CaseInsensitiveKey> keySet) { this.keySet = keySet; }
e5736124-86bd-4603-8050-05c6e798dcbe
@Override public boolean add(String o) { throw new UnsupportedOperationException("Map.keySet must return a Set which does not support add"); }
039900d3-7a1b-4adc-8932-a8cc9050d8e1
@Override public boolean addAll(Collection<? extends String> c) { throw new UnsupportedOperationException("Map.keySet must return a Set which does not support addAll"); }
75ac1a2b-1613-4874-a8c5-e09a5ddf75bd
@Override public void clear() { this.keySet.clear(); }
a5681402-8d15-40c5-a386-5c14175040a4
@Override public boolean contains(Object o) { return o instanceof String ? this.keySet.contains(CaseInsensitiveKey.objectToKey(o)) : false; }
a3d1c9c1-206a-4733-9502-7d30a956ab90
@Override public Iterator<String> iterator() { return new KeySetIterator(this.keySet.iterator()); }
df8557a0-2cc6-4127-a20e-2aeec2171bb1
@Override public boolean remove(Object o) { // The following can throw ClassCastException which conforms to the method specification. return this.keySet.remove(CaseInsensitiveKey.objectToKey(o)); }
295584f3-2468-4a90-b7ec-28beef8af4a4
@Override public int size() { return this.keySet.size(); }
81bc971b-35bc-4b95-968f-6a4b6239c958
public MapEntry(Entry<CaseInsensitiveMap.CaseInsensitiveKey, V> entry) { this.entry = entry; }
11ff7d28-2dda-47b5-aea0-38350ce517c7
@Override public String getKey() { return this.entry.getKey().toString(); }
a904669d-166d-4e0b-b6b4-7f2ded8888b4
@Override public V getValue() { return this.entry.getValue(); }
fe93ca2b-a325-434a-91af-c50454de977c
@Override public V setValue(V value) { return this.entry.setValue(value); }
14e50b7c-b436-4ae7-8b0f-d7160bbaa052
public Entry<CaseInsensitiveMap.CaseInsensitiveKey, V> getEntry() { return this.entry; }
ed6bb7bb-ce64-475f-a2b4-1a36571c4800
public EntrySetIterator(Iterator<Entry<CaseInsensitiveKey, V>> iterator) { this.iterator = iterator; }
008e3930-6d1a-4a84-a7f6-287ac74afae8
@Override public boolean hasNext() { return this.iterator.hasNext(); }
435c0cc8-3cde-44b3-a171-7ad47b92d7a1
@Override public Entry<String, V> next() { return new MapEntry<V>(this.iterator.next()); }
2dcc3c2c-a4d9-4294-b05a-0073a56c10e8
@Override public void remove() { this.iterator.remove(); }
2a7fcb82-3c8f-4c9f-a8a4-556a488aaae1
public EntrySet(Set<Entry<CaseInsensitiveKey, V>> entrySet, CaseInsensitiveMap<V> map) { this.entrySet = entrySet; this.map = map; }
2cc59783-100f-46b0-8cb9-42ed2323a8c6
@Override public boolean add(Entry<String, V> o) { throw new UnsupportedOperationException("Map.entrySet must return a Set which does not support add"); }
f17a4081-ce6c-4139-8783-ef377ca4e6ea
@Override public boolean addAll(Collection<? extends Entry<String, V>> c) { throw new UnsupportedOperationException("Map.entrySet must return a Set which does not support addAll"); }
0211b11d-3a59-4d66-9405-0d598025b3f9
@Override public void clear() { this.entrySet.clear(); }
0751479e-81ef-4374-917c-6ca7914a45a8
@SuppressWarnings("unchecked") @Override public boolean contains(Object o) { if (o instanceof Entry) { Entry<String, V> e = (Entry<String, V>) o; V value = this.map.get(e.getKey()); return value.equals(e.getValue()); } return false; }
77753c6a-bc0f-4214-bc3a-2f85cdd9f0b0
@Override public Iterator<Entry<String, V>> iterator() { return new EntrySetIterator<V>(this.entrySet.iterator()); }
9fbd491b-ff3e-46ab-9a4c-fa6854de0074
@SuppressWarnings("unchecked") @Override public boolean remove(Object o) { try { return this.entrySet.remove(((MapEntry<V>) o).getEntry()); } catch (ClassCastException e) { } return false; }
0c1af0a5-9a75-4c99-ac70-3b1f93679c0f
@Override public int size() { return this.entrySet.size(); }
8ff8878b-bad6-4964-b917-b152136f3d43
private CaseInsensitiveKey(String key) { this.key = key; }
6fa1447b-0115-423b-b467-953043582525
@Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + key.toLowerCase().hashCode(); return result; }
102f6114-a3b2-4d76-bdf3-99ac6deb0357
@Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } CaseInsensitiveKey other = (CaseInsensitiveKey) obj; if (key == null) { if (other.key != null) { return false; } } else if (!key.equalsIgnoreCase(other.key)) { return false; } return true; }
6e63c99a-404d-474a-b4b5-6e2fca0f4fc9
@Override public String toString() { return key; }
3645681f-3de8-4b5e-abc5-074cc16b5a3a
public static CaseInsensitiveKey objectToKey(Object key) { return new CaseInsensitiveKey((String) key); }
2deec1c2-fa60-4471-a1af-5a0adb6d433a
public CaseInsensitiveMap() { }
c9f60a04-c32c-445a-9da4-0282d9c4c13b
public CaseInsensitiveMap(CaseInsensitiveMap<? extends V> map) { this.map.putAll(map.map); }
b76a0330-4b50-462c-97ad-42b5e0705ed1
@Override public void clear() { this.map.clear(); }
e2a63da0-301e-4ad8-9114-c194db09f3e1
@Override public boolean containsKey(Object key) { return key instanceof String ? this.map.containsKey(CaseInsensitiveKey.objectToKey(key)) : false; }
c6b6b6da-53be-4b8a-a70d-c61e8df550e0
@Override public boolean containsValue(Object value) { return this.map.containsValue(value); }
7982f8c0-feaf-44bc-af38-c17507cd4a6b
@Override public Set<Entry<String, V>> entrySet() { return new EntrySet<V>(this.map.entrySet(), this); }
63436505-a1ee-4022-9161-7ef3389e629c
@Override public V get(Object key) { return key instanceof String ? this.map.get(CaseInsensitiveKey.objectToKey(key)) : null; }
baa0ab5d-9e70-430e-b92a-63403a0c1267
@Override public Set<String> keySet() { return new KeySet(this.map.keySet()); }
0a9b83db-932a-46c1-a15c-685ff654b095
@Override public V put(String key, V value) { if (key == null) { throw new NullPointerException("CaseInsensitiveMap does not permit null keys"); } return this.map.put(CaseInsensitiveKey.objectToKey(key), value); }
1cb03372-0075-475a-a6fe-779b03404ddc
@Override public V remove(Object key) { return key instanceof String ? this.map.remove(CaseInsensitiveKey.objectToKey(key)) : null; }
499f8610-374c-4e0e-88a6-cfe0612c5017
@Override public int size() { return this.map.size(); }
d001a472-2319-4789-a0d8-b26b8474ae25
@Override public Collection<V> values() { return this.map.values(); }
2ca18a68-6894-4274-9256-5aafe793535a
public static void main(String[] args) throws IOException { long startTime = System.currentTimeMillis(); ////////////////////////////////////////////////////////////// if(args.length == 2){ trainingDirectory = args[0]; testingDirectory = args[1]; } else if (args.length == 0){ //trainingDirectory = "D:/cs571data/data/train"; //testingDirectory = "D:/cs571data/data/test"; trainingDirectory = "/aut/proj/ir/eugene/Data/CS571/project2/data/train"; testingDirectory = "/aut/proj/ir/eugene/Data/CS571/project2/data/test"; } else { System.err.println("Argument Wrong, please provide valid " + "[TrainingDirectory] [TestingDirectory]"); } try{ /////////////////////////////////////////////////////////////// System.out.println("Training Start..."); myDict = readDirectory(trainingDirectory); System.out.println("Training Done!"); System.out.println(); /////////////////////////////////////////////////////////////// System.out.println("Testing Start..."); testDirectory(testingDirectory); System.out.println("Testing Done!"); System.out.println(); /////////////////////////////////////////////////////////////// System.out.println("Evaluation Start..."); evaluate(); System.out.println("Evaluation Done!"); System.out.println(); } catch(IOException e){ System.err.println("File Not Found"); } /////////////////////////////////////////////////////////////// long endTime = System.currentTimeMillis(); long totalTime = endTime - startTime; System.out.println("Total time : " + totalTime + "mSec"); }//main()
f1c64e4f-9c8b-4dd0-aefc-64257aa7aa43
public static HashMap<String, wordFeatures> readDirectory(String address) throws FileNotFoundException { File[] files = new File(address).listFiles(); //loop thru files for (File file : files){ extractFile(file); fileCounter++; if(((fileCounter%300)== 0)) System.out.println(fileCounter + " files read, still reading, please wait"); }//end loop thru files System.out.println("Model not saved"); System.out.println("Number of Files Read : " + fileCounter); System.out.println("Number of Lines Read : " + lineCounter); return myDict; }//readDirectory()
fb6a3e5d-087a-45f0-8687-9c6d41101ff4
public static void extractFile(File file) throws FileNotFoundException{ Scanner sc = new Scanner(file); //loop thru lines while (sc.hasNext()) { String line = sc.nextLine(); String[] tokens = line.split ("\n"); //loop thru tokens for (int i = 0; i < tokens.length; i++) { if (tokens[i].length() != 0) { String[] tokenizedLine = tokens[i].split ("\t"); featureExtract(tokenizedLine); lineCounter++; } }//end loop thru tokens }//end loop thru lines }//extractFile()
aa8f823e-4970-4199-9f0e-d4eef5f9bbce
public static void featureExtract(String[] tokenizedLine){ //String[] labelSet = new String[]{"B-PER", "B-LOC", "B-ORG", "B-MISC", // "I-PER", "I-LOC", "I-ORG", "I-MISC"}; //sentenceNum = features[0]; //wordNum = features[1]; if(tokenizedLine.length ==7 ){ nextWord = tokenizedLine[2]; nextLabel = tokenizedLine[6]; }else { nextWord = tokenizedLine[2]; nextLabel = "-<S>-"; } if(myDict.containsKey(word)){ myDict.get(word).record(word, label, previousWord, nextWord); } else { myDict.put(word, new wordFeatures(word, label, previousWord, nextWord)); } /* if(word.equals("Atlanta")){ System.out.println(previousWord + " - " + word + " - " + nextWord + " has occured " + myDict.get(word).getWordCounts() + " times and as " + label + " for "+ myDict.get(word).getLabelCounts(label) + " times."); }*/ previousWord = word; previousLabel = label; word = nextWord; label = nextLabel; }// featureExtract()
450fa467-4e04-43de-9a28-ca180f26e38a
public static void testDirectory(String address) throws FileNotFoundException{ File[] files = new File(address).listFiles(); for (File file : files){ testFile(file); testfileCounter++; }//end loop thru files }
079c758a-3fdf-4228-a9bd-742bb0ca231c
public static void testFile(File file) throws FileNotFoundException{ Scanner sc = new Scanner(file); //loop thru lines while (sc.hasNext()) { String line = sc.nextLine(); String[] tokens = line.split ("\n"); //loop thru tokens for (int i = 0; i < tokens.length; i++) { if (tokens[i].length() != 0) { String[] tokenizedLine = tokens[i].split ("\t"); featurePrediction(tokenizedLine); lineCounter++; } }//end loop thru tokens }//end loop thru lines }
5f7d4317-7c95-44f7-a3fa-a6be5bb26a95
public static void featurePrediction(String[] tokenizedLine){ if(tokenizedLine.length ==7 ){ //nextWord = tokenizedLine[2]; //nextLabel = tokenizedLine[6]; word = tokenizedLine[2]; label = tokenizedLine[6]; String predictedLabel; if(myDict.containsKey(word)){ predictedLabel = myDict.get(word).returnHighestLabel(); } else { predictedLabel = "O"; } compareLabels(label, predictedLabel); } //previousWord = word; //previousLabel = label; //word = nextWord; //label = nextLabel; }
fcc5857f-966e-4535-8193-0fe8775b052d
public static void compareLabels(String label, String predictedLabel){ if(!labelCounts.containsKey(label)){ labelCounts.put(label, 1); } else if(labelCounts.containsKey(label)){ int labelCount = labelCounts.get(label) + 1; labelCounts.put(label, labelCount); } if(!predictedLabelCounts.containsKey(predictedLabel)){ predictedLabelCounts.put(predictedLabel, 1); } else if(predictedLabelCounts.containsKey(predictedLabel)){ int predictedLabelCount = predictedLabelCounts.get(predictedLabel) + 1; predictedLabelCounts.put(predictedLabel, predictedLabelCount); } if(label.equals(predictedLabel)){ if(!correctLabelCounts.containsKey(label)){ correctLabelCounts.put(label, 1); } else if(correctLabelCounts.containsKey(label)){ int correctLabelCount = correctLabelCounts.get(label) + 1; correctLabelCounts.put(label, correctLabelCount); } } }
7da4f0c1-70df-4442-9307-dc32db4995f9
public static void evaluate(){ System.out.printf("%-7s \t\t %s \t %s \t %s \t %s \t %s \t %s \n", "Label", "Precision", "Recall", "F1", "correctLabelCounts", "predictedLabelCounts", "labelCounts"); double totalCorrectCount = 0; double totalpredictedCount = 0; double totalLabelCount = 0; for(String label : labelCounts.keySet()){ if(label.equals("O")) continue; double Precision; double Recall; double F1; double correctCount; double predictedCount; double labelCount; if(correctLabelCounts.containsKey(label) && predictedLabelCounts.containsKey(label)){ correctCount = correctLabelCounts.get(label).doubleValue(); predictedCount = predictedLabelCounts.get(label).doubleValue(); Precision = correctCount / predictedCount; } else { correctCount = 0; predictedCount = 0; Precision = -1; } if(correctLabelCounts.containsKey(label) && labelCounts.containsKey(label)){ correctCount = correctLabelCounts.get(label).doubleValue(); labelCount = labelCounts.get(label).doubleValue(); Recall = correctCount / labelCount; } else { correctCount = 0; labelCount = 0; Recall = -1; } if(Precision > 0 && Recall > 0){ F1 = 2/(1/Precision + 1/Recall); } else { F1 = -1; } totalCorrectCount += correctCount; totalpredictedCount += predictedCount; totalLabelCount += labelCount; System.out.printf("%-7s \t\t %f \t %f \t %f \t %f \t %f \t %f \n", label, Precision, Recall, F1, correctCount, predictedCount, labelCount); } double totalPrecision = totalCorrectCount/totalpredictedCount; double totalRecall = totalCorrectCount/totalLabelCount; double totalF1 = 2/(1/totalPrecision + 1/totalRecall); System.out.printf("%-7s \t\t %f \t %f \t %f \t %f \t %f \t %f \n", "Total", totalPrecision, totalRecall, totalF1, totalCorrectCount, totalpredictedCount, totalLabelCount); //System.out.println(labelCounts.keySet().toString()); //System.out.println(predictedLabelCounts.keySet().toString()); //System.out.println(correctLabelCounts.keySet().toString()); }
c09e4657-cafa-484b-97cd-7dd1c87bc7d2
public wordFeatures(String word, String label, String prefixWord, String suffixWord) { this.word = word; this.wordCounts++; if(!this.labels.contains(label)){ this.labels.add(label); int labelIndex = this.labels.indexOf(label); this.labelCounts.add(labelIndex, 1); } else if(this.labels.contains(label)){ int labelIndex = this.labels.indexOf(label); int labelCount = this.labelCounts.get(labelIndex); labelCount += 1; this.labelCounts.set(labelIndex, labelCount); } if(!this.prefixWords.contains(prefixWord)){ this.prefixWords.add(prefixWord); int prefixWordsIndex = this.prefixWords.indexOf(prefixWord); this.prefixWordCounts.add(prefixWordsIndex, 1); } else if(this.prefixWords.contains(prefixWord)){ int prefixWordsIndex = this.labels.indexOf(prefixWord); int prefixWordCount = this.prefixWordCounts.get(prefixWordsIndex); prefixWordCount += 1; this.prefixWordCounts.set(prefixWordsIndex, prefixWordCount); } if(!this.suffixWords.contains(suffixWord)){ this.suffixWords.add(suffixWord); int suffixWordIndex = this.suffixWords.indexOf(suffixWord); this.suffixWordCounts.add(suffixWordIndex, 1); } else if(this.suffixWords.contains(suffixWord)){ int suffixWordIndex = this.suffixWords.indexOf(suffixWord); int suffixWordCount = this.suffixWordCounts.get(suffixWordIndex); suffixWordCount += 1; this.suffixWordCounts.set(suffixWordIndex, suffixWordCount); } }
dfd48afe-e858-4001-8f20-218d65160749
public void record(String word, String label, String prefixWord, String suffixWord) { this.wordCounts++; if(!this.labels.contains(label)){ this.labels.add(label); int labelIndex = this.labels.indexOf(label); this.labelCounts.add(labelIndex, 1); } else if(this.labels.contains(label)){ int labelIndex = this.labels.indexOf(label); int labelCount = this.labelCounts.get(labelIndex); labelCount += 1; this.labelCounts.set(labelIndex, labelCount); } if(!this.prefixWords.contains(prefixWord)){ this.prefixWords.add(prefixWord); int prefixWordsIndex = this.prefixWords.indexOf(prefixWord); this.prefixWordCounts.add(prefixWordsIndex, 1); } else if(this.prefixWords.contains(prefixWord)){ int prefixWordsIndex = this.prefixWords.indexOf(prefixWord); int prefixWordCount = this.prefixWordCounts.get(prefixWordsIndex); prefixWordCount += 1; this.prefixWordCounts.set(prefixWordsIndex, prefixWordCount); } if(!this.suffixWords.contains(suffixWord)){ this.suffixWords.add(suffixWord); int suffixWordIndex = this.suffixWords.indexOf(suffixWord); this.suffixWordCounts.add(suffixWordIndex, 1); } else if(this.suffixWords.contains(suffixWord)){ int suffixWordIndex = this.suffixWords.indexOf(suffixWord); int suffixWordCount = this.suffixWordCounts.get(suffixWordIndex); suffixWordCount += 1; this.suffixWordCounts.set(suffixWordIndex, suffixWordCount); } }
d26e3ff3-55cb-4057-8d2d-4460dd38f5e0
public int getLabelOccurance(String label) { if(labels.contains(label)){ return 1; //labels.indexOf(label); } else{ return 0; } }
f894a5d3-7d45-46bb-a336-da6f750a115c
public int getWordCounts(){ return wordCounts; }
9cfa8c3e-d884-4f8c-9535-d349346a16e3
public int getLabelCounts(String label){ return this.labelCounts.get(this.labels.indexOf(label)); }
6c24e637-2b0d-4f42-8d47-05a623f45d55
public int getTotalLabelCounts(){ int totalLabelCounts = 0; for(String label : labels){ totalLabelCounts += this.labelCounts.get(this.labels.indexOf(label)); } return totalLabelCounts; }
d67eb527-edbc-405e-9420-700b127bcbdb
public String returnHighestLabel(){ int highestLabelCounts = 0; String highestLabel = ""; for(int i = 0; i < this.labels.size(); i++){ if (highestLabelCounts < this.labelCounts.get(i)){ highestLabelCounts = this.labelCounts.get(i); highestLabel = this.labels.get(i); } } return highestLabel; }
c6f3d838-4efd-4643-80a5-ccd554d459c5
public TrainCRF(String trainingFileFolder, String testingFileFolder) throws IOException { ArrayList<Pipe> pipeList = new ArrayList<Pipe>(); // Construct pipes pipeList.add(new Input2CharSequence("UTF-8")); pipeList.add(new ImprovedSimpleLabelNERdata2TokenSequence(true)); // true to extract feature pipeList.add(new TokenSequence2FeatureVectorSequence()); ////////////////////////////////////////////////// Pipe pipe = new SerialPipes(pipeList); InstanceList trainingInstances = new InstanceList(pipe); InstanceList testingInstances = new InstanceList(pipe); File[] trainingFiles = new File(trainingFileFolder).listFiles(); for(File trainingfile : trainingFiles){ LineGroupIterator it = new LineGroupIterator(new BufferedReader(new InputStreamReader( new FileInputStream(trainingfile))), Pattern.compile("^\\s*$"), true); trainingInstances.addThruPipe(it); } System.out.println("Training loaded"); File[] testingFiles = new File(testingFileFolder).listFiles(); for(File testingfile : testingFiles){ testingInstances.addThruPipe(new LineGroupIterator(new BufferedReader(new InputStreamReader( new FileInputStream(testingfile))), Pattern.compile("^\\s*$"), true)); } System.out.println("Testing loaded"); System.out.println(); // Taking 20%, 40%, 60%, 80%, 100% of Training Data as input InstanceList[] ilists = trainingInstances.split(new Randoms(), new double[] {1.0, 0.0, 0.0}); CRF crf = new CRF(pipe, null); // Better result use All Label Connections // Higher efficiency use less Label Connections // Choose one : // crf.addFullyConnectedStatesForLabels(); // or crf.addStatesForLabelsConnectedAsIn(ilists[0]); // or // crf.addStatesForThreeQuarterLabelsConnectedAsIn(ilists[0]); // or // crf.addStatesForBiLabelsConnectedAsIn (ilists[0]); // or // crf.addStatesForHalfLabelsConnectedAsIn (ilists[0]); // crf.addStartState(); // Use Start State CRFTrainerByThreadedLabelLikelihood trainer = new CRFTrainerByThreadedLabelLikelihood(crf, 6); trainer.setGaussianPriorVariance (100.0); // CRFTrainerByStochasticGradient trainer = // new CRFTrainerByStochasticGradient(crf, 1.0); // CRFTrainerByL1LabelLikelihood trainer = // new CRFTrainerByL1LabelLikelihood(crf, 0.75); // CRFTrainerByValueGradients trainer = // new CRFTrainerByValueGradients(crf, null); // DON'T UNDERSTAND, need to check the source trainer.addEvaluator(new PerClassAccuracyEvaluator(testingInstances, "testing")); trainer.train(ilists[0]); trainer.shutdown(); }