问:
counter: with click, the number should increase by one
I'm a beginner when it comes to Javascript. With click, the number should increase by one. I don't want to use tag IDs here, but as if made in class.

I am trying to give you a quick overview of the ClapsCounter here. The clap clicks are stored in the respective _ClapsCounter.txt file and the vote is stored in the browser localStorage as "applaudiert". Click on the counter to increase the value of all divs with the class "ClapsCounterCount".

 let clicks = document.querySelectorAll('.ClapsCounterTrigger');
 let count = Array.from(document.querySelectorAll('.ClapsCounterCount'));

 let TxtContainer = Array.from(document.querySelectorAll('.ClapsCounterTxtContainer'));
 let beforClick = "Applaudieren Sie diesen Artikel";
 let afterClick = "Danke für Ihren Applaus!";
 let alreadyClick = "Danke, Sie haben schon applaudiert!";

 let i;
 TxtContainer.forEach(i => i.innerHTML = beforClick);

// something wrong here!?
// take the current number from the .ClapsCounterCount
 let plus = count.forEach(i => i.innerHTML);

 for (let i = 0; i < clicks.length; i++) {

   clicks[i].onclick = function () {
    // after the click increase the current click number with 1
    count.forEach(i => i.innerHTML = ++plus);
    TxtContainer.forEach(i => i.innerHTML = afterClick);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <div class="ClapsCounter">
   <h4>View @media (min-width: 960px)</h4>
   <p><span class="ClapsCounterCount">123<!-- '.$count.' --></span> <span>Applause erhalten</span></p>
   <p class="ClapsCounterTxtContainer"></p>
   <button class="ClapsCounterTrigger">Count +1 Button</button>
 </div>

 <div class="ClapsCounter large">
   <h4>View @media (min-width: 1200px)</h4>
   <p><span class="ClapsCounterCount">123<!-- '.$count.' --></span> <span>Applause erhalten</span></p>
   <p class="ClapsCounterTxtContainer"></p>
   <button class="ClapsCounterTrigger">Count +1 Button</button>
 </div></code>```

Wrong with these lines !?

    // something wrong here!?
    // take the current number from the .ClapsCounterCount
     let plus = count.forEach(i => i.innerHTML);

    // after the click increase the current click number with 1
     count.forEach(i => i.innerHTML = ++plus);
```
<p><strong>expected output before click</strong></p>
<blockquote>
<p>123</p>
</blockquote>
<p><strong>expected output after click</strong></p>
<blockquote>
<p>124</p>
</blockquote>
<p><strong>Please see it in JSFiddle</strong></p>
<h1>Update & Solved:</h1>
<p>Thanks for your the answer from T.J. Crowder.</p>
<p>The line</p>
<pre class="lang-php prettyprint-override"><code>count.forEach (i => i.innerHTML = ++ plus);
</code>```

with this addition

count.forEach (element => element.innerHTML = parseInt (element.innerHTML, 10) + 1);
```

solved my problem.

答:
Yes, as you've said in a comment, the problem is here:

```<code>let plus = count.forEach(i => i.innerHTML);
</code>```

forEach doesn't return anything, so plus will always be undefined. ++undefined is NaN.

Instead of trying to store the number in advance, use it as it is when the click occurs. Also, I recommend parsing it intentionally rather than relying on implicit conversion from the string you get from innerHTML to a number:

```<code>count.forEach(element => element.innerHTML = parseInt(element.innerHTML, 10) + 1);
</code>```

Here's y our code with that change (I also removed plus entirely):

let clicks = document.querySelectorAll('.ClapsCounterTrigger');
 let count = Array.from(document.querySelectorAll('.ClapsCounterCount'));

 let TxtContainer = Array.from(document.querySelectorAll('.ClapsCounterTxtContainer'));
 let beforClick = "Applaudieren Sie diesen Artikel";
 let afterClick = "Danke für Ihren Applaus!";
 let alreadyClick = "Danke, Sie haben schon applaudiert!";

 let i;
 TxtContainer.forEach(i => i.innerHTML = beforClick);

 for (let i = 0; i < clicks.length; i++) {

   clicks[i].onclick = function () {
    // after the click increase the current click number with 1
    count.forEach(element => element.innerHTML = parseInt(element.innerHTML, 10) + 1);
    TxtContainer.forEach(i => i.innerHTML = afterClick);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="ClapsCounter">
   <h4>View @media (min-width: 960px)</h4>
   <p><span class="ClapsCounterCount">123<!-- '.$count.' --></span> <span>Applause erhalten</span></p>
   <p class="ClapsCounterTxtContainer"></p>
   <button class="ClapsCounterTrigger">Count +1 Button</button>
 </div>

 <div class="ClapsCounter large">
   <h4>View @media (min-width: 1200px)</h4>
   <p><span class="ClapsCounterCount">123<!-- '.$count.' --></span> <span>Applause erhalten</span></p>
   <p class="ClapsCounterTxtContainer"></p>
   <button class="ClapsCounterTrigger">Count +1 Button</button>
 </div></code>```

As you can see, it increments to 124 now.

FWIW, I've made a few other changes and marked them out with *** comments:

let clicks = document.querySelectorAll('.ClapsCounterTrigger');
let count = Array.from(document.querySelectorAll('.ClapsCounterCount'));

//*** Standard JavaScript naming is that you wouldn't use a capital letter at
// the beginning of `txtContainer`, so I've changed it throughout
let txtContainer = Array.from(document.querySelectorAll('.ClapsCounterTxtContainer'));
let beforClick = "Applaudieren Sie diesen Artikel";
let afterClick = "Danke für Ihren Applaus!";
let alreadyClick = "Danke, Sie haben schon applaudiert!";

// *** The `let i` that was here declared a variable that wasn't used; I
// removed it
txtContainer.forEach(i => i.innerHTML = beforClick);

// *** I suspect you want to increase the counter only in the counter div
//  where the button was, rather than increasing all of them. To do that,
// I've replaced your loop with the following:
clicks.forEach(btn => btn.addEventListener("click", function() {
    // *** Within this callback, `this` refers to the button that was
    // clicked. To use that feature, notice that this is a traditional
    // `function` function, not an arrow function. But the element is also
    // available as `currentTarget` on the event object this function
    // receives, so if you wanted to use an arrow function, you'd accept
    // a parameter and use the `currentTarget` property of it instead..
    // Starting from the button that was clicked, we can find the ancestor
    // .ClapsCounter element, and then only update the counter and text inside
    // it.
    const container = this.closest(".ClapsCounter");
    if (container) {
        const counter = container.querySelector(".ClapsCounterCount");
        if (counter) {
            counter.innerHTML = parseInt(counter.innerHTML) + 1;
            if (txt) {
                const txt = container.querySelector(".ClapsCounterTxtContainer");
                txt.innerHTML = afterClick;
            }
        }
    }
}));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="ClapsCounter">
   <h4>View @media (min-width: 960px)</h4>
   <p><span class="ClapsCounterCount">123<!-- '.$count.' --></span> <span>Applause erhalten</span></p>
   <p class="ClapsCounterTxtContainer"></p>
   <button class="ClapsCounterTrigger">Count +1 Button</button>
 </div>

 <div class="ClapsCounter large">
   <h4>View @media (min-width: 1200px)</h4>
   <p><span class="ClapsCounterCount">123<!-- '.$count.' --></span> <span>Applause erhalten</span></p>
   <p class="ClapsCounterTxtContainer"></p>
   <button class="ClapsCounterTrigger">Count +1 Button</button>
 </div></code>```

Body:
I'm a beginner when it comes to Javascript. With click, the number should increase by one. I don't want to use tag IDs here, but as if made in class.

I am trying to give you a quick overview of the ClapsCounter here. The clap clicks are stored in the respective _ClapsCounter.txt file and the vote is stored in the browser localStorage as "applaudiert". Click on the counter to increase the value of all divs with the class "ClapsCounterCount".

 let clicks = document.querySelectorAll('.ClapsCounterTrigger');
 let count = Array.from(document.querySelectorAll('.ClapsCounterCount'));

 let TxtContainer = Array.from(document.querySelectorAll('.ClapsCounterTxtContainer'));
 let beforClick = "Applaudieren Sie diesen Artikel";
 let afterClick = "Danke für Ihren Applaus!";
 let alreadyClick = "Danke, Sie haben schon applaudiert!";

 let i;
 TxtContainer.forEach(i => i.innerHTML = beforClick);

// something wrong here!?
// take the current number from the .ClapsCounterCount
 let plus = count.forEach(i => i.innerHTML);

 for (let i = 0; i < clicks.length; i++) {

   clicks[i].onclick = function () {
    // after the click increase the current click number with 1
    count.forEach(i => i.innerHTML = ++plus);
    TxtContainer.forEach(i => i.innerHTML = afterClick);
  }
}

View @media (min-width: 960px)

123 Applause erhalten

   <button class="ClapsCounterTrigger">Count +1 Button</button>

View @media (min-width: 1200px)

123 Applause erhalten

   <button class="ClapsCounterTrigger">Count +1 Button</button>

Wrong with these lines !?

    // something wrong here!?
    // take the current number from the .ClapsCounterCount
     let plus = count.forEach(i => i.innerHTML);

    // after the click increase the current click number with 1
     count.forEach(i => i.innerHTML = ++plus);

expected output before click

123

expected output after click

124

Please see it in JSFiddle

Update & Solved:

Thanks for your the answer from T.J. Crowder.

The line

count.forEach (i => i.innerHTML = ++ plus);

with this addition

count.forEach (element => element.innerHTML = parseInt (element.innerHTML, 10) + 1);

solved my problem.

Body:
Yes, as you've said in a comment, the problem is here:

let plus = count.forEach(i => i.innerHTML);

forEach doesn't return anything, so plus will always be undefined. ++undefined is NaN.

Instead of trying to store the number in advance, use it as it is when the click occurs. Also, I recommend parsing it intentionally rather than relying on implicit conversion from the string you get from innerHTML to a number:

count.forEach(element => element.innerHTML = parseInt(element.innerHTML, 10) + 1);

Here's y our code with that change (I also removed plus entirely):

let clicks = document.querySelectorAll('.ClapsCounterTrigger');
 let count = Array.from(document.querySelectorAll('.ClapsCounterCount'));

 let TxtContainer = Array.from(document.querySelectorAll('.ClapsCounterTxtContainer'));
 let beforClick = "<span class=\"muted italic\">Applaudieren Sie diesen Artikel</span>";
 let afterClick = "<span class=\"success italic\">Danke für Ihren Applaus!</span>";
 let alreadyClick = "<span class=\"warning italic\">Danke, Sie haben schon applaudiert!</span>";

 let i;
 TxtContainer.forEach(i => i.innerHTML = beforClick);

 for (let i = 0; i < clicks.length; i++) {

   clicks[i].onclick = function () {
    // after the click increase the current click number with 1
    count.forEach(element => element.innerHTML = parseInt(element.innerHTML, 10) + 1);
    TxtContainer.forEach(i => i.innerHTML = afterClick);
  }
}

<div class="ClapsCounter">
   <h4>View @media (min-width: 960px)</h4>
   <p><span class="ClapsCounterCount">123<!-- '.$count.' --></span> <span>Applause erhalten</span></p>
   <p class="ClapsCounterTxtContainer"></p>
   <button class="ClapsCounterTrigger">Count +1 Button</button>
 </div>

 <div class="ClapsCounter large">
   <h4>View @media (min-width: 1200px)</h4>
   <p><span class="ClapsCounterCount">123<!-- '.$count.' --></span> <span>Applause erhalten</span></p>
   <p class="ClapsCounterTxtContainer"></p>
   <button class="ClapsCounterTrigger">Count +1 Button</button>
 </div>

As you can see, it increments to 124 now.

FWIW, I've made a few other changes and marked them out with *** comments:

let clicks = document.querySelectorAll('.ClapsCounterTrigger');
let count = Array.from(document.querySelectorAll('.ClapsCounterCount'));

//*** Standard JavaScript naming is that you wouldn't use a capital letter at
// the beginning of `txtContainer`, so I've changed it throughout
let txtContainer = Array.from(document.querySelectorAll('.ClapsCounterTxtContainer'));
let beforClick = "<span class=\"muted italic\">Applaudieren Sie diesen Artikel</span>";
let afterClick = "<span class=\"success italic\">Danke für Ihren Applaus!</span>";
let alreadyClick = "<span class=\"warning italic\">Danke, Sie haben schon applaudiert!</span>";

// *** The `let i` that was here declared a variable that wasn't used; I
// removed it
txtContainer.forEach(i => i.innerHTML = beforClick);

// *** I suspect you want to increase the counter only in the counter div
//  where the button was, rather than increasing all of them. To do that,
// I've replaced your loop with the following:
clicks.forEach(btn => btn.addEventListener("click", function() {
    // *** Within this callback, `this` refers to the button that was
    // clicked. To use that feature, notice that this is a traditional
    // `function` function, not an arrow function. But the element is also
    // available as `currentTarget` on the event object this function
    // receives, so if you wanted to use an arrow function, you'd accept
    // a parameter and use the `currentTarget` property of it instead..
    // Starting from the button that was clicked, we can find the ancestor
    // .ClapsCounter element, and then only update the counter and text inside
    // it.
    const container = this.closest(".ClapsCounter");
    if (container) {
        const counter = container.querySelector(".ClapsCounterCount");
        if (counter) {
            counter.innerHTML = parseInt(counter.innerHTML) + 1;
            if (txt) {
                const txt = container.querySelector(".ClapsCounterTxtContainer");
                txt.innerHTML = afterClick;
            }
        }
    }
}));

<div class="ClapsCounter">
   <h4>View @media (min-width: 960px)</h4>
   <p><span class="ClapsCounterCount">123<!-- '.$count.' --></span> <span>Applause erhalten</span></p>
   <p class="ClapsCounterTxtContainer"></p>
   <button class="ClapsCounterTrigger">Count +1 Button</button>
 </div>

 <div class="ClapsCounter large">
   <h4>View @media (min-width: 1200px)</h4>
   <p><span class="ClapsCounterCount">123<!-- '.$count.' --></span> <span>Applause erhalten</span></p>
   <p class="ClapsCounterTxtContainer"></p>
   <button class="ClapsCounterTrigger">Count +1 Button</button>
 </div>


来源: stackexchange

问:
React state -> h2 tag won't display updated state, just initial one
I have a hook state that should be displayed in a h2 tag in JSX. The state is updated through a fetch order. The thing is, the result only displays the initial values of the state, not the updated ones. By using console.log, I verified the state is indeed varying. First, the state is initialized, being an array of objects with 'artist' properties. Artists peter and Andrew are already in the state:

```<code>const [itemList, setItemList] = useState([{artist:'peter'},{artist:'andrew'}]);
</code>```

I also have a button that, when clicked, orders the program to fetch an array of artists from musixmatch api through a onClick() function and update the state itemList:

```<code><button onClick={onClick}>Search</button>
</code>```

The function onClick() code:

```<code>const onClick = (e) => {
          fetch('https://api.musixmatch.com/ws/1.1/track.search?q_track=hello&apikey=53f4d72479049111a39ff26f9827d7e9')
        .then(response => response.json())
        .then(response => {
                response.message.body.track_list.map(item => {
                let copyItemList = itemList;
                copyItemList.push({ artist: item.track.artist_name });
                setItemList(copyItemList);
            })
        });
}
</code>```

The result should then be displayed in a h2 tag:

```<code><h2>Test:{itemList.map(item => <p>{item.artist}</p>)}</h2>
</code>```

As I said before, it shows only the initial artists, Peter and Andrew, but no new artists after I press the update state button. What is the problem here, why is the new state not being shown in the h2 tag ? I wrote another function that updates the state locally, no fetch order, and it worked as intended.

答:
If this is an array:

```<code>response.message.body.track_list
</code>```

Try

```<code>setItemList([...itemList,response.message.body.track_list])
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a hook state that should be displayed in a h2 tag in JSX. The state is updated through a fetch order. The thing is, the result only displays the initial values of the state, not the updated ones. By using console.log, I verified the state is indeed varying. First, the state is initialized, being an array of objects with 'artist' properties. Artists peter and Andrew are already in the state:

const [itemList, setItemList] = useState([{artist:'peter'},{artist:'andrew'}]);

I also have a button that, when clicked, orders the program to fetch an array of artists from musixmatch api through a onClick() function and update the state itemList:

<button onClick={onClick}>Search</button>

The function onClick() code:

const onClick = (e) => {
          fetch('https://api.musixmatch.com/ws/1.1/track.search?q_track=hello&apikey=53f4d72479049111a39ff26f9827d7e9')
        .then(response => response.json())
        .then(response => {
                response.message.body.track_list.map(item => {
                let copyItemList = itemList;
                copyItemList.push({ artist: item.track.artist_name });
                setItemList(copyItemList);
            })
        });
}

The result should then be displayed in a h2 tag:

Test:{itemList.map(item =>
{item.artist}
)}

As I said before, it shows only the initial artists, Peter and Andrew, but no new artists after I press the update state button. What is the problem here, why is the new state not being shown in the h2 tag ? I wrote another function that updates the state locally, no fetch order, and it worked as intended.

Body:
If this is an array:

response.message.body.track_list

Try

setItemList([...itemList,response.message.body.track_list])


问:
How to change jQuery code to Vanilla JavaScript
I am trying to push my JS knowledge, hence I am trying to convert JQuery code to JavaScript. This is jQuery code

```<code>      $('a[href*="#"]')// Select all links with hashes
              // Remove links that don't actually link to anything
              .not('[href="#"]')
              .not('[href="#0"]')
              .click(function(event) {
                // On-page links
                if (
                  location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '')
                  &&
                  location.hostname == this.hostname
                ) {
                  // Figure out element to scroll to
                  var target = $(this.hash);
                  target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
                  // Does a scroll target exist?
                  if (target.length) {
                    // Only prevent default if animation is actually going to happen
                    event.preventDefault();
                    $('html, body').animate({
                      scrollTop: target.offset().top
                    }, 850, function() {
                      // Callback after animation
                      // Must change focus!
                      var $target = $(target);
                      $target.focus();
                      if ($target.is(":focus")) { // Checking if the target was focused
                        return false;
                      } else {
                        $target.attr('tabindex','-1'); // Adding tabindex for elements not focusable
                        $target.focus(); // Set focus again
                      };
                    });
                  }
                }
              });
</code>```

And this is something that I have changed, but I'm not sure how to continue, I'm a beginner so I am facing some struggles.I try my level best to convert that JQuery code to "vanilla" JS but did some mistakes. Can you please tell me where I went wrong??

```<code>  document.querySelectorAll('a[href*="#"]')// Select all links with hashes
  // Remove links that don't actually link to anything
  .not('[href="#"]')
  .not('[href="#0"]')
  .addEventListener(function(event) {
    // On-page links
    if (
      location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '')
      &&
      location.hostname == this.hostname
    ) {
      // Figure out element to scroll to
      var target =document.querySelector(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
      // Does a scroll target exist?
      if (target.length) {
        // Only prevent default if animation is actually going to happen
        event.preventDefault();
        $('html, body').animate({
          scrollTop: target.offset().top
        }, 850, function() {
          // Callback after animation
          // Must change focus!
          var $target = $(target);
          $target.focus();
          if ($target.is(":focus")) { // Checking if the target was focused
            return false;
          } else {
            $target.attr('tabindex','-1'); // Adding tabindex for elements not focusable
            $target.focus(); // Set focus again
          };
        });
      }
    }
  });
</code>```

答:
you can try something like:

```<code>// Select all links with hashes excluding links that don't actually link to anything
const selector = 'a[href*="#"]:not([href="#"]):not([href="#0"])';
document.querySelectorAll(selector).forEach(el => {
  el.addEventListener('click', event => {
    // On-page links
    const cond1 = location.pathname.replace(/^\//, '') == el.pathname.replace(/^\//, '');
    const cond2 = location.pathname == el.pethname;
    if (cond1 && cond2) {
      // Figure out element to scroll to
      let target = document.querySelector(el.hash);
      target = target ? target : document.querySelector(`[name="${el.hash.slice(1)}"]`);
      // Does a scroll target exist?
      if (target) {
        // Only prevent default if animation is actually going to happen
        event.preventDefault();

        document.body.animate({
          scrollTop: target.offsetTop
        }, {
          duration: 850
        });

        setTimeout(() => {
          // Callback after animation. Must change focus!
          target.focus();
          if (document.activeElement === target) {
            return false;
          }
          else {
            // Adding tabindex for elements not focusable
            target.setAttribute('tabindex', '-1');
            // Set focus again
            target.focus();
          }
        }, 850);

      }
    }
  });
  console.log(el.pathname, el.animatee);
});
</code>```

I did not check the logic of your code and did not test my code, but I hope, it can give you a starting point...

now regarding

where I went wrong??

in your code:

querySelectorAll() returns NodeList, which does not have not() method, so you have to loop over its returned HTML elements with forEach() method. In your example you can achieve same result only by CSS selector: a[href*="#"]:not([href="#"]):not([href="#0"]) (using CSS pseudo class :not)

addEventListener()'s first argument should be a string representing event type, I added click in your case. This should be applied for each element in returned NodeList

HTML element target (document.querySelector(this.hash)) does not have length property, so you can just check that it is not false or null

I replaced jQuery's animate with HTML Element animate() (please note, that it is marked as experimental feature, so test it well), which does not have callback function, so I used there duration property and setTimeout() function with the same duration.

to set focus use HTML Element focus() method

to check if element has focus use activeElement property: document.activeElement === target

to set attribute on HTML Element use setAttribute() method

Hope this will help you to move on :)

Body:
I am trying to push my JS knowledge, hence I am trying to convert JQuery code to JavaScript. This is jQuery code

      $('a[href*="#"]')// Select all links with hashes
              // Remove links that don't actually link to anything
              .not('[href="#"]')
              .not('[href="#0"]')
              .click(function(event) {
                // On-page links
                if (
                  location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '')
                  &&
                  location.hostname == this.hostname
                ) {
                  // Figure out element to scroll to
                  var target = $(this.hash);
                  target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
                  // Does a scroll target exist?
                  if (target.length) {
                    // Only prevent default if animation is actually going to happen
                    event.preventDefault();
                    $('html, body').animate({
                      scrollTop: target.offset().top
                    }, 850, function() {
                      // Callback after animation
                      // Must change focus!
                      var $target = $(target);
                      $target.focus();
                      if ($target.is(":focus")) { // Checking if the target was focused
                        return false;
                      } else {
                        $target.attr('tabindex','-1'); // Adding tabindex for elements not focusable
                        $target.focus(); // Set focus again
                      };
                    });
                  }
                }
              });

And this is something that I have changed, but I'm not sure how to continue, I'm a beginner so I am facing some struggles.I try my level best to convert that JQuery code to "vanilla" JS but did some mistakes. Can you please tell me where I went wrong??

  document.querySelectorAll('a[href*="#"]')// Select all links with hashes
  // Remove links that don't actually link to anything
  .not('[href="#"]')
  .not('[href="#0"]')
  .addEventListener(function(event) {
    // On-page links
    if (
      location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '')
      &&
      location.hostname == this.hostname
    ) {
      // Figure out element to scroll to
      var target =document.querySelector(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
      // Does a scroll target exist?
      if (target.length) {
        // Only prevent default if animation is actually going to happen
        event.preventDefault();
        $('html, body').animate({
          scrollTop: target.offset().top
        }, 850, function() {
          // Callback after animation
          // Must change focus!
          var $target = $(target);
          $target.focus();
          if ($target.is(":focus")) { // Checking if the target was focused
            return false;
          } else {
            $target.attr('tabindex','-1'); // Adding tabindex for elements not focusable
            $target.focus(); // Set focus again
          };
        });
      }
    }
  });

Body:
you can try something like:

// Select all links with hashes excluding links that don't actually link to anything
const selector = 'a[href*="#"]:not([href="#"]):not([href="#0"])';
document.querySelectorAll(selector).forEach(el => {
  el.addEventListener('click', event => {
    // On-page links
    const cond1 = location.pathname.replace(/^\//, '') == el.pathname.replace(/^\//, '');
    const cond2 = location.pathname == el.pethname;
    if (cond1 && cond2) {
      // Figure out element to scroll to
      let target = document.querySelector(el.hash);
      target = target ? target : document.querySelector(`[name="${el.hash.slice(1)}"]`);
      // Does a scroll target exist?
      if (target) {
        // Only prevent default if animation is actually going to happen
        event.preventDefault();

        document.body.animate({
          scrollTop: target.offsetTop
        }, {
          duration: 850
        });

        setTimeout(() => {
          // Callback after animation. Must change focus!
          target.focus();
          if (document.activeElement === target) {
            return false;
          }
          else {
            // Adding tabindex for elements not focusable
            target.setAttribute('tabindex', '-1');
            // Set focus again
            target.focus();
          }
        }, 850);

      }
    }
  });
  console.log(el.pathname, el.animatee);
});

I did not check the logic of your code and did not test my code, but I hope, it can give you a starting point...

now regarding

where I went wrong??

in your code:

querySelectorAll() returns NodeList, which does not have not() method, so you have to loop over its returned HTML elements with forEach() method. In your example you can achieve same result only by CSS selector: a[href*="#"]:not([href="#"]):not([href="#0"]) (using CSS pseudo class :not)

addEventListener()'s first argument should be a string representing event type, I added click in your case. This should be applied for each element in returned NodeList

HTML element target (document.querySelector(this.hash)) does not have length property, so you can just check that it is not false or null

I replaced jQuery's animate with HTML Element animate() (please note, that it is marked as experimental feature, so test it well), which does not have callback function, so I used there duration property and setTimeout() function with the same duration.

to set focus use HTML Element focus() method

to check if element has focus use activeElement property: document.activeElement === target

to set attribute on HTML Element use setAttribute() method

Hope this will help you to move on :)


问:
How to insert BLOB and CLOB files in MySQL?
I want to store images and .docx/.doc, .pptx/.ppt, .pdf files using the front end of my software. I don't understand how to implement this and how to insert the BLOB and CLOB files into the table. Please help.

I am using Kubuntu 11.04, MySQL5, Qt 4.7.3.

答:
If you are using mysql workbench, just right click on the field (cell) and select 'load value from file' option and then browse to the file and click open and then click on apply. It will automatically generate query like this </p>

```<code>UPDATE `dbname`.`tablename` SET `columnname` = ? WHERE (`row` = '1');
</code>```

ContentLicense: CC BY-SA 3.0

Body:
If you are using mysql workbench, just right click on the field (cell) and select 'load value from file' option and then browse to the file and click open and then click on apply. It will automatically generate query like this

UPDATE `dbname`.`tablename` SET `columnname` = ? WHERE (`row` = '1');


问:
Unable to perform filter n sorting in ag-grid for agNumberColumnFilter

I am displaying an ag-grid in react app which has a column with
  decimal number. I am using this column to display the decimal number
  in both English(ex: 100.00) and Italian number format(ex:100,00). I am
  able to display in both formats but filter n sorting is not working
  for Italian format.

```<code> {
            headerName: fieldLabelEn.PRICE, field: "price", cellStyle: {},
            sortable: true, menuTabs: ["filterMenuTab"], maxWidth: 210,
            filter: 'agNumberColumnFilter', suppressSizeToFit: true,
                     valueGetter: params => {
                if (params.data.price!== '' ) {
                    if (numberDisplayFormat === "Italian/Norwegian/Spanish") {
                        return params.data.price;
                    } else {
                        return parseFloat(params.data.price.replace(/,/g, ''));
                    }
                }
            return null
            }
}
</code>```

答:
Since you are using a valueGetter to do formatting, the underlying data that is passed to the grid is modified.

To be exact, the grid gets a number when display format is English whereas it gets a string when format is Italian/Norwegian/Spanish. That is the reason filtering/sorting won't work properly.

To overcome this, I would recommend using valueFormatter which would only modify the display and not the underlying data.

From docs -  Value formatters allow you to format values for display.
  This is useful when data is one type (e.g. numeric) but needs to be
  converted for human reading (e.g. putting in currency symbols and
  number formatting).

Value Formatter example

If you want to continue using valueGetter, you would have to come up with custom comparator and filter functions to parse the strings

Body:
I am displaying an ag-grid in react app which has a column with
  decimal number. I am using this column to display the decimal number
  in both English(ex: 100.00) and Italian number format(ex:100,00). I am
  able to display in both formats but filter n sorting is not working
  for Italian format.

 {
            headerName: fieldLabelEn.PRICE, field: "price", cellStyle: {},
            sortable: true, menuTabs: ["filterMenuTab"], maxWidth: 210,
            filter: 'agNumberColumnFilter', suppressSizeToFit: true,
                     valueGetter: params => {
                if (params.data.price!== '' ) {
                    if (numberDisplayFormat === "Italian/Norwegian/Spanish") {
                        return params.data.price;
                    } else {
                        return parseFloat(params.data.price.replace(/,/g, ''));
                    }
                }
            return null
            }
}


问:
Deflate compress a string in mule
I wanted to know if there's any way to compress a string using deflate algorithm in Mule 4. I am aware of Kryo serialization framework in mule, but I am not sure of the  correct configuration and how to verify the compressed string.Any code snippet of the same will be greatly useful.

Thanks in advance.

答:
The Compression Module offers zip and gzip compression/decompression operations. Both formats use the deflate algorithm.

If you don't the gzip or zip formats and only want the deflate compression, then you probably need to implement it yourself in a Java class or create your own module, and call from there a Java implementation of Deflate, like https://docs.oracle.com/javase/8/docs/api/java/util/zip/Deflater.html.

Title: Deflate compress a string in mule


问:
Custom ag-grid cells in group
I would like the cells of my grouping in ag-grid to be left justified.
Right now this is what I get:

This is the definition of the colums or at least part of it:

```<code> this.columnDefs = [
  { field: 'lot', rowGroup: true, hide: true, },
  {
    headerName: 'Titre', field: 'name', sortable: true, width: 150,
  },
</code>```

I tried cellStyle and cellClass but nothing changes.
How could I fix that?

答:
I found the solution for this

```<code>::ng-deep .ag-theme-balham .ag-row-group .ag-cell{
justify-content: flex-start !important;
}
</code>```

Title: Custom ag-grid cells in group

Body:
I would like the cells of my grouping in ag-grid to be left justified.
Right now this is what I get:

This is the definition of the colums or at least part of it:

 this.columnDefs = [
  { field: 'lot', rowGroup: true, hide: true, },
  {
    headerName: 'Titre', field: 'name', sortable: true, width: 150,
  },

I tried cellStyle and cellClass but nothing changes.
How could I fix that?

Body:
I found the solution for this

::ng-deep .ag-theme-balham .ag-row-group .ag-cell{
justify-content: flex-start !important;
}


问:
Throw an error preventing a table update in a MySQL trigger
If I have a trigger before the update on a table, how can I throw an error that prevents the update on that table?</p>

答:
```<code>DELIMITER @@
DROP TRIGGER IF EXISTS trigger_name @@
CREATE TRIGGER trigger_name
BEFORE UPDATE ON table_name
FOR EACH ROW
BEGIN

  --the condition of error is:
  --if NEW update value of the attribute age = 1 and OLD value was 0
  --key word OLD and NEW let you distinguish between the old and new value of an attribute

   IF (NEW.state = 1 AND OLD.state = 0) THEN
       signal sqlstate '-20000' set message_text = 'hey it's an error!';
   END IF;

END @@
DELIMITER ;
</code>```

LastEditorDisplayName: Jim Anderson


问:
Blazor DI – How to access a service in a class that is not a Blazor component?
I have a background class that is not a Blazor component, and I want to use the built-in logger (ILogger) service.

I can’t use “[Inject]” on a property (because it’s not a component), and I can’t use the supported constructor injection because the constructor has other parameters (i.e. not just the single ILogger parameter). I have looked for something like “Application.GetService” (similar to what I've used other IOC implementations) that I could use in the constructor but can’t find anything.

Any ideas?

答:
It looks like you need to register the default values for your service.
You can do it in Startup.cs and in ConfigureServices something like services.AddTransient(<your service>).

If you want to be able to get a service at runtime, you can either inject an IServiceProvider with it's .GetService<>() method, or if you want to be able to call it without DI you can create a singleton that you register when your app starts up. The singleton will have a property for the service provider that you can then call from whatever service you would like (although I'd recommend against this - rather use DI)

It's also possible to combine the MS DI with other DI containers via an adapter. It seems that you already have a DI solution for your service, and this may be the best way forward if that's the case. In your CreateHostBuilder() setup method start with a .UseServiceProviderFactory() to use a different container. You'll need to find the correct adapter for your container though


问:
Show loading message in bootbox while ajax process is running?
I have page in my application that displays status. The status is displayed in drop down menu with two options Active/Inactive. The user can change the status by simply clicking on the menu and choosing the option. For that process I use JQuery/Ajax onchange trigger to track status change. The code is working fine and saves the value in datatbase. The issue I'm experiencing is related to bootbox and displaying loading message. When user clicks on the menu and changes the status ajax will send the request. At that point dialog window will show on the user screen with the loading message. Once ajax request is complete loading dialog should hide and display message tot he user that status successfully saved. Here is the code example:

function alertBox(title, message, size) {
  title = title || "Alert";
  message = message || "Alert Box";
  size = size || "lg";

  bootbox.alert({
    size: size,
    title: title,
    message: message
  });
};

$('.status').on('change', function() {
  let $curr_fld = $(this),
    status_id = $curr_fld.attr('data-id'),
    dialog = bootbox.dialog({
      message: '
 Loading...
',
      closeButton: false
    });

  $curr_fld.prop("disabled", true);
  /*** Start: This is a code for testing. ***/
  /*
  setTimeout(function() {
    dialog.modal('hide');
    $curr_fld.prop("disabled", false);
    alertBox('Alert Message', status_id);
  }, 3000);
  */
  /*** End: This is a code for testing. ***/

  $.ajax({
    type: 'POST',
    url: 'test.php?id=1',
    data: {
      'status_id': status_id
    },
    dataType: 'json'
  }).done(function(obj) {
    dialog.modal('hide');
    $curr_fld.prop("disabled", false);
    if (obj.status === 200) {
      alertBox('Alert Message', obj);
    } else {
      alertBox('Alert Message', obj);
    }
  }).fail(function(jqXHR, textStatus, errorThrown) {
    $curr_fld.prop("disabled", false);
    alertBox('Error', textStatus);
  });

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootbox.js/5.4.0/bootbox.min.js"></script>

<table class="table table-striped table-bordered" id="tbl_nofa">
  <thead>
    <tr class="bg-dark">
      <th class="text-center text-white">Section</th>
      <th class="text-center text-white">Status</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td class="text-center"> South</td>
      <td class="text-center">
        <select class="custom-select status" name="status_1" id="status_1" data-id="1">
          <option value="A" selected>Active</option>
          <option value="I">Inactive</option>
        </select>
      </td>
    </tr>
    <tr>
      <td class="text-center"> North</td>
      <td class="text-center">
        <select class="custom-select status" name="status_2" id="status_2" data-id="2">
          <option value="A">Active</option>
          <option value="I" selected>Inactive</option>
        </select>
      </td>
    </tr>
    <tr>
      <td class="text-center"> East</td>
      <td class="text-center">
        <select class="custom-select status" name="status_3" id="status_3" data-id="3">
          <option value="A" selected>Active</option>
          <option value="I">Inactive</option>
        </select>
      </td>
    </tr>
    <tr>
      <td class="text-center"> West</td>
      <td class="text-center">
        <select class="custom-select status" name="status_4" id="status_4" data-id="4">
          <option value="A">Active</option>
          <option value="I" selected>Inactive</option>
        </select>
      </td>
    </tr>
  </tbody>
  <tfoot>
    <tr class="bg-dark">
      <th class="text-center text-white">Section</th>
      <th class="text-center text-white">Status</th>
    </tr>
  </tfoot>
</table></code>```

If you run code example above, you will see once the ajax request is complete loading dialog is still on the screen. I'm not sure why since I have .modal('hide') in place. If you comment out the block of code with setTimeout and comment out the ajax code you will see that loading dialog works just fine. If anyone knows how to solve this issue please let me know.

答:
I noticed a couple of issues:

You'll want to close the dialog from the always function of your ajax call. When testing the fail would occur, but you had no code to close the dialog.  However this still didn't fix the problem.

This appears to be an issue with the boostrap modal.  What's happening is that the hide function is being called too soon before the animation completes.  There are two solutions to work around this issue:

Disable the animation by using animate: false.

Add code that detects if the animation is complete, and if it isn't, act appropriately in the always function.

```<code>$('.status').on('change', function() {
  let $curr_fld = $(this),
    loading_shown = false,
    status_id = $curr_fld.attr('data-id'),
    dialog = bootbox.dialog({
      // animate: false, // <-- simple way that makes the issue go away.
      message: '<p class="text-center mb-0"><i class="fa fa-spin fa-cog"></i> Loading...</p>',
      closeButton: false,
    }).on('shown.bs.modal', () => loading_shown = true);

  $curr_fld.prop("disabled", true);

  $.ajax({
    type: 'POST',
    url: 'test.php?id=1',
    data: {
      'status_id': status_id
    },
    dataType: 'json'
  }).done(function(obj) {
    $curr_fld.prop("disabled", false);
    if (obj.status === 200) {
      alertBox('Alert Message', obj);
    } else {
      alertBox('Alert Message', obj);
    }
  }).fail(function(jqXHR, textStatus, errorThrown) {
    $curr_fld.prop("disabled", false);
    alertBox('Error', textStatus);
  }).always(() => {
    // hide immediately, or wait until the animation is complete by listening
    // to shown.bs.modal.
    loading_shown
      ? dialog.modal('hide')
      : dialog.on('shown.bs.modal', () => dialog.modal('hide'));
  });
});

</code>```

There might be more succinct ways to handle the animation issue without disabling the animation itself.  This was just one method.

Body:
I have page in my application that displays status. The status is displayed in drop down menu with two options Active/Inactive. The user can change the status by simply clicking on the menu and choosing the option. For that process I use JQuery/Ajax onchange trigger to track status change. The code is working fine and saves the value in datatbase. The issue I'm experiencing is related to bootbox and displaying loading message. When user clicks on the menu and changes the status ajax will send the request. At that point dialog window will show on the user screen with the loading message. Once ajax request is complete loading dialog should hide and display message tot he user that status successfully saved. Here is the code example:

function alertBox(title, message, size) {
  title = title || "Alert";
  message = message || "Alert Box";
  size = size || "lg";

  bootbox.alert({
    size: size,
    title: title,
    message: message
  });
};

$('.status').on('change', function() {
  let $curr_fld = $(this),
    status_id = $curr_fld.attr('data-id'),
    dialog = bootbox.dialog({
      message: '
 Loading...
',
      closeButton: false
    });

  $curr_fld.prop("disabled", true);
  /*** Start: This is a code for testing. ***/
  /*
  setTimeout(function() {
    dialog.modal('hide');
    $curr_fld.prop("disabled", false);
    alertBox('Alert Message', status_id);
  }, 3000);
  */
  /*** End: This is a code for testing. ***/

  $.ajax({
    type: 'POST',
    url: 'test.php?id=1',
    data: {
      'status_id': status_id
    },
    dataType: 'json'
  }).done(function(obj) {
    dialog.modal('hide');
    $curr_fld.prop("disabled", false);
    if (obj.status === 200) {
      alertBox('Alert Message', obj);
    } else {
      alertBox('Alert Message', obj);
    }
  }).fail(function(jqXHR, textStatus, errorThrown) {
    $curr_fld.prop("disabled", false);
    alertBox('Error', textStatus);
  });

});

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">

      Section
      Status

       South

        <select class="custom-select status" name="status_1" id="status_1" data-id="1">
          <option value="A" selected>Active</option>
          <option value="I">Inactive</option>
        </select>

       North

        <select class="custom-select status" name="status_2" id="status_2" data-id="2">
          <option value="A">Active</option>
          <option value="I" selected>Inactive</option>
        </select>

       East

        <select class="custom-select status" name="status_3" id="status_3" data-id="3">
          <option value="A" selected>Active</option>
          <option value="I">Inactive</option>
        </select>

       West

        <select class="custom-select status" name="status_4" id="status_4" data-id="4">
          <option value="A">Active</option>
          <option value="I" selected>Inactive</option>
        </select>

      Section
      Status

If you run code example above, you will see once the ajax request is complete loading dialog is still on the screen. I'm not sure why since I have .modal('hide') in place. If you comment out the block of code with setTimeout and comment out the ajax code you will see that loading dialog works just fine. If anyone knows how to solve this issue please let me know.

Body:
I noticed a couple of issues:

You'll want to close the dialog from the always function of your ajax call. When testing the fail would occur, but you had no code to close the dialog.  However this still didn't fix the problem.

This appears to be an issue with the boostrap modal.  What's happening is that the hide function is being called too soon before the animation completes.  There are two solutions to work around this issue:

Disable the animation by using animate: false.

Add code that detects if the animation is complete, and if it isn't, act appropriately in the always function.

$('.status').on('change', function() {
  let $curr_fld = $(this),
    loading_shown = false,
    status_id = $curr_fld.attr('data-id'),
    dialog = bootbox.dialog({
      // animate: false, // <-- simple way that makes the issue go away.
      message: '<p class="text-center mb-0"><i class="fa fa-spin fa-cog"></i> Loading...</p>',
      closeButton: false,
    }).on('shown.bs.modal', () => loading_shown = true);

  $curr_fld.prop("disabled", true);

  $.ajax({
    type: 'POST',
    url: 'test.php?id=1',
    data: {
      'status_id': status_id
    },
    dataType: 'json'
  }).done(function(obj) {
    $curr_fld.prop("disabled", false);
    if (obj.status === 200) {
      alertBox('Alert Message', obj);
    } else {
      alertBox('Alert Message', obj);
    }
  }).fail(function(jqXHR, textStatus, errorThrown) {
    $curr_fld.prop("disabled", false);
    alertBox('Error', textStatus);
  }).always(() => {
    // hide immediately, or wait until the animation is complete by listening
    // to shown.bs.modal.
    loading_shown
      ? dialog.modal('hide')
      : dialog.on('shown.bs.modal', () => dialog.modal('hide'));
  });
});

There might be more succinct ways to handle the animation issue without disabling the animation itself.  This was just one method.


问:
Why is my Symfony 5 local server showing the HTTP request as text instead of a rendered page?
I just wanted to try out Symfony 5 for my own education, so I followed the instructions here.

symfony check:requirements shows that I have the requirements needed to run the application (I'm running Windows 10 with php 7.3.4 running via php-cgi.exe)

I created the project by running symfony new my_project_name then, as per the instructions, cd into the project directory and run symfony server:start

The command line output says

[OK] Web server listening

        The Web server is using PHP CGI 7.3.4

        https://127.0.0.1:8000

But when I open the local IP address at port 8000 in my browser, I see an HTTP request as raw text, not the expected welcome page or even a 404 page.

Can anyone advise as to why the standard Symfony 5 startup instructions would not be producing the expected output and whether there's something more I need to configure to get the expected output?

答:
You should create the application like this: symfony new my_project_name --full

Like the documentation page you linked says, symfony new my_project_name is for microservices, console applications and APIs. It does not have the packages required to be interpreted from plain text to a web page.


问:
How to change widget's size without pushing others
The "ok" button separates the two entry boxes from each other. I want them to stick together and the button making a square at the end of the two entries:

Here's the code

```<code>ventana = Tk()
ventana.geometry("500x300")

pathLabel = Label(ventana, text="Path of file: ").grid(row=0)
nameLabel = Label(text="Name of file").grid(row=1)

ePath = Entry()
eName = Entry()

ePath.grid(row=0, column=1)
eName.grid(row=1, column=1)

Ok = Button(text="okay", command=savepath)
Ok.grid(row=1, column=2, sticky=N)
Ok.configure(height=5)

ventana.mainloop()

</code>```

This is how it looks

I want it to look like this

Thanks.

答:
It sounds like what you want is for the button to be on row zero and extend to row one. So, that's exactly what you should tell grid.

If you want the button to exactly fit those two rows, I recommend not giving the button an explicit size. Instead, let grid make the button expand to fill the two rows by using the sticky option.

```<code>Ok.grid(row=0, column=2, rowspan=2, sticky="nsew")
</code>```

Body:
The "ok" button separates the two entry boxes from each other. I want them to stick together and the button making a square at the end of the two entries:

Here's the code

ventana = Tk()
ventana.geometry("500x300")

pathLabel = Label(ventana, text="Path of file: ").grid(row=0)
nameLabel = Label(text="Name of file").grid(row=1)

ePath = Entry()
eName = Entry()

ePath.grid(row=0, column=1)
eName.grid(row=1, column=1)

Ok = Button(text="okay", command=savepath)
Ok.grid(row=1, column=2, sticky=N)
Ok.configure(height=5)

ventana.mainloop()

This is how it looks

I want it to look like this

Thanks.

Body:
It sounds like what you want is for the button to be on row zero and extend to row one. So, that's exactly what you should tell grid.

If you want the button to exactly fit those two rows, I recommend not giving the button an explicit size. Instead, let grid make the button expand to fill the two rows by using the sticky option.

Ok.grid(row=0, column=2, rowspan=2, sticky="nsew")


问:
iPhone: Increase volume
I have got an audio file which is quite quiet.
I'm playing it using AVAudioPlayer, but I can barely hear anything, especially without headphones.

Is there a way to increase the volume of an audio record?

答:
Maybe, you can use SpeakHere Apple Sample, as I did. To increase audio volume on this sample you need to set Player to Speaker Mode.

Add this code in AQPlayer.mm:

```<code>OSStatus error;
UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
error = AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute, sizeof (audioRouteOverride), &audioRouteOverride);
if (error) printf("couldn't set audio speaker!");
</code>```

Before this code:

```<code>XThrowIfError (AudioQueueSetParameter(mQueue, kAudioQueueParam_Volume, 1.0), "set queue volume");
</code>```

Maybe it's to late but, I hope it helps.

Title: iPhone: Increase volume

Body:
Maybe, you can use SpeakHere Apple Sample, as I did. To increase audio volume on this sample you need to set Player to Speaker Mode.

Add this code in AQPlayer.mm:

OSStatus error;
UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
error = AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute, sizeof (audioRouteOverride), &audioRouteOverride);
if (error) printf("couldn't set audio speaker!");

Before this code:

XThrowIfError (AudioQueueSetParameter(mQueue, kAudioQueueParam_Volume, 1.0), "set queue volume");

Maybe it's to late but, I hope it helps.


问:
Split dataframe into many sub-dataframes based on timestamp
I have a large csv with the following format:

```<code>timestamp,name,age
2020-03-01 00:00:01,nick
2020-03-01 00:00:01,john
2020-03-01 00:00:02,nick
2020-03-01 00:00:02,john
2020-03-01 00:00:04,peter
2020-03-01 00:00:05,john
2020-03-01 00:00:10,nick
2020-03-01 00:00:12,john
2020-03-01 00:00:54,hank
2020-03-01 00:01:03,peter
</code>```

I load csv into a dataframe with:

```<code>df = pd.read_csv("/home/test.csv")
</code>```

and then I want to create multiple dataframes every 2 seconds. For example:

df1 contains:

```<code>2020-03-01 00:00:01,nick
2020-03-01 00:00:01,john
2020-03-01 00:00:02,nick
2020-03-01 00:00:02,john
</code>```

df2 contains :

```<code>2020-03-01 00:00:04,peter
2020-03-01 00:00:05,john
</code>```

and so on.

I achieve to split timestamps with command below:

```<code>full_idx = pd.date_range(start=df['timestamp'].min(), end = df['timestamp'].max(), freq ='0.2T')
</code>```

but how I can store these spitted dataframes? How can I split a dataset based on timestamps into multiple dataframes?

答:
Probably that question can help us: Pandas: Timestamp index rounding to the nearest 5th minute</p>

```<code>import numpy as np
import pandas as pd

df = pd.read_csv("test.csv")
df['timestamp'] = pd.to_datetime(df['timestamp'])

ns2sec=2*1000000000   # 2 seconds in nanoseconds
# next we round our timestamp to every 2nd second with rounding down
timestamp_rounded = df['timestamp'].astype(np.int64) // ns2sec
df['full_idx'] = pd.to_datetime(((timestamp_rounded - timestamp_rounded % 2) * ns2sec))

# store array for each unique value of your idx
store_array = []
for value in df['full_idx'].unique():
    store_array.append(df[df['full_idx']==value][['timestamp', 'name', 'age']])
</code>```

Body:
I have a large csv with the following format:

timestamp,name,age
2020-03-01 00:00:01,nick
2020-03-01 00:00:01,john
2020-03-01 00:00:02,nick
2020-03-01 00:00:02,john
2020-03-01 00:00:04,peter
2020-03-01 00:00:05,john
2020-03-01 00:00:10,nick
2020-03-01 00:00:12,john
2020-03-01 00:00:54,hank
2020-03-01 00:01:03,peter

I load csv into a dataframe with:

df = pd.read_csv("/home/test.csv")

and then I want to create multiple dataframes every 2 seconds. For example:

df1 contains:

2020-03-01 00:00:01,nick
2020-03-01 00:00:01,john
2020-03-01 00:00:02,nick
2020-03-01 00:00:02,john

df2 contains :

2020-03-01 00:00:04,peter
2020-03-01 00:00:05,john

and so on.

I achieve to split timestamps with command below:

full_idx = pd.date_range(start=df['timestamp'].min(), end = df['timestamp'].max(), freq ='0.2T')

but how I can store these spitted dataframes? How can I split a dataset based on timestamps into multiple dataframes?

Body:
Probably that question can help us: Pandas: Timestamp index rounding to the nearest 5th minute

import numpy as np
import pandas as pd

df = pd.read_csv("test.csv")
df['timestamp'] = pd.to_datetime(df['timestamp'])

ns2sec=2*1000000000   # 2 seconds in nanoseconds
# next we round our timestamp to every 2nd second with rounding down
timestamp_rounded = df['timestamp'].astype(np.int64) // ns2sec
df['full_idx'] = pd.to_datetime(((timestamp_rounded - timestamp_rounded % 2) * ns2sec))

# store array for each unique value of your idx
store_array = []
for value in df['full_idx'].unique():
    store_array.append(df[df['full_idx']==value][['timestamp', 'name', 'age']])


问:
Writing a normal python code into function called computepay()
How can I write the following program to prompt the user for hours and rate per hour using input to compute gross pay in a function called computepay() and use the function to do the computation. I want the function to return a value. In short, I want function to do it for me so that I can reduce the manual work from my side. Any help would be appreciated. Thanks.</p>

```<code>
sh = input("Enter hours:")
try:
    fh = float(sh)
except:
    print("Error, please enter numeric input")
    quit() # Commenting this line out will yield different result
sr = input("Enter Rate:")
try:
    fr = float(sr)
except:
    print("Error, please enter numeric input")
    quit() # Commenting this line out will yield different result

if fh > 40:
    reg = fr  * fh
    otp = (fh - 40.0) * (fr * 0.5)
    xp = reg + otp
else:
    xp = fh * fr
print("Pay:",xp)

</code>```

答:
Something like this will accept only numbers as input. Also, this demonstrates using a function for your calculations:

```<code>sh = 'none'

while(type(sh)!=float):
    sh=input("Enter hours:")
    try:
        sh=float(sh)
    except:
        pass

sr = 'none'
while(type(sr)!=float):
    sr=input("Enter Rate:")
    try:
        sr=float(sr)
    except:
        pass

def calculate_pay(hours, rate):
  if hours > 40:
    reg = rate  * hours
    otp = (hours - 40.0) * (rate * 0.5)
    xp = reg + otp
  else:
    xp = hours * rate
  return xp

print("Pay:",calculate_pay(sh, sr))
</code>```

Edit

Please search and look into how to create functions in Python. It is really quite simple. In your case, if you want everything in a function, then do this:

```<code>def get_paycheck():
  sh = 'none'

  while(type(sh)!=float):
      sh=input("Enter hours:")
      try:
          sh=float(sh)
      except:
          pass

  sr = 'none'
  while(type(sr)!=float):
      sr=input("Enter Rate:")
      try:
          sr=float(sr)
      except:
          pass

  if sh > 40:
    reg = sr  * sh
    otp = (sh - 40.0) * (sr * 0.5)
    xp = reg + otp
  else:
    xp = sh * sr
  return xp
</code>```

Now you can call the function from anywhere like so:

```<code>print("Pay:",get_paycheck())
</code>```

Body:
How can I write the following program to prompt the user for hours and rate per hour using input to compute gross pay in a function called computepay() and use the function to do the computation. I want the function to return a value. In short, I want function to do it for me so that I can reduce the manual work from my side. Any help would be appreciated. Thanks.

sh = input("Enter hours:")
try:
    fh = float(sh)
except:
    print("Error, please enter numeric input")
    quit() # Commenting this line out will yield different result
sr = input("Enter Rate:")
try:
    fr = float(sr)
except:
    print("Error, please enter numeric input")
    quit() # Commenting this line out will yield different result

if fh > 40:
    reg = fr  * fh
    otp = (fh - 40.0) * (fr * 0.5)
    xp = reg + otp
else:
    xp = fh * fr
print("Pay:",xp)

Body:
Something like this will accept only numbers as input. Also, this demonstrates using a function for your calculations:

sh = 'none'

while(type(sh)!=float):
    sh=input("Enter hours:")
    try:
        sh=float(sh)
    except:
        pass

sr = 'none'
while(type(sr)!=float):
    sr=input("Enter Rate:")
    try:
        sr=float(sr)
    except:
        pass

def calculate_pay(hours, rate):
  if hours > 40:
    reg = rate  * hours
    otp = (hours - 40.0) * (rate * 0.5)
    xp = reg + otp
  else:
    xp = hours * rate
  return xp

print("Pay:",calculate_pay(sh, sr))

Edit

Please search and look into how to create functions in Python. It is really quite simple. In your case, if you want everything in a function, then do this:

def get_paycheck():
  sh = 'none'

  while(type(sh)!=float):
      sh=input("Enter hours:")
      try:
          sh=float(sh)
      except:
          pass

  sr = 'none'
  while(type(sr)!=float):
      sr=input("Enter Rate:")
      try:
          sr=float(sr)
      except:
          pass

  if sh > 40:
    reg = sr  * sh
    otp = (sh - 40.0) * (sr * 0.5)
    xp = reg + otp
  else:
    xp = sh * sr
  return xp

Now you can call the function from anywhere like so:

print("Pay:",get_paycheck())


问:
Heroku producing 500 error when trying to send emails
I have a Rails application on Heroku that has started to produce 500 errors, I believe, when attempting to send emails – we use the SendGrid addon.

The error that I am seeing is this:

```<code>OpenSSL::SSL::SSLError: SSL_connect returned=1 errno=0 state=error: certificate verify failed (certificate has expired)
</code>```

Our certificates are managed by Heroku so I cannot see info about them in the Heroku control panel, but when I look at the certificate in Chrome it looks like they are valid until the end of July.

I have filed an issue with Heroku support, and am waiting for a response.

Update: Heroku said it was because their stack version 16 was an issue, and that I should upgrade to 18. I did that, but it did not help.

I have found that for some reason I am only apparently only getting this issue with Devise mailers.

I tested setting OpenSSL::SSL::VERIFY_PEER = OpenSSL::SSL::VERIFY_NONE and this solved the problem...

So now I’m not sure if Devise is doing something different than the other mailers, and if so why...

答:
Heroku thought it might be an issue related to the Heroku-16 stack. They advised upgrading to version 18 stack.

I tried updating to v18 stack but it did not solve our problem.

I later added a log entry to inspect the full stack trace and it started to look like it involved the premailer gem.

I noticed that we were including Bootstap from a CDN in our templates, and that premailer was possibly failing in attempting to get that CSS.

I ended up getting rid of both premailer and the Bootstrap CSS (which was really doing much for us anyway).

This solved the problem, but I never really understood the actual cause and it may have been a result of the Sectigo certificate expiring on May 30 2020 as Heroku suggested and mhale mentioned in an answer to this question.

Body:
I have a Rails application on Heroku that has started to produce 500 errors, I believe, when attempting to send emails – we use the SendGrid addon.

The error that I am seeing is this:

OpenSSL::SSL::SSLError: SSL_connect returned=1 errno=0 state=error: certificate verify failed (certificate has expired)

Our certificates are managed by Heroku so I cannot see info about them in the Heroku control panel, but when I look at the certificate in Chrome it looks like they are valid until the end of July.

I have filed an issue with Heroku support, and am waiting for a response.

Update: Heroku said it was because their stack version 16 was an issue, and that I should upgrade to 18. I did that, but it did not help.

I have found that for some reason I am only apparently only getting this issue with Devise mailers.

I tested setting OpenSSL::SSL::VERIFY_PEER = OpenSSL::SSL::VERIFY_NONE and this solved the problem...

So now I’m not sure if Devise is doing something different than the other mailers, and if so why...


问:
Could not start rails server on Ubuntu 20.04
I can't start my rails app after installing Ubuntu 20.04

There is traceback.

Also, I have the same errors:

...rbenv/versions/2.6.3/lib/ruby/2.6.0/x86_64-linux/etc.so: warning: already initialized constant Etc::...

then I've checked my rails version.

After reinstall my OS via erase, I have restored my backup of /home from Ubuntu 18.04
and checked my version of ruby rails and nodejs. Ruby and rails were the same, but I have to install nodejs and some postgres packages. Now, after that I've tried to run rails s in my project folder and there errors from traceback were appeared. Also, the command

yarn install --check-files

can't finish successfully, cause

info There appears to be trouble with your network connection. Retrying... error.

What should I do to start my app successfully?

My gemfile:

```<code>source 'https://rubygems.org'
git_source(:github) { |repo| "https://github.com/#{repo}.git" }

ruby '2.6.3'

gem "rails_12factor"
# gem "hashid-rails", "~> 1.0"
gem 'dotenv-rails', groups: [:development, :test]
# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '~> 6.0.2', '>= 6.0.2.2'
# Use postgresql as the database for Active Record
gem 'pg', '>= 0.18', '< 2.0'
# Use Puma as the app server
gem 'puma', '~> 4.1'
# Use SCSS for stylesheets
# gem 'sass-rails', '>= 6'
# Transpile app-like JavaScript. Read more: https://github.com/rails/webpacker
gem 'webpacker', '~> 4.0'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.7'
# Use Redis adapter to run Action Cable in production
gem 'redis', '~> 4.0'
# Use Active Model has_secure_password
# gem 'bcrypt', '~> 3.1.7'
gem 'pry'

# Use Active Storage variant
# gem 'image_processing', '~> 1.2'

# Reduces boot times through caching; required in config/boot.rb
gem 'bootsnap', '>= 1.4.2', require: false

group :development, :test do
  # Call 'byebug' anywhere in the code to stop execution and get a debugger console
  gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
  gem 'rspec-rails'
  gem 'database_cleaner'
  gem 'selenium-webdriver'
end

group :development do
  # Access an interactive console on exception pages or by calling 'console' anywhere in the code.
  gem 'web-console', '>= 3.3.0'
  gem 'listen', '>= 3.0.5', '< 3.2'
end

gem 'minitest-rails'

group :test do
  gem 'minitest-rails-capybara'
  gem 'capybara', '>= 2.15'
end

# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]

gem "active_model_serializers"
</code>```

Ruby: ruby 2.6.3p62 (2019-04-16 revision 67580) [x86_64-linux]

Rails: Rails 6.0.2.2

Nodejs: v10.19.0

答:
Okey, after post of @Bodh1004 I have an idea to do the same action with ffi gem, and this is works! Thanks for the idea!
Anyway, i have the same already initialized constant errors:

```<code>/home/procy/.rbenv/versions/2.6.3/lib/ruby/2.6.0/forwardable.rb:116: warning: already initialized constant Forwardable::VERSION
/home/procy/.rbenv/versions/2.6.3/lib/ruby/gems/2.6.0/gems/forwardable-1.3.1/lib/forwardable/version.rb:3: warning: previous definition of VERSION was here
/home/procy/.rbenv/versions/2.6.3/lib/ruby/2.6.0/forwardable.rb:117: warning: already initialized constant Forwardable::FORWARDABLE_VERSION
/home/procy/.rbenv/versions/2.6.3/lib/ruby/gems/2.6.0/gems/forwardable-1.3.1/lib/forwardable/version.rb:4: warning: previous definition of FORWARDABLE_VERSION was here
</code>```

I'll try to solve them.

Body:
I can't start my rails app after installing Ubuntu 20.04

There is traceback.

Also, I have the same errors:

...rbenv/versions/2.6.3/lib/ruby/2.6.0/x86_64-linux/etc.so: warning: already initialized constant Etc::...

then I've checked my rails version.

After reinstall my OS via erase, I have restored my backup of /home from Ubuntu 18.04
and checked my version of ruby rails and nodejs. Ruby and rails were the same, but I have to install nodejs and some postgres packages. Now, after that I've tried to run rails s in my project folder and there errors from traceback were appeared. Also, the command

yarn install --check-files

can't finish successfully, cause

info There appears to be trouble with your network connection. Retrying... error.

What should I do to start my app successfully?

My gemfile:

source 'https://rubygems.org'
git_source(:github) { |repo| "https://github.com/#{repo}.git" }

ruby '2.6.3'

gem "rails_12factor"
# gem "hashid-rails", "~> 1.0"
gem 'dotenv-rails', groups: [:development, :test]
# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '~> 6.0.2', '>= 6.0.2.2'
# Use postgresql as the database for Active Record
gem 'pg', '>= 0.18', '< 2.0'
# Use Puma as the app server
gem 'puma', '~> 4.1'
# Use SCSS for stylesheets
# gem 'sass-rails', '>= 6'
# Transpile app-like JavaScript. Read more: https://github.com/rails/webpacker
gem 'webpacker', '~> 4.0'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.7'
# Use Redis adapter to run Action Cable in production
gem 'redis', '~> 4.0'
# Use Active Model has_secure_password
# gem 'bcrypt', '~> 3.1.7'
gem 'pry'

# Use Active Storage variant
# gem 'image_processing', '~> 1.2'

# Reduces boot times through caching; required in config/boot.rb
gem 'bootsnap', '>= 1.4.2', require: false

group :development, :test do
  # Call 'byebug' anywhere in the code to stop execution and get a debugger console
  gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
  gem 'rspec-rails'
  gem 'database_cleaner'
  gem 'selenium-webdriver'
end

group :development do
  # Access an interactive console on exception pages or by calling 'console' anywhere in the code.
  gem 'web-console', '>= 3.3.0'
  gem 'listen', '>= 3.0.5', '< 3.2'
end

gem 'minitest-rails'

group :test do
  gem 'minitest-rails-capybara'
  gem 'capybara', '>= 2.15'
end

# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]

gem "active_model_serializers"

Ruby: ruby 2.6.3p62 (2019-04-16 revision 67580) [x86_64-linux]

Rails: Rails 6.0.2.2

Nodejs: v10.19.0

Body:
Okey, after post of @Bodh1004 I have an idea to do the same action with ffi gem, and this is works! Thanks for the idea!
Anyway, i have the same already initialized constant errors:

/home/procy/.rbenv/versions/2.6.3/lib/ruby/2.6.0/forwardable.rb:116: warning: already initialized constant Forwardable::VERSION
/home/procy/.rbenv/versions/2.6.3/lib/ruby/gems/2.6.0/gems/forwardable-1.3.1/lib/forwardable/version.rb:3: warning: previous definition of VERSION was here
/home/procy/.rbenv/versions/2.6.3/lib/ruby/2.6.0/forwardable.rb:117: warning: already initialized constant Forwardable::FORWARDABLE_VERSION
/home/procy/.rbenv/versions/2.6.3/lib/ruby/gems/2.6.0/gems/forwardable-1.3.1/lib/forwardable/version.rb:4: warning: previous definition of FORWARDABLE_VERSION was here

I'll try to solve them.


问:
Powershell add type in class in PSM1
In a PS1, this works

```<code>class pxInitFailureMessage {
    static [void] Send ([int32]$processID, [String]$title, [string]$message) {
        Add-Type -AssemblyName:System.Windows.Forms
        Add-Type -AssemblyName:System.Drawing
        $balloonTip = New-Object System.Windows.Forms.NotifyIcon
        $balloonTip.icon = [system.drawing.icon]::ExtractAssociatedIcon($(Get-Process -id:$processID | Select-Object -expandProperty:Path))
        $balloonTip.balloonTipIcon = 'Error'
        $balloonTip.balloonTipTitle = $title
        $balloonTip.balloonTipText = $message
        $balloonTip.visible = $true
        $balloonTip.ShowBalloonTip(0)
        $balloonTip.Dispose
    }
}
[pxInitFailureMessage]::Send($pid, 'Title', 'Message is just some extra text')
</code>```

But, move that class to a library.PSM1 file, and this in the PS1

```<code>Using module '\\Mac\iCloud Drive\Px Tools 4.#\Dev 4.0\#Spikes\Windows7\library.psm1'
[pxInitFailureMessage]::Send($pid, 'Title', 'Message is just some extra text')
</code>```

And it works in the ISE, but not in the console when run from a shortcut. I get Unable to find type [system.drawing.icon].

Obviously the first Add-Type works, I get no error at New-Object. So why is the second type load failing? I also tried moving the two Add-Type lines out of the class, and into the root of the module file, with the same results. What DOES work is adding those lines to the PS1, between using module (which has to be the first non remarked line) and the call. That works, but then you don't have a self contained class, which seems to suck a bit. What am I misunderstanding here?

How does one make a self contained class that uses .NET types and work with it from  a module file?

答:
For anyone interested, the solution I came up with is as follows. In library.PSM1 I have...

```<code>class pxInitFailureMessage {
    static [void] Send ([int32]$processID, [String]$title, [string]$message, [System.Drawing.Icon]$icon) {
        Add-Type -AssemblyName:System.Windows.Forms
        $balloonTip = New-Object System.Windows.Forms.NotifyIcon
        $balloonTip.icon = $icon
        $balloonTip.balloonTipIcon = 'Error'
        $balloonTip.balloonTipTitle = $title
        $balloonTip.balloonTipText = $message
        $balloonTip.visible = $true
        $balloonTip.ShowBalloonTip(0)
        $balloonTip.Dispose
    }
}
</code>```

And in my scrip I have...

```<code>using assembly System.Drawing
Using module '.\library.psm1'

$processIcon = [system.drawing.icon]::ExtractAssociatedIcon($(Get-Process -id:$pID | Select-Object -expandProperty:Path))

[pxInitFailureMessage]::Send($pid, 'Title', 'Message is just some extra text', $processIcon)
</code>```

The key is that the class IS now self contained, and follows good practice of providing the class with everything it needs, so it doesn't have to go looking outside itself. I could just as easily use my own ICO file for the icon, like so...

```<code>$processIcon = [system.drawing.icon]::New('\\Mac\iCloud Drive\Px Tools 4.#\Dev 4.0\Px_Resources\PxIcon.ico')
</code>```

Again with a literal path in this example.

So, I learned a thing today. Woot.

Title: Powershell add type in class in PSM1

Body:
In a PS1, this works

class pxInitFailureMessage {
    static [void] Send ([int32]$processID, [String]$title, [string]$message) {
        Add-Type -AssemblyName:System.Windows.Forms
        Add-Type -AssemblyName:System.Drawing
        $balloonTip = New-Object System.Windows.Forms.NotifyIcon
        $balloonTip.icon = [system.drawing.icon]::ExtractAssociatedIcon($(Get-Process -id:$processID | Select-Object -expandProperty:Path))
        $balloonTip.balloonTipIcon = 'Error'
        $balloonTip.balloonTipTitle = $title
        $balloonTip.balloonTipText = $message
        $balloonTip.visible = $true
        $balloonTip.ShowBalloonTip(0)
        $balloonTip.Dispose
    }
}
[pxInitFailureMessage]::Send($pid, 'Title', 'Message is just some extra text')

But, move that class to a library.PSM1 file, and this in the PS1

Using module '\\Mac\iCloud Drive\Px Tools 4.#\Dev 4.0\#Spikes\Windows7\library.psm1'
[pxInitFailureMessage]::Send($pid, 'Title', 'Message is just some extra text')

And it works in the ISE, but not in the console when run from a shortcut. I get Unable to find type [system.drawing.icon].

Obviously the first Add-Type works, I get no error at New-Object. So why is the second type load failing? I also tried moving the two Add-Type lines out of the class, and into the root of the module file, with the same results. What DOES work is adding those lines to the PS1, between using module (which has to be the first non remarked line) and the call. That works, but then you don't have a self contained class, which seems to suck a bit. What am I misunderstanding here?

How does one make a self contained class that uses .NET types and work with it from  a module file?

Body:
For anyone interested, the solution I came up with is as follows. In library.PSM1 I have...

class pxInitFailureMessage {
    static [void] Send ([int32]$processID, [String]$title, [string]$message, [System.Drawing.Icon]$icon) {
        Add-Type -AssemblyName:System.Windows.Forms
        $balloonTip = New-Object System.Windows.Forms.NotifyIcon
        $balloonTip.icon = $icon
        $balloonTip.balloonTipIcon = 'Error'
        $balloonTip.balloonTipTitle = $title
        $balloonTip.balloonTipText = $message
        $balloonTip.visible = $true
        $balloonTip.ShowBalloonTip(0)
        $balloonTip.Dispose
    }
}

And in my scrip I have...

using assembly System.Drawing
Using module '.\library.psm1'

$processIcon = [system.drawing.icon]::ExtractAssociatedIcon($(Get-Process -id:$pID | Select-Object -expandProperty:Path))

[pxInitFailureMessage]::Send($pid, 'Title', 'Message is just some extra text', $processIcon)

The key is that the class IS now self contained, and follows good practice of providing the class with everything it needs, so it doesn't have to go looking outside itself. I could just as easily use my own ICO file for the icon, like so...

$processIcon = [system.drawing.icon]::New('\\Mac\iCloud Drive\Px Tools 4.#\Dev 4.0\Px_Resources\PxIcon.ico')

Again with a literal path in this example.

So, I learned a thing today. Woot.


问:
Implementing a cache
I'm trying to implement a transparent cache that can load a specific object when it's not available, or return an already existing object indexed by (name).

I've tried running this:

```<code>loader' objs name = case findObj objs name of
  Nothing →  (new_obj, loader' new_objs)
  Just obj →  (obj, loader' objs)
  where
    new_objs = [(name, new_obj)] ++ objs
    new_obj = readObj name
loader = loader' []
</code>```

but I'm getting a

```
Occurs check: cannot construct the infinite type:
  t = (ObjType, String -> t)
```

which looks exactly like something I want :)

How can I fix the function so that it compiles?

Clarifications:

As requested, signatures (findObj either returns a known value found via a key, or Nothing, readObj creates a new obj for a key):

```<code>findObj :: [(String, ObjType)] -> String -> Maybe ObjType
readObj :: String -> ObjType
</code>```

And yes - I need a cache, because the keys are filenames and I don't want to read+parse the file each time some object is needed.

答:
Two thoughts (wild guesses?) it looks as if it is failing to produce the right type signature in the Just obj clause and/or from readObj name, and it might be interesting to try something like this:

```<code>loader' :: [(String, ObjType)] -> String -> (ObjType, String -> ObjType)
loader' objs name = case findObj objs name of
  Nothing →  (new_obj, loader' new_objs) where
    new_objs = [(name, new_obj)] ++ objs
    new_obj = readObj name
  Just obj →  (obj, loader' objs)
loader = loader' []
</code>```

I'm not saying that that will fix it (but I suppose that it might); rather, I'm saying that it may transform the problem into one that makes more sense, or otherwise shed light on the situation.

Edit:

Applying Tom Lokhorst's suggestion of naming the cache type leads us to this:

```<code>type Cache = [(String, ObjType)]
loader' :: Cache -> String -> (ObjType, ????)
loader' objs name = case findObj objs name of
  Nothing →  (new_obj, loader' new_objs) where
    new_objs = [(name, new_obj)] ++ objs
    new_obj = readObj name
  Just obj →  (obj, loader' objs)
loader = loader' []
</code>```

which makes it obvious what the problem is.  The type of the second result of loader' is a function that takes a string an produces a pair consisting of an ObjType and a function that takes a string an produces a pair consisting of an ObjType and a function that takes a string an produces a pair consisting of an ObjType and a function that takes a string an produces a pair consisting of an ObjType and ... you get the picture.

If you rewrite it like this:

```<code>type Cache = [(String, ObjType)]
loader' :: Cache -> String -> (ObjType, Cache)
loader' objs name = case findObj objs name of
  Nothing →  (new_obj, new_objs) where
    new_objs = [(name, new_obj)] ++ objs
    new_obj = readObj name
  Just obj →  (obj, objs)
</code>```

it should compile but you'll have to change how you use it.

OwnerDisplayName: viraptor

ContentLicense: CC BY-SA 2.5

Title: Implementing a cache

Body:
I'm trying to implement a transparent cache that can load a specific object when it's not available, or return an already existing object indexed by (name).

I've tried running this:

loader' objs name = case findObj objs name of
  Nothing →  (new_obj, loader' new_objs)
  Just obj →  (obj, loader' objs)
  where
    new_objs = [(name, new_obj)] ++ objs
    new_obj = readObj name
loader = loader' []

but I'm getting a

Occurs check: cannot construct the infinite type:
  t = (ObjType, String -> t)

which looks exactly like something I want :)

How can I fix the function so that it compiles?

Clarifications:

As requested, signatures (findObj either returns a known value found via a key, or Nothing, readObj creates a new obj for a key):

findObj :: [(String, ObjType)] -> String -> Maybe ObjType
readObj :: String -> ObjType

And yes - I need a cache, because the keys are filenames and I don't want to read+parse the file each time some object is needed.

LastEditorDisplayName: David Segonds

Body:
Two thoughts (wild guesses?) it looks as if it is failing to produce the right type signature in the Just obj clause and/or from readObj name, and it might be interesting to try something like this:

loader' :: [(String, ObjType)] -> String -> (ObjType, String -> ObjType)
loader' objs name = case findObj objs name of
  Nothing →  (new_obj, loader' new_objs) where
    new_objs = [(name, new_obj)] ++ objs
    new_obj = readObj name
  Just obj →  (obj, loader' objs)
loader = loader' []

I'm not saying that that will fix it (but I suppose that it might); rather, I'm saying that it may transform the problem into one that makes more sense, or otherwise shed light on the situation.

Edit:

Applying Tom Lokhorst's suggestion of naming the cache type leads us to this:

type Cache = [(String, ObjType)]
loader' :: Cache -> String -> (ObjType, ????)
loader' objs name = case findObj objs name of
  Nothing →  (new_obj, loader' new_objs) where
    new_objs = [(name, new_obj)] ++ objs
    new_obj = readObj name
  Just obj →  (obj, loader' objs)
loader = loader' []

which makes it obvious what the problem is.  The type of the second result of loader' is a function that takes a string an produces a pair consisting of an ObjType and a function that takes a string an produces a pair consisting of an ObjType and a function that takes a string an produces a pair consisting of an ObjType and a function that takes a string an produces a pair consisting of an ObjType and ... you get the picture.

If you rewrite it like this:

type Cache = [(String, ObjType)]
loader' :: Cache -> String -> (ObjType, Cache)
loader' objs name = case findObj objs name of
  Nothing →  (new_obj, new_objs) where
    new_objs = [(name, new_obj)] ++ objs
    new_obj = readObj name
  Just obj →  (obj, objs)

it should compile but you'll have to change how you use it.

OwnerDisplayName: MarkusQ

LastEditorDisplayName: MarkusQ


问:
how to do Monitor fit application in winform?
In my winform application want to cover full computer monitor. But, windows 7 task bar visible.

how to code Monitor fit application in winform?

thanks in advance!.

答:
its already answered here

How do I make a WinForms app go Full Screen


问:
Sum up amount in parquets using Java API
I am new to Spark in java. I have multiple parquets in HDFS whose paths are stored in a String[] paths and the parquets are in this format:

```<code>Amount |  User
10     |  User1
</code>```

Now I want to calculate the sum of amounts in all parquets, how should I do this?

Is it enough to do:

```<code>sparkSession.read().parquet(paths)
</code>```

or do I need to first do a union or join?

答:
sparkSession.read().parquet(paths) should load all your parquet data in a single go

You can use below code to get the sum of Amount column

```<code>val sumDf = df.agg(functions.sum("Amount"))
    val sum = sumDf.collectAsList().get(0).getDouble(0)
    println(sum)
</code>```

Note: Amount should be of type Double for above code to work

Body:
I am new to Spark in java. I have multiple parquets in HDFS whose paths are stored in a String[] paths and the parquets are in this format:

Amount |  User
10     |  User1

Now I want to calculate the sum of amounts in all parquets, how should I do this?

Is it enough to do:

sparkSession.read().parquet(paths)

or do I need to first do a union or join?

Body:
sparkSession.read().parquet(paths) should load all your parquet data in a single go

You can use below code to get the sum of Amount column

val sumDf = df.agg(functions.sum("Amount"))
    val sum = sumDf.collectAsList().get(0).getDouble(0)
    println(sum)

Note: Amount should be of type Double for above code to work


问:
Pandas count occurence of value in dictionary
Given a DF:

```<code>pd.DataFrame({"A":[1,2,3],
              "B": [{"Mon":"Closed", "Tue":"Open", "Wed":"Closed"},
                    {"Mon":"Open", "Tue":"Open", "Wed":"Closed"},
                    {"Mon":"Open", "Tue":"Open", "Wed":"Open"}]
              })
</code>```

How do i get a count of number of times "Closed" appears in the dict?

```<code>A  B    count
1 {..}  2
2 {..}  1
3 {..}  0
</code>```

I really don't know how to start on this to try

答:
I will do </p>

```<code>df.B.astype(str).str.count('Closed')
Out[30]:
0    2
1    1
2    0
Name: B, dtype: int64
</code>```

<p>Or </p>

```<code>df['Cnt']=pd.DataFrame(df.B.tolist()).eq('Closed').sum(1).values
Out[35]:
0    2
1    1
2    0
dtype: int64
</code>```

Body:
Given a DF:

pd.DataFrame({"A":[1,2,3],
              "B": [{"Mon":"Closed", "Tue":"Open", "Wed":"Closed"},
                    {"Mon":"Open", "Tue":"Open", "Wed":"Closed"},
                    {"Mon":"Open", "Tue":"Open", "Wed":"Open"}]
              })

How do i get a count of number of times "Closed" appears in the dict?

A  B    count
1 {..}  2
2 {..}  1
3 {..}  0

I really don't know how to start on this to try

Body:
I will do

df.B.astype(str).str.count('Closed')
Out[30]:
0    2
1    1
2    0
Name: B, dtype: int64

Or

df['Cnt']=pd.DataFrame(df.B.tolist()).eq('Closed').sum(1).values
Out[35]:
0    2
1    1
2    0
dtype: int64


问:
sscanf Wildcard multi string %s not return first string rightly?
I am using sscanf to read string. The string is split by space. sscanf does not return first string.
The code like this:

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

int main(int argc, char** argv) {
    char TransactionID[15], CardID[8];
    char Datetime[50];
    int Amount;
    char * s="aaaabbbbcccc defadbed 2020:04:29:23:07:00 1234";
    sscanf(s,"%s %s %s %d", TransactionID, CardID, Datetime, &Amount);
    printf("s[0] = %c\n", s[0]);
    printf("amount = %d\n", Amount);
    printf("TransactionID = %s\n", TransactionID);
    printf("CardID = %s\n", CardID);
    printf("Datetime = %s\n", Datetime);
    return 0;
}
</code>```

The output is:

```<code>s[0] = a
amount = 1234
TransactionID =
CardID = defadbed
Datetime = 2020:04:29:23:07:00
</code>```

The TransactionID not return right result. But the other all are right.

答:
You have a buffer overflow in your code: CardID is only 8 bytes long. While the card ID in the input string is 8 characters, there is another byte necessary for the terminating NUL byte at the end. Changing the declaration of CardID to:

```<code>char TransactionID[15], CardID[9];
</code>```

Should fix parsing this particular input string.

However, if the input has errors, or someone maliciously gives you input with longer card IDs than your code expects, you will still run into problems. You should therefore ensure that you can never have a buffer overflow.

One way is to tell scanf() how big each buffer is, like so:

```<code>sscanf(s,"%14s %7s %49s %d", TransactionID, CardID, Datetime, &Amount);
</code>```

Note that you again have to specify one less than the size of the buffer. So if you want to handle card IDs of 8 characters, you still need to set the buffer size to 9 bytes. However, while this prevents buffer overflows, if the input strings are larger than the buffers, the rest is silently truncated, or possibly the next %s conversion will pick up the remaining characters.

If you know the input is separated by spaces, then an alternative way is to use strtok() to split the input into the individual parts.

Body:
I am using sscanf to read string. The string is split by space. sscanf does not return first string.
The code like this:

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

int main(int argc, char** argv) {
    char TransactionID[15], CardID[8];
    char Datetime[50];
    int Amount;
    char * s="aaaabbbbcccc defadbed 2020:04:29:23:07:00 1234";
    sscanf(s,"%s %s %s %d", TransactionID, CardID, Datetime, &Amount);
    printf("s[0] = %c\n", s[0]);
    printf("amount = %d\n", Amount);
    printf("TransactionID = %s\n", TransactionID);
    printf("CardID = %s\n", CardID);
    printf("Datetime = %s\n", Datetime);
    return 0;
}

The output is:

s[0] = a
amount = 1234
TransactionID =
CardID = defadbed
Datetime = 2020:04:29:23:07:00

The TransactionID not return right result. But the other all are right.

Body:
You have a buffer overflow in your code: CardID is only 8 bytes long. While the card ID in the input string is 8 characters, there is another byte necessary for the terminating NUL byte at the end. Changing the declaration of CardID to:

char TransactionID[15], CardID[9];

Should fix parsing this particular input string.

However, if the input has errors, or someone maliciously gives you input with longer card IDs than your code expects, you will still run into problems. You should therefore ensure that you can never have a buffer overflow.

One way is to tell scanf() how big each buffer is, like so:

sscanf(s,"%14s %7s %49s %d", TransactionID, CardID, Datetime, &Amount);

Note that you again have to specify one less than the size of the buffer. So if you want to handle card IDs of 8 characters, you still need to set the buffer size to 9 bytes. However, while this prevents buffer overflows, if the input strings are larger than the buffers, the rest is silently truncated, or possibly the next %s conversion will pick up the remaining characters.

If you know the input is separated by spaces, then an alternative way is to use strtok() to split the input into the individual parts.


问:
SQL Server Left Join producing duplicates
I have 3 tables, Budgets, Income, and Expenses.

Budget table:

Income table:

Expenses table:

This is my SQL statement:

```<code>SELECT
    Budgets.BudgetID, Budgets.BudgetName, Budgets.Username_FK,
    Budgets.BudgetAmount, Budgets.SavePercentage,
    Expenses.ExpensesID, Expenses.ExpensesAmount, Expenses.ExpensesCategory,
    Income.IncomeID, Income.IncomeAmount, Income.IncomeCategory
FROM
    Budgets
LEFT JOIN
    Income ON Budgets.BudgetID = Income.BudgetID_FK
LEFT JOIN
    Expenses ON Budgets.BudgetID = Expenses.BudgetID_FK
WHERE
    BudgetName = '2019
</code>```

And the results are as follows:

Based on my Income table, there is only 1 record tied to BudgetID = 3, but in the left join, it duplicates.

Ideally, I would want it to return "null" on the duplicates. How do I do this?

答:
For budgetID 3 , you have 4 expenses( distinct expense IDs) of 50.00 in your expense table for the same user. I think what you would want is the total expenses of same category and budget ID i.e budgetID 3 in this case</p>

```<code>SELECT
Budgets.BudgetID, Budgets.BudgetName, Budgets.Username_FK,
Budgets.BudgetAmount, Budgets.SavePercentage,
Income.IncomeID, Income.IncomeAmount, Income.IncomeCategory,
ex.ExpensesCategory,
ex.Total_ExpensesAmount,

FROM Budgets
LEFT JOIN Income ON Budgets.BudgetID = Income.BudgetID_FK
LEFT JOIN (Select BudgetID_FK, ExpensesCategory, SUM(ExpensesAmount) as Total_ExpensesAmount
           FROM Expenses
           GROUP BY BudgetID_FK, ExpensesCategory) ex ON Budgets.BudgetID = ex.BudgetID_FK
WHERE BudgetName = '2019'
</code>```

Body:
I have 3 tables, Budgets, Income, and Expenses.

Budget table:

Income table:

Expenses table:

This is my SQL statement:

SELECT
    Budgets.BudgetID, Budgets.BudgetName, Budgets.Username_FK,
    Budgets.BudgetAmount, Budgets.SavePercentage,
    Expenses.ExpensesID, Expenses.ExpensesAmount, Expenses.ExpensesCategory,
    Income.IncomeID, Income.IncomeAmount, Income.IncomeCategory
FROM
    Budgets
LEFT JOIN
    Income ON Budgets.BudgetID = Income.BudgetID_FK
LEFT JOIN
    Expenses ON Budgets.BudgetID = Expenses.BudgetID_FK
WHERE
    BudgetName = '2019

And the results are as follows:

Based on my Income table, there is only 1 record tied to BudgetID = 3, but in the left join, it duplicates.

Ideally, I would want it to return "null" on the duplicates. How do I do this?

Body:
For budgetID 3 , you have 4 expenses( distinct expense IDs) of 50.00 in your expense table for the same user. I think what you would want is the total expenses of same category and budget ID i.e budgetID 3 in this case

SELECT
Budgets.BudgetID, Budgets.BudgetName, Budgets.Username_FK,
Budgets.BudgetAmount, Budgets.SavePercentage,
Income.IncomeID, Income.IncomeAmount, Income.IncomeCategory,
ex.ExpensesCategory,
ex.Total_ExpensesAmount,

FROM Budgets
LEFT JOIN Income ON Budgets.BudgetID = Income.BudgetID_FK
LEFT JOIN (Select BudgetID_FK, ExpensesCategory, SUM(ExpensesAmount) as Total_ExpensesAmount
           FROM Expenses
           GROUP BY BudgetID_FK, ExpensesCategory) ex ON Budgets.BudgetID = ex.BudgetID_FK
WHERE BudgetName = '2019'


问:
C++ const char with .begin() and .end()
So I have a program that looks something like this:

```<code>const char *Argv[] = {"stuff", "stuff1", "stuff3"};

bool pass = xxxxx::yyyyy(Argv.begin(), Argv.end(), Tri);
</code>```

I think this is illegal because const char * is not a user-defined type. However, I am not sure how to fix this. Would I need to change the first line or the second? Or both?

答:
Argv is an array (of const char*s), and yes you can't call begin() and end() as your code showed, array doesn't have such member functions. Instead, you can use std::begin and std::end for it.

```<code>const char *Argv[] = {"stuff", "stuff1", "stuff3"};
bool pass = xxxxx::yyyyy(std::begin(Argv), std::end(Argv), Tri);
</code>```

If you use other standard containers like std::vector or std::array instead, then you can call the member functions begin() and end() on them. Note that even for these containers you can still use std::begin and std::end on them, which have the same effect as calling their member function begin() and end().

Title: C++ const char with .begin() and .end()

Body:
So I have a program that looks something like this:

const char *Argv[] = {"stuff", "stuff1", "stuff3"};

bool pass = xxxxx::yyyyy(Argv.begin(), Argv.end(), Tri);

I think this is illegal because const char * is not a user-defined type. However, I am not sure how to fix this. Would I need to change the first line or the second? Or both?

Body:
Argv is an array (of const char*s), and yes you can't call begin() and end() as your code showed, array doesn't have such member functions. Instead, you can use std::begin and std::end for it.

const char *Argv[] = {"stuff", "stuff1", "stuff3"};
bool pass = xxxxx::yyyyy(std::begin(Argv), std::end(Argv), Tri);

If you use other standard containers like std::vector or std::array instead, then you can call the member functions begin() and end() on them. Note that even for these containers you can still use std::begin and std::end on them, which have the same effect as calling their member function begin() and end().