Beispiel #1
1
 /*
  * public HashMap getLeafElements() { HashMap map = new HashMap(); Object[]
  * elts = dataElements.values().toArray(); for (int j=0; j<elts.length; j++)
  * { PDMDataElement data = (PDMDataElement) elts[j];
  * map.put(data.getID(),data); } Object[] ops =
  * operations.values().toArray(); for (int i=0; i<ops.length; i++){
  * PDMOperation op = (PDMOperation) ops[i]; if
  * (!(op.getInputElements().isEmpty())){ HashMap outs =
  * op.getOutputElements(); Object[] outArray = outs.values().toArray(); for
  * (int j=0; j<outArray.length; j++) { PDMDataElement d = (PDMDataElement)
  * outArray[j]; map.remove(d.getID()); } } } return map; }
  */
 public HashMap getLeafElements() {
   HashMap result = new HashMap();
   HashSet leafOps = getLeafOperations();
   if (!(leafOps.isEmpty())) {
     Iterator it = leafOps.iterator();
     while (it.hasNext()) {
       PDMOperation op = (PDMOperation) it.next();
       PDMDataElement data = op.getOutputElement();
       result.put(data.getID(), data);
     }
   } else {
     Object[] elts = dataElements.values().toArray();
     for (int j = 0; j < elts.length; j++) {
       PDMDataElement data = (PDMDataElement) elts[j];
       result.put(data.getID(), data);
     }
     Object[] ops = operations.values().toArray();
     for (int i = 0; i < ops.length; i++) {
       PDMOperation op = (PDMOperation) ops[i];
       HashMap outs = op.getOutputElements();
       Object[] outArray = outs.values().toArray();
       for (int j = 0; j < outArray.length; j++) {
         PDMDataElement d = (PDMDataElement) outArray[j];
         result.remove(d.getID());
       }
     }
   }
   return result;
 }
 @Override
 public HSDeck getDeckDetail(final HSDeck hsDeck, final float n) {
   try {
     final Document value = Jsoup.connect(HPDeckSource.BASE_URL + hsDeck.getUrl()).get();
     final Elements select = value.select("section.class-listing table.listing td.col-name");
     final HashMap<String, String> classHsItemMap = new HashMap<String, String>();
     final ArrayList<String> list = new ArrayList<String>();
     for (int i = 0; i < select.size(); ++i) {
       final String text = select.get(i).select("a").get(0).text();
       classHsItemMap.put(
           text, select.get(i).text().trim().substring(select.get(i).text().trim().length() - 1));
       list.add(text);
     }
     hsDeck.setClassHsItemMap(classHsItemMap);
     hsDeck.setClassHsItemList(DataBaseManager.getInstance().getAllCardsByNames(list));
     final Elements select2 = value.select("section.neutral-listing table.listing td.col-name");
     final HashMap<String, String> neutralHsItemMap = new HashMap<String, String>();
     final ArrayList<String> list2 = new ArrayList<String>();
     for (int j = 0; j < select2.size(); ++j) {
       final String text2 = select2.get(j).select("a").get(0).text();
       neutralHsItemMap.put(
           text2,
           select2.get(j).text().trim().substring(select2.get(j).text().trim().length() - 1));
       list2.add(text2);
     }
     hsDeck.setNeutralHsItemMap(neutralHsItemMap);
     hsDeck.setNeutralHsItemList(DataBaseManager.getInstance().getAllCardsByNames(list2));
     hsDeck.setDescription(
         HtmlHelper.parseDescription(value.select("div.deck-description").html(), n, false));
     return hsDeck;
   } catch (IOException ex) {
     ex.printStackTrace();
     return hsDeck;
   }
 }
Beispiel #3
1
 /**
  * Returns a map with variable bindings.
  *
  * @param opts main options
  * @return bindings
  */
 public static HashMap<String, String> bindings(final MainOptions opts) {
   final HashMap<String, String> bindings = new HashMap<>();
   final String bind = opts.get(MainOptions.BINDINGS).trim();
   final StringBuilder key = new StringBuilder();
   final StringBuilder val = new StringBuilder();
   boolean first = true;
   final int sl = bind.length();
   for (int s = 0; s < sl; s++) {
     final char ch = bind.charAt(s);
     if (first) {
       if (ch == '=') {
         first = false;
       } else {
         key.append(ch);
       }
     } else {
       if (ch == ',') {
         if (s + 1 == sl || bind.charAt(s + 1) != ',') {
           bindings.put(key.toString().trim(), val.toString());
           key.setLength(0);
           val.setLength(0);
           first = true;
           continue;
         }
         // literal commas are escaped by a second comma
         s++;
       }
       val.append(ch);
     }
   }
   if (key.length() != 0) bindings.put(key.toString().trim(), val.toString());
   return bindings;
 }
Beispiel #4
0
  /*
   * Adds nodes to graph
   */
  private static void addNodes() {
    String current;
    Node node;
    Node fromNode;

    try {
      line = br.readLine();

      while (line.indexOf(",") != -1) {
        current = line.substring(0, line.indexOf(","));
        current = current.trim();
        line = line.substring(line.indexOf(",") + 1);

        if (nodeMap.get(current.charAt(1)) == null) {
          node = new Node(current.charAt(1));
          nodeMap.put(current.charAt(1), node);
        }
        if (nodeMap.get(current.charAt(0)) == null) {
          node = new Node(current.charAt(1));
          nodeMap.put(current.charAt(0), node);
        }
        fromNode = nodeMap.get(current.charAt(0));
        fromNode.addEdge(nodeMap.get(current.charAt(1)), current.charAt(2) - '0');
      }
    } catch (IOException e) {
      System.out.println(e);
    }
  }
Beispiel #5
0
  public Conversation insertNewConversation(long rmt_ip, int lcl_port, int rmt_port) {
    gc();

    Conversation conv = new Conversation(rmt_ip, lcl_port, rmt_port);

    modLong.setLong(rmt_ip);
    modInt.setInt((lcl_port << 16) | (rmt_port & 0xFFFF));

    ModInteger mInt = new ModInteger();
    mInt.setInt((lcl_port << 16) | (rmt_port & 0xFFFF));

    HashMap portsMap = (HashMap) hostsMap.get(modLong);
    if (portsMap == null) {
      ModLong mLong = new ModLong();

      mLong.setLong(rmt_ip);
      portsMap = new HashMap();
      hostsMap.put(mLong, portsMap);
    }
    portsMap.put(mInt, conv);
    allConversations.add(conv);
    hasChanged = true;

    return conv;
  }
    public static void printViewPatterns() {
      processedViewsForPatterns = new HashSet<ViewTrace>();
      HashMap<String, Integer> viewPatterns = new HashMap<String, Integer>();

      ps.println("ViewPatterns ------------------- \n");
      for (ViewTrace trace : viewsRegistry) {
        if (processedViewsForPatterns.contains(trace)) {
          continue;
        }
        ViewTrace v = trace.getRootView();
        StringBuilder p = new StringBuilder();
        p.append("PATTERN ");
        extractViewPattern(0, v, p);
        p.append("\n");
        String pattern = p.toString();
        Integer count = viewPatterns.get(pattern);
        if (count == null) {
          viewPatterns.put(pattern, 1);
        } else {
          viewPatterns.put(pattern, count + 1);
        }
      }
      processedViewsForPatterns = null;
      for (Map.Entry<String, Integer> e : viewPatterns.entrySet()) {
        ps.print("(" + e.getValue() + ") ");
        ps.println(e.getKey());
      }
    }
  public static void countPairs(Integer[] arr) {

    HashMap<Integer, Integer> seenElements = new HashMap<Integer, Integer>();

    // ArrayList<Integer> countList = new ArrayList<Integer

    for (int i = 0; i < arr.length; i++) {

      if (!seenElements.containsKey(arr[i])) {
        seenElements.put(arr[i], 1);
      } else {

        seenElements.put(arr[i], seenElements.get(arr[i]) + 1);
      }
    }

    BigInteger count = null;
    for (int element : seenElements.keySet()) {
      if (seenElements.get(element) > 1) {
        System.out.println("count is :" + seenElements.get(element));
        count.add(
            factorial(seenElements.get(element)).divide(factorial(seenElements.get(element) - 2)));
        System.out.println(count);
      }
    }

    if (count == null) {
      System.out.println("0");
    }
  }
Beispiel #8
0
  public static void main(String[] args) throws IOException {

    Scanner scanner = new Scanner(new BufferedInputStream(System.in));
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

    while (true) {
      int a = Integer.parseInt(br.readLine());
      if (a == 0) break;
      HashMap<String, Integer> map = new HashMap<String, Integer>();
      int sum = 0;

      while (a-- > 0) {
        StringTokenizer st = new StringTokenizer(br.readLine());
        int one = Integer.parseInt(st.nextToken()), two = Integer.parseInt(st.nextToken());
        country c = new country(one, two);
        country c_rev = new country(two, one);
        int s = 0;

        if (map.get(c.tostring()) != null) {
          s = map.get(c.tostring()) + 1;
          map.put(c.tostring(), s);
          sum++;
        } else if (map.get(c_rev.tostring()) != null) {
          s = map.get(c_rev.tostring()) - 1;
          map.put(c_rev.tostring(), s);
          sum--;
        } else {
          map.put(c.tostring(), 1);
          sum++;
        }
      }
      if (sum != 0) System.out.println("NO");
      else System.out.println("YES");
    }
  }
  JarFile get(URL url, boolean useCaches) throws IOException {

    JarFile result = null;
    JarFile local_result = null;

    if (useCaches) {
      synchronized (this) {
        result = getCachedJarFile(url);
      }
      if (result == null) {
        local_result = URLJarFile.getJarFile(url);
        synchronized (this) {
          result = getCachedJarFile(url);
          if (result == null) {
            fileCache.put(url, local_result);
            urlCache.put(local_result, url);
            result = local_result;
          } else {
            if (local_result != null) {
              local_result.close();
            }
          }
        }
      }
    } else {
      result = URLJarFile.getJarFile(url);
    }
    if (result == null) throw new FileNotFoundException(url.toString());

    return result;
  }
Beispiel #10
0
 public static void main(String[] args) throws IOException {
   Scanner s = new Scanner(new File("gift1.in"));
   PrintWriter out = new PrintWriter(new FileWriter("gift1.out"));
   int people = s.nextInt();
   HashMap<String, Integer> moneyGiven = new HashMap<String, Integer>();
   HashMap<String, Integer> moneyReceived = new HashMap<String, Integer>();
   String[] names = new String[people];
   for (int x = 0; x < people; x++) {
     String name = s.next();
     names[x] = name;
     moneyGiven.put(name, 0);
     moneyReceived.put(name, 0);
   }
   for (int x = 0; x < people; x++) {
     String person = s.next();
     int give = s.nextInt();
     int receivers = s.nextInt();
     if (receivers == 0) continue;
     give = give - give % receivers;
     moneyGiven.put(person, give);
     for (int y = 0; y < receivers; y++) {
       String name = s.next();
       moneyReceived.put(name, give / receivers + moneyReceived.get(name));
     }
   }
   for (int x = 0; x < people; x++) {
     out.println(names[x] + " " + (moneyReceived.get(names[x]) - moneyGiven.get(names[x])));
   }
   out.close();
 }
Beispiel #11
0
  public Uploader(HttpServletRequest request) {
    this.request = request;
    this.params = new HashMap<String, String>();

    this.setMaxSize(Uploader.MAX_SIZE);

    HashMap<String, String> tmp = this.errorInfo;
    tmp.put("SUCCESS", "SUCCESS"); // 默认成功
    // 未包含文件上传域
    tmp.put("NOFILE", "\\u672a\\u5305\\u542b\\u6587\\u4ef6\\u4e0a\\u4f20\\u57df");
    // 不允许的文件格式
    tmp.put("TYPE", "\\u4e0d\\u5141\\u8bb8\\u7684\\u6587\\u4ef6\\u683c\\u5f0f");
    // 文件大小超出限制
    tmp.put("SIZE", "\\u6587\\u4ef6\\u5927\\u5c0f\\u8d85\\u51fa\\u9650\\u5236");
    // 请求类型错误
    tmp.put("ENTYPE", "\\u8bf7\\u6c42\\u7c7b\\u578b\\u9519\\u8bef");
    // 上传请求异常
    tmp.put("REQUEST", "\\u4e0a\\u4f20\\u8bf7\\u6c42\\u5f02\\u5e38");
    // 未找到上传文件
    tmp.put("FILE", "\\u672a\\u627e\\u5230\\u4e0a\\u4f20\\u6587\\u4ef6");
    // IO异常
    tmp.put("IO", "IO\\u5f02\\u5e38");
    // 目录创建失败
    tmp.put("DIR", "\\u76ee\\u5f55\\u521b\\u5efa\\u5931\\u8d25");
    // 未知错误
    tmp.put("UNKNOWN", "\\u672a\\u77e5\\u9519\\u8bef");

    this.parseParams();
  }
Beispiel #12
0
  /**
   * puts the value for the column aginst the column Name
   *
   * @param os
   * @param rows
   * @param oldResultSet
   * @param index
   * @param modifiedColumns
   * @param columnName
   * @throws SQLException
   * @throws IOException
   */
  public void writeUpdate(
      Writer os,
      ResultSet rows,
      ResultSet oldResultSet,
      int index,
      HashMap modifiedColumns,
      String columnName,
      ArrayList encodedCols)
      throws SQLException, IOException {
    Object newObject = rows.getObject(index);
    Object oldObject = oldResultSet.getObject(index);

    if (newObject == null) {
      write(os, "NULL", encodedCols, columnName);
      if (oldObject != null) {
        modifiedColumns.put(columnName, "NULL");
      }
    } else {
      write(os, newObject, encodedCols, columnName);
      if (oldObject != null) {
        if (!(newObject.equals(oldObject))) {
          modifiedColumns.put(columnName, newObject);
        }
      } else {
        modifiedColumns.put(columnName, newObject);
      }
    }
  }
  private void write(List<String> words, String documentsName) throws DictionaryException {

    for (int i = 0; i < words.size(); i++) {
      HashMap<String, Integer> hashMap = new HashMap<String, Integer>();

      if (dictionary.containsKey(words.get(i))) {
        hashMap = dictionary.get(words.get(i));
        int countWords;

        if (hashMap.containsKey(documentsName)) {
          countWords = hashMap.get(documentsName);
          countWords += 1;
          hashMap.remove(documentsName);
          hashMap.put(documentsName, countWords);
        } else {
          hashMap.put(documentsName, 1);
        }
        dictionary.remove(words.get(i));
        dictionary.put(words.get(i), hashMap);
      } else {
        hashMap.put(documentsName, 1);
        dictionary.put(words.get(i), hashMap);
      }
    }
    writeToFile();
  }
  // Determine F(k+1) by support counting on (C(K+1), T) and retaining itemsets from C(k+1) with
  // support at least minsup
  private static List<Itemset> determineFrequentItemsets(
      List<Itemset> candicates, List<Transaction> transactions, double minsup) {
    if (candicates.isEmpty()) {
      return null;
    }

    HashTree hashTree = new HashTree(candicates, candicates.get(0).getNumOfItems());
    HashMap<Itemset, Integer> frequentCount = new HashMap<>();
    for (Itemset itemset : candicates) {
      frequentCount.put(itemset, 0);
    }

    for (Transaction transaction : transactions) {
      Set<Itemset> candidatesInTranscation = hashTree.candidatesInTransaction(transaction);
      if (candidatesInTranscation == null) {
        continue;
      }
      for (Itemset itemset : candidatesInTranscation) {
        if (transaction.containItemset(itemset)) {
          frequentCount.put(itemset, frequentCount.get(itemset) + 1);
        }
      }
    }

    List<Itemset> result = new ArrayList<>();
    for (Itemset itemset : candicates) {
      if ((double) (frequentCount.get(itemset)) / transactions.size() >= minsup) {
        result.add(itemset);
      }
    }
    return result;
  }
Beispiel #15
0
  private void insertAfter(JPegStmt node, JPegStmt after) {
    // System.out.println("node: "+node);
    // System.out.println("after: "+after);
    //		System.out.println("succs of node: "+getSuccsOf(node));

    // this must be done first because the succs of node will be chanaged lately
    List succOfAfter = new ArrayList();
    succOfAfter.addAll(getSuccsOf(node));
    unitToSuccs.put(after, succOfAfter);

    Iterator succsIt = getSuccsOf(node).iterator();
    while (succsIt.hasNext()) {
      Object succ = succsIt.next();
      List pred = getPredsOf(succ);
      pred.remove(node);
      pred.add(after);
    }

    List succOfNode = new ArrayList();
    succOfNode.add(after);
    unitToSuccs.put(node, succOfNode);

    List predOfAfter = new ArrayList();
    predOfAfter.add(node);
    unitToPreds.put(after, predOfAfter);

    //	buildPredecessor(Chain pegChain);
  }
Beispiel #16
0
 public static void main(String[] args) throws IOException {
   BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
   String[] temp = in.readLine().split(" ");
   int n = Integer.parseInt(temp[0]);
   int s = Integer.parseInt(temp[1]);
   HashMap<Integer, Integer> buy = new HashMap<>();
   HashMap<Integer, Integer> sell = new HashMap<>();
   for (int i = 1; i <= n; i++) {
     temp = in.readLine().split(" ");
     int p = Integer.parseInt(temp[1]);
     int q = Integer.parseInt(temp[2]);
     if (temp[0].charAt(0) == 'B') {
       if (buy.containsKey(p)) buy.put(p, buy.get(p) + q);
       else buy.put(p, q);
     } else {
       if (sell.containsKey(p)) sell.put(p, sell.get(p) + q);
       else sell.put(p, q);
     }
   }
   ArrayList<Integer> buyArr = new ArrayList<>();
   ArrayList<Integer> sellArr = new ArrayList<>();
   for (Integer i : buy.keySet()) buyArr.add(i);
   for (Integer i : sell.keySet()) sellArr.add(i);
   Collections.sort(buyArr, Comparator.reverseOrder());
   Collections.sort(sellArr);
   for (int i = Math.min(s, sellArr.size()) - 1; i >= 0; i--)
     System.out.println("S " + sellArr.get(i) + " " + sell.get(sellArr.get(i)));
   for (int i = 0; i < s && i < buyArr.size(); i++)
     System.out.println("B " + buyArr.get(i) + " " + buy.get(buyArr.get(i)));
 }
  public static void main(String[] args) {
    String testDataLocation = "testData/HighResolutionTerrain/";
    HashMap<String, Sector> sectors = new HashMap<String, Sector>();
    sectors.put(
        testDataLocation + "HRTOutputTest01.txt", Sector.fromDegrees(37.8, 38.3, -120, -119.3));
    sectors.put(
        testDataLocation + "HRTOutputTest02.txt",
        Sector.fromDegrees(32.34767, 32.77991, 70.88239, 71.47658));
    sectors.put(
        testDataLocation + "HRTOutputTest03.txt",
        Sector.fromDegrees(32.37825, 71.21130, 32.50050, 71.37926));

    try {
      if (args.length > 0 && args[0].equals("-generateTestData")) {
        for (Map.Entry<String, Sector> sector : sectors.entrySet()) {
          String filePath = sector.getKey();

          generateReferenceValues(filePath, sector.getValue());
        }
      }

      for (Map.Entry<String, Sector> sector : sectors.entrySet()) {
        String filePath = sector.getKey();

        ArrayList<Position> referencePositions = readReferencePositions(filePath);
        ArrayList<Position> computedPositions = computeElevations(referencePositions);
        testPositions(filePath, referencePositions, computedPositions);
      }
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    }
  }
 // keyboard discovery code
 private void _mapKey(char charCode, int keyindex, boolean shift, boolean altgraph) {
   log("_mapKey: " + charCode);
   // if character is not in map, add it
   if (!charMap.containsKey(new Integer(charCode))) {
     log("Notified: " + (char) charCode);
     KeyEvent event =
         new KeyEvent(
             applet(),
             0,
             0,
             (shift ? KeyEvent.SHIFT_MASK : 0) + (altgraph ? KeyEvent.ALT_GRAPH_MASK : 0),
             ((Integer) vkKeys.get(keyindex)).intValue(),
             (char) charCode);
     charMap.put(new Integer(charCode), event);
     log("Mapped char " + (char) charCode + " to KeyEvent " + event);
     if (((char) charCode) >= 'a' && ((char) charCode) <= 'z') {
       // put shifted version of a-z in automatically
       int uppercharCode = (int) Character.toUpperCase((char) charCode);
       event =
           new KeyEvent(
               applet(),
               0,
               0,
               KeyEvent.SHIFT_MASK + (altgraph ? KeyEvent.ALT_GRAPH_MASK : 0),
               ((Integer) vkKeys.get(keyindex)).intValue(),
               (char) uppercharCode);
       charMap.put(new Integer(uppercharCode), event);
       log("Mapped char " + (char) uppercharCode + " to KeyEvent " + event);
     }
   }
 }
  public void addToCache(
      Class<? extends Plugin> plugin,
      final RemoteManagerEndpoint manager,
      final DiscoveredPlugin src) {
    synchronized (this.cache) {
      // 1) get all managers providing this plugin
      HashMap<RemoteManagerEndpoint, Entry> managers = this.cache.get(plugin);
      if (null == managers) { // if we dont have one, so create
        managers = new HashMap<RemoteManagerEndpoint, Entry>();
        managers.put(manager, new Entry(plugin.getCanonicalName(), manager, src));

        this.cache.put(plugin, managers);

        return;
      }

      // 2) get the entry providing this plugin.
      Entry entry = managers.get(manager);
      if (null == entry) { // no entry
        managers.put(manager, new Entry(plugin.getCanonicalName(), manager, src));
        return;
      }

      // 3) here it means we have already an entry... so skip!!!
    }
  }
Beispiel #20
0
  /**
   * Constructor
   *
   * @param name name of bot
   * @param path root path of Program AB
   * @param action Program AB action
   */
  public Bot(String name, String path, String action) {
    int cnt = 0;
    int elementCnt = 0;
    this.name = name;
    setAllPaths(path, name);
    this.brain = new Graphmaster(this);

    this.learnfGraph = new Graphmaster(this, "learnf");
    this.learnGraph = new Graphmaster(this, "learn");
    //      this.unfinishedGraph = new Graphmaster(this);
    //  this.categories = new ArrayList<Category>();

    preProcessor = new PreProcessor(this);
    addProperties();
    cnt = addAIMLSets();
    if (MagicBooleans.trace_mode) System.out.println("Loaded " + cnt + " set elements.");
    cnt = addAIMLMaps();
    if (MagicBooleans.trace_mode) System.out.println("Loaded " + cnt + " map elements");
    this.pronounSet = getPronouns();
    AIMLSet number = new AIMLSet(MagicStrings.natural_number_set_name, this);
    setMap.put(MagicStrings.natural_number_set_name, number);
    AIMLMap successor = new AIMLMap(MagicStrings.map_successor, this);
    mapMap.put(MagicStrings.map_successor, successor);
    AIMLMap predecessor = new AIMLMap(MagicStrings.map_predecessor, this);
    mapMap.put(MagicStrings.map_predecessor, predecessor);
    AIMLMap singular = new AIMLMap(MagicStrings.map_singular, this);
    mapMap.put(MagicStrings.map_singular, singular);
    AIMLMap plural = new AIMLMap(MagicStrings.map_plural, this);
    mapMap.put(MagicStrings.map_plural, plural);
    // System.out.println("setMap = "+setMap);
    Date aimlDate = new Date(new File(aiml_path).lastModified());
    Date aimlIFDate = new Date(new File(aimlif_path).lastModified());
    if (MagicBooleans.trace_mode)
      System.out.println("AIML modified " + aimlDate + " AIMLIF modified " + aimlIFDate);
    // readUnfinishedIFCategories();
    MagicStrings.pannous_api_key = Utilities.getPannousAPIKey(this);
    MagicStrings.pannous_login = Utilities.getPannousLogin(this);
    if (action.equals("aiml2csv")) addCategoriesFromAIML();
    else if (action.equals("csv2aiml")) addCategoriesFromAIMLIF();
    else if (action.equals("chat-app")) {
      if (MagicBooleans.trace_mode) System.out.println("Loading only AIMLIF files");
      cnt = addCategoriesFromAIMLIF();
    } else if (aimlDate.after(aimlIFDate)) {
      if (MagicBooleans.trace_mode) System.out.println("AIML modified after AIMLIF");
      cnt = addCategoriesFromAIML();
      writeAIMLIFFiles();
    } else {
      addCategoriesFromAIMLIF();
      if (brain.getCategories().size() == 0) {
        System.out.println("No AIMLIF Files found.  Looking for AIML");
        cnt = addCategoriesFromAIML();
      }
    }
    Category b =
        new Category(
            0, "PROGRAM VERSION", "*", "*", MagicStrings.program_name_version, "update.aiml");
    brain.addCategory(b);
    brain.nodeStats();
    learnfGraph.nodeStats();
  }
  public static ArrayList<ArrayList<TaggedWord>> getPhrasesNaive(
      String sentence, LexicalizedParser lp, AbstractSequenceClassifier<CoreLabel> classifier) {
    ArrayList<ArrayList<TaggedWord>> newList = new ArrayList<ArrayList<TaggedWord>>();
    ArrayList<TaggedWord> taggedWords = StanfordNER.parse(sentence, lp, classifier);
    HashMap<String, String> phraseBoundaries = new HashMap<String, String>();
    phraseBoundaries.put(",", ",");
    phraseBoundaries.put("\"", "\"");
    phraseBoundaries.put("''", "''");
    phraseBoundaries.put("``", "``");
    phraseBoundaries.put("--", "--");
    // List<Tree> leaves = parse.getLeaves();
    ArrayList<TaggedWord> temp = new ArrayList<TaggedWord>();
    int index = 0;
    while (index < taggedWords.size()) {
      if ((phraseBoundaries.containsKey(taggedWords.get(index).word()))) {
        if (temp.size() > 0) {
          // System.out.println(temp);
          ArrayList<TaggedWord> tempCopy = new ArrayList<TaggedWord>(temp);
          newList.add(Preprocess(tempCopy));
        }
        temp.clear();
      } else {
        // System.out.println(taggedWords.get(index).toString());
        temp.add(taggedWords.get(index));
      }
      index += 1;
    }
    if (temp.size() > 0) {
      ArrayList<TaggedWord> tempCopy = new ArrayList<TaggedWord>(temp);
      newList.add(Preprocess(tempCopy));
    }

    // System.out.println(newList);
    return newList;
  }
Beispiel #22
0
  /**
   * Determines and retrieves data related to the first confluence node (defined as a node with two
   * or more incoming transitions) of a _transition path corresponding to a given String from a
   * given node.
   *
   * @param originNode the MDAGNode from which the _transition path corresponding to str starts from
   * @param str a String corresponding to a _transition path in the MDAG
   * @return a HashMap of Strings to Objects containing: - an int denoting the length of the path to
   *     the first confluence node in the _transition path of interest - the MDAGNode which is the
   *     first confluence node in the _transition path of interest (or null if one does not exist)
   */
  private HashMap<String, Object> getTransitionPathFirstConfluenceNodeData(
      MDAGNode originNode, String str) {
    int currentIndex = 0;
    int charCount = str.length();
    MDAGNode currentNode = originNode;

    // Loop thorugh the characters in str, sequentially using them to _transition through the MDAG
    // in search of
    // (and breaking upon reaching) the first node that is the target of two or more transitions.
    // The loop is
    // also broken from if the currently processing node doesn't have a _transition labeled with the
    // currently processing char.
    for (; currentIndex < charCount; currentIndex++) {
      char currentChar = str.charAt(currentIndex);
      currentNode =
          (currentNode.hasOutgoingTransition(currentChar)
              ? currentNode.transition(currentChar)
              : null);

      if (currentNode == null || currentNode.isConfluenceNode()) break;
    }
    /////

    boolean noConfluenceNode = (currentNode == originNode || currentIndex == charCount);

    // Create a HashMap containing the index of the last char in the substring corresponding
    // to the transitoin path to the confluence node, as well as the actual confluence node
    HashMap<String, Object> confluenceNodeDataHashMap = new HashMap<String, Object>(2);
    confluenceNodeDataHashMap.put(
        "toConfluenceNodeTransitionCharIndex", (noConfluenceNode ? null : currentIndex));
    confluenceNodeDataHashMap.put("confluenceNode", noConfluenceNode ? null : currentNode);
    /////

    return confluenceNodeDataHashMap;
  }
Beispiel #23
0
 public void testMapSelection() throws Exception {
   // Drop
   removeAll(MapHolder.class);
   // Create
   MapHolder mapHolder = new MapHolder();
   Book book = new Book("Book of Bokonon", "9");
   HashMap meta = new HashMap();
   meta.put("meta1", new Author("Geordi", "LaForge"));
   meta.put("meta2", new Author("Data", ""));
   meta.put("meta3", new Author("Scott", "Montgomery"));
   meta.put("book", book);
   mapHolder.setMeta(meta);
   // Save
   getStore().save(mapHolder);
   // Select
   List result =
       getStore()
           .find(
               "find mapholder where mapholder.meta['book'](book)=book and book.title like 'Book%'");
   Assert.assertEquals(result.size(), 1);
   result =
       getStore()
           .find("find mapholder where mapholder.meta['book'](book)=book and book.title like '9'");
   Assert.assertEquals(result.size(), 0);
 }
Beispiel #24
0
 public static void traverseAMLforObjectNames(
     HashMap partialMap, Node currentNode, HashMap ObjDef_LinkId, HashMap ModelId_ModelType) {
   if (currentNode.hasChildNodes()) {
     for (int i = 0; i < currentNode.getChildNodes().getLength(); i++) {
       Node currentChild = currentNode.getChildNodes().item(i);
       if (currentChild.getNodeName().equals("Group")) {
         traverseAMLforObjectNames(partialMap, currentChild, ObjDef_LinkId, ModelId_ModelType);
       }
       if (currentChild.getNodeName().equals("Model")) {
         if (currentChild.hasAttributes()) {
           String mid = currentChild.getAttributes().getNamedItem("Model.ID").getNodeValue();
           String type = currentChild.getAttributes().getNamedItem("Model.Type").getNodeValue();
           ModelId_ModelType.put(mid, type);
         }
         // traverseAMLforObjectNames(partialMap, currentChild,
         // ObjDef_LinkId);
       }
       if (currentChild.getNodeName().equals("ObjDef")) {
         String id = currentChild.getAttributes().getNamedItem("ObjDef.ID").getNodeValue();
         NodeList currentChildren = currentChild.getChildNodes();
         String ObjName = "";
         for (int k = 0; k < currentChildren.getLength(); k++) {
           Node Child = currentChildren.item(k);
           if (!Child.getNodeName().equals("AttrDef")) {
             continue;
           } else if (!Child.getAttributes()
               .getNamedItem("AttrDef.Type")
               .getNodeValue()
               .equals("AT_NAME")) {
             continue;
           } else if (Child.hasChildNodes()) {
             for (int l = 0; l < Child.getChildNodes().getLength(); l++) {
               if (!(Child.getChildNodes().item(l).getNodeName().equals("AttrValue"))) {
                 continue;
               } else {
                 ObjName = getTextContent(Child.getChildNodes().item(l));
                 ObjName = ObjName.replaceAll("\n", "\\\\n");
                 break;
               }
             }
           }
         }
         partialMap.put(id, ObjName);
         for (int j = 0; j < currentChild.getAttributes().getLength(); j++) {
           if (currentChild.getAttributes().item(j).getNodeName().equals("LinkedModels.IdRefs")) {
             String links =
                 currentChild.getAttributes().getNamedItem("LinkedModels.IdRefs").getNodeValue();
             /*
              * if (links.indexOf(" ") > -1) {
              * Message.add("yes, yes, yes"); links =
              * links.substring(0, links.indexOf(" ")); }
              */
             ObjDef_LinkId.put(id, links);
           }
         }
       }
     }
   }
 }
Beispiel #25
0
 static {
   humanColorCodes.put("GRE", "9D9");
   humanColorCodes.put("BLU", "55B");
   humanColorCodes.put("PNK", "FAA");
   humanColorCodes.put("RED", "E32");
   humanColorCodes.put("YEL", "FF3");
   humanColorCodes.put("BLK", "000");
 }
Beispiel #26
0
  /**
   * Find mod classes in the class path and enumerated mod files list
   *
   * @param classPathEntries Java class path split into string entries
   * @return map of classes to load
   */
  private HashMap<String, Class> findModClasses(
      String[] classPathEntries, LinkedList<File> modFiles) {
    // To try to avoid loading the same mod multiple times if it appears in more than one entry in
    // the class path, we index
    // the mods by name and hopefully match only a single instance of a particular mod
    HashMap<String, Class> modsToLoad = new HashMap<String, Class>();

    try {
      logger.info("Searching protection domain code source...");

      File packagePath =
          new File(LiteLoader.class.getProtectionDomain().getCodeSource().getLocation().toURI());
      LinkedList<Class> modClasses =
          getSubclassesFor(packagePath, Minecraft.class.getClassLoader(), LiteMod.class, "LiteMod");

      for (Class mod : modClasses) {
        modsToLoad.put(mod.getSimpleName(), mod);
      }

      if (modClasses.size() > 0)
        logger.info(String.format("Found %s potential matches", modClasses.size()));
    } catch (Throwable th) {
      logger.warning("Error loading from local class path: " + th.getMessage());
    }

    // Search through the class path and find mod classes
    for (String classPathPart : classPathEntries) {
      logger.info(String.format("Searching %s...", classPathPart));

      File packagePath = new File(classPathPart);
      LinkedList<Class> modClasses =
          getSubclassesFor(packagePath, Minecraft.class.getClassLoader(), LiteMod.class, "LiteMod");

      for (Class mod : modClasses) {
        modsToLoad.put(mod.getSimpleName(), mod);
      }

      if (modClasses.size() > 0)
        logger.info(String.format("Found %s potential matches", modClasses.size()));
    }

    // Search through mod files and find mod classes
    for (File modFile : modFiles) {
      logger.info(String.format("Searching %s...", modFile.getAbsolutePath()));

      LinkedList<Class> modClasses =
          getSubclassesFor(modFile, Minecraft.class.getClassLoader(), LiteMod.class, "LiteMod");

      for (Class mod : modClasses) {
        modsToLoad.put(mod.getSimpleName(), mod);
      }

      if (modClasses.size() > 0)
        logger.info(String.format("Found %s potential matches", modClasses.size()));
    }

    return modsToLoad;
  }
Beispiel #27
0
  @Override
  protected void setUp() throws Exception {
    tmp = IO.getFile("generated/tmp");
    tmp.mkdirs();
    IO.copy(IO.getFile("testdata/ws"), tmp);
    workspace = Workspace.getWorkspace(tmp);
    workspace.refresh();

    InfoRepository repo = workspace.getPlugin(InfoRepository.class);
    t1 = create("bsn-1", new Version(1, 0, 0));
    t2 = create("bsn-2", new Version(1, 0, 0));

    repo.put(new FileInputStream(t1), null);
    repo.put(new FileInputStream(t2), null);
    t1 = repo.get("bsn-1", new Version(1, 0, 0), null);
    t2 = repo.get("bsn-2", new Version(1, 0, 0), null);
    repo.put(new FileInputStream(IO.getFile("generated/biz.aQute.remote.launcher.jar")), null);

    workspace.getPlugins().add(repo);

    File storage = IO.getFile("generated/storage-1");
    storage.mkdirs();

    configuration = new HashMap<String, Object>();
    configuration.put(
        Constants.FRAMEWORK_STORAGE_CLEAN, Constants.FRAMEWORK_STORAGE_CLEAN_ONFIRSTINIT);
    configuration.put(Constants.FRAMEWORK_STORAGE, storage.getAbsolutePath());

    configuration.put(
        Constants.FRAMEWORK_SYSTEMPACKAGES_EXTRA, "org.osgi.framework.launch;version=1.2");

    framework = new org.apache.felix.framework.FrameworkFactory().newFramework(configuration);
    framework.init();
    framework.start();
    context = framework.getBundleContext();
    location = "reference:" + IO.getFile("generated/biz.aQute.remote.agent.jar").toURI().toString();
    agent = context.installBundle(location);
    agent.start();

    thread =
        new Thread() {
          @Override
          public void run() {
            try {
              Main.main(
                  new String[] {
                    "-s", "generated/storage", "-c", "generated/cache", "-p", "1090", "-et"
                  });
            } catch (Exception e) {
              e.printStackTrace();
            }
          }
        };
    thread.setDaemon(true);
    thread.start();

    super.setUp();
  }
Beispiel #28
0
  private boolean validateTables(TSelectSqlStatement stmt) {
    HashMap<String, Integer> present = new HashMap<String, Integer>();
    if (!stmt.getResultColumnList().getResultColumn(0).toString().equals("*")) {

      int cols = stmt.getResultColumnList().size();
      for (int a = 0; a < cols; a++) {
        present.put(
            stmt.getResultColumnList()
                .getResultColumn(a)
                .toString()
                .toLowerCase()
                .replace("(", "")
                .replace(")", ""),
            0);
      }
    }

    TJoinList joins = stmt.joins;
    int j = joins.size();
    int invalid = 1;
    for (int i = 0; i < j; i++) {
      Iterator<Table> it = DBSystem.tableList.iterator();
      Table table = null;
      while (it.hasNext()) {
        table = it.next();
        if (table.getName().equalsIgnoreCase(joins.getJoin(i).toString())) {
          invalid = 0;
          if (!stmt.getResultColumnList().getResultColumn(0).toString().equals("*")) {
            Iterator it1 = table.getColumnData().entrySet().iterator();

            while (it1.hasNext()) {
              Map.Entry pairs = (Map.Entry) it1.next();
              if (present.get(pairs.getKey().toString().toLowerCase()) != null
                  && present.get(pairs.getKey().toString().toLowerCase()) == 0) {
                present.put(pairs.getKey().toString(), 1);
              } else if (present.get(pairs.getKey().toString().toLowerCase()) != null
                  && present.get(pairs.getKey().toString().toLowerCase()) == 1) return false;
            }
          }
        }
      }
      if (invalid == 1) return false;
      else {
        invalid = 1;
      }
    }
    if (!stmt.getResultColumnList().getResultColumn(0).toString().equals("*")) {
      Iterator it2 = present.entrySet().iterator();
      while (it2.hasNext()) {
        Map.Entry pairs = (Map.Entry) it2.next();
        if ((Integer) pairs.getValue() == 0) {
          return false;
        }
      }
    }
    return true;
  }
Beispiel #29
0
  private void loadDataXM(RandomAccessFile fp) throws IOException {
    byte[] b = new byte[20];

    // WHY THE HELL AM I DOING THIS
    name = Util.readStringNoNul(fp, b, 20);
    System.out.printf("name: \"%s\"\n", name);
    fp.read(); // skip 0x1A byte

    // THIS CAN'T BE HAPPENING
    fp.read(b, 0, 20); // skip tracker name

    // OH HELL NO
    int xmver = 0xFFFF & (int) Short.reverseBytes(fp.readShort());
    System.out.printf("XM version: %04X\n", xmver);

    // WHAT IS THIS CRAP
    InhibitedFileBlock ifb = new InhibitedFileBlock(fp, Integer.reverseBytes(fp.readInt()) - 4);

    // HELP ME PLEASE
    int ordnum = 0xFFFF & (int) Short.reverseBytes(ifb.readShort());
    int respos =
        0xFFFF & (int) Short.reverseBytes(ifb.readShort()); // can't be bothered right now --GM
    int chnnum =
        0xFFFF & (int) Short.reverseBytes(ifb.readShort()); // yeah sure, allow out of range values
    if (chnnum > 64)
      throw new RuntimeException(
          String.format("%d-channel modules not supported (max 64)", chnnum));
    int patnum = 0xFFFF & (int) Short.reverseBytes(ifb.readShort());
    int insnum = 0xFFFF & (int) Short.reverseBytes(ifb.readShort());
    int xmflags = 0xFFFF & (int) Short.reverseBytes(ifb.readShort());
    int xmspeed = 0xFFFF & (int) Short.reverseBytes(ifb.readShort());
    int xmtempo = 0xFFFF & (int) Short.reverseBytes(ifb.readShort());

    // OH PLEASE, STOP IT
    if (ordnum > 255) ordnum = 255;
    if (xmtempo > 255) xmtempo = 255;
    if (xmspeed > 255) xmspeed = 255;
    this.bpm = xmtempo;
    this.spd = xmspeed;
    this.flags = FLAG_COMPATGXX | FLAG_OLDEFFECTS | FLAG_INSMODE | FLAG_STEREO | FLAG_VOL0MIX;

    if ((xmflags & 0x01) != 0) this.flags |= FLAG_LINEAR;

    // NONONONONONO
    System.out.printf("chn=%d ordnum=%d tempo=%d speed=%s\n", chnnum, ordnum, xmtempo, xmspeed);
    for (int i = 0; i < 256; i++) orderlist[i] = ifb.read();
    for (int i = ordnum; i < 256; i++) orderlist[i] = 255;

    ifb.done();

    // SAVE ME PLEEEEEAAASSSSEEEE
    for (int i = 0; i < patnum; i++)
      map_pat.put((Integer) i, new SessionPattern(this, fp, SessionPattern.FORMAT_XM, chnnum));
    for (int i = 0; i < insnum; i++)
      map_ins.put((Integer) (i + 1), new SessionInstrument(fp, SessionInstrument.FORMAT_XM, this));
  }
Beispiel #30
0
 // static initialization
 static {
   sbmlUnitNames = new HashMap<Integer, String>();
   sbmlUnitKinds = new HashMap<String, Integer>();
   for (int i = 0; i < SBML_UNIT_NAMES.length; i++) {
     String name = SBML_UNIT_NAMES[i];
     Integer code = new Integer(SBML_UNIT_KINDS[i]);
     sbmlUnitNames.put(code, name);
     sbmlUnitKinds.put(name, code);
   }
 }