问:
Use jQuery to scroll up and down to div id
jQuery noob here. I have a fixed nav bar where I have an About div that I want to click on to scroll to the about section of the page. It's halfway working right now. If I am above the about section, clicking on the div will successfully scroll down to the about section, but if I choose to scroll past the about section it will not scroll back up to it if I click on the button. I am unsure about how to get it to scroll back up instead of only being able to go in one direction.

Here's my HTML:

```<code><nav>
  <div id="about-button">About</div>
  <div id="projects-button">Projects</div>
</nav>

<section class="about-me">
  <div class="about" id="about">
    <div class="about-box"><h1>About</h1></div>
      <div class="bio-box">
        <h3>Bio</h3>
        <p class="bio-text">Bio text yada yada.</p>
        <p class="bio-text">More bio text yada yada</p>
      </div>
    </div>
  </div>
</section>

<section class="projects-section">
  <div class="projects" id="projects">
     <div class="project-main"><h1>Projects</h1></div>
       <a class="project-link" href="">
         <div class="project-picture"></div>
       </a>
     <div class="project-title">Project Name</div>
  </div>
</section>
</code>```

And this is my jQuery:

```<code>function scrollToSection() {
 $("#about-button").click(function() {
    $('html, body').animate({
        scrollTop: $("#about").offset().top
    }, 2000);
 });
}

</code>```

答:
I took the liberty of adding some basic CSS and longer dummy text for visual purposes based on your comments. Both buttons are working correctly now.

Changes I made to your original code:

Removed the scrollToSection() function wrapper. Instead $("#about-button") is inside the $(document).ready() function. DOM element click handlers usually belong here so they are active only after the page finishes loading. If you wanted, you could refactor the function call to take "#about-button" and "#about" as parameters to a scrollToSection() function.

Added a "#projects-button" click handler since it helps to complete the example.

Removed extraneous
 closure before each
 closure. You already have a
 right after the
 closure.

$(document).ready(function() {
  $("#about-button").click(function() {
    $('html, body').animate({
      scrollTop: $("#about").offset().top
    }, 2000);
  });
  $("#projects-button").click(function() {
    $('html, body').animate({
      scrollTop: $("#projects").offset().top
    }, 2000);
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>nav {
  position: fixed;
  border-bottom: 1px solid black;
  display: flex;
  width: 100%;
  top: 0;
  background-color: white;
}

nav>div {
  margin: 5px;
  border: 1px solid black;
  padding: 5px;
}

section {
  margin: 50px 0 0 0;
}</code>```

About

Projects

About

Bio

        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin tempor, metus eu finibus commodo, dui nisl ullamcorper nibh, sit amet venenatis quam nisl id metus. Integer tempor urna diam, a sollicitudin ex pellentesque sit amet. In hac habitasse platea
        dictumst. Integer eget aliquet lacus, ut volutpat tortor. Maecenas sit amet dignissim tellus. Quisque magna velit, maximus sed feugiat ac, imperdiet vitae risus. Duis vitae faucibus nunc. Aliquam erat volutpat. Praesent porttitor augue id felis
        molestie, eu pulvinar velit sollicitudin. Vestibulum at iaculis nulla. Maecenas semper, urna ut pharetra semper, felis quam pharetra orci, eu luctus ipsum velit egestas eros. Aliquam dui justo, volutpat id mi sit amet, finibus tincidunt turpis.
        Suspendisse gravida a lorem eget interdum. Curabitur laoreet, ipsum quis faucibus iaculis, odio massa tincidunt ante, non hendrerit lacus dolor ut elit.

        Praesent scelerisque elit sit amet pretium rhoncus. Cras sagittis ex a nunc consectetur, eget congue felis imperdiet. Proin varius interdum nibh et auctor. Donec pharetra eget arcu non ultrices. Phasellus lacinia ultrices risus vel tincidunt. Vestibulum
        vitae erat ligula. Aliquam vestibulum volutpat felis. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Mauris purus libero, fermentum sit amet quam sit amet, aliquam facilisis erat. Sed fermentum arcu diam.
        Proin iaculis commodo mi eget pharetra.

Projects

      Morbi posuere id urna quis vestibulum. Proin semper dignissim nisi. Proin ut lectus ac est aliquam blandit vitae ut justo. Praesent fermentum lorem diam, pharetra tristique risus dapibus et. Fusce id urna arcu. Donec sit amet nulla laoreet neque congue
      placerat. Integer pretium laoreet ipsum ut sagittis. Aliquam feugiat volutpat arcu ac varius. Suspendisse a lorem ut justo sodales scelerisque elementum sed ligula. Donec ac porttitor lorem, et venenatis ipsum. Proin ut felis in augue consectetur
      dignissim quis vel dolor.

```
</div>
</div>
</p>

<p>In case you really want to refactor scrolling to a function:</p>

<ul>
<li>The DOM click handlers are still initialized from <code>$(document).ready()</code></li>
<li>I'm assuming the section name is intentionally consistent for the button and the target. Otherwise, you'll need to pass separate string parameters for the button id and target id.</li>
</ul>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function scrollToSection(section) {
  $("#" + section + "-button").click(function() {
    $('html, body').animate({
      scrollTop: $("#" + section).offset().top
    }, 2000);
  });
}

$(document).ready(function() {
  scrollToSection("about");
  scrollToSection("projects");
});</code>```

nav {
  position: fixed;
  border-bottom: 1px solid black;
  display: flex;
  width: 100%;
  top: 0;
  background-color: white;
}

nav>div {
  margin: 5px;
  border: 1px solid black;
  padding: 5px;
}

section {
  margin: 50px 0 0 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<nav>
  <div id="about-button">About</div>
  <div id="projects-button">Projects</div>
</nav>

<section class="about-me">
  <div class="about" id="about">
    <div class="about-box">
      <h1>About</h1>
    </div>
    <div class="bio-box">
      <h3>Bio</h3>
      <p class="bio-text">
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin tempor, metus eu finibus commodo, dui nisl ullamcorper nibh, sit amet venenatis quam nisl id metus. Integer tempor urna diam, a sollicitudin ex pellentesque sit amet. In hac habitasse platea
        dictumst. Integer eget aliquet lacus, ut volutpat tortor. Maecenas sit amet dignissim tellus. Quisque magna velit, maximus sed feugiat ac, imperdiet vitae risus. Duis vitae faucibus nunc. Aliquam erat volutpat. Praesent porttitor augue id felis
        molestie, eu pulvinar velit sollicitudin. Vestibulum at iaculis nulla. Maecenas semper, urna ut pharetra semper, felis quam pharetra orci, eu luctus ipsum velit egestas eros. Aliquam dui justo, volutpat id mi sit amet, finibus tincidunt turpis.
        Suspendisse gravida a lorem eget interdum. Curabitur laoreet, ipsum quis faucibus iaculis, odio massa tincidunt ante, non hendrerit lacus dolor ut elit.
      </p>
      <p class="bio-text">
        Praesent scelerisque elit sit amet pretium rhoncus. Cras sagittis ex a nunc consectetur, eget congue felis imperdiet. Proin varius interdum nibh et auctor. Donec pharetra eget arcu non ultrices. Phasellus lacinia ultrices risus vel tincidunt. Vestibulum
        vitae erat ligula. Aliquam vestibulum volutpat felis. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Mauris purus libero, fermentum sit amet quam sit amet, aliquam facilisis erat. Sed fermentum arcu diam.
        Proin iaculis commodo mi eget pharetra.
      </p>
    </div>
  </div>
</section>

<section class="projects-section">
  <div class="projects" id="projects">
    <div class="project-main">
      <h1>Projects</h1>
    </div>

      <div class="project-picture"></div>

    <div class="project-title">
      Morbi posuere id urna quis vestibulum. Proin semper dignissim nisi. Proin ut lectus ac est aliquam blandit vitae ut justo. Praesent fermentum lorem diam, pharetra tristique risus dapibus et. Fusce id urna arcu. Donec sit amet nulla laoreet neque congue
      placerat. Integer pretium laoreet ipsum ut sagittis. Aliquam feugiat volutpat arcu ac varius. Suspendisse a lorem ut justo sodales scelerisque elementum sed ligula. Donec ac porttitor lorem, et venenatis ipsum. Proin ut felis in augue consectetur
      dignissim quis vel dolor.
    </div>
  </div>
</section></code>```

Body:
jQuery noob here. I have a fixed nav bar where I have an About div that I want to click on to scroll to the about section of the page. It's halfway working right now. If I am above the about section, clicking on the div will successfully scroll down to the about section, but if I choose to scroll past the about section it will not scroll back up to it if I click on the button. I am unsure about how to get it to scroll back up instead of only being able to go in one direction.

Here's my HTML:

About

Projects

About

Bio

Bio text yada yada.

More bio text yada yada

Projects

Project Name

And this is my jQuery:

function scrollToSection() {
 $("#about-button").click(function() {
    $('html, body').animate({
        scrollTop: $("#about").offset().top
    }, 2000);
 });
}

Body:
I took the liberty of adding some basic CSS and longer dummy text for visual purposes based on your comments. Both buttons are working correctly now.

Changes I made to your original code:

Removed the scrollToSection() function wrapper. Instead $("#about-button") is inside the $(document).ready() function. DOM element click handlers usually belong here so they are active only after the page finishes loading. If you wanted, you could refactor the function call to take "#about-button" and "#about" as parameters to a scrollToSection() function.

Added a "#projects-button" click handler since it helps to complete the example.

Removed extraneous </div> closure before each </section> closure. You already have a </div> right after the </h1> closure.

$(document).ready(function() {
  $("#about-button").click(function() {
    $('html, body').animate({
      scrollTop: $("#about").offset().top
    }, 2000);
  });
  $("#projects-button").click(function() {
    $('html, body').animate({
      scrollTop: $("#projects").offset().top
    }, 2000);
  });
});

nav {
  position: fixed;
  border-bottom: 1px solid black;
  display: flex;
  width: 100%;
  top: 0;
  background-color: white;
}

nav>div {
  margin: 5px;
  border: 1px solid black;
  padding: 5px;
}

section {
  margin: 50px 0 0 0;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<nav>
  <div id="about-button">About</div>
  <div id="projects-button">Projects</div>
</nav>

<section class="about-me">
  <div class="about" id="about">
    <div class="about-box">
      <h1>About</h1>
    </div>
    <div class="bio-box">
      <h3>Bio</h3>
      <p class="bio-text">
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin tempor, metus eu finibus commodo, dui nisl ullamcorper nibh, sit amet venenatis quam nisl id metus. Integer tempor urna diam, a sollicitudin ex pellentesque sit amet. In hac habitasse platea
        dictumst. Integer eget aliquet lacus, ut volutpat tortor. Maecenas sit amet dignissim tellus. Quisque magna velit, maximus sed feugiat ac, imperdiet vitae risus. Duis vitae faucibus nunc. Aliquam erat volutpat. Praesent porttitor augue id felis
        molestie, eu pulvinar velit sollicitudin. Vestibulum at iaculis nulla. Maecenas semper, urna ut pharetra semper, felis quam pharetra orci, eu luctus ipsum velit egestas eros. Aliquam dui justo, volutpat id mi sit amet, finibus tincidunt turpis.
        Suspendisse gravida a lorem eget interdum. Curabitur laoreet, ipsum quis faucibus iaculis, odio massa tincidunt ante, non hendrerit lacus dolor ut elit.
      </p>
      <p class="bio-text">
        Praesent scelerisque elit sit amet pretium rhoncus. Cras sagittis ex a nunc consectetur, eget congue felis imperdiet. Proin varius interdum nibh et auctor. Donec pharetra eget arcu non ultrices. Phasellus lacinia ultrices risus vel tincidunt. Vestibulum
        vitae erat ligula. Aliquam vestibulum volutpat felis. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Mauris purus libero, fermentum sit amet quam sit amet, aliquam facilisis erat. Sed fermentum arcu diam.
        Proin iaculis commodo mi eget pharetra.
      </p>
    </div>
  </div>
</section>

<section class="projects-section">
  <div class="projects" id="projects">
    <div class="project-main">
      <h1>Projects</h1>
    </div>
    <a class="project-link" href="">
      <div class="project-picture"></div>
    </a>
    <div class="project-title">
      Morbi posuere id urna quis vestibulum. Proin semper dignissim nisi. Proin ut lectus ac est aliquam blandit vitae ut justo. Praesent fermentum lorem diam, pharetra tristique risus dapibus et. Fusce id urna arcu. Donec sit amet nulla laoreet neque congue
      placerat. Integer pretium laoreet ipsum ut sagittis. Aliquam feugiat volutpat arcu ac varius. Suspendisse a lorem ut justo sodales scelerisque elementum sed ligula. Donec ac porttitor lorem, et venenatis ipsum. Proin ut felis in augue consectetur
      dignissim quis vel dolor.
    </div>
  </div>
</section>

In case you really want to refactor scrolling to a function:

The DOM click handlers are still initialized from $(document).ready()

I'm assuming the section name is intentionally consistent for the button and the target. Otherwise, you'll need to pass separate string parameters for the button id and target id.

function scrollToSection(section) {
  $("#" + section + "-button").click(function() {
    $('html, body').animate({
      scrollTop: $("#" + section).offset().top
    }, 2000);
  });
}

$(document).ready(function() {
  scrollToSection("about");
  scrollToSection("projects");
});

nav {
  position: fixed;
  border-bottom: 1px solid black;
  display: flex;
  width: 100%;
  top: 0;
  background-color: white;
}

nav>div {
  margin: 5px;
  border: 1px solid black;
  padding: 5px;
}

section {
  margin: 50px 0 0 0;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<nav>
  <div id="about-button">About</div>
  <div id="projects-button">Projects</div>
</nav>

<section class="about-me">
  <div class="about" id="about">
    <div class="about-box">
      <h1>About</h1>
    </div>
    <div class="bio-box">
      <h3>Bio</h3>
      <p class="bio-text">
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin tempor, metus eu finibus commodo, dui nisl ullamcorper nibh, sit amet venenatis quam nisl id metus. Integer tempor urna diam, a sollicitudin ex pellentesque sit amet. In hac habitasse platea
        dictumst. Integer eget aliquet lacus, ut volutpat tortor. Maecenas sit amet dignissim tellus. Quisque magna velit, maximus sed feugiat ac, imperdiet vitae risus. Duis vitae faucibus nunc. Aliquam erat volutpat. Praesent porttitor augue id felis
        molestie, eu pulvinar velit sollicitudin. Vestibulum at iaculis nulla. Maecenas semper, urna ut pharetra semper, felis quam pharetra orci, eu luctus ipsum velit egestas eros. Aliquam dui justo, volutpat id mi sit amet, finibus tincidunt turpis.
        Suspendisse gravida a lorem eget interdum. Curabitur laoreet, ipsum quis faucibus iaculis, odio massa tincidunt ante, non hendrerit lacus dolor ut elit.
      </p>
      <p class="bio-text">
        Praesent scelerisque elit sit amet pretium rhoncus. Cras sagittis ex a nunc consectetur, eget congue felis imperdiet. Proin varius interdum nibh et auctor. Donec pharetra eget arcu non ultrices. Phasellus lacinia ultrices risus vel tincidunt. Vestibulum
        vitae erat ligula. Aliquam vestibulum volutpat felis. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Mauris purus libero, fermentum sit amet quam sit amet, aliquam facilisis erat. Sed fermentum arcu diam.
        Proin iaculis commodo mi eget pharetra.
      </p>
    </div>
  </div>
</section>

<section class="projects-section">
  <div class="projects" id="projects">
    <div class="project-main">
      <h1>Projects</h1>
    </div>
    <a class="project-link" href="">
      <div class="project-picture"></div>
    </a>
    <div class="project-title">
      Morbi posuere id urna quis vestibulum. Proin semper dignissim nisi. Proin ut lectus ac est aliquam blandit vitae ut justo. Praesent fermentum lorem diam, pharetra tristique risus dapibus et. Fusce id urna arcu. Donec sit amet nulla laoreet neque congue
      placerat. Integer pretium laoreet ipsum ut sagittis. Aliquam feugiat volutpat arcu ac varius. Suspendisse a lorem ut justo sodales scelerisque elementum sed ligula. Donec ac porttitor lorem, et venenatis ipsum. Proin ut felis in augue consectetur
      dignissim quis vel dolor.
    </div>
  </div>
</section>


来源: stackexchange

问:
How to make a Discord.js bot read and use image urls which have been sent in chat
I am making a bot which will check if a message contains an image link matches a preset image list, and so it responds accordingly!

e.g.

```<code>User1: This is an image: discordapp.com/attachments/test123test123
Bot: That image is of blank!
</code>```

If someone tells me the function which gets image urls it would be great! It would be even more useful if someone could show me how to apply this by checking the URL against a preset list which will name what the image is of!
Cheers!

答:
Its EZ

message.channel.send(message.attachments.first().url)
```

ContentLicense: CC BY-SA 4.0

Body:
I am making a bot which will check if a message contains an image link matches a preset image list, and so it responds accordingly!

e.g.

User1: This is an image: discordapp.com/attachments/test123test123
Bot: That image is of blank!

If someone tells me the function which gets image urls it would be great! It would be even more useful if someone could show me how to apply this by checking the URL against a preset list which will name what the image is of!
Cheers!


问:
how to initialize list of string from linq select query?
I am initializing a list of strings from the code below:

```<code>            var headerValues = new Dictionary<string, List<string>>
            {
                {
                    "section1",
                    new List<string>()
                    {
                        "id",
                        "item"
                    }
                },
                {
                    "section2",
                    new List<string>()
                    {
                        "titile",
                        "content1",
                        "content2"
                    }
                },
                // and the rest of sections
            };
            var results = from s1 in section1Collection
                          from s2 in section2Collection
                          from s3 in section3Collection
                          from s4 in section4Collection
                          select new List<string>
                          {
                              // section1
                              GetValue(s1, headerValues["section1"][0]),
                              GetValue(s1, headerValues["section1"][1]),
                              // section2
                              GetValue(s2, headerValues["section2"][0]),
                              GetValue(s2, headerValues["section2"][1]),
                              GetValue(s2, headerValues["section2"][2]),
                              // and the rest of sections
                          };
</code>```

But there must be a way to do it in a loop, right? Or maybe initialize the results list in a function?

How do I produce this result list in a smarter, more reliable and more readable way?

BTW, the GetValue method just lookup the value in the s1, s2, etc from the passed in header value string.

Edit: what I'm looking for is something like this:

```<code>var results = from s1 in section1
              from s2 in section2
              from s3 in section3
              from s4 in section4
              select new List<string>
              {
                  // GetValues should return all section1 strings based on the headerValues["section1"] array
                  GetValues(s1, headerValues["section1"]),
                  // section2
                  GetValues(s2, headerValues["section2"]),
                  // and the rest of sections
               };
</code>```

答:
As already mentioned before what you are looking for is SelectMany. It flattens nested collections into one-dimensional one. Here is how you should use it.

```<code>var results = headerValues.SelectMany(item => item.Value);
</code>```

so what it does? 'item' here is a KeyValuePair(since Dictionary which you use consists of them), and the item.Value is a list(because it is the type of this particular dictionary's value). Now given list of lists SelectMany joins them and return as a single IEnumerable of strings

Body:
I am initializing a list of strings from the code below:

            var headerValues = new Dictionary<string, List<string>>
            {
                {
                    "section1",
                    new List<string>()
                    {
                        "id",
                        "item"
                    }
                },
                {
                    "section2",
                    new List<string>()
                    {
                        "titile",
                        "content1",
                        "content2"
                    }
                },
                // and the rest of sections
            };
            var results = from s1 in section1Collection
                          from s2 in section2Collection
                          from s3 in section3Collection
                          from s4 in section4Collection
                          select new List<string>
                          {
                              // section1
                              GetValue(s1, headerValues["section1"][0]),
                              GetValue(s1, headerValues["section1"][1]),
                              // section2
                              GetValue(s2, headerValues["section2"][0]),
                              GetValue(s2, headerValues["section2"][1]),
                              GetValue(s2, headerValues["section2"][2]),
                              // and the rest of sections
                          };

But there must be a way to do it in a loop, right? Or maybe initialize the results list in a function?

How do I produce this result list in a smarter, more reliable and more readable way?

BTW, the GetValue method just lookup the value in the s1, s2, etc from the passed in header value string.

Edit: what I'm looking for is something like this:

var results = from s1 in section1
              from s2 in section2
              from s3 in section3
              from s4 in section4
              select new List<string>
              {
                  // GetValues should return all section1 strings based on the headerValues["section1"] array
                  GetValues(s1, headerValues["section1"]),
                  // section2
                  GetValues(s2, headerValues["section2"]),
                  // and the rest of sections
               };

Body:
As already mentioned before what you are looking for is SelectMany. It flattens nested collections into one-dimensional one. Here is how you should use it.

var results = headerValues.SelectMany(item => item.Value);

so what it does? 'item' here is a KeyValuePair(since Dictionary which you use consists of them), and the item.Value is a list(because it is the type of this particular dictionary's value). Now given list of lists SelectMany joins them and return as a single IEnumerable of strings


问:
Swift - placing TableView below another view with constraints programmatically
I am using Swift 4.2.

I am trying to get a tableview below another view, for example - label.

What I want is something like this:

```<code>+----------------------------------------+
|        label                           |
+----------------------------------------+

+----------------------------------------+
|                                        |
|                                        |
|                                        |
|                                        |
|        tableView                       |
|                                        |
|                                        |
|                                        |
|                                        |
+----------------------------------------+

// label constraints
label.translatesAutoresizingMaskIntoConstraints = false
let label_Leading_Constraint = NSLayoutConstraint(item: label, attribute: NSLayoutConstraint.Attribute.leading, relatedBy: NSLayoutConstraint.Relation.equal, toItem: self.view, attribute: NSLayoutConstraint.Attribute.leading, multiplier: 1, constant: 0)
let label_Trailing_Constraint = NSLayoutConstraint(item: label, attribute: NSLayoutConstraint.Attribute.trailing, relatedBy: NSLayoutConstraint.Relation.equal, toItem: self.view, attribute: NSLayoutConstraint.Attribute.trailing, multiplier: 1, constant: 0)
let label_Top_Constraint = NSLayoutConstraint(item: label, attribute: NSLayoutConstraint.Attribute.top, relatedBy: NSLayoutConstraint.Relation.equal, toItem: previous_label, attribute: NSLayoutConstraint.Attribute.bottom, multiplier: 1, constant: 10)
NSLayoutConstraint.activate([label_Leading_Constraint, label_Trailing_Constraint, label_Top_Constraint])

var tableView = UITableView()
tableView.translatesAutoresizingMaskIntoConstraints = false
tableView.dataSource = self
tableView.delegate = self
tableView.backgroundColor = UIColor.white

tableView.register(UITableViewCell.self, forCellReuseIdentifier: "mycell")

self.view.addSubview(tableView)

tableView.leftAnchor.constraint(equalTo: self.view.leftAnchor, constant: 20.0).isActive = true
tableView.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 20.0).isActive = true
tableView.rightAnchor.constraint(equalTo: self.view.rightAnchor, constant: -20.0).isActive = true
tableView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor, constant: -20.0).isActive = true
</code>```

When I use the above code, the tableview is shown. The tableview constraints are relatively to the ALL view (self.view) which is not what I want because, I want the tableview to appear below the label.

If I change this code to my desired code (the top of the tableview should be 20 below the label view):

```<code>tableView.leftAnchor.constraint(equalTo: self.view.leftAnchor, constant: 20.0).isActive = true
tableView.topAnchor.constraint(equalTo: label.bottomAnchor, constant: 20).isActive = true
tableView.rightAnchor.constraint(equalTo: self.view.rightAnchor, constant: -20.0).isActive = true
tableView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor, constant: -20.0).isActive = true
</code>```

I get the label view messed up at the bottom of the screen and the tableview is not showing at all.

Please don't suggest a table header of something like that. You can assume I have some more views in the top section of the screen and I simply want the tableview to be shown below them.

Also, please don't suggest the storyboard. I am trying to do it all programmatically.

What am I missing?

Thanks!

答:
My guess would be that your UILabels constraint are not set properly.

for instance if you have set label.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true this would lead to the "messed up" result you are getting.

The labels anchors should be :

```<code>label.translatesAutoresizingMaskIntoConstraints = false
label.leftAnchor.constraint(equalTo: self.view.leftAnchor, constant: 20.0).isActive = true
label.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 20.0).isActive = true
label.rightAnchor.constraint(equalTo: self.view.rightAnchor, constant: -20.0).isActive = true
</code>```

and nothing more

Body:
I am using Swift 4.2.

I am trying to get a tableview below another view, for example - label.

What I want is something like this:

+----------------------------------------+
|        label                           |
+----------------------------------------+

+----------------------------------------+
|                                        |
|                                        |
|                                        |
|                                        |
|        tableView                       |
|                                        |
|                                        |
|                                        |
|                                        |
+----------------------------------------+

// label constraints
label.translatesAutoresizingMaskIntoConstraints = false
let label_Leading_Constraint = NSLayoutConstraint(item: label, attribute: NSLayoutConstraint.Attribute.leading, relatedBy: NSLayoutConstraint.Relation.equal, toItem: self.view, attribute: NSLayoutConstraint.Attribute.leading, multiplier: 1, constant: 0)
let label_Trailing_Constraint = NSLayoutConstraint(item: label, attribute: NSLayoutConstraint.Attribute.trailing, relatedBy: NSLayoutConstraint.Relation.equal, toItem: self.view, attribute: NSLayoutConstraint.Attribute.trailing, multiplier: 1, constant: 0)
let label_Top_Constraint = NSLayoutConstraint(item: label, attribute: NSLayoutConstraint.Attribute.top, relatedBy: NSLayoutConstraint.Relation.equal, toItem: previous_label, attribute: NSLayoutConstraint.Attribute.bottom, multiplier: 1, constant: 10)
NSLayoutConstraint.activate([label_Leading_Constraint, label_Trailing_Constraint, label_Top_Constraint])

var tableView = UITableView()
tableView.translatesAutoresizingMaskIntoConstraints = false
tableView.dataSource = self
tableView.delegate = self
tableView.backgroundColor = UIColor.white

tableView.register(UITableViewCell.self, forCellReuseIdentifier: "mycell")

self.view.addSubview(tableView)

tableView.leftAnchor.constraint(equalTo: self.view.leftAnchor, constant: 20.0).isActive = true
tableView.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 20.0).isActive = true
tableView.rightAnchor.constraint(equalTo: self.view.rightAnchor, constant: -20.0).isActive = true
tableView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor, constant: -20.0).isActive = true

When I use the above code, the tableview is shown. The tableview constraints are relatively to the ALL view (self.view) which is not what I want because, I want the tableview to appear below the label.

If I change this code to my desired code (the top of the tableview should be 20 below the label view):

tableView.leftAnchor.constraint(equalTo: self.view.leftAnchor, constant: 20.0).isActive = true
tableView.topAnchor.constraint(equalTo: label.bottomAnchor, constant: 20).isActive = true
tableView.rightAnchor.constraint(equalTo: self.view.rightAnchor, constant: -20.0).isActive = true
tableView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor, constant: -20.0).isActive = true

I get the label view messed up at the bottom of the screen and the tableview is not showing at all.

Please don't suggest a table header of something like that. You can assume I have some more views in the top section of the screen and I simply want the tableview to be shown below them.

Also, please don't suggest the storyboard. I am trying to do it all programmatically.

What am I missing?

Thanks!

Body:
My guess would be that your UILabels constraint are not set properly.

for instance if you have set label.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true this would lead to the "messed up" result you are getting.

The labels anchors should be :

label.translatesAutoresizingMaskIntoConstraints = false
label.leftAnchor.constraint(equalTo: self.view.leftAnchor, constant: 20.0).isActive = true
label.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 20.0).isActive = true
label.rightAnchor.constraint(equalTo: self.view.rightAnchor, constant: -20.0).isActive = true

and nothing more


问:
Created Class Won't Pass Assertion Check
I have to create a class, and 3 methods within it. We were given a bunch of assertion checks, and I can't seem to get past the first one.
This method doesn't pass, so I'm sure that the other two won't either (the other two use the value that I get from the first one). Have I missed something?

```<code>class Loan(object):
"""Calculates information regarding Loans."""
def __init__(self,principal,rate,time):
    self.principal = principal
    self.rate = rate
    self.time = time

def calculate_monthly_payment(self):
  """Calculates monthly loan payments"""
  part_1 = self.rate*((1+self.rate)**self.time)
  part_2 = ((1+self.rate)**self.time)-1
  monthly_pmt = self.principal*(part_1//part_2)
  return monthly_pmt
</code>```

Formula I have to use:

Assertion check I was given:

```<code># Testing Loan
loan1 = Loan(100, 0.1, 10)
assert math.isclose(loan1.principal, 100, abs_tol=0.00001), "{} != {}".format(loan1.principal, 100)
assert math.isclose(loan1.rate, 0.1, abs_tol=0.00001), "{} != {}".format(loan1.rate, 0.1)
assert math.isclose(loan1.time, 10, abs_tol=0.00001), "{} != {}".format(loan1.time, 10)
assert math.isclose(loan1.calculate_monthly_payment(), 16.274539488251154, abs_tol=0.00001), "{} != {}".format(loan1.calculate_monthly_payment(), 16.274539488251154)
</code>```

Assertion Error:

```<code>File "main.py", line 161, in main
assert math.isclose(loan1.calculate_monthly_payment(), 16.274539488251154, abs_tol=0.00001), "{} != {}".format(loan1.calculate_monthly_payment(), 16.274539488251154)

AssertionError: 0.0 != 16.274539488251154
</code>```

答: You're using integer division (//) where you want float division (/) in your second-to-last line. part1 // part2 is rounded to zero, and so you return zero, which is incorrect.

Body:
I have to create a class, and 3 methods within it. We were given a bunch of assertion checks, and I can't seem to get past the first one.
This method doesn't pass, so I'm sure that the other two won't either (the other two use the value that I get from the first one). Have I missed something?

class Loan(object):
"""Calculates information regarding Loans."""
def __init__(self,principal,rate,time):
    self.principal = principal
    self.rate = rate
    self.time = time

def calculate_monthly_payment(self):
  """Calculates monthly loan payments"""
  part_1 = self.rate*((1+self.rate)**self.time)
  part_2 = ((1+self.rate)**self.time)-1
  monthly_pmt = self.principal*(part_1//part_2)
  return monthly_pmt

Formula I have to use:

Assertion check I was given:

# Testing Loan
loan1 = Loan(100, 0.1, 10)
assert math.isclose(loan1.principal, 100, abs_tol=0.00001), "{} != {}".format(loan1.principal, 100)
assert math.isclose(loan1.rate, 0.1, abs_tol=0.00001), "{} != {}".format(loan1.rate, 0.1)
assert math.isclose(loan1.time, 10, abs_tol=0.00001), "{} != {}".format(loan1.time, 10)
assert math.isclose(loan1.calculate_monthly_payment(), 16.274539488251154, abs_tol=0.00001), "{} != {}".format(loan1.calculate_monthly_payment(), 16.274539488251154)

Assertion Error:

File "main.py", line 161, in main
assert math.isclose(loan1.calculate_monthly_payment(), 16.274539488251154, abs_tol=0.00001), "{} != {}".format(loan1.calculate_monthly_payment(), 16.274539488251154)

AssertionError: 0.0 != 16.274539488251154


问:
How to scrollup when a div has a programmerly added class
I'm having problems with my code. When you click on next, it does calculations and adds a class scrollup (in this example, it's the first three posts). When you click previous, it's suppose to scroll up if a div has a class .scrollup. When clicking previous it does not scroll up, even if the item has .scrollup.

Example HTML:

```<code><button id="prev-item">Previous</button>
<button id="next-item">Next</button>
<div class="main">
  <div class="item first"><div class="current">item 1</div></div>
  <div class="item">item 2</div>
  <div class="item">item 3</div>
  <div class="item">item 4</div>
  <div class="item">item 5</div>
  <div class="item">item 6</div>
  <div class="item">item 7</div>
  <div class="item">item 8</div>
  <div class="item">item 9</div>
  <div class="item">item 10</div>
</div>
</code>```

JS:

```<code>$("#next-item").on("click", function () {
    var curr = $('.main .current').parent(); //find .current's parent
    var $children = $('.main').children();
    var firstcal = $children.length;
    var actual = firstcal - 7
    $children.each(function (i) {
        if (i < actual) {
            $(this).addClass('scrollup')
        }
    });
    if (curr.next().length > 0) {
        $('.main').animate({scrollTop: '+=35px'}, 400);
        curr.children('.current').contents().unwrap(); // remove .current
        curr.next().wrapInner('<div class="current"></div>'); // add it to the next element
    }
});

$("#prev-item").on("click", function () {
    if (!$(this).hasClass("first")) {
        var curr = $('.main .current').parent(); //find .current's parent
        if (curr.next().length > 0) {
            if ($(this).hasClass("scrollup")) {
                $('.main').animate({scrollTop: '-=35px'}, 400);
            }
            curr.children('.current').contents().unwrap(); // remove .current
            curr.prev().wrapInner('<div class="current"></div>'); // add it to the next element
        }
    }
});
</code>```

JS Fiddle: https://jsfiddle.net/openbayou/425Leuq6/

答:
The problem is: $(this) needs to be curr in some positions in your code

if ($(this).hasClass("scrollup")){  .. $(this) in your line of code here refer to the #prev-item button and the previous button doesn't have scrollup class .. the scrollup class is for item/parent element of the current class element.. so with $(this) the if statement will not work .It needs to be curr.hasClass("scrollup")

Also the same thing in !$(this).hasClass("first") should be !curr.hasClass("first") And use var curr line before the if statement .. see the code below

$("#next-item").on("click", function(){
  var curr = $('.main .current').parent(); //find .current's parent
  var $children = $('.main').children();
    var firstcal = $children.length;
    var actual = firstcal - 7
    $children.each(function (i) {
      if (i < actual) {
        $(this).addClass('scrollup')
      }
    });
  if (curr.next().length > 0) {
    $('.main').animate({scrollTop: '+=35px'}, 400);
    curr.children('.current').contents().unwrap(); // remove .current
    curr.next().wrapInner('

'); // add it to the next element
  }
});
$("#prev-item").on("click", function(){
  /* HERE >>*/ var curr = $('.main .current').parent(); //find .current's parent
  /* HERE >>*/if (!curr.hasClass("first")) {
     if (curr.next().length > 0) {
      /* HERE >>*/ if (curr.hasClass("scrollup")){
        $('.main').animate({scrollTop: '-=35px'}, 400);
      }
      curr.children('.current').contents().unwrap(); // remove .current
      curr.prev().wrapInner('

'); // add it to the next element
    }
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.current { color: red; }
.item { padding: 7px; }
.main { height: 265px; overflow: auto; }
.scrollup { border-left: 5px solid blue; }</code>```

<button id="prev-item">Previous</button>
<button id="next-item">Next</button>

item 1

item 2

item 3

item 4

item 5

item 6

item 7

item 8

item 9

item 10

```

Looking for /* HERE >>*/ commented in the code to know which lines changed

Body:
I'm having problems with my code. When you click on next, it does calculations and adds a class scrollup (in this example, it's the first three posts). When you click previous, it's suppose to scroll up if a div has a class .scrollup. When clicking previous it does not scroll up, even if the item has .scrollup.

Example HTML:

<button id="prev-item">Previous</button>
<button id="next-item">Next</button>

item 1

item 2

item 3

item 4

item 5

item 6

item 7

item 8

item 9

item 10

JS:

$("#next-item").on("click", function () {
    var curr = $('.main .current').parent(); //find .current's parent
    var $children = $('.main').children();
    var firstcal = $children.length;
    var actual = firstcal - 7
    $children.each(function (i) {
        if (i < actual) {
            $(this).addClass('scrollup')
        }
    });
    if (curr.next().length > 0) {
        $('.main').animate({scrollTop: '+=35px'}, 400);
        curr.children('.current').contents().unwrap(); // remove .current
        curr.next().wrapInner('

'); // add it to the next element
    }
});

$("#prev-item").on("click", function () {
    if (!$(this).hasClass("first")) {
        var curr = $('.main .current').parent(); //find .current's parent
        if (curr.next().length > 0) {
            if ($(this).hasClass("scrollup")) {
                $('.main').animate({scrollTop: '-=35px'}, 400);
            }
            curr.children('.current').contents().unwrap(); // remove .current
            curr.prev().wrapInner('

'); // add it to the next element
        }
    }
});

JS Fiddle: https://jsfiddle.net/openbayou/425Leuq6/

Body:
The problem is: $(this) needs to be curr in some positions in your code

if ($(this).hasClass("scrollup")){  .. $(this) in your line of code here refer to the #prev-item button and the previous button doesn't have scrollup class .. the scrollup class is for item/parent element of the current class element.. so with $(this) the if statement will not work .It needs to be curr.hasClass("scrollup")

Also the same thing in !$(this).hasClass("first") should be !curr.hasClass("first") And use var curr line before the if statement .. see the code below

$("#next-item").on("click", function(){
  var curr = $('.main .current').parent(); //find .current's parent
  var $children = $('.main').children();
    var firstcal = $children.length;
    var actual = firstcal - 7
    $children.each(function (i) {
      if (i < actual) {
        $(this).addClass('scrollup')
      }
    });
  if (curr.next().length > 0) {
    $('.main').animate({scrollTop: '+=35px'}, 400);
    curr.children('.current').contents().unwrap(); // remove .current
    curr.next().wrapInner('<div class="current"></div>'); // add it to the next element
  }
});
$("#prev-item").on("click", function(){
  /* HERE >>*/ var curr = $('.main .current').parent(); //find .current's parent
  /* HERE >>*/if (!curr.hasClass("first")) {
     if (curr.next().length > 0) {
      /* HERE >>*/ if (curr.hasClass("scrollup")){
        $('.main').animate({scrollTop: '-=35px'}, 400);
      }
      curr.children('.current').contents().unwrap(); // remove .current
      curr.prev().wrapInner('<div class="current"></div>'); // add it to the next element
    }
  }
});

.current { color: red; }
.item { padding: 7px; }
.main { height: 265px; overflow: auto; }
.scrollup { border-left: 5px solid blue; }

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="prev-item">Previous</button>
<button id="next-item">Next</button>
<div class="main">
  <div class="item first"><div class="current">item 1</div></div>
  <div class="item">item 2</div>
  <div class="item">item 3</div>
  <div class="item">item 4</div>
  <div class="item">item 5</div>
  <div class="item">item 6</div>
  <div class="item">item 7</div>
  <div class="item">item 8</div>
  <div class="item">item 9</div>
  <div class="item">item 10</div>
</div>

Looking for /* HERE >>*/ commented in the code to know which lines changed


问:
C - read specific line from file
I'm trying to read a specific line from a file and I can get the line number but I'm not sure how to go about doing it, this is what I have so far:

```<code>#include <stdlib.h>
#include <stdio.h>
#include <string.h>

int main(int argc, char **argv)
{
  FILE *file;
  file = fopen("temp.txt","r");
  char tmp[256]={0x0};
  char *tmpline;
  int numline = 1;
  while(file != NULL && fgets(tmp, sizeof(tmp),file) !=NULL)
  {
    tmpline = strstr(tmp,"status:green");

    if(tmpline) {
      printf("%d - %s", numline, tmpline);
    }

    numline++;
  }
  if (file != NULL) fclose(file);

  return 0;
}
</code>```

The test file looks like:

```<code>s1.server.com
127.0.0.1
status:green

s2.server.com
127.0.0.1
status:red

s3.server.com
127.0.0.1
status:red

s4.server.com
127.0.0.1
status:green
</code>```

The output that I have is:

```<code>3 - status:green
15 - status:green
</code>```

But what I really want it to show is:

```<code>s1.server.com
s4.server.com
</code>```

I want it to search for "status:green" then go back a few lines to show which server it belongs to

答:
It sounds as if you need to do one of two things.

Simpler option: keep a little circular buffer of lines. Read into line 0, line 1, line 2, ..., line n-1, line 0, line 1, etc. Then, when you see the text you want, look in entry (current_index - 2) mod buffer_size. (Here it sounds as if a buffer size of 3 will suffice.)

More sophisticated option: actually parse the input so that for each block you work out the server name, its IP address and its status, and then display the information you need using that.

The "more sophisticated option" would be substantially more work, but more robust if the syntax of your input ever changes (e.g., with optional extra lines with more information about the server -- multiple IP addresses or multiple names, perhaps).

There are some other things you could do that I think are worse. (1) Call ftell on each line and put the results of that in a circular buffer, and then use fseek when you see "status:green". (2) Read the whole file using code like you currently have, building up a list of "good" servers' line numbers. Then go through the file again and report the good ones. I think these are both uglier and less efficient than the approaches I listed above. There's one possible advantage: you can adapt them to count in "stanzas" separated by blank lines, without needing to parse things properly. That would get you part of the flexibility of the "more sophisticated" approach I mentioned, without needing a proper parser.

And here's a hybrid possibility: don't use a circular buffer, but one whose size can increase if need be. Start at the first entry in the buffer each time you see a blank line. Let the buffer grow if there are "long" stanzas. Then when you see "status:green", do whatever processing you need to on the (presumably complete) stanza now held in your buffer.

None of the above is necessary, of course, if you're sure that the file format will never change.

ContentLicense: CC BY-SA 3.0

Title: C - read specific line from file

Body:
I'm trying to read a specific line from a file and I can get the line number but I'm not sure how to go about doing it, this is what I have so far:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

int main(int argc, char **argv)
{
  FILE *file;
  file = fopen("temp.txt","r");
  char tmp[256]={0x0};
  char *tmpline;
  int numline = 1;
  while(file != NULL && fgets(tmp, sizeof(tmp),file) !=NULL)
  {
    tmpline = strstr(tmp,"status:green");

    if(tmpline) {
      printf("%d - %s", numline, tmpline);
    }

    numline++;
  }
  if (file != NULL) fclose(file);

  return 0;
}

The test file looks like:

s1.server.com
127.0.0.1
status:green

s2.server.com
127.0.0.1
status:red

s3.server.com
127.0.0.1
status:red

s4.server.com
127.0.0.1
status:green

The output that I have is:

3 - status:green
15 - status:green

But what I really want it to show is:

s1.server.com
s4.server.com

I want it to search for "status:green" then go back a few lines to show which server it belongs to


问:
Looping through Excel cells
I have an excel spreadsheet - First column contain ID numbers, 2nd column contains the name that the specific ID number should be assigned to.

The intention of my macro is to copy the ID number from A2, enter it into a web application, scrape the name associated with the ID number off of the web application and enter that name into the 3rd column.

I have successfully accomplished this with the very first value in A2.

My problem is that I can not for the life of me figure out how to use a loop so that the macro cycles through each cell in column A until it reaches a blank cell. I'm very new to VBA so forgive my ignorance.
The code below is the piece of my macro that must loop.

```<code>  IE.document.getElementById("caseId").Value = ThisWorkbook.Sheets("StarsID").Range("A2").Value

'Tells macro to click on 'Search Cases' Button
       IE.document.getElementById("_eventId_search").Click

'Tells macro to wait for browser to load completely
       Do While IE.Busy = True Or IE.readyState <> 4: DoEvents: Loop

'Tells macro that first search result will be entered into row 2
       y = 2
        currentQueue = IE.document.getElementById("results").Children(1).Children(0).Children(3).Children(0).innerText
        Sheets("StarsID").Cells(y, 3).Value = currentQueue
         ActiveCell.Offset(1, 0).Select
</code>```

答:
try

```<code>y = 2
    Do While ThisWorkbook.Sheets("StarsID").Range("A" & y).Value <> ""
    IE.document.getElementById("caseId").Value = ThisWorkbook.Sheets("StarsID").Range("A" & y).Value
    IE.document.getElementById("_eventId_search").Click
    Do While IE.Busy = True Or IE.readyState <> 4: DoEvents: Loop
    currentQueue = IE.document.getElementById("results").Children(1).Children(0).Children(3).Children(0).innerText
    ThisWorkbook.Sheets("StarsID").Cells(y, 3).Value = currentQueue
    ActiveCell.Offset(1, 0).Select
    y = y + 1
    Loop
</code>```

may add some wait time depending of the response of the website.

Title: Looping through Excel cells

Body:
I have an excel spreadsheet - First column contain ID numbers, 2nd column contains the name that the specific ID number should be assigned to.

The intention of my macro is to copy the ID number from A2, enter it into a web application, scrape the name associated with the ID number off of the web application and enter that name into the 3rd column.

I have successfully accomplished this with the very first value in A2.

My problem is that I can not for the life of me figure out how to use a loop so that the macro cycles through each cell in column A until it reaches a blank cell. I'm very new to VBA so forgive my ignorance.
The code below is the piece of my macro that must loop.

  IE.document.getElementById("caseId").Value = ThisWorkbook.Sheets("StarsID").Range("A2").Value

'Tells macro to click on 'Search Cases' Button
       IE.document.getElementById("_eventId_search").Click

'Tells macro to wait for browser to load completely
       Do While IE.Busy = True Or IE.readyState <> 4: DoEvents: Loop

'Tells macro that first search result will be entered into row 2
       y = 2
        currentQueue = IE.document.getElementById("results").Children(1).Children(0).Children(3).Children(0).innerText
        Sheets("StarsID").Cells(y, 3).Value = currentQueue
         ActiveCell.Offset(1, 0).Select

Body:
try

y = 2
    Do While ThisWorkbook.Sheets("StarsID").Range("A" & y).Value <> ""
    IE.document.getElementById("caseId").Value = ThisWorkbook.Sheets("StarsID").Range("A" & y).Value
    IE.document.getElementById("_eventId_search").Click
    Do While IE.Busy = True Or IE.readyState <> 4: DoEvents: Loop
    currentQueue = IE.document.getElementById("results").Children(1).Children(0).Children(3).Children(0).innerText
    ThisWorkbook.Sheets("StarsID").Cells(y, 3).Value = currentQueue
    ActiveCell.Offset(1, 0).Select
    y = y + 1
    Loop

may add some wait time depending of the response of the website.


问:
How do I assign multiple different type of infomation to one name?
Sorry If the question was asked wrong, but I am doing a final project in CSP where I want to make a sorting system in Java 1.8.

I have used Hashmaps to store elements in the past, but apparently, they can only store up to 2 elements,
I want to do something along the line of:

```<code><String,Double,Int,Int,String>
sortPls.put("Jackson",8.2,12,6000,"A");
</code>```

how do I do it and is there an easier way?

I am using this website called Repl.it, this is my first year coding.

```<code>public static HashMap<String,Double,Int,Int,String> sortPls= new HashMap<String,Double,Int,Int,String>();
  public static void setList(){
sortPls.put("Jackson",8.2,12,6000,"A");

  }
</code>```

I expected the Hashmaps to hold more than 2 elements, but it returned an error that limits the elements to 2, with the data types after the first 2 being returned as cannot find symbol.

答:
You have to do something like this

```<code>public class Data {

    private String name;
    private int val1;
    private long val2;
    private char val3;

    public Data (String name, int val1, long val2, char val3) {
        this.name = name;
        this.val1 = val1;
        this.val2 = val2;
        this.val3 = val3;
    }
    public String getName() {
        return name;
    }
    public int getVal1() {
        return val1;
    }
    public long getVal2() {
        return val2;
    }
    public char getVal3() {
        return val3;
    }
}
</code>```

Using...

```<code>public static HashMap<String, Data> sortPls= new HashMap();
public static void setList(){
    Data d = new Data("A",32,12L,'u');
    sortPls.put("Jackson",d);
}
</code>```

Body:
Sorry If the question was asked wrong, but I am doing a final project in CSP where I want to make a sorting system in Java 1.8.

I have used Hashmaps to store elements in the past, but apparently, they can only store up to 2 elements,
I want to do something along the line of:

<String,Double,Int,Int,String>
sortPls.put("Jackson",8.2,12,6000,"A");

how do I do it and is there an easier way?

I am using this website called Repl.it, this is my first year coding.

public static HashMap<String,Double,Int,Int,String> sortPls= new HashMap<String,Double,Int,Int,String>();
  public static void setList(){
sortPls.put("Jackson",8.2,12,6000,"A");

  }

I expected the Hashmaps to hold more than 2 elements, but it returned an error that limits the elements to 2, with the data types after the first 2 being returned as cannot find symbol.

Body:
You have to do something like this

public class Data {

    private String name;
    private int val1;
    private long val2;
    private char val3;

    public Data (String name, int val1, long val2, char val3) {
        this.name = name;
        this.val1 = val1;
        this.val2 = val2;
        this.val3 = val3;
    }
    public String getName() {
        return name;
    }
    public int getVal1() {
        return val1;
    }
    public long getVal2() {
        return val2;
    }
    public char getVal3() {
        return val3;
    }
}

Using...

public static HashMap<String, Data> sortPls= new HashMap();
public static void setList(){
    Data d = new Data("A",32,12L,'u');
    sortPls.put("Jackson",d);
}


问:
How can I recognize RTL strings in C++
I need to know the direction of my text before printing.

I'm using Unicode Characters.

How can I do that in C++?

答:
If you don't want to use ICU, you can always manually parse the unicode database (.e.g., with a python script). It's a semicolon-separated text file, with each line representing a character code point. Look for the fifth record in each line - that's the character class. If it's R or AL, you have an RTL character, and 'L' is an LTR character. Other classes are weak or neutral types (like numerals), which I guess you'd want to ignore. Using that info, you can generate a lookup table of all RTL characters and then use it in your C++ code. If you really care about code size, you can minimize the size the lookup table takes in your code by using ranges (instead of an entry for each character), since most characters come in blocks of their BiDi class.

Now, define a function called GetCharDirection(wchar_t ch) which returns an enum value (say: Dir_LTR, Dir_RTL or Dir_Neutral) by checking the lookup table.

Now you can define a function GetStringDirection(const wchar_t*) which runs through all characters in the string until it encounters a character which is not Dir_Neutral. This first non-neutral character in the string should set the base direction for that string. Or at least that's how ICU seems to work.

ContentLicense: CC BY-SA 2.5

Title: How can I recognize RTL strings in C++


问:
Get Internal id for country list in NetSuite SuiteScript 2.0 by passing the country code
Invested lot of time to get the internal Ids of country list in NetSuite, could not find a standard way. if anyone knows any better way to do it please post in the comment</p>

```<code>function getCountryInternalId(code){
        var internalId = '';
        var idPlusName = {"Afghanistan":"3","Aland Islands":"247","Albania":"6","Algeria":"62","American Samoa":"12","Andorra":"1","Angola":"9","Anguilla":"5","Antarctica":"10","Antigua and Barbuda":"4","Argentina":"11","Armenia":"7","Aruba":"15","Australia":"14","Austria":"13","Azerbaijan":"16","Bahamas":"31","Bahrain":"23","Bangladesh":"19","Barbados":"18","Belarus":"35","Belgium":"20","Belize":"36","Benin":"25","Bermuda":"27","Bhutan":"32","Bolivia":"29","Bonaire, Saint Eustatius and Saba":"250","Bosnia and Herzegovina":"17","Botswana":"34","Bouvet Island":"33","Brazil":"30","British Indian Ocean Territory":"106","Brunei Darussalam":"28","Bulgaria":"22","Burkina Faso":"21","Burundi":"24","Cambodia":"117","Cameroon":"46","Canada":"37","Canary Islands":"249","Cape Verde":"53","Cayman Islands":"124","Central African Republic":"40","Ceuta and Melilla":"248","Chad":"212","Chile":"45","China":"47","Christmas Island":"54","Cocos (Keeling) Islands":"38","Colombia":"48","Comoros":"119","Congo, Democratic Republic of":"39","Congo, Republic of":"41","Cook Islands":"44","Costa Rica":"49","Cote d'Ivoire":"43","Croatia/Hrvatska":"98","Cuba":"52","Curaçao":"251","Cyprus":"55","Czech Republic":"56","Denmark":"59","Djibouti":"58","Dominica":"60","Dominican Republic":"61","East Timor":"221","Ecuador":"63","Egypt":"65","El Salvador":"208","Equatorial Guinea":"88","Eritrea":"67","Estonia":"64","Ethiopia":"69","Falkland Islands":"72","Faroe Islands":"74","Fiji":"71","Finland":"70","France":"75","French Guiana":"80","French Polynesia":"175","French Southern Territories":"213","Gabon":"76","Gambia":"85","Georgia":"79","Germany":"57","Ghana":"82","Gibraltar":"83","Greece":"89","Greenland":"84","Grenada":"78","Guadeloupe":"87","Guam":"92","Guatemala":"91","Guernsey":"81","Guinea":"86","Guinea-Bissau":"93","Guyana":"94","Haiti":"99","Heard and McDonald Islands":"96","Holy See (City Vatican State)":"233","Honduras":"97","Hong Kong":"95","Hungary":"100","Iceland":"109","India":"105","Indonesia":"101","Iran (Islamic Republic of)":"108","Iraq":"107","Ireland":"102","Isle of Man":"104","Israel":"103","Italy":"110","Jamaica":"112","Japan":"114","Jersey":"111","Jordan":"113","Kazakhstan":"125","Kenya":"115","Kiribati":"118","Korea, Democratic People's Republic":"121","Korea, Republic of":"122","Kosovo":"254","Kuwait":"123","Kyrgyzstan":"116","Lao People's Democratic Republic":"126","Latvia":"135","Lebanon":"127","Lesotho":"132","Liberia":"131","Libya":"136","Liechtenstein":"129","Lithuania":"133","Luxembourg":"134","Macau":"148","Macedonia":"144","Madagascar":"142","Malawi":"156","Malaysia":"158","Maldives":"155","Mali":"145","Malta":"153","Marshall Islands":"143","Martinique":"150","Mauritania":"151","Mauritius":"154","Mayotte":"243","Mexico":"157","Micronesia, Federal State of":"73","Moldova, Republic of":"139","Monaco":"138","Mongolia":"147","Montenegro":"140","Montserrat":"152","Morocco":"137","Mozambique":"159","Myanmar (Burma)":"146","Namibia":"160","Nauru":"169","Nepal":"168","Netherlands":"166","Netherlands Antilles (Deprecated)":"8","New Caledonia":"161","New Zealand":"171","Nicaragua":"165","Niger":"162","Nigeria":"164","Niue":"170","Norfolk Island":"163","Northern Mariana Islands":"149","Norway":"167","Oman":"172","Pakistan":"178","Palau":"185","Panama":"173","Papua New Guinea":"176","Paraguay":"186","Peru":"174","Philippines":"177","Pitcairn Island":"181","Poland":"179","Portugal":"184","Puerto Rico":"182","Qatar":"187","Reunion Island":"188","Romania":"189","Russian Federation":"190","Rwanda":"191","Saint Barthélemy":"26","Saint Helena":"198","Saint Kitts and Nevis":"120","Saint Lucia":"128","Saint Martin":"141","Saint Vincent and the Grenadines":"234","Samoa":"241","San Marino":"203","Sao Tome and Principe":"207","Saudi Arabia":"192","Senegal":"204","Serbia":"50","Serbia and Montenegro (Deprecated)":"51","Seychelles":"194","Sierra Leone":"202","Singapore":"197","Sint Maarten":"252","Slovak Republic":"201","Slovenia":"199","Solomon Islands":"193","Somalia":"205","South Africa":"244","South Georgia":"90","South Sudan":"253","Spain":"68","Sri Lanka":"130","St. Pierre and Miquelon":"180","State of Palestine":"183","Sudan":"195","Suriname":"206","Svalbard and Jan Mayen Islands":"200","Swaziland":"210","Sweden":"196","Switzerland":"42","Syrian Arab Republic":"209","Taiwan":"225","Tajikistan":"216","Tanzania":"226","Thailand":"215","Togo":"214","Tokelau":"217","Tonga":"220","Trinidad and Tobago":"223","Tunisia":"219","Turkey":"222","Turkmenistan":"218","Turks and Caicos Islands":"211","Tuvalu":"224","Uganda":"228","Ukraine":"227","United Arab Emirates":"2","United Kingdom":"77","United States":"230","Uruguay":"231","US Minor Outlying Islands":"229","Uzbekistan":"232","Vanuatu":"239","Venezuela":"235","Vietnam":"238","Virgin Islands (British)":"236","Virgin Islands (USA)":"237","Wallis and Futuna":"240","Western Sahara":"66","Yemen":"242","Zambia":"245","Zimbabwe":"246"};
        var codePlusName =  {"AF":"Afghanistan","AX":"Aland Islands","AL":"Albania","DZ":"Algeria","AS":"American Samoa","AD":"Andorra","AO":"Angola","AI":"Anguilla","AQ":"Antarctica","AG":"Antigua and Barbuda","AR":"Argentina","AM":"Armenia","AW":"Aruba","AU":"Australia","AT":"Austria","AZ":"Azerbaijan","BS":"Bahamas","BH":"Bahrain","BD":"Bangladesh","BB":"Barbados","BY":"Belarus","BE":"Belgium","BZ":"Belize","BJ":"Benin","BM":"Bermuda","BT":"Bhutan","BO":"Bolivia","BQ":"Bonaire, Saint Eustatius and Saba","BA":"Bosnia and Herzegovina","BW":"Botswana","BV":"Bouvet Island","BR":"Brazil","IO":"British Indian Ocean Territory","BN":"Brunei Darussalam","BG":"Bulgaria","BF":"Burkina Faso","BI":"Burundi","KH":"Cambodia","CM":"Cameroon","CA":"Canada","IC":"Canary Islands","CV":"Cape Verde","KY":"Cayman Islands","CF":"Central African Republic","EA":"Ceuta and Melilla","TD":"Chad","CL":"Chile","CN":"China","CX":"Christmas Island","CC":"Cocos (Keeling) Islands","CO":"Colombia","KM":"Comoros","CD":"Congo, Democratic Republic of","CG":"Congo, Republic of","CK":"Cook Islands","CR":"Costa Rica","CI":"Cote d'Ivoire","HR":"Croatia/Hrvatska","CU":"Cuba","CW":"CuraÃ§ao","CY":"Cyprus","CZ":"Czech Republic","DK":"Denmark","DJ":"Djibouti","DM":"Dominica","DO":"Dominican Republic","TL":"East Timor","EC":"Ecuador","EG":"Egypt","SV":"El Salvador","GQ":"Equatorial Guinea","ER":"Eritrea","EE":"Estonia","ET":"Ethiopia","FK":"Falkland Islands","FO":"Faroe Islands","FJ":"Fiji","FI":"Finland","FR":"France","GF":"French Guiana","PF":"French Polynesia","TF":"French Southern Territories","GA":"Gabon","GM":"Gambia","GE":"Georgia","DE":"Germany","GH":"Ghana","GI":"Gibraltar","GR":"Greece","GL":"Greenland","GD":"Grenada","GP":"Guadeloupe","GU":"Guam","GT":"Guatemala","GG":"Guernsey","GN":"Guinea","GW":"Guinea-Bissau","GY":"Guyana","HT":"Haiti","HM":"Heard and McDonald Islands","VA":"Holy See (City Vatican State)","HN":"Honduras","HK":"Hong Kong","HU":"Hungary","IS":"Iceland","IN":"India","ID":"Indonesia","IR":"Iran (Islamic Republic of)","IQ":"Iraq","IE":"Ireland","IM":"Isle of Man","IL":"Israel","IT":"Italy","JM":"Jamaica","JP":"Japan","JE":"Jersey","JO":"Jordan","KZ":"Kazakhstan","KE":"Kenya","KI":"Kiribati","KP":"Korea, Democratic People's Republic","KR":"Korea, Republic of","XK":"Kosovo","KW":"Kuwait","KG":"Kyrgyzstan","LA":"Lao People's Democratic Republic","LV":"Latvia","LB":"Lebanon","LS":"Lesotho","LR":"Liberia","LY":"Libya","LI":"Liechtenstein","LT":"Lithuania","LU":"Luxembourg","MO":"Macau","MK":"Macedonia","MG":"Madagascar","MW":"Malawi","MY":"Malaysia","MV":"Maldives","ML":"Mali","MT":"Malta","MH":"Marshall Islands","MQ":"Martinique","MR":"Mauritania","MU":"Mauritius","YT":"Mayotte","MX":"Mexico","FM":"Micronesia, Federal State of","MD":"Moldova, Republic of","MC":"Monaco","MN":"Mongolia","ME":"Montenegro","MS":"Montserrat","MA":"Morocco","MZ":"Mozambique","MM":"Myanmar (Burma)","NA":"Namibia","NR":"Nauru","NP":"Nepal","NL":"Netherlands","AN":"Netherlands Antilles (Deprecated)","NC":"New Caledonia","NZ":"New Zealand","NI":"Nicaragua","NE":"Niger","NG":"Nigeria","NU":"Niue","NF":"Norfolk Island","MP":"Northern Mariana Islands","NO":"Norway","OM":"Oman","PK":"Pakistan","PW":"Palau","PS":"Palestinian Territories","PA":"Panama","PG":"Papua New Guinea","PY":"Paraguay","PE":"Peru","PH":"Philippines","PN":"Pitcairn Island","PL":"Poland","PT":"Portugal","PR":"Puerto Rico","QA":"Qatar","RE":"Reunion Island","RO":"Romania","RU":"Russian Federation","RW":"Rwanda","BL":"Saint BarthÃ©lemy","SH":"Saint Helena","KN":"Saint Kitts and Nevis","LC":"Saint Lucia","MF":"Saint Martin","VC":"Saint Vincent and the Grenadines","WS":"Samoa","SM":"San Marino","ST":"Sao Tome and Principe","SA":"Saudi Arabia","SN":"Senegal","RS":"Serbia","CS":"Serbia and Montenegro (Deprecated)","SC":"Seychelles","SL":"Sierra Leone","SG":"Singapore","SX":"Sint Maarten","SK":"Slovak Republic","SI":"Slovenia","SB":"Solomon Islands","SO":"Somalia","ZA":"South Africa","GS":"South Georgia","SS":"South Sudan","ES":"Spain","LK":"Sri Lanka","PM":"St. Pierre and Miquelon","SD":"Sudan","SR":"Suriname","SJ":"Svalbard and Jan Mayen Islands","SZ":"Swaziland","SE":"Sweden","CH":"Switzerland","SY":"Syrian Arab Republic","TW":"Taiwan","TJ":"Tajikistan","TZ":"Tanzania","TH":"Thailand","TG":"Togo","TK":"Tokelau","TO":"Tonga","TT":"Trinidad and Tobago","TN":"Tunisia","TR":"Turkey","TM":"Turkmenistan","TC":"Turks and Caicos Islands","TV":"Tuvalu","UG":"Uganda","UA":"Ukraine","AE":"United Arab Emirates","GB":"United Kingdom (GB)","US":"United States","UY":"Uruguay","UM":"US Minor Outlying Islands","UZ":"Uzbekistan","VU":"Vanuatu","VE":"Venezuela","VN":"Vietnam","VG":"Virgin Islands (British)","VI":"Virgin Islands (USA)","WF":"Wallis and Futuna","EH":"Western Sahara","YE":"Yemen","ZM":"Zambia","ZW":"Zimbabwe"};

        var name = codePlusName[code];
        internalId = idPlusName[name]
        log.debug({title:'Country-internalId',
            details:internalId
        });
        return internalId;
    }
</code>```

答:
It's in Suite answers, Normally when we look at
Setup>company>countries>open any country and check the url there would be ID, that only shows the Alphabetical ID.

In Suite answers check the Answer ID's: 71731 & 38434
or links below
https://netsuite.custhelp.com/app/answers/detail/a_id/71731/kw/country%20internal%20id's

https://netsuite.custhelp.com/app/answers/detail/a_id/38434/kw/country%20internal%20id&/related/1

```<code>Country Name    Country Code    Internal ID
Afghanistan AF  3
Aland Islands   AX  247
Albania AL  6
Algeria DZ  62
American Samoa  AS  12
Andorra AD  1
Angola  AO  9
Anguilla    AI  5
Antarctica  AQ  10
Antigua and Barbuda AG  4
Argentina   AR  11
Armenia AM  7
Aruba   AW  15
Australia   AU  14
Austria AT  13
Azerbaijan  AZ  16
Bahamas BS  31
Bahrain BH  23
Bangladesh  BD  19
Barbados    BB  18
Belarus BY  35
Belgium BE  20
Belize  BZ  36
Benin   BJ  25
Bermuda BM  27
Bhutan  BT  32
Bolivia BO  29
Bonaire, Saint Eustatius and Saba   BQ  250
Bosnia and Herzegovina  BA  17
Botswana    BW  34
Bouvet Island   BV  33
Brazil  BR  30
British Indian Ocean Territory  IO  106
Brunei Darussalam   BN  28
Bulgaria    BG  22
Burkina Faso    BF  21
Burundi BI  24
Cambodia    KH  117
Cameroon    CM  46
Canada  CA  37
Canary Islands  IC  249
Cape Verde  CV  53
Cayman Islands  KY  124
Central African Republic    CF  40
Ceuta and Melilla   EA  248
Chad    TD  212
Chile   CL  45
China   CN  47
Christmas Island    CX  54
Cocos (Keeling) Islands CC  38
Colombia    CO  48
Comoros KM  119
Congo, Democratic Republic of   CD  39
Congo, Republic of  CG  41
Cook Islands    CK  44
Costa Rica  CR  49
Cote d\u0027Ivoire  CI  43
Croatia/Hrvatska    HR  98
Cuba    CU  52
Curaçao CW  251
Cyprus  CY  55
Czech Republic  CZ  56
Denmark DK  59
Djibouti    DJ  58
Dominica    DM  60
Dominican Republic  DO  61
East Timor  TP  221
Ecuador EC  63
Egypt   EG  65
El Salvador SV  208
Equatorial Guinea   GQ  88
Eritrea ER  67
Estonia EE  64
Ethiopia    ET  69
Falkland Islands    FK  72
Faroe Islands   FO  74
Fiji    FJ  71
Finland FI  70
France  FR  75
French Guiana   GF  80
French Polynesia    PF  175
French Southern Territories TF  213
Gabon   GA  76
Gambia  GM  85
Georgia GE  79
Germany DE  57
Ghana   GH  82
Gibraltar   GI  83
Greece  GR  89
Greenland   GL  84
Grenada GD  78
Guadeloupe  GP  87
Guam    GU  92
Guatemala   GT  91
Guernsey    GG  81
Guinea  GN  86
Guinea-Bissau   GW  93
Guyana  GY  94
Haiti   HT  99
Heard and McDonald Islands  HM  96
Holy See (City Vatican State)   VA  233
Honduras    HN  97
Hong Kong   HK  95
Hungary HU  100
Iceland IS  109
India   IN  105
Indonesia   ID  101
Iran (Islamic Republic of)  IR  108
Iraq    IQ  107
Ireland IE  102
Isle of Man IM  104
Israel  IL  103
Italy   IT  110
Jamaica JM  112
Japan   JP  114
Jersey  JE  111
Jordan  JO  113
Kazakhstan  KZ  125
Kenya   KE  115
Kiribati    KI  118
Korea, Democratic People\u0027s Republic    KP  121
Korea, Republic of  KR  122
Kosovo  XK  254
Kuwait  KW  123
Kyrgyzstan  KG  116
Lao People\u0027s Democratic Republic   LA  126
Latvia  LV  135
Lebanon LB  127
Lesotho LS  132
Liberia LR  131
Libya   LY  136
Liechtenstein   LI  129
Lithuania   LT  133
Luxembourg  LU  134
Macau   MO  148
Macedonia   MK  144
Madagascar  MG  142
Malawi  MW  156
Malaysia    MY  158
Maldives    MV  155
Mali    ML  145
Malta   MT  153
Marshall Islands    MH  143
Martinique  MQ  150
Mauritania  MR  151
Mauritius   MU  154
Mayotte YT  243
Mexico  MX  157
Micronesia, Federal State of    FM  73
Moldova, Republic of    MD  139
Monaco  MC  138
Mongolia    MN  147
Montenegro  ME  140
Montserrat  MS  152
Morocco MA  137
Mozambique  MZ  159
Myanmar (Burma) MM  146
Namibia NA  160
Nauru   NR  169
Nepal   NP  168
Netherlands NL  166
Netherlands Antilles (Deprecated)       8
New Caledonia   NC  161
New Zealand NZ  171
Nicaragua   NI  165
Niger   NE  162
Nigeria NG  164
Niue    NU  170
Norfolk Island  NF  163
Northern Mariana Islands    MP  149
Norway  NO  167
Oman    OM  172
Pakistan    PK  178
Palau   PW  185
Panama  PA  173
Papua New Guinea    PG  176
Paraguay    PY  186
Peru    PE  174
Philippines PH  177
Pitcairn Island PN  181
Poland  PL  179
Portugal    PT  184
Puerto Rico PR  182
Qatar   QA  187
Reunion Island  RE  188
Romania RO  189
Russian Federation  RU  190
Rwanda  RW  191
Saint Barthélemy    BL  26
Saint Helena    SH  198
Saint Kitts and Nevis   KN  120
Saint Lucia LC  128
Saint Martin    MF  141
Saint Vincent and the Grenadines    VC  234
Samoa   WS  241
San Marino  SM  203
Sao Tome and Principe   ST  207
Saudi Arabia    SA  192
Senegal SN  204
Serbia  RS  50

Seychelles  SC  194
Sierra Leone    SL  202
Singapore   SG  197
Sint Maarten    SX  252
Slovak Republic SK  201
Slovenia    SI  199
Solomon Islands SB  193
Somalia SO  205
South Africa    ZA  244
South Georgia   GS  90
South Sudan SS  253
Spain   ES  68
Sri Lanka   LK  130
St. Pierre and Miquelon PS  180
State of Palestine  PM  183
Sudan   SD  195
Suriname    SR  206
Svalbard and Jan Mayen Islands  SJ  200
Swaziland   SZ  210
Sweden  SE  196
Switzerland CH  42
Syrian Arab Republic    SY  209
Taiwan  TW  225
Tajikistan  TJ  216
Tanzania    TZ  226
Thailand    TH  215
Togo    TG  214
Tokelau TK  217
Tonga   TO  220
Trinidad and Tobago TT  223
Tunisia TN  219
Turkey  TR  222
Turkmenistan    TM  218
Turks and Caicos Islands    TC  211
Tuvalu  TV  224
Uganda  UG  228
Ukraine UA  227
United Arab Emirates    AE  2
United Kingdom  GB  77
United States   US  230
Uruguay UY  231
US Minor Outlying Islands   UM  229
Uzbekistan  UZ  232
Vanuatu VU  239
Venezuela   VE  235
Vietnam VN  238
Virgin Islands (British)    VG  236
Virgin Islands (USA)    VI  237
Wallis and Futuna   WF  240
Western Sahara  EH  66
Yemen   YE  242
Zambia  ZM  245
Zimbabwe    ZW  246
</code>```

Body:
Invested lot of time to get the internal Ids of country list in NetSuite, could not find a standard way. if anyone knows any better way to do it please post in the comment

function getCountryInternalId(code){
        var internalId = '';
        var idPlusName = {"Afghanistan":"3","Aland Islands":"247","Albania":"6","Algeria":"62","American Samoa":"12","Andorra":"1","Angola":"9","Anguilla":"5","Antarctica":"10","Antigua and Barbuda":"4","Argentina":"11","Armenia":"7","Aruba":"15","Australia":"14","Austria":"13","Azerbaijan":"16","Bahamas":"31","Bahrain":"23","Bangladesh":"19","Barbados":"18","Belarus":"35","Belgium":"20","Belize":"36","Benin":"25","Bermuda":"27","Bhutan":"32","Bolivia":"29","Bonaire, Saint Eustatius and Saba":"250","Bosnia and Herzegovina":"17","Botswana":"34","Bouvet Island":"33","Brazil":"30","British Indian Ocean Territory":"106","Brunei Darussalam":"28","Bulgaria":"22","Burkina Faso":"21","Burundi":"24","Cambodia":"117","Cameroon":"46","Canada":"37","Canary Islands":"249","Cape Verde":"53","Cayman Islands":"124","Central African Republic":"40","Ceuta and Melilla":"248","Chad":"212","Chile":"45","China":"47","Christmas Island":"54","Cocos (Keeling) Islands":"38","Colombia":"48","Comoros":"119","Congo, Democratic Republic of":"39","Congo, Republic of":"41","Cook Islands":"44","Costa Rica":"49","Cote d'Ivoire":"43","Croatia/Hrvatska":"98","Cuba":"52","Curaçao":"251","Cyprus":"55","Czech Republic":"56","Denmark":"59","Djibouti":"58","Dominica":"60","Dominican Republic":"61","East Timor":"221","Ecuador":"63","Egypt":"65","El Salvador":"208","Equatorial Guinea":"88","Eritrea":"67","Estonia":"64","Ethiopia":"69","Falkland Islands":"72","Faroe Islands":"74","Fiji":"71","Finland":"70","France":"75","French Guiana":"80","French Polynesia":"175","French Southern Territories":"213","Gabon":"76","Gambia":"85","Georgia":"79","Germany":"57","Ghana":"82","Gibraltar":"83","Greece":"89","Greenland":"84","Grenada":"78","Guadeloupe":"87","Guam":"92","Guatemala":"91","Guernsey":"81","Guinea":"86","Guinea-Bissau":"93","Guyana":"94","Haiti":"99","Heard and McDonald Islands":"96","Holy See (City Vatican State)":"233","Honduras":"97","Hong Kong":"95","Hungary":"100","Iceland":"109","India":"105","Indonesia":"101","Iran (Islamic Republic of)":"108","Iraq":"107","Ireland":"102","Isle of Man":"104","Israel":"103","Italy":"110","Jamaica":"112","Japan":"114","Jersey":"111","Jordan":"113","Kazakhstan":"125","Kenya":"115","Kiribati":"118","Korea, Democratic People's Republic":"121","Korea, Republic of":"122","Kosovo":"254","Kuwait":"123","Kyrgyzstan":"116","Lao People's Democratic Republic":"126","Latvia":"135","Lebanon":"127","Lesotho":"132","Liberia":"131","Libya":"136","Liechtenstein":"129","Lithuania":"133","Luxembourg":"134","Macau":"148","Macedonia":"144","Madagascar":"142","Malawi":"156","Malaysia":"158","Maldives":"155","Mali":"145","Malta":"153","Marshall Islands":"143","Martinique":"150","Mauritania":"151","Mauritius":"154","Mayotte":"243","Mexico":"157","Micronesia, Federal State of":"73","Moldova, Republic of":"139","Monaco":"138","Mongolia":"147","Montenegro":"140","Montserrat":"152","Morocco":"137","Mozambique":"159","Myanmar (Burma)":"146","Namibia":"160","Nauru":"169","Nepal":"168","Netherlands":"166","Netherlands Antilles (Deprecated)":"8","New Caledonia":"161","New Zealand":"171","Nicaragua":"165","Niger":"162","Nigeria":"164","Niue":"170","Norfolk Island":"163","Northern Mariana Islands":"149","Norway":"167","Oman":"172","Pakistan":"178","Palau":"185","Panama":"173","Papua New Guinea":"176","Paraguay":"186","Peru":"174","Philippines":"177","Pitcairn Island":"181","Poland":"179","Portugal":"184","Puerto Rico":"182","Qatar":"187","Reunion Island":"188","Romania":"189","Russian Federation":"190","Rwanda":"191","Saint Barthélemy":"26","Saint Helena":"198","Saint Kitts and Nevis":"120","Saint Lucia":"128","Saint Martin":"141","Saint Vincent and the Grenadines":"234","Samoa":"241","San Marino":"203","Sao Tome and Principe":"207","Saudi Arabia":"192","Senegal":"204","Serbia":"50","Serbia and Montenegro (Deprecated)":"51","Seychelles":"194","Sierra Leone":"202","Singapore":"197","Sint Maarten":"252","Slovak Republic":"201","Slovenia":"199","Solomon Islands":"193","Somalia":"205","South Africa":"244","South Georgia":"90","South Sudan":"253","Spain":"68","Sri Lanka":"130","St. Pierre and Miquelon":"180","State of Palestine":"183","Sudan":"195","Suriname":"206","Svalbard and Jan Mayen Islands":"200","Swaziland":"210","Sweden":"196","Switzerland":"42","Syrian Arab Republic":"209","Taiwan":"225","Tajikistan":"216","Tanzania":"226","Thailand":"215","Togo":"214","Tokelau":"217","Tonga":"220","Trinidad and Tobago":"223","Tunisia":"219","Turkey":"222","Turkmenistan":"218","Turks and Caicos Islands":"211","Tuvalu":"224","Uganda":"228","Ukraine":"227","United Arab Emirates":"2","United Kingdom":"77","United States":"230","Uruguay":"231","US Minor Outlying Islands":"229","Uzbekistan":"232","Vanuatu":"239","Venezuela":"235","Vietnam":"238","Virgin Islands (British)":"236","Virgin Islands (USA)":"237","Wallis and Futuna":"240","Western Sahara":"66","Yemen":"242","Zambia":"245","Zimbabwe":"246"};
        var codePlusName =  {"AF":"Afghanistan","AX":"Aland Islands","AL":"Albania","DZ":"Algeria","AS":"American Samoa","AD":"Andorra","AO":"Angola","AI":"Anguilla","AQ":"Antarctica","AG":"Antigua and Barbuda","AR":"Argentina","AM":"Armenia","AW":"Aruba","AU":"Australia","AT":"Austria","AZ":"Azerbaijan","BS":"Bahamas","BH":"Bahrain","BD":"Bangladesh","BB":"Barbados","BY":"Belarus","BE":"Belgium","BZ":"Belize","BJ":"Benin","BM":"Bermuda","BT":"Bhutan","BO":"Bolivia","BQ":"Bonaire, Saint Eustatius and Saba","BA":"Bosnia and Herzegovina","BW":"Botswana","BV":"Bouvet Island","BR":"Brazil","IO":"British Indian Ocean Territory","BN":"Brunei Darussalam","BG":"Bulgaria","BF":"Burkina Faso","BI":"Burundi","KH":"Cambodia","CM":"Cameroon","CA":"Canada","IC":"Canary Islands","CV":"Cape Verde","KY":"Cayman Islands","CF":"Central African Republic","EA":"Ceuta and Melilla","TD":"Chad","CL":"Chile","CN":"China","CX":"Christmas Island","CC":"Cocos (Keeling) Islands","CO":"Colombia","KM":"Comoros","CD":"Congo, Democratic Republic of","CG":"Congo, Republic of","CK":"Cook Islands","CR":"Costa Rica","CI":"Cote d'Ivoire","HR":"Croatia/Hrvatska","CU":"Cuba","CW":"CuraÃ§ao","CY":"Cyprus","CZ":"Czech Republic","DK":"Denmark","DJ":"Djibouti","DM":"Dominica","DO":"Dominican Republic","TL":"East Timor","EC":"Ecuador","EG":"Egypt","SV":"El Salvador","GQ":"Equatorial Guinea","ER":"Eritrea","EE":"Estonia","ET":"Ethiopia","FK":"Falkland Islands","FO":"Faroe Islands","FJ":"Fiji","FI":"Finland","FR":"France","GF":"French Guiana","PF":"French Polynesia","TF":"French Southern Territories","GA":"Gabon","GM":"Gambia","GE":"Georgia","DE":"Germany","GH":"Ghana","GI":"Gibraltar","GR":"Greece","GL":"Greenland","GD":"Grenada","GP":"Guadeloupe","GU":"Guam","GT":"Guatemala","GG":"Guernsey","GN":"Guinea","GW":"Guinea-Bissau","GY":"Guyana","HT":"Haiti","HM":"Heard and McDonald Islands","VA":"Holy See (City Vatican State)","HN":"Honduras","HK":"Hong Kong","HU":"Hungary","IS":"Iceland","IN":"India","ID":"Indonesia","IR":"Iran (Islamic Republic of)","IQ":"Iraq","IE":"Ireland","IM":"Isle of Man","IL":"Israel","IT":"Italy","JM":"Jamaica","JP":"Japan","JE":"Jersey","JO":"Jordan","KZ":"Kazakhstan","KE":"Kenya","KI":"Kiribati","KP":"Korea, Democratic People's Republic","KR":"Korea, Republic of","XK":"Kosovo","KW":"Kuwait","KG":"Kyrgyzstan","LA":"Lao People's Democratic Republic","LV":"Latvia","LB":"Lebanon","LS":"Lesotho","LR":"Liberia","LY":"Libya","LI":"Liechtenstein","LT":"Lithuania","LU":"Luxembourg","MO":"Macau","MK":"Macedonia","MG":"Madagascar","MW":"Malawi","MY":"Malaysia","MV":"Maldives","ML":"Mali","MT":"Malta","MH":"Marshall Islands","MQ":"Martinique","MR":"Mauritania","MU":"Mauritius","YT":"Mayotte","MX":"Mexico","FM":"Micronesia, Federal State of","MD":"Moldova, Republic of","MC":"Monaco","MN":"Mongolia","ME":"Montenegro","MS":"Montserrat","MA":"Morocco","MZ":"Mozambique","MM":"Myanmar (Burma)","NA":"Namibia","NR":"Nauru","NP":"Nepal","NL":"Netherlands","AN":"Netherlands Antilles (Deprecated)","NC":"New Caledonia","NZ":"New Zealand","NI":"Nicaragua","NE":"Niger","NG":"Nigeria","NU":"Niue","NF":"Norfolk Island","MP":"Northern Mariana Islands","NO":"Norway","OM":"Oman","PK":"Pakistan","PW":"Palau","PS":"Palestinian Territories","PA":"Panama","PG":"Papua New Guinea","PY":"Paraguay","PE":"Peru","PH":"Philippines","PN":"Pitcairn Island","PL":"Poland","PT":"Portugal","PR":"Puerto Rico","QA":"Qatar","RE":"Reunion Island","RO":"Romania","RU":"Russian Federation","RW":"Rwanda","BL":"Saint BarthÃ©lemy","SH":"Saint Helena","KN":"Saint Kitts and Nevis","LC":"Saint Lucia","MF":"Saint Martin","VC":"Saint Vincent and the Grenadines","WS":"Samoa","SM":"San Marino","ST":"Sao Tome and Principe","SA":"Saudi Arabia","SN":"Senegal","RS":"Serbia","CS":"Serbia and Montenegro (Deprecated)","SC":"Seychelles","SL":"Sierra Leone","SG":"Singapore","SX":"Sint Maarten","SK":"Slovak Republic","SI":"Slovenia","SB":"Solomon Islands","SO":"Somalia","ZA":"South Africa","GS":"South Georgia","SS":"South Sudan","ES":"Spain","LK":"Sri Lanka","PM":"St. Pierre and Miquelon","SD":"Sudan","SR":"Suriname","SJ":"Svalbard and Jan Mayen Islands","SZ":"Swaziland","SE":"Sweden","CH":"Switzerland","SY":"Syrian Arab Republic","TW":"Taiwan","TJ":"Tajikistan","TZ":"Tanzania","TH":"Thailand","TG":"Togo","TK":"Tokelau","TO":"Tonga","TT":"Trinidad and Tobago","TN":"Tunisia","TR":"Turkey","TM":"Turkmenistan","TC":"Turks and Caicos Islands","TV":"Tuvalu","UG":"Uganda","UA":"Ukraine","AE":"United Arab Emirates","GB":"United Kingdom (GB)","US":"United States","UY":"Uruguay","UM":"US Minor Outlying Islands","UZ":"Uzbekistan","VU":"Vanuatu","VE":"Venezuela","VN":"Vietnam","VG":"Virgin Islands (British)","VI":"Virgin Islands (USA)","WF":"Wallis and Futuna","EH":"Western Sahara","YE":"Yemen","ZM":"Zambia","ZW":"Zimbabwe"};

        var name = codePlusName[code];
        internalId = idPlusName[name]
        log.debug({title:'Country-internalId',
            details:internalId
        });
        return internalId;
    }

Body:
It's in Suite answers, Normally when we look at
Setup>company>countries>open any country and check the url there would be ID, that only shows the Alphabetical ID.

In Suite answers check the Answer ID's: 71731 & 38434
or links below
https://netsuite.custhelp.com/app/answers/detail/a_id/71731/kw/country%20internal%20id's

https://netsuite.custhelp.com/app/answers/detail/a_id/38434/kw/country%20internal%20id&/related/1

Country Name    Country Code    Internal ID
Afghanistan AF  3
Aland Islands   AX  247
Albania AL  6
Algeria DZ  62
American Samoa  AS  12
Andorra AD  1
Angola  AO  9
Anguilla    AI  5
Antarctica  AQ  10
Antigua and Barbuda AG  4
Argentina   AR  11
Armenia AM  7
Aruba   AW  15
Australia   AU  14
Austria AT  13
Azerbaijan  AZ  16
Bahamas BS  31
Bahrain BH  23
Bangladesh  BD  19
Barbados    BB  18
Belarus BY  35
Belgium BE  20
Belize  BZ  36
Benin   BJ  25
Bermuda BM  27
Bhutan  BT  32
Bolivia BO  29
Bonaire, Saint Eustatius and Saba   BQ  250
Bosnia and Herzegovina  BA  17
Botswana    BW  34
Bouvet Island   BV  33
Brazil  BR  30
British Indian Ocean Territory  IO  106
Brunei Darussalam   BN  28
Bulgaria    BG  22
Burkina Faso    BF  21
Burundi BI  24
Cambodia    KH  117
Cameroon    CM  46
Canada  CA  37
Canary Islands  IC  249
Cape Verde  CV  53
Cayman Islands  KY  124
Central African Republic    CF  40
Ceuta and Melilla   EA  248
Chad    TD  212
Chile   CL  45
China   CN  47
Christmas Island    CX  54
Cocos (Keeling) Islands CC  38
Colombia    CO  48
Comoros KM  119
Congo, Democratic Republic of   CD  39
Congo, Republic of  CG  41
Cook Islands    CK  44
Costa Rica  CR  49
Cote d\u0027Ivoire  CI  43
Croatia/Hrvatska    HR  98
Cuba    CU  52
Curaçao CW  251
Cyprus  CY  55
Czech Republic  CZ  56
Denmark DK  59
Djibouti    DJ  58
Dominica    DM  60
Dominican Republic  DO  61
East Timor  TP  221
Ecuador EC  63
Egypt   EG  65
El Salvador SV  208
Equatorial Guinea   GQ  88
Eritrea ER  67
Estonia EE  64
Ethiopia    ET  69
Falkland Islands    FK  72
Faroe Islands   FO  74
Fiji    FJ  71
Finland FI  70
France  FR  75
French Guiana   GF  80
French Polynesia    PF  175
French Southern Territories TF  213
Gabon   GA  76
Gambia  GM  85
Georgia GE  79
Germany DE  57
Ghana   GH  82
Gibraltar   GI  83
Greece  GR  89
Greenland   GL  84
Grenada GD  78
Guadeloupe  GP  87
Guam    GU  92
Guatemala   GT  91
Guernsey    GG  81
Guinea  GN  86
Guinea-Bissau   GW  93
Guyana  GY  94
Haiti   HT  99
Heard and McDonald Islands  HM  96
Holy See (City Vatican State)   VA  233
Honduras    HN  97
Hong Kong   HK  95
Hungary HU  100
Iceland IS  109
India   IN  105
Indonesia   ID  101
Iran (Islamic Republic of)  IR  108
Iraq    IQ  107
Ireland IE  102
Isle of Man IM  104
Israel  IL  103
Italy   IT  110
Jamaica JM  112
Japan   JP  114
Jersey  JE  111
Jordan  JO  113
Kazakhstan  KZ  125
Kenya   KE  115
Kiribati    KI  118
Korea, Democratic People\u0027s Republic    KP  121
Korea, Republic of  KR  122
Kosovo  XK  254
Kuwait  KW  123
Kyrgyzstan  KG  116
Lao People\u0027s Democratic Republic   LA  126
Latvia  LV  135
Lebanon LB  127
Lesotho LS  132
Liberia LR  131
Libya   LY  136
Liechtenstein   LI  129
Lithuania   LT  133
Luxembourg  LU  134
Macau   MO  148
Macedonia   MK  144
Madagascar  MG  142
Malawi  MW  156
Malaysia    MY  158
Maldives    MV  155
Mali    ML  145
Malta   MT  153
Marshall Islands    MH  143
Martinique  MQ  150
Mauritania  MR  151
Mauritius   MU  154
Mayotte YT  243
Mexico  MX  157
Micronesia, Federal State of    FM  73
Moldova, Republic of    MD  139
Monaco  MC  138
Mongolia    MN  147
Montenegro  ME  140
Montserrat  MS  152
Morocco MA  137
Mozambique  MZ  159
Myanmar (Burma) MM  146
Namibia NA  160
Nauru   NR  169
Nepal   NP  168
Netherlands NL  166
Netherlands Antilles (Deprecated)       8
New Caledonia   NC  161
New Zealand NZ  171
Nicaragua   NI  165
Niger   NE  162
Nigeria NG  164
Niue    NU  170
Norfolk Island  NF  163
Northern Mariana Islands    MP  149
Norway  NO  167
Oman    OM  172
Pakistan    PK  178
Palau   PW  185
Panama  PA  173
Papua New Guinea    PG  176
Paraguay    PY  186
Peru    PE  174
Philippines PH  177
Pitcairn Island PN  181
Poland  PL  179
Portugal    PT  184
Puerto Rico PR  182
Qatar   QA  187
Reunion Island  RE  188
Romania RO  189
Russian Federation  RU  190
Rwanda  RW  191
Saint Barthélemy    BL  26
Saint Helena    SH  198
Saint Kitts and Nevis   KN  120
Saint Lucia LC  128
Saint Martin    MF  141
Saint Vincent and the Grenadines    VC  234
Samoa   WS  241
San Marino  SM  203
Sao Tome and Principe   ST  207
Saudi Arabia    SA  192
Senegal SN  204
Serbia  RS  50

Seychelles  SC  194
Sierra Leone    SL  202
Singapore   SG  197
Sint Maarten    SX  252
Slovak Republic SK  201
Slovenia    SI  199
Solomon Islands SB  193
Somalia SO  205
South Africa    ZA  244
South Georgia   GS  90
South Sudan SS  253
Spain   ES  68
Sri Lanka   LK  130
St. Pierre and Miquelon PS  180
State of Palestine  PM  183
Sudan   SD  195
Suriname    SR  206
Svalbard and Jan Mayen Islands  SJ  200
Swaziland   SZ  210
Sweden  SE  196
Switzerland CH  42
Syrian Arab Republic    SY  209
Taiwan  TW  225
Tajikistan  TJ  216
Tanzania    TZ  226
Thailand    TH  215
Togo    TG  214
Tokelau TK  217
Tonga   TO  220
Trinidad and Tobago TT  223
Tunisia TN  219
Turkey  TR  222
Turkmenistan    TM  218
Turks and Caicos Islands    TC  211
Tuvalu  TV  224
Uganda  UG  228
Ukraine UA  227
United Arab Emirates    AE  2
United Kingdom  GB  77
United States   US  230
Uruguay UY  231
US Minor Outlying Islands   UM  229
Uzbekistan  UZ  232
Vanuatu VU  239
Venezuela   VE  235
Vietnam VN  238
Virgin Islands (British)    VG  236
Virgin Islands (USA)    VI  237
Wallis and Futuna   WF  240
Western Sahara  EH  66
Yemen   YE  242
Zambia  ZM  245
Zimbabwe    ZW  246


问:
How can I center an absolutely positioned element in a div?
I want to place a div (with position:absolute;) element in the center of the window. But I'm having problems doing so, because the width is unknown.

I tried the following CSS code, but it needs to be adjusted because the width is responsive.

```<code>.center {
  left: 50%;
  bottom: 5px;
}
</code>```

How can I achieve this?

答:
This is a mix of other answers, which worked for us:

.el {
   position: absolute;
   top: 50%;
   margin: auto;
   transform: translate(-50%, -50%);
}
```

Body:
I want to place a div (with position:absolute;) element in the center of the window. But I'm having problems doing so, because the width is unknown.

I tried the following CSS code, but it needs to be adjusted because the width is responsive.

.center {
  left: 50%;
  bottom: 5px;
}

How can I achieve this?


问:
How to make a multiline QLabel elide the last line, be constrained by a max height, but also shrink if text doesn't fill to max height?
EDIT: Updated with working example and example screenshots of current and desired behavior.

Description

I'm trying to get a multiline QLabel to have these behaviors:

It should expand to fill available width.

If its text is longer than it can show, it should show all it can (expanding to its max height) and elide the last line.

If its text is not the longest it can show, it should show all text, but shrink its height to fit the text.

The label is in a layout. Maybe I'm thinking about this wrong, like maybe instead of a label it should be a text area wrapped in something else?

Anyway, I've found solutions that cover one or two of these behaviors, but not all three. I've tried tweaking Qt's ElidedLabel, but I can't quite figure out how to tweak it to achieve all three.

I've considered overriding sizeHint(), but I'm not Qt-savvy enough to know if that's the right way to do this. I feel like maybe the right combination of layoutSizeConstraint on the layout and size policies on the ElidedLabel might make this possible, but I'm not sure.

I've slightly modified Qt's ElidedLabel example code so that it doesn't take its content in its constructor.

Example code

https://gist.github.com/jahabrewer/bd0c79ac2255953eeadf87c9767ce693

Screenshots

Current behavior

Left column has text short enough that the ElidedLabel should reduce its height and cede that vertical space to the QLabel underneath it. Right column has text long enough that it's elided, which is correct/desired.

Desired behavior

(to be clear, I want a single configuration that will produce behavior like the left column when text is short and like the right column when text is long)

答:
You have to constraint the height of your label to the minimum needed to draw the text. You can get this height by using the QFontMetrics class and the method QFontMetrics::boundingRect:

```<code>QFontMetrics const fontMetrics(font());
QRect const r = fontMetrics.boundingRect(
            QRect(QPoint(0, 0), size()),
            Qt::TextWordWrap | Qt::ElideRight,
            content
            );
qDebug() << "Needed Height:" << r.height();
</code>```

First, define the method QWidget::sizeHint to force your label to have a size:

```<code>virtual QSize sizeHint() const override
{
    QFontMetrics const fontMetrics(font());
    QRect const r = fontMetrics.boundingRect(
            QRect(QPoint(0, 0), size()),
            Qt::TextWordWrap | Qt::ElideRight,
            content
            );
    return QSize(width(), r.height());
}
</code>```

We want to shrink the height, only. That's why we will not use the width returned by the font metrics

Now, we will use the resize events to check if we can shrink the height:

So, we can override the QWidget::resizeEvent method:

```<code>virtual void resizeEvent(QResizeEvent* event) override
{
    QFrame::resizeEvent(event); // Process the event. The label is now resized
    QSize const size = sizeHint();
    if (size.height() < height()) // Shrink the height if needed
        resize(QSize(width(), size.height()));
}
</code>```

If the text has to change during the runtime, we have to readjust the size:

```<code>void setText(const QString &newText)
{
   content = newText;
   update();
   adjustSize(); // Will resize the label
}
</code>```

The code I used for the tests:

```<code>QWidget* w = new QWidget();
QVBoxLayout* l = new QVBoxLayout(w);

QString const lorem("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.");
ElidedLabel* label = new ElidedLabel(lorem);
label->setFrameShape(QFrame::Box); // To see its bounds

l->addWidget(label);
l->addWidget(new QLabel("Text Label"));

QTimer::singleShot(3000, [=]() { label->setText(lorem.left(100)); });

w->show();

</code>```

Body:
You have to constraint the height of your label to the minimum needed to draw the text. You can get this height by using the QFontMetrics class and the method QFontMetrics::boundingRect:

QFontMetrics const fontMetrics(font());
QRect const r = fontMetrics.boundingRect(
            QRect(QPoint(0, 0), size()),
            Qt::TextWordWrap | Qt::ElideRight,
            content
            );
qDebug() << "Needed Height:" << r.height();

First, define the method QWidget::sizeHint to force your label to have a size:

virtual QSize sizeHint() const override
{
    QFontMetrics const fontMetrics(font());
    QRect const r = fontMetrics.boundingRect(
            QRect(QPoint(0, 0), size()),
            Qt::TextWordWrap | Qt::ElideRight,
            content
            );
    return QSize(width(), r.height());
}

We want to shrink the height, only. That's why we will not use the width returned by the font metrics

Now, we will use the resize events to check if we can shrink the height:

So, we can override the QWidget::resizeEvent method:

virtual void resizeEvent(QResizeEvent* event) override
{
    QFrame::resizeEvent(event); // Process the event. The label is now resized
    QSize const size = sizeHint();
    if (size.height() < height()) // Shrink the height if needed
        resize(QSize(width(), size.height()));
}

If the text has to change during the runtime, we have to readjust the size:

void setText(const QString &newText)
{
   content = newText;
   update();
   adjustSize(); // Will resize the label
}

The code I used for the tests:

QWidget* w = new QWidget();
QVBoxLayout* l = new QVBoxLayout(w);

QString const lorem("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.");
ElidedLabel* label = new ElidedLabel(lorem);
label->setFrameShape(QFrame::Box); // To see its bounds

l->addWidget(label);
l->addWidget(new QLabel("Text Label"));

QTimer::singleShot(3000, [=]() { label->setText(lorem.left(100)); });

w->show();


问:
fatal: pathspec '.' did not match any files when trying git rm
I am just running following command on a folder which is part of git repo

The command I am running is: git rm -r --cached . However git is constantly throwing following error:

fatal: pathspec '.' did not match any files

I have no idea why is that. . definitely exists and is definitely part of a git repo. The error does not explain much in detail

答: Probably you have gotten yourself into a folder with no tracked files. Since git does not track folders, only files, there is no useful sense in which this folder "exists" for git.</p>