コード例 #1
0
ファイル: Solution.java プロジェクト: aafak/java-projects
  public static void main(String[] args) {
    // TODO Auto-generated method stub

    Scanner in = new Scanner(System.in);
    Hashtable numbers = new Hashtable();

    N = in.nextInt();
    K = in.nextLong();

    long[] arr = new long[N];
    for (int i = 0; i < N; i++) {
      arr[i] = in.nextLong();
      numbers.put(Long.toString(arr[i]), arr[i]);
    }

    result = 0;

    for (int i = 0; i < N; i++) {
      long tmp = 0, tmp2 = 0;
      tmp = arr[i] + K;
      try {
        tmp2 = (Long) numbers.get(Long.toString(tmp));
        result++;
      } catch (Exception ex) {

      }
    }

    System.out.println(result);
  }
コード例 #2
0
ファイル: LlamaChat.java プロジェクト: raulgq1/LlamaChat
 /**
  * creates a new channel, if the channel exists it is removed (this method doubles as a
  * removeChannel)
  *
  * @param name the name of the channel
  */
 public void newChannel(String name, boolean pass) {
   if (channels.containsKey(name)) {
     channels.remove(name);
     cboChannels.removeItem(name);
   } else {
     channels.put(name, new Boolean(pass));
     cboChannels.addItem(name);
   }
 }
コード例 #3
0
  /**
   * This Method returns the 2D Array which is the list of the Items for the selected WorkOrder of
   * the Customer.
   *
   * @param workorderId - WorkOrder Id Foreign Key of WRK_ORDR_DETS table
   * @return Object[][] - 2D Array which is List of the Items for the WorkOrder
   */
  public Object[][] getWorkOrderItems(long workorderId) throws RemoteException {

    WrkOrdrDets wrkordrdts_obj = new WrkOrdrDets(conn);

    RHCCBlgKeys blgkeys_obj = new RHCCBlgKeys(conn);

    Vector workorderdetList = wrkordrdts_obj.getProductList(workorderId);

    // Hashtable BSysList = (Hashtable) USFEnv.getBillSystems();
    BlgSys blgsys = new BlgSys();

    Hashtable BSysList = (Hashtable) blgsys.searchBlgSys();

    Enumeration BSys = BSysList.keys();

    // The 2-Dimensional array to hold the Items Billing System wise.
    Object[][] prodList = new Object[BSysList.size()][workorderdetList.size() + 1];

    // The Number of Billing Systems are assumed to be equal to the
    // Static Load Billing Systems Hashtable size. The Billing Systems will
    // be in order starting from 1 and incrementing by one.
    for (int i = 0; i < BSysList.size(); i++) {
      // Set the 2D array to store the Billing System as the first element
      // of each row.
      prodList[i][0] = String.valueOf(i + 1);
    }

    // Loop throught the WorkOrder Items List and place them in the appropriate
    // positions in the 2D array.
    for (int j = 0; j < workorderdetList.size(); j++) {
      // Determine the Billing System of the Product
      Vector tmpVector = new Vector();

      WrkOrdrDets workorderObj = (WrkOrdrDets) workorderdetList.elementAt(j);

      RHCCBlgKeys bkObj =
          blgkeys_obj.searchRHCCBlgKeys(((WrkOrdrDets) workorderdetList.elementAt(j)).getRBKID());
      int bsid = (new Long(bkObj.getBsId())).intValue();

      tmpVector.addElement(bkObj);
      tmpVector.addElement(workorderObj);

      // Based on the Billing System Id retreived place the Product Object
      // in the 2D array.
      int k = 1;
      while (prodList[bsid - 1][k] != null) {
        k = k + 1;
      }
      prodList[bsid - 1][k] = tmpVector;
    }

    // Return the 2D array
    return prodList;
  }
コード例 #4
0
ファイル: TTConnection.java プロジェクト: plucena/talkagent
 protected String queryString(String query) throws IOException {
   if (USECACHE) {
     if (cache == null) cache = new Hashtable();
     Object r = cache.get(query);
     if (r != null) return (String) r;
     String r1 = queryString1(query);
     cache.put(query, r1);
     return r1;
   } else {
     return queryString1(query);
   }
 }
コード例 #5
0
ファイル: TTConnection.java プロジェクト: plucena/talkagent
 protected Vector /* of TTPNode */ queryPNodes(String query) throws IOException {
   if (USECACHE) {
     if (cache == null) cache = new Hashtable();
     Object r = cache.get(query);
     if (r != null) return (Vector) r;
     Vector r1 = queryPNodes1(query);
     cache.put(query, r1);
     return r1;
   } else {
     return queryPNodes1(query);
   }
 }
コード例 #6
0
ファイル: TTConnection.java プロジェクト: plucena/talkagent
 protected boolean queryBoolean(String query) throws IOException {
   if (USECACHE) {
     if (cache == null) cache = new Hashtable();
     Object r = cache.get(query);
     if (r != null) return ((Boolean) r).booleanValue();
     Boolean r1 = queryBoolean1(query);
     cache.put(query, r1);
     return r1.booleanValue();
   } else {
     return queryBoolean1(query).booleanValue();
   }
 }
コード例 #7
0
  public static void main(String args[]) {
    Hashtable<String, Integer> table = new Hashtable<String, Integer>();

    table.put("Hello", 4);
    table.put("Intro", 24);
    table.put("Auroville", 10);

    // iterate over the keys of the hash table
    Enumeration<String> keys = table.keys();
    while (keys.hasMoreElements()) {
      String k = keys.nextElement();
      System.out.println("found key " + k);
    }
  }
コード例 #8
0
  public void setParameters(Hashtable params) {
    setName("TiniBogusLocationResource");
    setScalingFactor((long) Constants.Geophysical.DEGTOBILLIONTHS);
    attrtable = params;
    if (params != null) {
      if (params.get("Latitude") != null) {
        String pstr = (String) params.get("Latitude");
        Double temp = new Double(pstr);
        latitude = temp.doubleValue();
      }
      if (params.get("Longitude") != null) {
        String pstr = (String) params.get("Longitude");
        Double temp = new Double(pstr);
        longitude = temp.doubleValue();
      }
      if (params.get("Heading") != null) {
        String pstr = (String) params.get("Heading");
        Double temp = new Double(pstr);
        heading = temp.doubleValue();
      }

      if (params.get("Altitude") != null) {
        String pstr = (String) params.get("Altitude");
        Double temp = new Double(pstr);
        altitude = temp.doubleValue();
      }
    }
  }
コード例 #9
0
  /** Get the panel for a given form. * */
  public JPanel getPanelFor(ArrayList elements) {
    JPanel p = new JPanel(new GridBagLayout());
    int maxCols = 1;
    int elementSize = elements.size();
    for (int i = 0; i < elementSize; i++) { // count max number of cols
      // ((XmlUIElement)elements.get(i)).setEditable(true);//by jai
      int cols = ((XmlUIElement) elements.get(i)).getNumberOfColumns();
      if (cols > maxCols) {
        maxCols = cols;
      }
    }
    GridBagConstraints c = new GridBagConstraints();
    c.fill = GridBagConstraints.BOTH;
    c.weightx = 1.0;
    c.gridx = 0;
    c.gridy = 0;
    if (elementSize < 5) c.insets = new Insets(8, 8, 8, 14);
    else if (elementSize < 20) c.insets = new Insets(4, 4, 4, 10);
    else if ((elementSize > 40 && maxCols == 2) || (elementSize > 80 && maxCols == 4))
      c.insets = new Insets(1, 1, 1, 8);
    else c.insets = new Insets(2, 2, 2, 8);

    int rowsAdded = 0;
    for (int i = 0; i < elementSize; i++) {
      elementsAndPanels.put(elements.get(i), p);
      rowsAdded += ((XmlUIElement) elements.get(i)).addComponents(p, c, 0, rowsAdded, maxCols);
    }
    return p;
  }
コード例 #10
0
  // ------------------------------------------------------------------------
  // SCREEN PAINTER
  // Put some function here to paint whatever you want over the screen before and after
  // all edges and nodes have been painted.
  public void PaintScreenBefore(Graphics g) {

    Dimension d = MainClass.mainFrame.GetGraphDisplayPanel().getSize();
    NodeInfo nodeInfo;
    int x = 0;
    int y = 0;
    int step = 10;

    for (; x < d.width; x += step) {
      for (y = 0; y < d.height; y += step) {
        double val = 0;
        double sum = 0;
        double total = 0;
        double min = 10000000;
        for (Enumeration nodes = proprietaryNodeInfo.elements(); nodes.hasMoreElements(); ) {
          nodeInfo = (NodeInfo) nodes.nextElement();
          double dist = distance(x, y, nodeInfo.centerX, nodeInfo.centerY);
          if (nodeInfo.value != -1 && nodeInfo.nodeNumber.intValue() != 1) { // 121
            if (dist < min) min = dist;
            val += ((double) nodeInfo.value) / dist / dist;
            sum += (1 / dist / dist);
          }
        }
        int reading = (int) (val / sum);
        reading = reading >> 2;
        if (reading > 255) reading = 255;
        g.setColor(new Color(reading, reading, reading));
        g.fillRect(x, y, step, step);
      }
    }
  }
コード例 #11
0
 public double getLossRate(int senderID, int receiverID) {
   Double d = (Double) connectivityGraph.get(graphKey(senderID, receiverID));
   if (d == null) {
     throw new ArrayIndexOutOfBoundsException(
         "no connectivity entry for " + senderID + " -> " + receiverID);
   }
   return d.doubleValue();
 }
コード例 #12
0
ファイル: ScanWord.java プロジェクト: christinapanto/project
  /**
   * return the matching token given the keyword
   *
   * @param s Keyword.
   */
  public int getKeyValue(String s) {

    if (s == null) return UNKNOWN;

    Integer i = (Integer) kwords.get(s.toLowerCase());

    if (i == null) return UNKNOWN;
    else return i.intValue();
  }
コード例 #13
0
 // ------------------------------------------------------------------------
 // NODE PAINTER
 // Put some function here to paint whatever you want over the node.
 // The x1,y1 coordinates are the top left corner within which the node will be drawn
 // The x2,y2 coordinates are the bottom right corner
 // Paint everything on the graphics object
 // this function is called by DisplayManager
 public void PaintNode(Integer pNodeNumber, int x1, int y1, int x2, int y2, Graphics g) {
   NodeInfo nodeInfo = (NodeInfo) proprietaryNodeInfo.get(pNodeNumber);
   if (nodeInfo == null) return;
   int light = nodeInfo.GetValue();
   if (light == -1) return;
   nodeInfo.centerX = (x1 + x2) / 2;
   nodeInfo.centerY = (y1 + y2) / 2;
   // System.out.println(pNodeNumber);
 }
コード例 #14
0
 private JPanel getPanelWithTable(ArrayList list, Table element) throws InvalidTemplateException {
   JTable table = getTable(list, element);
   JPanel panel = new JPanel();
   panel.setLayout(new BorderLayout());
   panel.add(new JScrollPane(table));
   for (int j = 0; j < list.size(); j++) {
     elementsAndPanels.put(list.get(j), panel);
   }
   return panel;
 }
コード例 #15
0
  public void register() {
    debug.out.println("RADIOMODEL: registering radio model plugin");
    connectivityGraph = new Hashtable();

    EmpiricalModel empiricalModel = new EmpiricalModel();
    models.put("empirical", empiricalModel);
    curModel = empiricalModel;

    // User can use scaling factor to adjust
    DiscModel dm;
    dm = new DiscModel(10.0);
    models.put("disc10", dm);
    dm = new DiscModel(100.0);
    models.put("disc100", dm);
    dm = new DiscModel(1000.0);
    models.put("disc1000", dm);

    updateModel();
  }
コード例 #16
0
ファイル: LlamaChat.java プロジェクト: raulgq1/LlamaChat
 /** cleans up a connection by removing all user from all maintained lists */
 public void close() {
   error("Connection to server was lost");
   admin = false;
   users.clear();
   afks.clear();
   ignores.clear();
   admins.clear();
   channels.clear();
   cboChannels.removeAllItems();
   updateList();
 }
コード例 #17
0
 public boolean areInputValuesValid() {
   for (int i = 0; i < uiList.size(); i++) {
     XmlUIElement el = (XmlUIElement) uiElementsList.get(i);
     try {
       el.checkConstraints();
     } catch (Exception e) {
       errorMessage = e.getMessage();
       incompletePanel = (JPanel) elementsAndPanels.get(el);
       return false;
     }
     if ((el.isRequired()) && (el.isValueNull())) {
       errorMessage =
           MessageFormat.format(
               ProvClientUtils.getString("{0} field cannot be empty"),
               new Object[] {el.getLabelName()});
       incompletePanel = (JPanel) elementsAndPanels.get(el);
       return false;
     }
   }
   return true;
 }
コード例 #18
0
ファイル: ExtractEmails.java プロジェクト: andrewh-code/stuff
 {
     //create out of bounds exception emailList.get(-1)
     if (emailList.get(i) == emailList.get(i-1))
     {
         dupEmailCount++;
     }
     else
     {
         //insert domain email, dupEmailCount into hashtable
         domainCount.put(emailList.get(i), dupEmailCount);
         dupEmailCount = 0;
     }
 }
コード例 #19
0
  public void handleEvent(SimEvent event) {
    if (event instanceof SimObjectEvent) {
      SimObjectEvent simObjectEvent = (SimObjectEvent) event;
      SimObject simObject = simObjectEvent.getSimObject();
      switch (simObjectEvent.getType()) {
        case SimObjectEvent.OBJECT_ADDED:
        case SimObjectEvent.OBJECT_REMOVED:
          // always fully update the model
          debug.err.println("RADIOMODEL: sim object add/remove, updating model");
          updateModel();
          break;
      }
    } else if (event instanceof AttributeEvent) {
      AttributeEvent attributeEvent = (AttributeEvent) event;
      switch (attributeEvent.getType()) {
        case ATTRIBUTE_CHANGED:
          if (attributeEvent.getAttribute() instanceof MoteCoordinateAttribute) {
            MoteSimObject mote = (MoteSimObject) attributeEvent.getOwner();
            debug.err.println("RADIOMODEL: " + mote + " moved, updating links");
            updateLossRates(mote);
          }
          break;
      }
    }

    // XXX/demmer this isn't necessary since we already respond to the
    // updated location attributes
    //     else if (event instanceof SimObjectDraggedEvent) {
    //       updateModel(true);
    //     }

    else if (event instanceof OptionSetEvent) {
      OptionSetEvent ose = (OptionSetEvent) event;

      if (ose.name.equals("radiomodel")) {
        PropagationModel pm = (PropagationModel) models.get(ose.value);
        if (pm != null) {
          debug.err.println("RADIOMODEL: Setting model to " + pm);
          curModel = pm;
          updateModel();
        }
      }

      // also not necessary since it generates new simobjectevents
      //     } else if (event instanceof TossimInitEvent) {
      //       driver.pause();
      //       updateModel();
      //       publishModel();
      //       driver.resume();
    }
  }
コード例 #20
0
  // ------------------------------------------------------------------------
  // *****---Packet Recieved event handler---******//
  // this function will be called by the thread running the packetReciever
  // everytime a new packet is recieved
  // make sure it is synchronized if it modifies any of your data
  public synchronized void PacketReceived(PacketEvent e) {
    // this function defines what you do when a new packet is heard by the system (recall that the
    // parent class (PacketAnalyzer) already registered you to listen for new packets automatically)
    // if this is a long function, you should call it in a seperate thread to allow the
    // PacketReciever thread to continue recieving packets

    Packet packet = e.GetPacket();
    Vector node_list = packet.CreateRoutePathArray();
    for (int i = 0; i < node_list.size() - 1; i++) {
      Integer currentNodeNumber = (Integer) node_list.elementAt(i);
      NodeInfo currentNodeInfo;
      if ((currentNodeInfo = (NodeInfo) proprietaryNodeInfo.get(currentNodeNumber)) != null) {
        currentNodeInfo.SetValue(packet.getValue());
      }
    }
  }
コード例 #21
0
  // Send the loss rate for all pairs of motes to the simulator
  public void publishModel() {
    debug.err.println("RADIOMODEL: Publishing model, current is " + curModel);
    Iterator it1 = state.getMoteSimObjects().iterator();
    while (it1.hasNext()) {
      MoteSimObject moteSender = (MoteSimObject) it1.next();
      MoteCoordinateAttribute moteSenderCoord = moteSender.getCoordinate();
      Iterator it2 = state.getMoteSimObjects().iterator();
      while (it2.hasNext()) {
        MoteSimObject moteReceiver = (MoteSimObject) it2.next();
        if (moteReceiver.getID() == moteSender.getID()) continue;

        String key = graphKey(moteSender, moteReceiver);
        double prob = ((Double) connectivityGraph.get(key)).doubleValue();
        publishLossRate(moteSender, moteReceiver, prob);
      }
    }
  }
コード例 #22
0
  // Recalculate the loss rate for the pair of motes based on their
  // distance and the current model
  public void updateLossRate(MoteSimObject moteSender, MoteSimObject moteReceiver) {
    double distance = moteSender.getDistance(moteReceiver);
    double prob = curModel.getPacketLossRate(distance, this.scalingFactor);

    debug.out.println(
        "RADIOMODEL: "
            + moteSender
            + "->"
            + moteReceiver
            + " dist "
            + distance
            + " scale "
            + scalingFactor
            + " prob "
            + prob);

    long scaledBitLossRate = (long) (curModel.getBitLossRate(prob) * 10000);

    debug.out.println(
        "RADIOMODEL: sampleLossRate "
            + "[moteSender "
            + moteSender
            + "] 1"
            + "[moteReceiver "
            + moteReceiver
            + "] "
            + "[packetLossRate "
            + prob
            + "] "
            + "[scaledBitLossRate "
            + scaledBitLossRate
            + "]");

    connectivityGraph.put(graphKey(moteSender, moteReceiver), new Double(prob));

    if (autoPublish) {
      publishLossRate(moteSender, moteReceiver, prob);
    }
  }
コード例 #23
0
 // ------------------------------------------------------------------------
 // GET PROPRIETARY NODE INFO PANEL
 // This function returns the Panel that you define it to retunr
 // which will then automatically appear ina dialog when a node is clicked.
 // this function is called by DisplayManager
 public ActivePanel GetProprietaryNodeInfoPanel(Integer pNodeNumber) {
   NodeInfo nodeInfo = (NodeInfo) proprietaryNodeInfo.get(pNodeNumber);
   if (nodeInfo == null) return null;
   ProprietaryNodeInfoPanel panel = new ProprietaryNodeInfoPanel(nodeInfo);
   return (ActivePanel) panel;
 }
コード例 #24
0
 // ------------------------------------------------------------------------
 // *****---Node Deleted---******//
 // this function defines what you do when a new node is deleted
 // It is called by net.tinyos.tinydb.topology.PacketAnalyzer.ObjectMainter
 public synchronized void NodeDeleted(NodeEvent e) {
   Integer deletedNodeNumber =
       e.GetNodeNumber(); // you probably want to delete the info pbject to track the data of
   // this new node
   proprietaryNodeInfo.remove(deletedNodeNumber);
 }
コード例 #25
0
 // It is called by net.tinyos.tinydb.topology.PacketAnalyzer.ObjectMainter
 public synchronized void NodeCreated(NodeEvent e) {
   Integer newNodeNumber =
       e.GetNodeNumber(); // you probably want to create a new info pbject to track the data of
   // this new node
   proprietaryNodeInfo.put(newNodeNumber, new NodeInfo(newNodeNumber));
 }
コード例 #26
0
ファイル: ScanWord.java プロジェクト: christinapanto/project
  /**
   * Add a keyword/token pair.
   *
   * @param s String contining the keyword
   * @param i Token to return when the keyword is encountered.
   */
  public void addKeyWord(String s, int i) {

    if (s == null) return;

    kwords.put(s.toLowerCase(), new Integer(i));
  }
コード例 #27
0
ファイル: ScanWord.java プロジェクト: christinapanto/project
 /** Clear the internal table containing the keyword/token pairs */
 public void resetKeyWords() {
   kwords.clear();
 }
コード例 #28
0
 // ------------------------------------------------------------------------
 // INTERFACE TO PROPRIETARY DATA
 // write some functions here that will let other Analyzers find and user your data
 public NodeInfo GetNodeInfo(Integer nodeNumber) {
   return (NodeInfo) proprietaryNodeInfo.get(nodeNumber);
 }
コード例 #29
0
 //	public EdgeInfo GetEdgeInfo(Integer sourceNumber, Integer destinationNumber){return
 // (EdgeInfo)proprietaryEdgeInfo.get(sourceNumber,destinationNumber);}
 public Enumeration GetNodeInfo() {
   return proprietaryNodeInfo.elements();
 }
コード例 #30
0
 public PropagationModel getModel(String name) {
   return (PropagationModel) models.get(name);
 }