Iterating through a HashMap

Hi!
I am trying to iterate through a HashMap that stores the 2 length words as keys and their number of occurrence in the given text. What I want to do is to count the total number of 2letter words which starts with the same letter. Unfortunately I could not find the code that will compare the 2 adjacent keys. I can take the next entry with Map.Entry meNext = (Map.Entry)iter.next(); but I cannot take the current entry with Map.Entry me = (Map.Entry)iter;. Or the next next entry.
I hope I am clear. I would be really glad for your advices. Below is my code, which gives error:
java.lang.ClassCastException: java.util.HashMap$EntryIterator cannot be cast to java.util.Map$Entry
Iterator iter=symbols.entrySet().iterator();
          while (iter.hasNext()) {
               Map.Entry me = (Map.Entry)iter;
               Map.Entry meNext = (Map.Entry)iter.next();
               String valueToString = (me.getValue()).toString();
               String valueToStringNext = (meNext.getValue()).toString();
               String keyToString = (me.getKey()).toString();
               String keyToStringNext = (meNext.getKey()).toString();
               int numberOfElements = (int)Integer.valueOf(valueToString).intValue();
               while (keyToString.substring(0,1).equals(keyToStringNext.substring(0, 1))) {
                          numberOfElements += (int)Integer.valueOf(valueToStringNext).intValue();
          }

thanks a lot for your answer yawmark, but I think I really need to take and compare the 2 adjacent key entries of the hashmap. because later on if the userchoice=2gram, I want to calculate the probability of the 2nd char given the first char. i.e. Prob(b when given a)=numberof(ab) / numberof(words starting with a), otherwise it calculates the probability of the word. i.e. Prob(ab) = numberof(ab) / numberof(all words in the document)
so length in the code = number of all words in the doc.
I have my hashmap in sorted, so all the words starting with the same letter will be next to each other. So it can count until it sees another starting letter in the next word.
The output should be the contents of the probability hashmap, which contains <entries of symbols hashmap which are <words,occurances>, probability of the words>
for ex. (in this ex it just calculates the probability = occurance/numberof all words.
&#12362;&#12452;=2=0.5
&#12452;&#12403;=1=0.25
&#12403;&#12362;=1=0.25
for the document: &#12362;&#12452;&#12403;&#12362;&#12452;
          Iterator iter=symbols.entrySet().iterator();
          while (iter.hasNext()) {
               Map.Entry me = (Map.Entry)iter;
               Map.Entry me = (Map.Entry)iter.next();
               String valueToString = (me.getValue()).toString();
               String valueToStringNext = (meNext.getValue()).toString();
               String keyToString = (me.getKey()).toString();
               String keyToStringNext = (meNext.getKey()).toString();
               int numberOfElements = (int)Integer.valueOf(valueToString).intValue();
               while (keyToString.substring(0,1).equals(keyToStringNext.substring(0,1))) {
                          numberOfElements += (int)Integer.valueOf(valueToStringNext).intValue();
               if(userChoice.equals("2gram")) {
                    probability.put(me, ((double)Double.valueOf(valueToString).doubleValue()) / numberOfElements);
               else
               probability.put(me, ((double)Double.valueOf(valueToString).doubleValue()) / length);
          }Edited by: koksalasli on Dec 21, 2009 3:06 PM

Similar Messages

  • Iterating through HashMap

    I found a tutorial and am wrote this into my code:
    for (Iterator i=m.entrySet().iterator(); i.hasNext(); ) {
    Map.Entry e = (Map.Entry) i.next();
    System.out.println(e.getKey() + ": " + e.getValue());
    Now I get the exception:
    Exception in thread "main" java.lang.ClassCastException
    on the line
    Map.Entry e = (Map.Entry) i.next();
    Is there another way to iterate through the Hashmap so I can print the keys and values?

    Results are
    java.util.Collections$UnmodifiableMap
    java.lang.Integer
    I used keySet and my Keys are Integers
    Maybe I should have used entrySet
    When I use entrySet I get:
    java.util.Collections$UnmodifiableMap
    java.util.Collections$UnmodifiableMap$UnmodifiableEntrySet$UnmodifiableEntry
    java.util.Collections$UnmodifiableMap$UnmodifiableEntrySet$UnmodifiableEntry
    java.util.Collections$UnmodifiableMap$UnmodifiableEntrySet$UnmodifiableEntry
    java.util.Collections$UnmodifiableMap$UnmodifiableEntrySet$UnmodifiableEntry
    java.util.Collections$UnmodifiableMap$UnmodifiableEntrySet$UnmodifiableEntry
    java.util.Collections$UnmodifiableMap$UnmodifiableEntrySet$UnmodifiableEntry
    java.util.Collections$UnmodifiableMap$UnmodifiableEntrySet$UnmodifiableEntry
    java.util.Collections$UnmodifiableMap$UnmodifiableEntrySet$UnmodifiableEntry
    Exception in thread "main" java.util.NoSuchElementException
    at java.util.HashMap$HashIterator.nextEntry(HashMap.java:765)
    at java.util.HashMap$EntryIterator.next(HashMap.java:804)
    at java.util.Collections$3.next(Collections.java:1324)

  • Iterating through entrys of HashMap

    I have a HashMap that is already populated. I'm iterating through the entrySet and want to get the keys and values and use them to create another object. I've searched the forum and googled but can't quite seem to find what I need. Here's the code I have so far.
    Iterator iterator = map.entrySet().iterator();
    while (iterator.hasNext()) {
    if (iterator.next() != null) {
         reasonsList.add(new DropDownData(key, value)); // here's where I'm not sure what to do
    }The DropDownData object accepts twos strings, one for the key and one for the displayed value. These strings should be the key and value from my current HashMap entry. But I can't seem to figure out how to do it.
    thanks for any help/suggestions

    iterating over the not-null entries or iteratingover
    gotten entries that are not null is equivalent,maps
    return "null" for unexisting keys...
    I do not understand what you are saying here.
    It is not required that Map implementations return "null" for non-existent keys.
    It just happens to be the way the implementations in the JDK are implemented.
    The documentation specifically says that Map.get(key) could be allowed to throw a NullPointerException.
    http://java.sun.com/j2se/1.5.0/docs/api/java/util/Map.html#get(java.lang.Object )
    >
    I would add that map's structure suggests it's the
    way to go (I mean, mine of course ;))
    That's a matter of interpretation.
    what's the point in iterating over the values when
    you need the key ?When you need the keys and the values (as in the case of the OP), then there is plenty of point in it.
    >
    the only way (the API should define) to iterate over
    a map is through the key (hence the "map" name),
    entrySet is (as far as a I reckon) a twisted bypass...It's in the API. It works well. It's useful. So there's no reason not to use it when it is applicable.

  • SharePoint Online Iterating through Document Libraries CSOM

    Hi,
    I am trying to iterate though a document library and set each document/items whithin to inherit permissions (at the moment each doc/item is using uniquer permissions).
    I am able to get the specific document library that I am interesting in, however I cannot at the moment iterate though each of the items/documents within it, but here is what I have so far:
    Add-Type -Path "Libraries\Microsoft.SharePoint.Client.dll"
    Add-Type -Path "Libraries\Microsoft.SharePoint.Client.Runtime.dll"
    Add-Type -Path "Libraries\Microsoft.SharePoint.Linq.dll"
    Add-Type -Path "Libraries\Microsoft.SharePoint.dll"
    $webUrl = "https://test.sharepoint.com/sites/testsite"
    $username = "####"
    $password = "####"
    $securePass = ConvertTo-SecureString $password -AsPlainText -Force
    $listname = "TestDoc";
    $ctx = New-Object Microsoft.SharePoint.Client.ClientContext($webUrl)
    $ctx.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($username, $securePass)
    #variables
    $web = $ctx.Web
    $lists = $web.Lists
    $ctx.Load($lists)
    $ctx.Load($web)
    $ctx.ExecuteQuery()
    #print web URL
    write-host `n "Web Url:" `n $web.Url
    foreach ($list in $lists)
    if ($list.Title -eq "TestDoc")
    #print list name if found
    write-host `n "Found the list:" `n $list.Title `n
    #attempting to iterate through items in the document library
    foreach ($item2 in $list.Items)
    #list the items/documents in the document library
    write-host $item2.Title
    It is the foreach loop I am having trouble at the moment as I am not sure how to loop though each of the items/documents in the document library.
    Any suggestions on the approach I should take would be much appreciated.

    Thanks for the heads up, I have re-worked my script which is simpler and now works like a charm:
    Add-Type -Path "Libraries\Microsoft.SharePoint.Client.dll"
    Add-Type -Path "Libraries\Microsoft.SharePoint.Client.Runtime.dll"
    Add-Type -Path "Libraries\Microsoft.SharePoint.Linq.dll"
    Add-Type -Path "Libraries\Microsoft.SharePoint.dll"
    $webUrl = "https://test.sharepoint.com/sites/testsite"
    $username = "####"
    $password = "####"
    $securePass = ConvertTo-SecureString $password -AsPlainText -Force
    $listname = "TestDoc"
    $ctx = New-Object Microsoft.SharePoint.Client.ClientContext($webUrl)
    $ctx.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($username, $securePass)
    #get the List/DocLib and load it for use
    $listUpdate = $ctx.Web.Lists.GetByTitle($listname)
    $ctx.Load($listUpdate)
    $ctx.ExecuteQuery()
    #CAML Query to get all items inclusing sub-folders
    $spQuery = New-Object Microsoft.SharePoint.Client.CamlQuery
    $spQuery.ViewXml = "<View Scope='RecursiveAll' />";
    $itemki = $listUpdate.GetItems($spQuery)
    $ctx.Load($itemki)
    $ctx.ExecuteQuery()
    #iterating through the items and reseting permission inheritence
    for($j=0; $j -lt $itemki.Count; $j++)
    $itemki[$j].ResetRoleInheritance()
    $ctx.ExecuteQuery()

  • Avoid iterating through everything

    Hello all,
    Hope you guys can help me with this problem. I have a program that draws anywhere from 1-300,000 letters on a canvas. Each letter is created from a class called StringState which extends Rectangle. What I would like to do is have each letter respond when the user moves the mouse over the letter by growing bigger. I figured I can just see if the letters bounds contains the point where the mouse moved to and if it does change the letters size and repaint around that letter to update the display. This works great from 1-5000 letters but getting up to 10,000 or even higher creates a very visible lag while the program is iterating through the letters to check if the mouse location intersects the letters bounds. What I was wondering is there a way to get this result without iterating through the entire collection of letters to see if it contains the mouse location? Like can I attach some kind of mouse listener to each letter or something like that? The following program just demonstrates how I create and display the letters I haven't really had a chance to create a demonstration of how they would grow when hovered over. The program i'm working on that actually demonstrates this is very large and hard to trim down to show an example so the following code is actually from a previous question I asked and was provided by Aephyr. Thanks in advance for your guys help :)
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.*;
    import java.util.List;
    public class PaintSurface implements Runnable, ActionListener {
         public static void main(String[] args) {
              SwingUtilities.invokeLater(new PaintSurface());
         Tableaux tableaux;
         Random random = new Random();
    //        Point mouselocation = new Point(0,0);
         static final int WIDTH = 1000;
         static final int HEIGHT = 1000;
            JFrame frame = new JFrame();
         public void run() {
              tableaux = new Tableaux();
              for (int i=15000; --i>=0;)
                   addRandom();
              frame.add(tableaux, BorderLayout.CENTER);
              JButton add = new JButton("Add");
              add.addActionListener(this);
              frame.add(add, BorderLayout.SOUTH);
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setSize(WIDTH, HEIGHT);
              frame.setLocationRelativeTo(null);
    //                frame.addMouseMotionListener(new MouseListener());
              frame.setVisible(true);
         public void actionPerformed(ActionEvent e) {
              addRandom();
         void addRandom() {
              tableaux.add(
                        Character.toString((char)('a'+random.nextInt(26))),
                        UIManager.getFont("Button.font"),
                        random.nextInt(WIDTH), random.nextInt(HEIGHT));
    //        class MouseListener extends MouseAdapter {
    //            public void mouseMoved(MouseEvent e) {
    //                mouselocation = new Point(e.getX(),e.getY());
    //                frame.repaint();
            class StringState extends Rectangle {
                    StringState(String str, Font font, int x, int y, int w, int h) {
                            super(x, y, w, h);
                            string = str;
                            this.font = font;
                    String string;
                    Font font;
            class Tableaux extends JComponent {
                 Tableaux() {
                      this.enableEvents(MouseEvent.MOUSE_MOTION_EVENT_MASK);
                      lagState = createState("Lag", new Font("Arial",Font.BOLD,20), 0, 0);
                 protected void processMouseMotionEvent(MouseEvent e) {
                      repaint(lagState);
                      lagState.setLocation(e.getX(), e.getY());
                      repaint(lagState);
                      super.processMouseMotionEvent(e);
                 StringState lagState;
                    List<StringState> states = new ArrayList<StringState>();
                    StringState createState(String str, Font font, int x, int y) {
                        FontMetrics metrics = getFontMetrics(font);
                        int w = metrics.stringWidth(str);
                        int h = metrics.getHeight();
                        return new StringState(str, font, x, y-metrics.getAscent(), w, h);
                    public void add(String str, Font font, int x, int y) {
                         StringState state = createState(str, font, x, y);
                            states.add(state);
                            repaint(state);
                    protected void paintComponent(Graphics g) {
                            Rectangle clip = g.getClipBounds();
                            FontMetrics metrics = g.getFontMetrics();
                            for (StringState state : states) {
                                    if (state.intersects(clip)) {
                                            if (!state.font.equals(g.getFont())) {
                                                    g.setFont(state.font);
                                                    metrics = g.getFontMetrics();
                                            g.drawString(state.string, state.x, state.y+metrics.getAscent());
                            if (lagState.intersects(clip)) {
                            g.setColor(Color.red);
                            if (!lagState.font.equals(g.getFont())) {
                                g.setFont(lagState.font);
                                metrics = g.getFontMetrics();
                            g.drawString("Lag", lagState.x, lagState.y+metrics.getAscent());
    }Here is the code that iterates through the letters to see if a letter contains the mouse location:
                if(e.getSource()==canvas&&edit) {
                    for(Letter l : letters) {
                        Rectangle rec = new Rectangle(l.x+l.xoffset,l.y+l.yoffset,l.width,l.height);
                        if(rec.contains(new Point(e.getX(),e.getY()))&&l.resizing==false&&l.defaultSize==l.font.getSize()) {
                            l.resizing = true;
                            new Thread(new ExpandLetter(l)).start();
                        else if(!rec.contains(new Point(e.getX(),e.getY()))&&l.resizing==false){
                            l.font = new Font(l.font.getName(),l.font.getStyle(),l.defaultSize);
                            l.resizeLetter(l.text);
                }However I just learned that this loop itself is taking up a huge amount of memory by saying
    l.font = new Font(l.font.getName(),l.font.getStyle(),l.defaultSize); When I take that line out the lag is reduced by a lot. Also I think that it isn't forgetting the "old" letters font that it is replacing by saying new Font() and after running this loop once my program runs slow and laggy as if it doesn't have enough memory to run fast anymore. Is there something I am doing wrong by initiating a new Font. I would have thought that it wouldn't take up anymore memory because it replaces the old font the the letter "l" has. The loop seems to have some kind of memory leak if someone could point it out to me that would be great. Thanks :)
    Edited by: neptune692 on Feb 16, 2010 8:18 PM

    neptune692 wrote:
    can I attach some kind of mouse listener to each letterTry this:
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.font.*;
    import java.awt.geom.*;
    import javax.swing.*;
    import java.util.*;
    import javax.swing.event.*;
    public class SimplePaintSurface implements Runnable, ActionListener {
        private static final int WIDTH = 1250;
        private static final int HEIGHT = 800;
        private Random random = new Random();
        private JFrame frame = new JFrame("SimplePaintSurface");
        private JPanel tableaux;
        public void run() {
            tableaux = new JPanel(null);
            for (int i = 15000; --i >= 0;) {
                addRandom();
            frame.add(tableaux, BorderLayout.CENTER);
            JButton add = new JButton("Add");
            add.addActionListener(this);
            frame.add(add, BorderLayout.SOUTH);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(WIDTH, HEIGHT);
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
            tableaux.requestFocusInWindow();
        public void actionPerformed(final ActionEvent e) {
            addRandom();
            tableaux.repaint();
        void addRandom() {
            Letter letter = new Letter(Character.toString((char) ('a' + random.nextInt(26))));
            letter.setBounds(random.nextInt(WIDTH), random.nextInt(HEIGHT), 16, 16);
            tableaux.add(letter);
        public static void main(final String[] args) {
            SwingUtilities.invokeLater(new SimplePaintSurface());
    class Letter extends JLabel {
        Font font1;
        Font font2;
        private final FontRenderContext fontRenderContext1;
        private final FontRenderContext fontRenderContext2;
        public Letter(final String letter) {
            super(letter);
            setFocusable(true);
            setBackground(Color.RED);
            font1 = getFont();
            font2 = font1.deriveFont(48f);
            fontRenderContext1 = getFontMetrics(font1).getFontRenderContext();
            fontRenderContext2 = getFontMetrics(font2).getFontRenderContext();
            MouseInputAdapter mouseHandler = new MouseInputAdapter() {
                @Override
                public void mouseEntered(final MouseEvent e) {
                    Letter.this.setOpaque(true);
                    setFont(font2);
                    Rectangle bounds = getBounds();
                    Rectangle2D stringBounds = font2.getStringBounds(getText(), fontRenderContext2);
                    bounds.width = (int) stringBounds.getWidth();
                    bounds.height = (int) stringBounds.getHeight();
                    setBounds(bounds);
                @Override
                public void mouseExited(final MouseEvent e) {
                    Letter.this.setOpaque(false);
                    setFont(font1);
                    Rectangle bounds = getBounds();
                    Rectangle2D stringBounds = font1.getStringBounds(getText(), fontRenderContext1);
                    bounds.width = (int) stringBounds.getWidth();
                    bounds.height = (int) stringBounds.getHeight();
                    setBounds(bounds);
            addMouseListener(mouseHandler);
    }

  • Concurrent modification exception while iterating through list

    Hi,
    I have a list of objects. I use for each loop in java to iterate through that list of objects and display them.
    The problem is that while iterating other thread can add or remove some objects from that list, and I get ConcurrentModificationException.
    How can I handle this problem. How can I be sure that I am iteration through the updated list.
    Thank you

    Synchonize on the list before iterating through it, and make sure that other code also synchronizes on the list before adding to it or removing from it. Using a list implementation that simply synchronizes all the methods (e.g. Vector) will not do that, you have to do it yourself.

  • Iterating through View Object RowIterator Bug.

    I use this code to loop through the rows of a view object (As described in javadoc of RowIteratior).
    public String checkIterations() {
    String res = "Iterated through : ";
    RowIterator view = this.getDepartmentsView1();
    view.reset();
    Row row;
    while ((row = view.next()) != null) {
    System.out.println("rownum: " + row.getAttribute("RowNum"));
    res += row.getAttribute("RowNum") + " ";
    return res;
    Yet this code never goes through the first row if the executequery has been performed for view object.
    details:
    [http://adfbugs.blogspot.com/2009/07/iterating-through-view-object.html]
    Is this a bug?
    Edited by: mkonio on Jul 28, 2009 11:41 PM

    Thanks Andrejus and Steve.
    Its a development bug
    problem and solution described in:
    Fusion Developer's Guide for Oracle ADF
    9.7.6 What You May Need to Know About Programmatic Row Set Iteration

  • Iterating through RWBTreeOnDisk

    Is there any way to Iterating through RWBTreeOnDisk, My problem is that i have 100 records in RWBTreeOnDisk and i want to fetch only first 20 records, how should i proceed to do the same, instead of getting all the records using applyToKeyAndValue(), i need to fetch particular number of records in the tree.
    Plz suggest me the way to proceed.
    Thanx

    We use sqlite for this sort of application. It gives you the power of sql but acts on files directly rather that via a server. see www.sqlite.org

  • Iterating through a generic list of unknown type

    Hi,
    I am in the process of creating pdf reports for my project.I have to deal with a persistence api to get the data for the report.The data will be in the form of a list,like List<SomeObject>,all these lists returned by the persistence framework contains object of some type which implements a common interface.But through that interface I wont be able to get all the data for my reports.So I am looking for a generic way for iterating through the list,by providing some metadata for the data within the list. I am planning to use reflection to query through the list.Is there any feature of generic,through which I can easily iterate through this unknown type,preferrably a combination of reflection and generics,I want to reduce the LOC.Any suggestions??

    If the List returned by the framework isn't parameterized, Like
    public List<K> getList(Class<K> classType);
    then you have to cast it to the appropriate type. If you are not sure about the type of the Objects in the list, and you have a bunch of class types you could expect from the list, then you could use instanceof operator.
    If it could be Class A or B, then
    if (obj instanceof A){
    A castObject = (A) obj;
    else if(obj instanceof B){
    B castObject = (B)obj;
    }Even to do reflection to invoke methods, you need to know the method Names. Which tells me you have the knowledge of what could come out of the list. So cast them. Invoking methods using reflection is really slow.

  • How to make and iterate through a HashMap with an ArrayList in it

    public class MailServer
    // Storage for the arbitrary number of mail items to be stored
    // on the server.
    private ArrayList <MailItem> items;
    private HashMap <String, ArrayList<MailItem>> mapper;
    * Construct a mail server.
    public MailServer()
    items = new ArrayList<MailItem>();
    mapper = new HashMap<String, ArrayList<MailItem>>();
    a MailItem is a class that has objects to: from: message: subject
    if I add
    mapper.put("bob", mailItem1);
    mapper.put("jo", mailItem2);
    mapper.put("bob", mailItem3);
    how can I go through the hashmap and display all the messages that there are for each person? (mailItem has a print() method that prints out the email info.
    thanks all, i'm a newbie

    If your map's values are lists, you have to append to that list, and create it the first time, too.
    Demo:
    import java.util.*;
    public class MapExample2 {
        private Map < String, List < Integer > > map = new HashMap < String, List < Integer > > ();
        public void append(String key, Integer valueElement) {
            List < Integer > list = map.get(key);
            if (list == null)
                map.put(key, list = new ArrayList < Integer > ());
            list.add(valueElement);
        public String toString() {
            return map.toString();
        public static void main(String[] args) {
            MapExample2 app = new MapExample2();
            app.append("even", 10);
            app.append("even", 20);
            app.append("odd", 17);
            app.append("even", 30);
            app.append("odd", 11);
            app.append("odd", 43);
            System.out.println(app);
    }

  • Simplest way to loop through a HashMap?

    Hi everyone,
    I'm a beginner at JSP, so please excuse my ignorance...
    I have a HashMap in which I need to loop through and print every "key" and associated "value".
    Doing research, I have come across multiple examples, but they all seem (to me) rather complex for something I think should be simple.
    Here is some code I have now. C_TITLE is a HashMap. My question is, is there an easier way to do this where I don't have to invoke a subclass? Or is this as simple and easy as it can get?
    Thanks!
    if (C_TITLE.size() > 0) { //only loop if there are items in this hashmap
         for (Iterator i=C_TITLE.entrySet().iterator(); i.hasNext(); ) {
                  Map.Entry mapentry = (Map.Entry) i.next();
              out.print (mapentry.getKey() + "|");
              out.print (mapentry.getValue() + "<BR>\n");
    }

      Iteratir iter = C_TITLE.keySet().iterator();
      while(iter.hasNext()) //or your for as well
          Object key = iter.next();
           Object value = C_TITLE.get(key);
      }With J2SDK 1.5 there is new for loop to iterate through collections.
    This will make Iterators almost unusable.

  • Iterating through List View Items using Group By and Jquery

    In my listview to my document library, I am using grouping. For each group (using month), it lists all the documents pertaining to that particular month.
    Using JQuery, I need to go through each item and parse them, but I'm having trouble finding a usable selector for the for/each function. My parsing code (JQuery) works, but since it uses the class of the table cell with a child anchor, it basically
    finds the first item and then all the subsequent file names are named the same (instead of different names, like it should be).
    Here's my current code that doesn't work (only the iteration and naming separately for each file - the parsing I'm doing seems to work):
    $(".ms-wpContentDivSpace" ).each(function( index ) {
    var val=$(".ms-vb2 a").html();
    var val2=val.replace(/_/g," ");
    $(".ms-vb2 a").html(val2);
    any ideas?

    That's because
    $(".ms-vb2 a").
    is bringing back all the pieces that have that class with an anchor on the whole page, not just the ones in the .ms-wpContentDivSpace
    I don't know the exact syntax, but I think you need to iterate through all the '.ms_vb2 a' items as well - there are multiple ones, and do something like this inside your other grouping
    $(".ms-vb2 a").each(function(index) {
        var val=$(this).html();
       var val2=val.replace(/_/g," ")
       $(this).html(val2);
    That's not quite right but maybe that will help.
    Robin

  • Yet another Try Catch question. Iterating through a ForEach loop

    Confused on error handling in a Powershell ForEach loop. I’m looping through a list of registry keys, attempting
     to open each one. If it succeeds, I do a bunch of stuff. If it fails, I want to skip to the next iteration.
    If I was doing It in VBScript I’d do this:
    For Each Thing In colThings
    Open Thing
    If Err.Number <> 0 Then
    “oops”
    Else
    Do stuff
    Do stuff
    Do stuff
    End If
    Next
    This is what I came up with in PowerShell. It seems to work, but just doesn’t seem powershell-ish. There must be a better way to use the catch output than just creating a $return variable and assigning it success or fail?
    ForEach ($subKeyName in $subKeyNames)
    try{$subKey = $baseKey.OpenSubKey("$subKeyName")}
    catch{$return = "error" }
    If($return -eq "error" )
    “Oops”
    Else
    Do stuff
    Do stuff
    Do Stuff

     
    I totally get what you're saying about formatting. I don't' have any habits yet, since I've only been working in Powershell since... well, what time is it now?
    Unfortunately, It Has Been Decreed that we are no longer to use VBScript for any engineering solutions at work, so my 15 years experience in it now needs to be transitioned over asap. I don't have the luxury of crawling before I run. I'm trying not to be
    frustrated, but it's like an English major waking up one day and being told "You must now speak French exclusively. Here's a book."
    The Do Stuff example of my ForEach loop is about 50 lines of code involving matching values in subkeys of this registry key with another and collecting output. I tried wrapping the whole thing in a try section based on some examples, but it seemed odd, that's
    why I'm asking. I'm used to tightly focused error handling at the point where an error may occur.
    In this example I'm only interested in whether or not I can open the subkey (it exists, but I may not have permission). If I can't, there's no point in continuing with this iteration of the loop, I want to skip to the next one. So why include all the "Do
    Stuff" in the the try section? From a readability viewpoint, it doesn't seem helpful.
    Also, there may be more error handling deeper in the code. If I then put that in a try/catch, and then something else inside that, now I have nested try/catches mixed in with nested if/elses, all wrapped in a For loop.
    Again, I can see how it works logically, but for readability not so much, and having all these braces 50 lines apart to match up is giving me eye strain :).
    It sounds like David is agreeing with jrv, that putting the entire ForEach loop code into a try/catch is the conventional way to do it. I guess it makes as much sense as putting it all in an If-else-Endif, and I just need to adjust my paradigm.
    But if not, my specific question was more along the lines of, is there a built in way to tell that the catch section has been executed, rather than me using it to populate an arbitrary variable and then read it? In VBScript, you execute something, and the
    next line, you check the Err.number. I wasn't sure if you could do that with a try/catch.

  • Problem in iterating through huge number of entries ... memory issue

    I am having large number of entries in lacs.
    I need to check each entry with previous ones , so I need to iterate through the each and every entry previous to current entry.
    Here I have put all the entries in arraylist and I am iterating though this arraylist and validating current entry.
    As I am using the arraylist for storing all the entries , the system is taking lot of memory because I am putting all in the memory.
    Is there anyway to resolve this memory issue?

    If you have a hundred thousand entries, to verify all the entries you would need to compare the later entries with the earlier ones such that:
    Entry 1 = 100,000 accesses
    Entry 2 = 99,999 accesses
    Entry 5 = 99,995 accesses
    Entry 10 = 99,990 accesses
    Entry 99,990 = 10 accesses
    Entry 99,995 = 5 accesses
    Entry 99,999 = 1 access (only to be compared with the 100,000th entry)
    It would then make sense to keep a certain (fixed) amount of entries in memory, those which get accessed the most, then write to file those which get accessed the least frequently. Have a method that can decide, based on the index of the entry, whether to get it from the ArrayList or to read it from the file. That will give you good performance.
    BufferedReader would be a good candidate to read the file, because it can skip more bytes at once should you need a line very late in the file. Also consider using RandomAccessFile and seek(entryNumber * ENTRY_SIZE) if your data can be represented with a fixed size in bytes.
    s
    Edited by Looce at 2009-03-25 20:33:11 GMT [Added BufferedReader advice]

  • Iterating through available virtual servers...

    Hello,
    I am writing a NSAPI filter on Sun ONE Web Server 6.1. Can someone point me to the docs that describe how one could programmatically iterate through all the virtual servers/sites, associated port numbers, etc., using Sun's C/C++ API?
    Thanks!

    No, there is no API for iterating over virtual servers. An NSAPI plugin typically is not aware of virtual servers. An NSAPI plugin that needs to be virtual server aware can register itself to receive virtual server creation and destruction events using the documented vs_register_cb() function.
    There is no API for parsing/modifying server.xml.

Maybe you are looking for