问:
How can I store divs content into an array?
Hello this is my first post, i have been learning javascript for a week.
I want to make a little app that calculate how much do you spend on subscription per month.

You can add a new subscription with the name and the subscription price with two inputs --> and it creates 2 new div(one is subscriptionName the other is subscriptionPrice) they are store into a new div (newSubscription).

Now i would like to store all the subscriptionPrice var into an array and addition all of them.
(is it the right logic to apply ? maybe im wrong).

I also thought about doing the addition of the :

.abo-list > .abo:nth-child(1) > .abo-price

.abo-list > .abo:nth-child(1+1) > .abo-price

...

I have tried with this technic but the consol do not show even the first oneAboPrice.

```<code> var pricesValues = [];
for (var i = 0; i < oneAboPrice.length; i++) {
    pricesValues.push(oneAboPrice[i].textContent);
}
console.log(pricesValues); /*dont show the values of every oneAboPrice*/
</code>```

//Selectors
const nameInput = document.querySelector('.name');
const price = document.querySelector('.price');
const validate = document.querySelector('.validate');
const abosList = document.querySelector('.abo-list');
const montantTotal = document.querySelector('.montant-total');

//event listeners

validate.addEventListener('click', addAbo);
abosList.addEventListener('click', clickModify);

//functions
function addAbo(event){
    event.preventDefault();
    //creating the NewAbo DIV
    const Abodiv = document.createElement('div');
    Abodiv.classList.add('abo');
    //creating a LI
    const newAbo = document.createElement('li');
    newAbo.innerText = nameInput.value + ' ' ;
    newAbo.classList.add('abo-item');
    Abodiv.appendChild(newAbo);
    //creating a div Price of one Sub
    const oneAboPrice = document.createElement('div');
    oneAboPrice.classList.add('abo-price');
    oneAboPrice.innerText = price.value;
    Abodiv.appendChild(oneAboPrice);
    //modify button
    const modifyAbo = document.createElement('button');
    modifyAbo.innerHTML = '';
    modifyAbo.classList.add('modifyAbo');
    Abodiv.appendChild(modifyAbo);
    //trash button
    const trashAbo = document.createElement('button');
    trashAbo.innerHTML = '';
    trashAbo.classList.add("trashAbo");
    Abodiv.appendChild(trashAbo);
    //append to Abo-list
    abosList.appendChild(Abodiv);

    //total Amount of every newAboPrice

    //reset input value
    nameInput.value ="";
    price.value="";

    //store every .abo price (oneAboPrice)value into an array (this is where i need help)
    var pricesValues = [];
    for (var i = 0; i < oneAboPrice.length; i++) {
        pricesValues.push(oneAboPrice[i].textContent);
    }
    console.log(pricesValues); /*dont show the values of every oneAboPrice*/

    montantTotal.innerHTML = parseFloat(oneAboPrice.textContent); /* + oneAboPrice nth:child(2) + ....*/
}

function clickModify(e) {
    const item = e.target;
    //Delete newAbo
    if(item.classList[0] === "trashAbo"){
        const abo = item.parentElement;
    abo.remove();
    }
    //modify newAbo (To do)

}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>@import url('https://fonts.googleapis.com/css2?family=Bebas+Neue&family=Poppins&family=Saira+Extra+Condensed:wght@500&display=swap');
*{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

.content-container{
    display: flex;
    justify-content: space-around;
}

.abo{
    display: flex;
    justify-content: space-between;
    list-style-type: none;
}

.abo li{
    flex: 1;
}
.fa-trash{
    pointer-events: none;
}

.abo-price{
    background: red;
}</code>```

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" integrity="sha512-9usAa10IRO0HhonpyAIVpjrylPvoDwiPUiKdWk5t3PyolY1cOd4DSE0Ga+ri4AuTroPR5aQvXU9xC6qOPnzFeg==" crossorigin="anonymous" referrerpolicy="no-referrer" />
    <link rel="stylesheet" href="style.css">
    <title>Gestionnaire d'abonnements</title>

Nom de l'abonnement
<input type="text"  class="name" placeholder="netflix">

Prix mensuel
<input type="number" class="price" placeholder="13,49">
            <input type="button" value="Valide" class="validate">

MES ABOS

```

答:
Here is a complete version

I know it is a lot different from your code, but it is all recommended methods

//Selectors
const nameInput = document.querySelector('.name');
const price = document.querySelector('.price');
const validate = document.querySelector('.validate');
const abosList = document.querySelector('.abo-list');
const montantTotal = document.querySelector('.montant-total');

//event listeners

validate.addEventListener('click', addAbo);
abosList.addEventListener('click', clickModify);

let abos = []; // the main array

const render = () => {
  let sum = 0;
  abosList.innerHTML = abos.map(({name,price}) => { // grb the name and price from the object array
    sum += price; // sum it for the montantTotal
    // create an array of template literals
    return `

${name}

${price}

  <button type="button" class="modifyAbo"></button>
  <button type="button" class="trashAbo"></button>

`
  }).join(""); // and join them with nothing

  montantTotal.innerHTML = sum.toFixed(2)

}

function addAbo(event) {
  event.preventDefault();
  abos.push({ name: nameInput.value, price: +price.value }); // create an array of names,prices
  //reset input value
  nameInput.value = "";
  price.value = "";
  render(); // show the array
}

function clickModify(e) {
  const item = e.target.closest('button');
  //Delete newAbo
  if (item.classList.contains("trashAbo")) {
    const parent = item.closest('div')
    const name = parent.querySelector('li').textContent; // save the name
    parent.remove(); // before removing
    abos = abos.filter(item => item.name != name); // remove the object with the name from the array
  } else if (item.classList.contains("modifyAbo")) {
    const parent = item.closest('div');
    const aboName = parent.querySelector('li').textContent; // copy from the div
    const aboPrice = +parent.querySelector('.abo-price').textContent; // copy from the div
    nameInput.value = aboName; // set the form values
    price.value = aboPrice;    // so they can be edited
    abos = abos.filter(item => item.name != aboName); // remove the abo so valide will add it back
  }
  render()
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>@import url('https://fonts.googleapis.com/css2?family=Bebas+Neue&family=Poppins&family=Saira+Extra+Condensed:wght@500&display=swap');
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.content-container {
  display: flex;
  justify-content: space-around;
}

.abo {
  display: flex;
  justify-content: space-between;
  list-style-type: none;
}

.abo li {
  flex: 1;
}

.fa-trash {
  pointer-events: none;
}

.abo-price {
  background: red;
}</code>```

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" integrity="sha512-9usAa10IRO0HhonpyAIVpjrylPvoDwiPUiKdWk5t3PyolY1cOd4DSE0Ga+ri4AuTroPR5aQvXU9xC6qOPnzFeg==" crossorigin="anonymous" referrerpolicy="no-referrer"
/>
<title>Gestionnaire d'abonnements</title>

Nom de l'abonnement
<input type="text" class="name" placeholder="netflix">

Prix mensuel
<input type="number" class="price" placeholder="13,49">
    <input type="button" value="Valide" class="validate">

MES ABOS

```

Body:
Hello this is my first post, i have been learning javascript for a week.
I want to make a little app that calculate how much do you spend on subscription per month.

You can add a new subscription with the name and the subscription price with two inputs --> and it creates 2 new div(one is subscriptionName the other is subscriptionPrice) they are store into a new div (newSubscription).

Now i would like to store all the subscriptionPrice var into an array and addition all of them.
(is it the right logic to apply ? maybe im wrong).

I also thought about doing the addition of the :

.abo-list > .abo:nth-child(1) > .abo-price

.abo-list > .abo:nth-child(1+1) > .abo-price

...

I have tried with this technic but the consol do not show even the first oneAboPrice.

 var pricesValues = [];
for (var i = 0; i < oneAboPrice.length; i++) {
    pricesValues.push(oneAboPrice[i].textContent);
}
console.log(pricesValues); /*dont show the values of every oneAboPrice*/

//Selectors
const nameInput = document.querySelector('.name');
const price = document.querySelector('.price');
const validate = document.querySelector('.validate');
const abosList = document.querySelector('.abo-list');
const montantTotal = document.querySelector('.montant-total');

//event listeners

validate.addEventListener('click', addAbo);
abosList.addEventListener('click', clickModify);

//functions
function addAbo(event){
    event.preventDefault();
    //creating the NewAbo DIV
    const Abodiv = document.createElement('div');
    Abodiv.classList.add('abo');
    //creating a LI
    const newAbo = document.createElement('li');
    newAbo.innerText = nameInput.value + ' ' ;
    newAbo.classList.add('abo-item');
    Abodiv.appendChild(newAbo);
    //creating a div Price of one Sub
    const oneAboPrice = document.createElement('div');
    oneAboPrice.classList.add('abo-price');
    oneAboPrice.innerText = price.value;
    Abodiv.appendChild(oneAboPrice);
    //modify button
    const modifyAbo = document.createElement('button');
    modifyAbo.innerHTML = '';
    modifyAbo.classList.add('modifyAbo');
    Abodiv.appendChild(modifyAbo);
    //trash button
    const trashAbo = document.createElement('button');
    trashAbo.innerHTML = '';
    trashAbo.classList.add("trashAbo");
    Abodiv.appendChild(trashAbo);
    //append to Abo-list
    abosList.appendChild(Abodiv);

    //total Amount of every newAboPrice

    //reset input value
    nameInput.value ="";
    price.value="";

    //store every .abo price (oneAboPrice)value into an array (this is where i need help)
    var pricesValues = [];
    for (var i = 0; i < oneAboPrice.length; i++) {
        pricesValues.push(oneAboPrice[i].textContent);
    }
    console.log(pricesValues); /*dont show the values of every oneAboPrice*/

    montantTotal.innerHTML = parseFloat(oneAboPrice.textContent); /* + oneAboPrice nth:child(2) + ....*/
}

function clickModify(e) {
    const item = e.target;
    //Delete newAbo
    if(item.classList[0] === "trashAbo"){
        const abo = item.parentElement;
    abo.remove();
    }
    //modify newAbo (To do)

}

@import url('https://fonts.googleapis.com/css2?family=Bebas+Neue&family=Poppins&family=Saira+Extra+Condensed:wght@500&display=swap');
*{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

.content-container{
    display: flex;
    justify-content: space-around;
}

.abo{
    display: flex;
    justify-content: space-between;
    list-style-type: none;
}

.abo li{
    flex: 1;
}
.fa-trash{
    pointer-events: none;
}

.abo-price{
    background: red;
}

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" integrity="sha512-9usAa10IRO0HhonpyAIVpjrylPvoDwiPUiKdWk5t3PyolY1cOd4DSE0Ga+ri4AuTroPR5aQvXU9xC6qOPnzFeg==" crossorigin="anonymous" referrerpolicy="no-referrer" />
    <link rel="stylesheet" href="style.css">
    <title>Gestionnaire d'abonnements</title>

Nom de l'abonnement
<input type="text"  class="name" placeholder="netflix">

Prix mensuel
<input type="number" class="price" placeholder="13,49">
            <input type="button" value="Valide" class="validate">

MES ABOS

Body:
Here is a complete version

I know it is a lot different from your code, but it is all recommended methods

//Selectors
const nameInput = document.querySelector('.name');
const price = document.querySelector('.price');
const validate = document.querySelector('.validate');
const abosList = document.querySelector('.abo-list');
const montantTotal = document.querySelector('.montant-total');

//event listeners

validate.addEventListener('click', addAbo);
abosList.addEventListener('click', clickModify);

let abos = []; // the main array

const render = () => {
  let sum = 0;
  abosList.innerHTML = abos.map(({name,price}) => { // grb the name and price from the object array
    sum += price; // sum it for the montantTotal
    // create an array of template literals
    return `<div class="abo"><li>${name}</li><div class="abo-price">${price}</div>
  <button type="button" class="modifyAbo"><i class="fa fa-pen"></i></button>
  <button type="button" class="trashAbo"><i class="fa fa-trash"></i></button>
  </div>`
  }).join(""); // and join them with nothing

  montantTotal.innerHTML = sum.toFixed(2)

}

function addAbo(event) {
  event.preventDefault();
  abos.push({ name: nameInput.value, price: +price.value }); // create an array of names,prices
  //reset input value
  nameInput.value = "";
  price.value = "";
  render(); // show the array
}

function clickModify(e) {
  const item = e.target.closest('button');
  //Delete newAbo
  if (item.classList.contains("trashAbo")) {
    const parent = item.closest('div')
    const name = parent.querySelector('li').textContent; // save the name
    parent.remove(); // before removing
    abos = abos.filter(item => item.name != name); // remove the object with the name from the array
  } else if (item.classList.contains("modifyAbo")) {
    const parent = item.closest('div');
    const aboName = parent.querySelector('li').textContent; // copy from the div
    const aboPrice = +parent.querySelector('.abo-price').textContent; // copy from the div
    nameInput.value = aboName; // set the form values
    price.value = aboPrice;    // so they can be edited
    abos = abos.filter(item => item.name != aboName); // remove the abo so valide will add it back
  }
  render()
}

@import url('https://fonts.googleapis.com/css2?family=Bebas+Neue&family=Poppins&family=Saira+Extra+Condensed:wght@500&display=swap');
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.content-container {
  display: flex;
  justify-content: space-around;
}

.abo {
  display: flex;
  justify-content: space-between;
  list-style-type: none;
}

.abo li {
  flex: 1;
}

.fa-trash {
  pointer-events: none;
}

.abo-price {
  background: red;
}

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" integrity="sha512-9usAa10IRO0HhonpyAIVpjrylPvoDwiPUiKdWk5t3PyolY1cOd4DSE0Ga+ri4AuTroPR5aQvXU9xC6qOPnzFeg==" crossorigin="anonymous" referrerpolicy="no-referrer"
/>
<title>Gestionnaire d'abonnements</title>
<div class="content-container">
  <div class="left">
    <p>Nom de l'abonnement</p><input type="text" class="name" placeholder="netflix">
    <p>Prix mensuel</p><input type="number" class="price" placeholder="13,49">
    <input type="button" value="Valide" class="validate">
  </div>
  <div class="right">
    <h1>MES ABOS</h1>
    <ul class="abo-list">

    </ul>
    <p class="montant-total"></p>
  </div>
</div>


来源: stackexchange

问:
Java comparing generic types
In Java, I wrote a Binary Search Tree class that adds nodes using recursion. Now I want to generalize it using Generics so I can learn more about them.

```<code>public class GBinNode<T> {
    T item;
    GBinNode<T> left;
    GBinNode<T> right;

public GBinNode(T newItem) {
    item = newItem;
    left = null;
    right = null;
    }
public GBinNode(T it, GBinNode<T> le, GBinNode<T> ri) {
    item = it;
    left = le;
    right = ri;
    }
public String toString() {
    return item.toString()+" ";
    }
}
</code>```

My function to add nodes is in the following class

```<code>public class GBinTree<T extends Comparable <T>> {
  GBinNode<T> add(T item, GBinNode<T> bn) {
    if (bn==null) {
        return new GBinNode<T>(item, null, null);
    }
    if (item < bn.item) {        // ERROR HERE
        bn.left = add( item, bn.left);
    }
    else {
        bn.right = add( item, bn.right);
    }
    return bn;
}

public void toString(GBinNode<T> root) {
    GBinNode<T> curr = root;
    if (curr == null)
        return;
    else {
        toString(curr.left);
        System.out.println(curr.toString());    // inorder traversal
        toString(curr.right);
    }
}
</code>```

The main class has the following code to kick things off. I'm using strings, but the data type could be some complex type.

```<code>GBinTree<String> bt = new GBinTree<String>();
    GBinNode<String> root = null;
    root = bt.add("Calex", root);
    root = bt.add("Ealex", root);
    root = bt.add("Balex", root);
    root = bt.add("Dalex", root);
    bt.toString(root);
</code>```

I started to use the Comparable interface but then how do I write the CompareTo() function? I don't know what type T will be? The error I got was "The operator < is undefined for the argument type(s) T, T".

Searching for a solution, one answer was Comparing generic types Java:

```<code>class Element<T extends Comparable<T>>
</code>```

I don't understand where this should go, and how it's different from the class implementing Comparable. The only place I know the type is in the main class, so should the compareTo() be there? I looked at making GBinTree an interface, but got confused whether that was the right track? Any help would be appreciated.

答: Came across this problem when writing generic sorting. Best solution that i came up with is to add a Comparator to the argument of sorting function and use the compare method. You will have to override the compare(T o1,To2) method at/before function call while creating new Comparator<T>() , T to be  replaced by the desired type.

ContentLicense: CC BY-SA 3.0

Title: Java comparing generic types

Body:
In Java, I wrote a Binary Search Tree class that adds nodes using recursion. Now I want to generalize it using Generics so I can learn more about them.

public class GBinNode<T> {
    T item;
    GBinNode<T> left;
    GBinNode<T> right;

public GBinNode(T newItem) {
    item = newItem;
    left = null;
    right = null;
    }
public GBinNode(T it, GBinNode<T> le, GBinNode<T> ri) {
    item = it;
    left = le;
    right = ri;
    }
public String toString() {
    return item.toString()+" ";
    }
}

My function to add nodes is in the following class

public class GBinTree<T extends Comparable <T>> {
  GBinNode<T> add(T item, GBinNode<T> bn) {
    if (bn==null) {
        return new GBinNode<T>(item, null, null);
    }
    if (item < bn.item) {        // ERROR HERE
        bn.left = add( item, bn.left);
    }
    else {
        bn.right = add( item, bn.right);
    }
    return bn;
}

public void toString(GBinNode<T> root) {
    GBinNode<T> curr = root;
    if (curr == null)
        return;
    else {
        toString(curr.left);
        System.out.println(curr.toString());    // inorder traversal
        toString(curr.right);
    }
}

The main class has the following code to kick things off. I'm using strings, but the data type could be some complex type.

GBinTree<String> bt = new GBinTree<String>();
    GBinNode<String> root = null;
    root = bt.add("Calex", root);
    root = bt.add("Ealex", root);
    root = bt.add("Balex", root);
    root = bt.add("Dalex", root);
    bt.toString(root);

I started to use the Comparable interface but then how do I write the CompareTo() function? I don't know what type T will be? The error I got was "The operator < is undefined for the argument type(s) T, T".

Searching for a solution, one answer was Comparing generic types Java:

class Element<T extends Comparable<T>>

I don't understand where this should go, and how it's different from the class implementing Comparable. The only place I know the type is in the main class, so should the compareTo() be there? I looked at making GBinTree an interface, but got confused whether that was the right track? Any help would be appreciated.

ContentLicense: CC BY-SA 4.0


问:
How to iterate over map using mustache in java
I'm newbie to mustache and was wondering how to iterate over HashMap using mustache given this Map

```<code>Map mapA = new HashMap();

mapA.put("key1", "element 1");
mapA.put("key2", "element 2");
mapA.put("key3", "element 3");
</code>```

The map key names vary. Ideally, I want mustache to iterate over both its key and values. So in java it will look like this:

```<code>for (Map.Entry<String, Object> entry : mapA.entrySet()) {
   String key = entry.getKey();
   String value = entry.getValue();
   // ...
}
</code>```

So can someone tell me how to achieve above in mustache. I mean how would the template looks like? I tried this template but had no luck so far :(

```<code>{{#mapA}}
  <li>{{key}}</li>
  <li>{{value}}</li>
{{/mapA>
</code>```

So when I run this template, the output
 tags comes out empty, why?
Thanks.

答:
it is much simpler than that, just do it like this:</p>
```<code>{{#mapA}}
  {{#entrySet}}
    <li>{{key}}</li>
    <li>{{value}}</li>
  {{/entrySet}}
{{/mapA}}
</code>```

Body:
I'm newbie to mustache and was wondering how to iterate over HashMap using mustache given this Map

Map mapA = new HashMap();

mapA.put("key1", "element 1");
mapA.put("key2", "element 2");
mapA.put("key3", "element 3");

The map key names vary. Ideally, I want mustache to iterate over both its key and values. So in java it will look like this:

for (Map.Entry<String, Object> entry : mapA.entrySet()) {
   String key = entry.getKey();
   String value = entry.getValue();
   // ...
}

So can someone tell me how to achieve above in mustache. I mean how would the template looks like? I tried this template but had no luck so far :(

{{#mapA}}

{{key}}

{{value}}

{{/mapA>

So when I run this template, the output
 tags comes out empty, why?
Thanks.

Body:
it is much simpler than that, just do it like this:

{{#mapA}}
  {{#entrySet}}
    <li>{{key}}</li>
    <li>{{value}}</li>
  {{/entrySet}}
{{/mapA}}


问:
Infinity - number = infinity
In javascript Infinity - 100 results in Infinity which makes sense,
but the resulted Infinity does not appear to be less than the initial Infinity like in real math.

I am trying to sort some array, and items from array that don't have a certain property are assigned a default Infinity value, then sorting should fallback to Infinity minus a different property. The problem is that this subtraction does not produce different Infinity values.

答:
You don't have to think of Infinity as a number. Infinity minus a finite number is still (the same) Infinity, it's math theory.
That's why you get that result.</p>

Title: Infinity - number = infinity


问:
How can I update an array using useState, with as many numbers as the ones I pass to the function?
I am trying to make an image slider that gives you n new images every time you click. I am struggling to understand how to make this piece of code dynamic so that it updates the array that takes care of the indexes as many times as the number I pass to the function (in this case 3)

```<code>  const handleIncrement = () => {
    setIndex((prevIndex) => [
      prevIndex[prevIndex.length - 1] + 1,
      prevIndex[prevIndex.length - 1] + 2,
      prevIndex[prevIndex.length - 1] + 3,
    ]);
  };
</code>```

This is the entire code

```<code>function useImageSlider(range: number = 3, length: number, steps: number = 1) {
  const [index, setIndex] = useState<number[]>(Array.from(Array(range).keys()));

  const handleDecrement = () => {
    setIndex((prevIndex) => [
      prevIndex[prevIndex.length - 1] - 1,
      prevIndex[prevIndex.length - 1] - 2,
      prevIndex[prevIndex.length - 1] - 3,
    ]);
  };
  const handleIncrement = () => {
    index[index.length - 1] + steps + 1 >= length &&
      setIndex((prevState) => [...prevState, -1]);
    setIndex((prevIndex) => [
      prevIndex[prevIndex.length - 1] + 1,
      prevIndex[prevIndex.length - 1] + 2,
      prevIndex[prevIndex.length - 1] + 3,
    ]);
  };
  return { length, steps, handleIncrement, handleDecrement, index };
}
export default useImageSlider;
</code>```

答:
```<code>const handleIncrement = (range) => {
setIndex((prevIndex) => [...Array(range).keys()].map(arrIndex =>
  prevIndex[prevIndex.length - 1] + arrIndex + 1));
};
</code>```

Body:
I am trying to make an image slider that gives you n new images every time you click. I am struggling to understand how to make this piece of code dynamic so that it updates the array that takes care of the indexes as many times as the number I pass to the function (in this case 3)

  const handleIncrement = () => {
    setIndex((prevIndex) => [
      prevIndex[prevIndex.length - 1] + 1,
      prevIndex[prevIndex.length - 1] + 2,
      prevIndex[prevIndex.length - 1] + 3,
    ]);
  };

This is the entire code

function useImageSlider(range: number = 3, length: number, steps: number = 1) {
  const [index, setIndex] = useState<number[]>(Array.from(Array(range).keys()));

  const handleDecrement = () => {
    setIndex((prevIndex) => [
      prevIndex[prevIndex.length - 1] - 1,
      prevIndex[prevIndex.length - 1] - 2,
      prevIndex[prevIndex.length - 1] - 3,
    ]);
  };
  const handleIncrement = () => {
    index[index.length - 1] + steps + 1 >= length &&
      setIndex((prevState) => [...prevState, -1]);
    setIndex((prevIndex) => [
      prevIndex[prevIndex.length - 1] + 1,
      prevIndex[prevIndex.length - 1] + 2,
      prevIndex[prevIndex.length - 1] + 3,
    ]);
  };
  return { length, steps, handleIncrement, handleDecrement, index };
}
export default useImageSlider;


问:
Using Case Statement in SQL
I have been learning SQL,and I was trying to learn about the CASE on Oracle LiveSQL:

This is the query I am trying to use:

```<code>SELECT FIRST_NAME,LAST_NAME, CASE
WHEN SALARY>10000 THEN 'Salary is greater than 10000'
WHEN SALARY<10000 THEN 'Salary is less than 10000'
ELSE 'Salary is equal to 10000'
END AS 'SALARY STATEMENT'
FROM hr.employees;
</code>```

This query gives me the output as:

```<code>ORA-00923: FROM keyword not found where expected
</code>```

Can anyone explain what's wrong?

答:
You got the perfect answer. But in oracle you can also use decode.</p>
```<code>SELECT FIRST_NAME, LAST_NAME,
DECODE(SIGN(SALARY-10000),1, 'Salary is greater than 10000',-1, 'Salary is less than 10000', 'Salary is equal to 10000')
FROM hr.employees;
</code>```

Title: Using Case Statement in SQL

Body:
I have been learning SQL,and I was trying to learn about the CASE on Oracle LiveSQL:

This is the query I am trying to use:

SELECT FIRST_NAME,LAST_NAME, CASE
WHEN SALARY>10000 THEN 'Salary is greater than 10000'
WHEN SALARY<10000 THEN 'Salary is less than 10000'
ELSE 'Salary is equal to 10000'
END AS 'SALARY STATEMENT'
FROM hr.employees;

This query gives me the output as:

ORA-00923: FROM keyword not found where expected

Can anyone explain what's wrong?

Body:
You got the perfect answer. But in oracle you can also use decode.

SELECT FIRST_NAME, LAST_NAME,
DECODE(SIGN(SALARY-10000),1, 'Salary is greater than 10000',-1, 'Salary is less than 10000', 'Salary is equal to 10000')
FROM hr.employees;


问:
Expanding mean over time per subgroup in dataframe
Still quite new to R, so trying to figure out what I am doing wrong in the following explanation.

I am trying to calculate the expanding mean over time per subgroup for a dataframe. My code works when there is only a single subgroup in the dataframe, but starts to break when multiple subgroups are available within the dataframe.

Apologies if I have overlooked something, but I cant figure out where exactly my code is incorrect. My hunch is that I am not filling in the width correctly, but I have not been able to figure out how to change width to a dynamically expanding window over time per subgroup.

See my data below;
sample file

See my code below;

```<code>library(ggplot2)
library(zoo)
library(RcppRoll)
library(dplyr)

x <- read.csv("stackoverflow.csv")

x$datatime <- as.POSIXlt(x$datatime,format="%m/%d/%Y %H:%M",tz=Sys.timezone())
x$Event <- as.factor(x$Event)

x2 <- arrange(x,x$Event,x$datatime) %>%
  group_by(x$Event) %>%
  mutate(ma=rollapply(data = x$Actual, width=seq_along(x$Actual), FUN=mean,
                          partial=TRUE, fill=NA,
                          align = "right"))
</code>```

Any help is very much appreciated!

Thanks

EDIT:

A fix has been found! Thanks to all the useful feedback.

The working code is;

```<code>x <-
  arrange(x,x$Event,x$datatime) %>%
  group_by(Event) %>%
  mutate(ma=rollapply(data = Actual,
                      width=seq_along(Actual),
                      FUN=mean,
                      partial=TRUE,
                      fill=NA,
                      align = "right"))
</code>```

答:
I think the problem here is that you’re using x$ to extract columns from
the original data in mutate(), rather than using the column name directly
to refer to the column in the grouped slice.
In dplyr verbs you can (and in case of grouped operations, must) refer to the columns directly.
The solution is to just remove
all x$ references from your code in dplyr functions.

Here’s a small example that illustrates what’s going on:

library(dplyr, warn.conflicts = FALSE)

tbl <- tibble(g = c(1, 1, 2, 2, 2), x = 1:5)
tbl
#> # A tibble: 5 x 2
#>       g     x
#>   <dbl> <int>
#> 1     1     1
#> 2     1     2
#> 3     2     3
#> 4     2     4
#> 5     2     5

tbl %>%
  group_by(g) %>%
  mutate(y = cumsum(tbl$x))
#> Error in `mutate_cols()`:
#> ! Problem with `mutate()` column `y`.
#> i `y = cumsum(tbl$x)`.
#> i `y` must be size 2 or 1, not 5.
#> i The error occurred in group 1: g = 1.
```
<p>And how to fix it:</p>
<pre class="lang-r prettyprint-override"><code>tbl %>%
  group_by(g) %>%
  mutate(y = cumsum(x))
#> # A tibble: 5 x 3
#> # Groups:   g [2]
#>       g     x     y
#>   <dbl> <int> <int>
#> 1     1     1     1
#> 2     1     2     3
#> 3     2     3     3
#> 4     2     4     7
#> 5     2     5    12
</code>```

Body:
Still quite new to R, so trying to figure out what I am doing wrong in the following explanation.

I am trying to calculate the expanding mean over time per subgroup for a dataframe. My code works when there is only a single subgroup in the dataframe, but starts to break when multiple subgroups are available within the dataframe.

Apologies if I have overlooked something, but I cant figure out where exactly my code is incorrect. My hunch is that I am not filling in the width correctly, but I have not been able to figure out how to change width to a dynamically expanding window over time per subgroup.

See my data below;
sample file

See my code below;

library(ggplot2)
library(zoo)
library(RcppRoll)
library(dplyr)

x <- read.csv("stackoverflow.csv")

x$datatime <- as.POSIXlt(x$datatime,format="%m/%d/%Y %H:%M",tz=Sys.timezone())
x$Event <- as.factor(x$Event)

x2 <- arrange(x,x$Event,x$datatime) %>%
  group_by(x$Event) %>%
  mutate(ma=rollapply(data = x$Actual, width=seq_along(x$Actual), FUN=mean,
                          partial=TRUE, fill=NA,
                          align = "right"))

Any help is very much appreciated!

Thanks

EDIT:

A fix has been found! Thanks to all the useful feedback.

The working code is;

x <-
  arrange(x,x$Event,x$datatime) %>%
  group_by(Event) %>%
  mutate(ma=rollapply(data = Actual,
                      width=seq_along(Actual),
                      FUN=mean,
                      partial=TRUE,
                      fill=NA,
                      align = "right"))

Body:
I think the problem here is that you’re using x$ to extract columns from
the original data in mutate(), rather than using the column name directly
to refer to the column in the grouped slice.
In dplyr verbs you can (and in case of grouped operations, must) refer to the columns directly.
The solution is to just remove
all x$ references from your code in dplyr functions.

Here’s a small example that illustrates what’s going on:

library(dplyr, warn.conflicts = FALSE)

tbl <- tibble(g = c(1, 1, 2, 2, 2), x = 1:5)
tbl
#> # A tibble: 5 x 2
#>       g     x
#>   <dbl> <int>
#> 1     1     1
#> 2     1     2
#> 3     2     3
#> 4     2     4
#> 5     2     5

tbl %>%
  group_by(g) %>%
  mutate(y = cumsum(tbl$x))
#> Error in `mutate_cols()`:
#> ! Problem with `mutate()` column `y`.
#> i `y = cumsum(tbl$x)`.
#> i `y` must be size 2 or 1, not 5.
#> i The error occurred in group 1: g = 1.

And how to fix it:

tbl %>%
  group_by(g) %>%
  mutate(y = cumsum(x))
#> # A tibble: 5 x 3
#> # Groups:   g [2]
#>       g     x     y
#>   <dbl> <int> <int>
#> 1     1     1     1
#> 2     1     2     3
#> 3     2     3     3
#> 4     2     4     7
#> 5     2     5    12


问:
Location Background - Network Connection
I am trying to post data on background and I want to receive response from in regular interval that so that I am trying to use CLLocation Manager . But didUpdateToLocation method calling only once.
Please suggest me !
enter code here

```<code>    - (void)applicationDidEnterBackgroundUIApplication *)application
    {
    locationManager = [[CLLocationManager alloc] init];
    locationManager.delegate = self;
    locationManager.distanceFilter = kCLDistanceFilterNone; // whenever we move
    locationManager.desiredAccuracy = kCLLocationAccuracyBest; // 100 m
    [locationManager startUpdatingLocation];
    UIApplication* app = [UIApplication sharedApplication];

    bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
    [app endBackgroundTask:bgTask];
     bgTask = UIBackgroundTaskInvalid;
    }];

    // Start the long-running task and return immediately.
    dispatch_async(dispatch_get_global_queue(DISPATCH_ QUEUE_PRIORITY_DEFAULT, 0), ^{

    //Do the work associated with the task
    // code for Posting Data Here
    NSLog(@"backgroundTimeRemaining: %f", [[UIApplication sharedApplication] backgroundTimeRemaining]);
    [app endBackgroundTask:bgTask];
    bgTask = UIBackgroundTaskInvalid;
    });

    }
    - (void)locationManagerCLLocationManager *)manager
</code>```

didUpdateToLocationCLLocation *)newLocation
fromLocationCLLocation *)oldLocation
{

NSLog(@"Location Change");
}
This Method Call Only Once.

答:
Of course, and you should be happy what delegate received message at least once. There is no code which will delay application suspending in your background execution code. Also this kind of code can work about 10 minutes and will be killed by system.

If you need to track user location in background, than maybe you just set this mode for application background operation in Info.plist (UIBackgroundModes and add option location) and your app won't be suspended (only in case of heavy memory usage)

Body:
I am trying to post data on background and I want to receive response from in regular interval that so that I am trying to use CLLocation Manager . But didUpdateToLocation method calling only once.
Please suggest me !
enter code here

    - (void)applicationDidEnterBackgroundUIApplication *)application
    {
    locationManager = [[CLLocationManager alloc] init];
    locationManager.delegate = self;
    locationManager.distanceFilter = kCLDistanceFilterNone; // whenever we move
    locationManager.desiredAccuracy = kCLLocationAccuracyBest; // 100 m
    [locationManager startUpdatingLocation];
    UIApplication* app = [UIApplication sharedApplication];

    bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
    [app endBackgroundTask:bgTask];
     bgTask = UIBackgroundTaskInvalid;
    }];

    // Start the long-running task and return immediately.
    dispatch_async(dispatch_get_global_queue(DISPATCH_ QUEUE_PRIORITY_DEFAULT, 0), ^{

    //Do the work associated with the task
    // code for Posting Data Here
    NSLog(@"backgroundTimeRemaining: %f", [[UIApplication sharedApplication] backgroundTimeRemaining]);
    [app endBackgroundTask:bgTask];
    bgTask = UIBackgroundTaskInvalid;
    });

    }
    - (void)locationManagerCLLocationManager *)manager

didUpdateToLocationCLLocation *)newLocation
fromLocationCLLocation *)oldLocation
{

NSLog(@"Location Change");
}
This Method Call Only Once.


问:
sqlalchemy: AttributeError: type object 'customer' has no attribute 'invoices'
I am new to sqlalchemy. I can create database tables by declarative mapping like this:

```<code>engine = create_engine("--engine works---")

Base = declarative_base()

class Customer(Base):
    __tablename__ = 'customer'

    customer_id = Column(Integer, primary_key=True)
    name = Column(String(30))
    email = Column(String(30))

    invoices = relationship(
        'Invoice',
        order_by="Invoice.inv_id",
        back_populates='customer',
        cascade="all, delete, delete-orphan"
    )

class Invoice(Base):
    __tablename__ = 'invoice'

    inv_id = Column(Integer, primary_key=True)
    name = Column(String(30))
    created = Column(Date)

    customer_id = Column(ForeignKey('customer.customer_id'))

    customer = relationship('Customer', back_populates='invoices')

Base.metadata.create_all(engine)
</code>```

This is fine. I added some data into both customer and invoice tables.

So far so good. Next, I would try out automap_base on this existing database like this:

```<code>from sqlalchemy import select, text
from sqlalchemy.orm import declarative_base, sessionmaker
from sqlalchemy.ext.automap import automap_base

engine = create_engine('--engine works---')
Base = automap_base()
# reflect
Base.prepare(engine, reflect=True)

Customer = Base.classes.customer
Invoice = Base.classes.invoice

Session = sessionmaker(bind=engine, future=True)
session = Session()

# query invoice
stmt = select(Customer, Invoice).join(Customer.invoices).order_by(Customer.customer_id, Invoice.inv_id)
res = session.execute(stmt)

for c in res:
    print(c.customer_id)
</code>```

When I ran the code, I got:

AttributeError: type object 'customer' has no attribute 'invoices'

What did I miss for the relationship on the Customer (one side) or Invoice (many side) in this case so that when I query for customers with its invoices attibute and for invoices with customer attribute? Thanks for any help.

答:
By default, automap will create the relation in the parent by appending "_collection" the lower-cased classname, so the name will be Customer.invoice_collection.

While answering this, I found that the join would raise an AttributeError on Customer.invoice_collection unless I performed a query on Customer beforehand, for example

session.execute(sa.select(Customer).where(False))
```
<p>I'm not sure why that happens, however you don't necessarily need the join as you can iterate over <code>Customer.invoice_collection</code> directly, or join against the invoice table:</p>
<pre class="lang-py prettyprint-override"><code>stmt = sa.select(Customer, Invoice).join(Invoice)
res = session.execute(stmt)
for c, i in res:
    print(c.customer_id, i.inv_id)
</code>```

Body:
I am new to sqlalchemy. I can create database tables by declarative mapping like this:

engine = create_engine("--engine works---")

Base = declarative_base()

class Customer(Base):
    __tablename__ = 'customer'

    customer_id = Column(Integer, primary_key=True)
    name = Column(String(30))
    email = Column(String(30))

    invoices = relationship(
        'Invoice',
        order_by="Invoice.inv_id",
        back_populates='customer',
        cascade="all, delete, delete-orphan"
    )

class Invoice(Base):
    __tablename__ = 'invoice'

    inv_id = Column(Integer, primary_key=True)
    name = Column(String(30))
    created = Column(Date)

    customer_id = Column(ForeignKey('customer.customer_id'))

    customer = relationship('Customer', back_populates='invoices')

Base.metadata.create_all(engine)

This is fine. I added some data into both customer and invoice tables.

So far so good. Next, I would try out automap_base on this existing database like this:

from sqlalchemy import select, text
from sqlalchemy.orm import declarative_base, sessionmaker
from sqlalchemy.ext.automap import automap_base

engine = create_engine('--engine works---')
Base = automap_base()
# reflect
Base.prepare(engine, reflect=True)

Customer = Base.classes.customer
Invoice = Base.classes.invoice

Session = sessionmaker(bind=engine, future=True)
session = Session()

# query invoice
stmt = select(Customer, Invoice).join(Customer.invoices).order_by(Customer.customer_id, Invoice.inv_id)
res = session.execute(stmt)

for c in res:
    print(c.customer_id)

When I ran the code, I got:

AttributeError: type object 'customer' has no attribute 'invoices'

What did I miss for the relationship on the Customer (one side) or Invoice (many side) in this case so that when I query for customers with its invoices attibute and for invoices with customer attribute? Thanks for any help.

Body:
By default, automap will create the relation in the parent by appending "_collection" the lower-cased classname, so the name will be Customer.invoice_collection.

While answering this, I found that the join would raise an AttributeError on Customer.invoice_collection unless I performed a query on Customer beforehand, for example

session.execute(sa.select(Customer).where(False))

I'm not sure why that happens, however you don't necessarily need the join as you can iterate over Customer.invoice_collection directly, or join against the invoice table:

stmt = sa.select(Customer, Invoice).join(Invoice)
res = session.execute(stmt)
for c, i in res:
    print(c.customer_id, i.inv_id)


问:
Why can there be const assignment operators
With C++23 there will be

```<code>std::pair<T1, T1>::operator =( const pair &other ) const;
</code>```

For me an assignment-operator operating on const-objects doesn't make any sense since the object can't be modified. Why will C++23 have this operator on pair ? And even more confusing, there's:

```<code>std::pair<T1, T1>::operator =( pair &&other ) const;
</code>```

[EDIT]: This won't work because what this points to will be const:

```<code>template<typename T>
struct S
{
    void operator +=( T x ) const;
    T m_x;
};

template<typename T>
void S<T>::operator +=( T x ) const
{
    m_x += x;
}

int main( int argc, char **argv )
{
    S<int> si;
    si += 1;
}
</code>```

So why is there a const-qualified assignment-operator with pair ?

答:
It makes sense for pairs of non-const references. Those remain assignable even when const. Consider:

```<code>#include <iostream>

template <typename T>
void foo(const T x) {x = 42;}

int main()
{
    int y = 1;
    foo<int &>(y);
    std::cout << y << '\n'; // 42
}
</code>```

But why bother supporting it in std::pair?

I've recently seen an explanation somewhere on SO, but can't find the link (found it). It went along the lines of:

You're making a generic algorithm, and you're assigning to a function result in a template (such as to a dereferenced iterator). If the function happens to return by value, you can silently get unexpected behavior (assignment doing nothing).

You would like a compilation error instead, but virtually nobody
&-qualifies their assignment operators.

Then a logical next step is to check the return type and reject non-references.

But you want to leave a loophole. E.g. dereferencing std::vector<bool> iterator returns (a proxy object) by value, and assigning to it should be allowed.

You could invent a type trait for it, but there's a clever alternative. You check if the assignment still compiles if you add const to the return type. If it doesn't, you raise a compilation error. This generalizes nicely to returning references, since adding const to them leaves the type unchanged (and still assignable, if the reference was non-const).

To make it work, you need to add const to assignment operators of all such types (and it was done for std::vector<bool>::reference).

As for why std::pair (and std::tuple) need it: iterators from std::views::zip() dereference to tuples of references, and you want to be able to assign to those tuples.

But I don't remember which standard algorithms are going to be constrained like this in C++23. Probably something in ranges...

Body:
With C++23 there will be

std::pair<T1, T1>::operator =( const pair &other ) const;

For me an assignment-operator operating on const-objects doesn't make any sense since the object can't be modified. Why will C++23 have this operator on pair ? And even more confusing, there's:

std::pair<T1, T1>::operator =( pair &&other ) const;

[EDIT]: This won't work because what this points to will be const:

template<typename T>
struct S
{
    void operator +=( T x ) const;
    T m_x;
};

template<typename T>
void S<T>::operator +=( T x ) const
{
    m_x += x;
}

int main( int argc, char **argv )
{
    S<int> si;
    si += 1;
}

So why is there a const-qualified assignment-operator with pair ?

Body:
It makes sense for pairs of non-const references. Those remain assignable even when const. Consider:

#include <iostream>

template <typename T>
void foo(const T x) {x = 42;}

int main()
{
    int y = 1;
    foo<int &>(y);
    std::cout << y << '\n'; // 42
}

But why bother supporting it in std::pair?

I've recently seen an explanation somewhere on SO, but can't find the link (found it). It went along the lines of:

You're making a generic algorithm, and you're assigning to a function result in a template (such as to a dereferenced iterator). If the function happens to return by value, you can silently get unexpected behavior (assignment doing nothing).

You would like a compilation error instead, but virtually nobody
&-qualifies their assignment operators.

Then a logical next step is to check the return type and reject non-references.

But you want to leave a loophole. E.g. dereferencing std::vector<bool> iterator returns (a proxy object) by value, and assigning to it should be allowed.

You could invent a type trait for it, but there's a clever alternative. You check if the assignment still compiles if you add const to the return type. If it doesn't, you raise a compilation error. This generalizes nicely to returning references, since adding const to them leaves the type unchanged (and still assignable, if the reference was non-const).

To make it work, you need to add const to assignment operators of all such types (and it was done for std::vector<bool>::reference).

As for why std::pair (and std::tuple) need it: iterators from std::views::zip() dereference to tuples of references, and you want to be able to assign to those tuples.

But I don't remember which standard algorithms are going to be constrained like this in C++23. Probably something in ranges...


问:
In Haskell, Can Kinds Be Anything Other Than a Sequence of Stars?
Please forgive me if this question is dumb.

While reading about Haskell kinds, I notice a theme:

```<code>*
* -> *
* -> * -> *
</code>```

I get the impression that kinds in Haskell ultimately boil down to how many asterisks there are. You might say that the kind of a type is really just the number of types you need to apply to it before it becomes *. In other words, you could count all *'s but the last one, and define a type's kind by an integer. Say 0, 1, 2, etc.

Here's my question:

Is this a correct observation about Haskell's type system? Or does it allow something other than *'s to go where you typically see *'s? For example:

```<code>* -> a -> *
</code>```

I imagine someone might want to do this to constrain type variables to have an instance of a type class, for example.

```<code>Functor a, Applicative b => * -> a -> b -> *
</code>```

Is that a thing?

答:
The most basic form of the kind language contains only * (or Type in more modern Haskell; I suspect we'll eventually move away from *) and ->.

But there are more things you can build with that language than you can express by just "counting the number of *s". It's not just the number of * or -> that matter, but how they are nested. For example * -> * -> * is the kind of things that take two type arguments to produce a type, but (* -> *) -> * is the kind of things that take a single argumemt to produce a type where that argument itself must be a thing that takes a type argument to produce a type. data ThreeStars a b = Cons a b makes a type constructor with kind * -> * -> *, while data AlsoThreeStars f = AlsoCons (f Integer) makes a type constructor with kind (* -> *) -> *.

There are several language extensions that add more features to the kind language.

PolyKinds adds kind variables that work exactly the same way type variables work. Now we can have kinds like forall k. (* -> k) -> k.

ConstraintKinds makes constraints (the stuff to the left of the => in type signatures, like Eq a) become ordinary type-level entities in a new kind: Constraint. Rather than the stuff left of the => being special purpose syntax fairly disconnected from the rest of the language, now what is acceptable there is anything with kind Constraint. Classes like Eq become type constructors with kind * -> Constraint; you apply it to a type like Eq Bool to produce a Constraint. The advantage is now we can use all of the language features for manipulating type-level entities to manipulate constraints (including PolyKinds!).

DataKinds adds the ability to create new user-defined kinds containing new type-level things, in exactly the same way that in vanilla Haskell we can create new user-defined types containing new term-level things. (Exactly the same way; the way DataKinds actually works is that it lets you use a data declaration as normal and then you can use the resulting type constructor at either the type or the kind level)

There are also kinds used for unboxed/unlifted types, which must not be ever mixed with "normal" Haskell types because they have a different memory layout; they can't contain thunks to implement lazy evaluation, so the runtime has to know never to try to "enter" them as a code pointer, or look for additional header bits, etc. They need to be kept separate at the kind level so that ordinary type variables of kind * can't be instantiated with these unlifted/unboxed types (which would allow you to pass these types that need special handling to generic code that doesn't know to provide the special handling). I'm vaguely aware of this stuff but have never actually had to use it, so I won't add any more so I don't get anything wrong. (Anyone who knows what they're talking about enough to write a brief summary paragraph here, please feel free to edit the answer)

There are probably some others I'm forgetting. But certainly the kind language is richer than the OP is imagining just with the basic Haskell features, and there is much more to it once you turn on a few (quite widely used) extensions.

Body:
Please forgive me if this question is dumb.

While reading about Haskell kinds, I notice a theme:

*
* -> *
* -> * -> *

I get the impression that kinds in Haskell ultimately boil down to how many asterisks there are. You might say that the kind of a type is really just the number of types you need to apply to it before it becomes *. In other words, you could count all *'s but the last one, and define a type's kind by an integer. Say 0, 1, 2, etc.

Here's my question:

Is this a correct observation about Haskell's type system? Or does it allow something other than *'s to go where you typically see *'s? For example:

* -> a -> *

I imagine someone might want to do this to constrain type variables to have an instance of a type class, for example.

Functor a, Applicative b => * -> a -> b -> *

Is that a thing?


问:
Jackson xml (de)serialization with custom boolean format
I have xml file:

```<code><?xml version="1.0" encoding="UTF-8"?>
<ADDRESSOBJECTS>
    <OBJECT ID="1802267" NAME="SomeName" ISACTIVE="1" />
</ADDRESSOBJECTS>
</code>```

and correponding classes in kotlin:

```<code>@JacksonXmlRootElement(localName = "ADDRESSOBJECTS")
class AddressingObjectCollection {
    @JacksonXmlProperty(localName = "OBJECT")
    @JacksonXmlElementWrapper(useWrapping = false)
    open lateinit var objects: List<AddressingObject>
}
</code>```

and

```<code>class AddressingObject : Serializable {
    @JacksonXmlProperty(isAttribute = true, localName = "ID")
    open var id: Long = 0

    @JacksonXmlProperty(isAttribute = true, localName = "NAME")
    open lateinit var name: String

    @JacksonXmlProperty(isAttribute = true, localName = "ISACTIVE")
    open var isActive: Boolean = false
}
</code>```

when I try to deserialize I get error:

```<code>val deserialized = mapper.readValue(File(file).readText(), AddressingObjectCollection::class.java)
</code>```

error:

```<code>Cannot deserialize value of type `boolean` from String "1": only "true"/"True"/"TRUE" or "false"/"False"/"FALSE" recognized
</code>```

How to tell jackson to (de)serialize this format properly?

答:
For this purpose I use Json attributes:

```<code>@JsonProperty("ISACTIVE")
@JacksonXmlProperty(isAttribute = true, localName = "ISACTIVE")
@JsonDeserialize(using = CustomBooleanDeserializer::class)
open var isActive: Boolean = false
</code>```

And CustomBooleanDeserializer:

```<code>class CustomBooleanDeserializer : JsonDeserializer<Boolean>() {
    override fun deserialize(p: JsonParser?, ctxt: DeserializationContext?): Boolean {
        if (p?.currentTokenId() == JsonTokenId.ID_STRING){
            var text = p.text

            if (text == "1") return true
        }

        return false;
    }
}
</code>```

It works for me.

Body:
I have xml file:

<?xml version="1.0" encoding="UTF-8"?>
<ADDRESSOBJECTS>
    <OBJECT ID="1802267" NAME="SomeName" ISACTIVE="1" />
</ADDRESSOBJECTS>

and correponding classes in kotlin:

@JacksonXmlRootElement(localName = "ADDRESSOBJECTS")
class AddressingObjectCollection {
    @JacksonXmlProperty(localName = "OBJECT")
    @JacksonXmlElementWrapper(useWrapping = false)
    open lateinit var objects: List<AddressingObject>
}

and

class AddressingObject : Serializable {
    @JacksonXmlProperty(isAttribute = true, localName = "ID")
    open var id: Long = 0

    @JacksonXmlProperty(isAttribute = true, localName = "NAME")
    open lateinit var name: String

    @JacksonXmlProperty(isAttribute = true, localName = "ISACTIVE")
    open var isActive: Boolean = false
}

when I try to deserialize I get error:

val deserialized = mapper.readValue(File(file).readText(), AddressingObjectCollection::class.java)

error:

Cannot deserialize value of type `boolean` from String "1": only "true"/"True"/"TRUE" or "false"/"False"/"FALSE" recognized

How to tell jackson to (de)serialize this format properly?

Body:
For this purpose I use Json attributes:

@JsonProperty("ISACTIVE")
@JacksonXmlProperty(isAttribute = true, localName = "ISACTIVE")
@JsonDeserialize(using = CustomBooleanDeserializer::class)
open var isActive: Boolean = false

And CustomBooleanDeserializer:

class CustomBooleanDeserializer : JsonDeserializer<Boolean>() {
    override fun deserialize(p: JsonParser?, ctxt: DeserializationContext?): Boolean {
        if (p?.currentTokenId() == JsonTokenId.ID_STRING){
            var text = p.text

            if (text == "1") return true
        }

        return false;
    }
}

It works for me.


问:
How to take only the integer input from a Sentence?
I want to get the integers or float or double values from a sentence. As an example - "John has 20 balls, from which 4 are red and 5 are green balls". this will be my input . I want to get the numbers 20 , 4 , 5 from that line. how to do that in java . Please tell me if i can do that using Scanner. I don't want to use bufferedreader.</p>

答:
Use regex to match numbers and collect them from your input:

```<code>List<String> numbers = Pattern.compile("\\d+(\\.\\d+)?")
  .matcher(sentence)
  .results() // stream the MatchResults
  .map(MatchResult::group) // get the entire match
  .collect(Collectors.toList()); // collect as a List
</code>```

See live demo.

This works for integers and decimals.

Body:
Use regex to match numbers and collect them from your input:

List<String> numbers = Pattern.compile("\\d+(\\.\\d+)?")
  .matcher(sentence)
  .results() // stream the MatchResults
  .map(MatchResult::group) // get the entire match
  .collect(Collectors.toList()); // collect as a List

See live demo.

This works for integers and decimals.


问:
Maven clean compile does not work
I have maven-compiler-plugin in my pom file as follows but compiler get angry with generic parameters. my maven version is "Apache Maven 3.0.3 (r1075438; 2011-02-28 19:31:09+0200)"

```<code><plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>2.3.2</version>
    <configuration>
        <source>1.6</source>
        <target>1.6</target>
        <compilerVersion>1.6</compilerVersion>
    </configuration>
</plugin>
</code>```

and the class which compiler get angry is as follows

```<code>List<EulTransactionHistory> list = hibernateTemplate.findByCriteria(criteria, -1, 1);
EulTransactionHistory existingRecord = DBUtils.oneAndOnlyOne(list);
</code>```

and the spec for DBUtils.oneAndOnlyOne is as follows

```<code>public static <T> T oneAndOnlyOne(List<T> list) {...}
</code>```

finally the exception is

```<code>Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:2.3.2:compile (default-compile) on project etlscheduler: Compilation failure: Compilation failure SchedulerDaoImpl.java:[329,18] incompatible types
found   : java.lang.Object
required: com.aric.etlscheduler.domain.EulTransactionHistory
</code>```

Moreover when I compile this project with eclipse it compiles sucessfully.

答:
Is DBUtils in a different project, and did you at one time have a DBUtils.oneAndOnlyOne() that returned an Object?  If so, you need to do a Maven install on that project.

Maven uses the last-installed jar, while Eclipse, assuming you set it up in the usual way, is snooping directly into the other project.

Title: Maven clean compile does not work

Body:
I have maven-compiler-plugin in my pom file as follows but compiler get angry with generic parameters. my maven version is "Apache Maven 3.0.3 (r1075438; 2011-02-28 19:31:09+0200)"

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>2.3.2</version>
    <configuration>
        <source>1.6</source>
        <target>1.6</target>
        <compilerVersion>1.6</compilerVersion>
    </configuration>
</plugin>

and the class which compiler get angry is as follows

List<EulTransactionHistory> list = hibernateTemplate.findByCriteria(criteria, -1, 1);
EulTransactionHistory existingRecord = DBUtils.oneAndOnlyOne(list);

and the spec for DBUtils.oneAndOnlyOne is as follows

public static <T> T oneAndOnlyOne(List<T> list) {...}

finally the exception is

Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:2.3.2:compile (default-compile) on project etlscheduler: Compilation failure: Compilation failure SchedulerDaoImpl.java:[329,18] incompatible types
found   : java.lang.Object
required: com.aric.etlscheduler.domain.EulTransactionHistory

Moreover when I compile this project with eclipse it compiles sucessfully.


问:
Robocopy only copy folders modified in last 7 days
I'm trying to create a robocopy program that runs every Sunday and pulls in the last 7 days of folders(and its sub-folders) .this is because the folder stores years' worth of data so I only want to pull in the new folders.
is there a way to do this? I've been playing around with the max/min age but its pulling in all folders

what i have so far:

```<code>robocopy \\myserver\test\main_folder \\myserver\test\main_folder_archive /MIR
</code>```

I want to run this every Sunday and it is smart enough to pull in the last 7 days.

Any help is appreciated, thanks

答:
robocopy \server\source_share \server\dest_share /MAXAGE:7 /S /E

Should do it. This is not compatible with /MIR though:

/MIR :: Mirror a complete directory tree.

So either mirror, or select 7 days worth of files.

Edit: added /S, which is what I think was the desired switch instead of /MIR

Body:
I'm trying to create a robocopy program that runs every Sunday and pulls in the last 7 days of folders(and its sub-folders) .this is because the folder stores years' worth of data so I only want to pull in the new folders.
is there a way to do this? I've been playing around with the max/min age but its pulling in all folders

what i have so far:

robocopy \\myserver\test\main_folder \\myserver\test\main_folder_archive /MIR

I want to run this every Sunday and it is smart enough to pull in the last 7 days.

Any help is appreciated, thanks


答:
If your only purpose is to get the total value of all subscriptions, you don't need an array. just call the function below every time a new subscription is added (call it inside addAbo).

// this will select all the `div` items with the class `.abo-price`
const subscriptionEls = document.querySelectorAll('.abo-price');

function calculateTotal() {
  let total = 0;

  // loop through each '.abo-price' element
  subscriptionEls.forEach((el) => {
    const textValue = el.innerText; // '12,49' (string)
    const numericValue = parseInt(textValue); // 12,49 (number)
    total += numericValue; // add each numerical value to the total
  })

  montantTotal.innerText = total;
}
```

Title: How can I store divs content into an array?

Body:
Hello this is my first post, i have been learning javascript for a week.
I want to make a little app that calculate how much do you spend on subscription per month.

You can add a new subscription with the name and the subscription price with two inputs --> and it creates 2 new div(one is subscriptionName the other is subscriptionPrice) they are store into a new div (newSubscription).

Now i would like to store all the subscriptionPrice var into an array and addition all of them.
(is it the right logic to apply ? maybe im wrong).

I also thought about doing the addition of the :

.abo-list > .abo:nth-child(1) > .abo-price

.abo-list > .abo:nth-child(1+1) > .abo-price

...

I have tried with this technic but the consol do not show even the first oneAboPrice.

 var pricesValues = [];
for (var i = 0; i < oneAboPrice.length; i++) {
    pricesValues.push(oneAboPrice[i].textContent);
}
console.log(pricesValues); /*dont show the values of every oneAboPrice*/

//Selectors
const nameInput = document.querySelector('.name');
const price = document.querySelector('.price');
const validate = document.querySelector('.validate');
const abosList = document.querySelector('.abo-list');
const montantTotal = document.querySelector('.montant-total');

//event listeners

validate.addEventListener('click', addAbo);
abosList.addEventListener('click', clickModify);

//functions
function addAbo(event){
    event.preventDefault();
    //creating the NewAbo DIV
    const Abodiv = document.createElement('div');
    Abodiv.classList.add('abo');
    //creating a LI
    const newAbo = document.createElement('li');
    newAbo.innerText = nameInput.value + ' ' ;
    newAbo.classList.add('abo-item');
    Abodiv.appendChild(newAbo);
    //creating a div Price of one Sub
    const oneAboPrice = document.createElement('div');
    oneAboPrice.classList.add('abo-price');
    oneAboPrice.innerText = price.value;
    Abodiv.appendChild(oneAboPrice);
    //modify button
    const modifyAbo = document.createElement('button');
    modifyAbo.innerHTML = '';
    modifyAbo.classList.add('modifyAbo');
    Abodiv.appendChild(modifyAbo);
    //trash button
    const trashAbo = document.createElement('button');
    trashAbo.innerHTML = '';
    trashAbo.classList.add("trashAbo");
    Abodiv.appendChild(trashAbo);
    //append to Abo-list
    abosList.appendChild(Abodiv);

    //total Amount of every newAboPrice

    //reset input value
    nameInput.value ="";
    price.value="";

    //store every .abo price (oneAboPrice)value into an array (this is where i need help)
    var pricesValues = [];
    for (var i = 0; i < oneAboPrice.length; i++) {
        pricesValues.push(oneAboPrice[i].textContent);
    }
    console.log(pricesValues); /*dont show the values of every oneAboPrice*/

    montantTotal.innerHTML = parseFloat(oneAboPrice.textContent); /* + oneAboPrice nth:child(2) + ....*/
}

function clickModify(e) {
    const item = e.target;
    //Delete newAbo
    if(item.classList[0] === "trashAbo"){
        const abo = item.parentElement;
    abo.remove();
    }
    //modify newAbo (To do)

}

@import url('https://fonts.googleapis.com/css2?family=Bebas+Neue&family=Poppins&family=Saira+Extra+Condensed:wght@500&display=swap');
*{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

.content-container{
    display: flex;
    justify-content: space-around;
}

.abo{
    display: flex;
    justify-content: space-between;
    list-style-type: none;
}

.abo li{
    flex: 1;
}
.fa-trash{
    pointer-events: none;
}

.abo-price{
    background: red;
}

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" integrity="sha512-9usAa10IRO0HhonpyAIVpjrylPvoDwiPUiKdWk5t3PyolY1cOd4DSE0Ga+ri4AuTroPR5aQvXU9xC6qOPnzFeg==" crossorigin="anonymous" referrerpolicy="no-referrer" />
    <link rel="stylesheet" href="style.css">
    <title>Gestionnaire d'abonnements</title>

Nom de l'abonnement
<input type="text"  class="name" placeholder="netflix">

Prix mensuel
<input type="number" class="price" placeholder="13,49">
            <input type="button" value="Valide" class="validate">

MES ABOS


问:
How to check if a variable is a typed array in javascript?
I'm working on a game and we make extensive use of typed arrays (Float32Arrays) for our math types. We save and load the gamestate from JSON. An example of JSON stringify output is for such an array (in Chrome) is:

```<code>"{"0":0,"1":0,"2":0,"length":3,"byteLength":12,"byteOffset":0,"buffer":{"byteLength":12}}"
</code>```

This wastes space and causes them to be loaded as objects which is inconvenient. Ideally we could use the stringify 'replacer' function to test if a variable is a typed array, and then convert it to a bog standard array in that case. Unfortunately I'm not sure how to reliably test whether a variable is a typed array or not.

Any help?

答:
Simple way to actually find all constructors that return a TypedArray:

```<code>isTypedArray = _ => _?.prototype?.__proto__?.constructor?.name == "TypedArray";
for (const key of Object.getOwnPropertyNames(window)) {
  const obj = window[key];
  if (isTypedArray(obj)) {
    console.log(key, "is a TypedArray");
  }
}
</code>```

Output in current Chrome:

```<code>Uint8Array is a TypedArray
Int8Array is a TypedArray
Uint16Array is a TypedArray
Int16Array is a TypedArray
Uint32Array is a TypedArray
Int32Array is a TypedArray
Float32Array is a TypedArray
Float64Array is a TypedArray
Uint8ClampedArray is a TypedArray
BigUint64Array is a TypedArray
BigInt64Array is a TypedArray
</code>```

Body:
I'm working on a game and we make extensive use of typed arrays (Float32Arrays) for our math types. We save and load the gamestate from JSON. An example of JSON stringify output is for such an array (in Chrome) is:

"{"0":0,"1":0,"2":0,"length":3,"byteLength":12,"byteOffset":0,"buffer":{"byteLength":12}}"

This wastes space and causes them to be loaded as objects which is inconvenient. Ideally we could use the stringify 'replacer' function to test if a variable is a typed array, and then convert it to a bog standard array in that case. Unfortunately I'm not sure how to reliably test whether a variable is a typed array or not.

Any help?

Body:
Simple way to actually find all constructors that return a TypedArray:

isTypedArray = _ => _?.prototype?.__proto__?.constructor?.name == "TypedArray";
for (const key of Object.getOwnPropertyNames(window)) {
  const obj = window[key];
  if (isTypedArray(obj)) {
    console.log(key, "is a TypedArray");
  }
}

Output in current Chrome:

Uint8Array is a TypedArray
Int8Array is a TypedArray
Uint16Array is a TypedArray
Int16Array is a TypedArray
Uint32Array is a TypedArray
Int32Array is a TypedArray
Float32Array is a TypedArray
Float64Array is a TypedArray
Uint8ClampedArray is a TypedArray
BigUint64Array is a TypedArray
BigInt64Array is a TypedArray


问:
How does "template" and "include" differ in helm
How does "template" and "include" keywords differ in helm. Both seem to be used to render template parameters</p>

答:
template is part of the core Go text/template language.  It always renders its results to the template output; it does not produce a value and its result cannot be captured in a variable or included in a pipeline.

include is a Helm extension.  It captures the template output and returns it as a string.  Its result can be used the same way as any other support function call.  include is not a "keyword" or "action" or "special form", from the point of view of the templating language it is an ordinary extension function.

If you're unsure, in the context of a Helm chart, include is usually not wrong.

The most important place where this difference matters is where you have a block that produces a YAML fragment, and you need to indent it.  Helm includes an indent function that can do this, but it needs a string to do this, so you need to use include and not template here.

```<code>{{- define "foo.labels" -}}
foo: bar
{{ end -}}

metadata:
  labels:
{{ include "foo.labels" . | indent 4 }}
spec:
  template:
    metadata:
{{ include "foo.labels" . | indent 8 }}
</code>```

For a more direct example, consider a template that just quotes its parameter.  If you call this with template, the template pipeline syntax applies to the template parameter.  If you call it with include, it applies to the result of the template call.  Combining this with indent, there's a visible difference whether you see the indentation inside or outside the quotes.

{{ define "quote" }}{{ quote . }}{{ end }}

{{/* "hello" is indented, then "  hello" is quoted */}}
Template: {{ template "quote" "hello" | indent 2 }}

{{/* "hello" is quoted, then '"hello"' is indented */}}
Include:  {{ include "quote" "hello" | indent 2 }}
```
<pre class="lang-none prettyprint-override"><code>Template: "  hello"

Include:    "hello"
</code>```

Body:
template is part of the core Go text/template language.  It always renders its results to the template output; it does not produce a value and its result cannot be captured in a variable or included in a pipeline.

include is a Helm extension.  It captures the template output and returns it as a string.  Its result can be used the same way as any other support function call.  include is not a "keyword" or "action" or "special form", from the point of view of the templating language it is an ordinary extension function.

If you're unsure, in the context of a Helm chart, include is usually not wrong.

The most important place where this difference matters is where you have a block that produces a YAML fragment, and you need to indent it.  Helm includes an indent function that can do this, but it needs a string to do this, so you need to use include and not template here.

{{- define "foo.labels" -}}
foo: bar
{{ end -}}

metadata:
  labels:
{{ include "foo.labels" . | indent 4 }}
spec:
  template:
    metadata:
{{ include "foo.labels" . | indent 8 }}

For a more direct example, consider a template that just quotes its parameter.  If you call this with template, the template pipeline syntax applies to the template parameter.  If you call it with include, it applies to the result of the template call.  Combining this with indent, there's a visible difference whether you see the indentation inside or outside the quotes.

{{ define "quote" }}{{ quote . }}{{ end }}

{{/* "hello" is indented, then "  hello" is quoted */}}
Template: {{ template "quote" "hello" | indent 2 }}

{{/* "hello" is quoted, then '"hello"' is indented */}}
Include:  {{ include "quote" "hello" | indent 2 }}

Template: "  hello"

Include:    "hello"


问:
mp3 http streaming : recording and playing simultaneosly
I have a server (linux) program that generates audio files (mp3). What
I need is to broadcast these files using http stream. The tricky part
is that the broadcast starts when the file to be transmitted is not
fully generated.
I tried to do this using mpd+mpc but once I use the "mpc play" command
only already existing part of the file is buffered and transmitted,
and the player disregards the part that appears after beginning of
playback.
Is there any way to send a mp3 http stream (using mpd or any other
server-side player) so that the player won't stop the playback as it
reaches the end of the part that was buffered initially?
Any ideas, please.</p>

答:
http://streamripper.sourceforge.net/ can record and broadcast the same stream

shotcast(or icecast, dont remember) was designed especially for this, and could re-encode your stream on the fly


问:
What is the difference between set() and update() method in Svelte Store?
I'm new to Svelte Store. Here in svelte tutorial, they used update() method in <Incrementer/> and <Decrementer/> components to update value. But in <Resetter/>, they used set() method to reset value. What exactly is the difference between update() and set() method in svelte store?

答:
From the docs:

set is a method that takes one argument which is the value to be set. The store value gets set to the value of the argument if the store value is not already equal to it.

update is a method that takes one argument which is a callback. The callback takes the existing store value as its argument and returns the new value to be set to the store.

So you can use update if the next value should be dependent on the current value.

Also: update only exists for convenience and is not part of the "store contract":

A readable store only requires the subscribe method

A writable store requires the set method

Component code like $store = value uses set internally.


问:
how to calculate vowel occurance ratio in scala
I'm new to scala and I'm trying to the following exercise:

An English teacher hates sentences with excessive vowels and wants you to write a program that can grade millions of SAT essays by calculating the average number of vowels per sentence in the essay. For example, if the essay contains the following text:
able was I ere I saw elba
a man a plan a canal panama
the future is uncertain and the end is always near

then the essay gets a vowel score of 0.3701234567901235 since the vowel to character ratio in each sentence is: 0.4, 0.37037037037037035, 0.34. In this English teacher's world, characters include anything that is not a vowel (spaces, punctuation, etc.).

Write a function essay_grade that, for a given essay provided as an argument, calculates the vowel ratio and returns (1-the ratio) times 100 as the grade on the exam. The final grade should be returned as a truncated Int (62 for the example case). For the purposes of this problem, you must use both the map function as well as the reduce function and you can assume the text is in lower case (i.e., it should work for the example above)

For now, I can calculate the occurrence of each individual character, and I can also find the total length of the text, but I'm stuck with how to calculate the percentage of each character and then group them by vowels. Can anyone help me figure out how to the next steps? Thank you!

The following is what I've done:

```<code>val sample_essay = """able was i ere i saw elba
a man a plan a canal panama
the future is uncertain and the end is always near"""

// the following gives me the occurance of each char
sample_essay.toLowerCase.toArray
    .map(w=>(w,1))
    .groupBy(_._1) //map and group by category
    .map(w => (w._1,(w._2.map(_=>1).reduce(_+_)))) // sum up

//the following part give me the text length to be 140
sample_essay.toLowerCase.toArray
    .map(w=>(w,1))
    .groupBy(_._1) //map and group by category
    .map(w => (w._1,(w._2.map(_=>1).reduce(_+_)))) // sum up
    .map(_._2).reduce(_+_).toDouble

// I think for my next step, I should calculate the occurrence ratio of each character compared with the full text
// Then, I need to group by vowels and calculate the sum of the ratio of vowels
// but I'm stuck with how to do these steps...

</code>```

答:
```<code>scala> def essay_grade(text: String): Int = {
     |   val lines = text.linesIterator.map(_.trim).toArray
     |   val ratio = lines.map(line => line.count("aeiou".contains).toDouble / line.size)
     |   ((1 - ratio.reduce(_ + _) / ratio.size) * 100).toInt
     | }
def essay_grade(text: String): Int

scala> essay_grade(sample_essay)
val res0: Int = 62
</code>```

Body:
I'm new to scala and I'm trying to the following exercise:

An English teacher hates sentences with excessive vowels and wants you to write a program that can grade millions of SAT essays by calculating the average number of vowels per sentence in the essay. For example, if the essay contains the following text:
able was I ere I saw elba
a man a plan a canal panama
the future is uncertain and the end is always near

then the essay gets a vowel score of 0.3701234567901235 since the vowel to character ratio in each sentence is: 0.4, 0.37037037037037035, 0.34. In this English teacher's world, characters include anything that is not a vowel (spaces, punctuation, etc.).

Write a function essay_grade that, for a given essay provided as an argument, calculates the vowel ratio and returns (1-the ratio) times 100 as the grade on the exam. The final grade should be returned as a truncated Int (62 for the example case). For the purposes of this problem, you must use both the map function as well as the reduce function and you can assume the text is in lower case (i.e., it should work for the example above)

For now, I can calculate the occurrence of each individual character, and I can also find the total length of the text, but I'm stuck with how to calculate the percentage of each character and then group them by vowels. Can anyone help me figure out how to the next steps? Thank you!

The following is what I've done:

val sample_essay = """able was i ere i saw elba
a man a plan a canal panama
the future is uncertain and the end is always near"""

// the following gives me the occurance of each char
sample_essay.toLowerCase.toArray
    .map(w=>(w,1))
    .groupBy(_._1) //map and group by category
    .map(w => (w._1,(w._2.map(_=>1).reduce(_+_)))) // sum up

//the following part give me the text length to be 140
sample_essay.toLowerCase.toArray
    .map(w=>(w,1))
    .groupBy(_._1) //map and group by category
    .map(w => (w._1,(w._2.map(_=>1).reduce(_+_)))) // sum up
    .map(_._2).reduce(_+_).toDouble

// I think for my next step, I should calculate the occurrence ratio of each character compared with the full text
// Then, I need to group by vowels and calculate the sum of the ratio of vowels
// but I'm stuck with how to do these steps...


问:
I have this div with absolute positioning and another positioned div inside with width:100%. Why doesn't it fill up its parent?
I have a div that is as high as the window and about 4 times as wide (it is stretched horizontally by elements inside it).

And then this other
 inside it, which is supposed to be as wide width:100% as its parent (it's for a background picture).

However, the child
 is only as wide as the window and doesn't quite fill up its parent. This happens in all browsers I've tried.

Why is that, and how can I fix it ?

Source :

```<code><style>
.parent
{
width:100%;
height:100%;
overflow-x:scroll;
overflow-y:hidden;
position:absolute;
top:0;
left:0;
background-color:#999;
}

.child
{
width:100%;
height:200px;
position:absolute;
bottom:0;
left:0;
background-color:#000;
color:#fff;
}

.stretcher
{
width:10000px;
height:32px;
position:absolute;
}
</style>

<div class="parent">
  <div class="child">this should stretch as much as its parent !</div>
  <div class="stretcher">this is some content that defines the page's width</div>
</div>
</code>```

JSFiddle

答:
Maybe the outside
 should be positioned relative. The inside
 can be absolute but you may want to try adding right:0px; as well as left:0px which you already have. I would avoid absolute positioning unless there is no other way to do it.

Body:
I have a div that is as high as the window and about 4 times as wide (it is stretched horizontally by elements inside it).

And then this other
 inside it, which is supposed to be as wide width:100% as its parent (it's for a background picture).

However, the child
 is only as wide as the window and doesn't quite fill up its parent. This happens in all browsers I've tried.

Why is that, and how can I fix it ?

Source :

this should stretch as much as its parent !

this is some content that defines the page's width

JSFiddle

Body: Maybe the outside <div> should be positioned relative. The inside <div> can be absolute but you may want to try adding right:0px; as well as left:0px which you already have. I would avoid absolute positioning unless there is no other way to do it.


问:
DataFormat.Error: We couldn't convert to Number
Using Power Query, I'm trying to change the type of a column that has values such as this into decimal.

But I get the following error:

DataFormat.Error: We couldn't convert to Number.

This is when in my Advanced Options, the decimal separator seems to be . which is the one used in the column.

答:
Try adding an index, then add a custom column with formula

```<code>=Number.From([Amount])
</code>```

Filter that for errors and that will find you your problem data row

Body:
Try adding an index, then add a custom column with formula

=Number.From([Amount])

Filter that for errors and that will find you your problem data row


问:
Clustering using SOM
I have a data set consisting from 6-dimensional data points. I want to produce a self-organizing map for this data to see how my data is clustered and how many different clusters are there in my dataset.
My dataset is UNLABELED. And all the examples that I came across are all labelled(iris dataset). I have used various python packages(minisom, sompy, susi) to implement SOM but I am unable to visualize and interpret those results.

I would request this community to help me with this and I would really appreciate if you can provide a link to good work on >3 dimensional data based on SOM-clustering with proper evaluation of results.

MORE INFO:::::::::::

Thanks. I was able to understand the UMATRIX. However, I am still struggling to cluster similar datapoints.

This is a sample of dataset:

```<code>A      B          C        D            E            F
1   0.000613    150386  20.279685   39400220.0  0.672270
1   0.000649    154428  21.069894   8444300.0   0.466464
1   0.000276    154017  20.890017   12361590.0  0.399357
1   0.000186    68675   20.419599   13973180.0  0.430975
1   0.000177    60795   23.276564   5686630.0   0.372155
</code>```

This is the result of the of the SOM clustering :

```<code>A      B             C      D          E       F      Cluster-id
5   1.096415e-07    274 12.599589   4870.0  0.000060    19
5   1.185185e-07    205 12.108413   10000.0 0.000402    19
5   1.131892e-07    221 12.282051   290.0   0.000014    19
5   1.447471e-07    338 12.708078   1750.0  0.000027    19
5   8.218939e-08    244 12.000000   30.0    0.000027    19
   ...  ... ... ... ... ... ... ... ...
5   2.425165e-08    26  12.517500   2020.0  0.000025    19
5   2.926305e-08    51  12.051724   2320.0  0.000012    19
5   2.326685e-08    18  11.724138   290.0   0.000009    19
5   2.465502e-08    18  12.288000   2500.0  0.000018    19
5   5.118597e-08    80  11.776271   2950.0  0.000093    19
</code>```

If you look at the above result attribute C and attribute E are varying significantly as compared to other attributes even though they belong to the same cluster
What is the plausible reason behind this?

and How can I solve this with the aim to have a cluster with similar data points?????(FYI: I did standard scaling on the dataset to equalize the variance of each attribute)

答:
With susi, this works like the following (taken from susi/SOMClustering.ipynb):

```<code>import susi
som = susi.SOMClustering()
som.fit(X) # <- X is your dataset without labels

# to get the clusters
clusters = som.get_clusters(X)

# to plot the clusters
plt.scatter(x=[c[1] for c in clusters], y=[c[0] for c in clusters], c=y, alpha=0.2)
plt.gca().invert_yaxis()
plt.show()
</code>```

Does that work for you? If not, please give us more information about your data.

Disclaimer: I am the developer of susi.

Title: Clustering using SOM

Body:
I have a data set consisting from 6-dimensional data points. I want to produce a self-organizing map for this data to see how my data is clustered and how many different clusters are there in my dataset.
My dataset is UNLABELED. And all the examples that I came across are all labelled(iris dataset). I have used various python packages(minisom, sompy, susi) to implement SOM but I am unable to visualize and interpret those results.

I would request this community to help me with this and I would really appreciate if you can provide a link to good work on >3 dimensional data based on SOM-clustering with proper evaluation of results.

MORE INFO:::::::::::

Thanks. I was able to understand the UMATRIX. However, I am still struggling to cluster similar datapoints.

This is a sample of dataset:

A      B          C        D            E            F
1   0.000613    150386  20.279685   39400220.0  0.672270
1   0.000649    154428  21.069894   8444300.0   0.466464
1   0.000276    154017  20.890017   12361590.0  0.399357
1   0.000186    68675   20.419599   13973180.0  0.430975
1   0.000177    60795   23.276564   5686630.0   0.372155

This is the result of the of the SOM clustering :

A      B             C      D          E       F      Cluster-id
5   1.096415e-07    274 12.599589   4870.0  0.000060    19
5   1.185185e-07    205 12.108413   10000.0 0.000402    19
5   1.131892e-07    221 12.282051   290.0   0.000014    19
5   1.447471e-07    338 12.708078   1750.0  0.000027    19
5   8.218939e-08    244 12.000000   30.0    0.000027    19
   ...  ... ... ... ... ... ... ... ...
5   2.425165e-08    26  12.517500   2020.0  0.000025    19
5   2.926305e-08    51  12.051724   2320.0  0.000012    19
5   2.326685e-08    18  11.724138   290.0   0.000009    19
5   2.465502e-08    18  12.288000   2500.0  0.000018    19
5   5.118597e-08    80  11.776271   2950.0  0.000093    19

If you look at the above result attribute C and attribute E are varying significantly as compared to other attributes even though they belong to the same cluster
What is the plausible reason behind this?

and How can I solve this with the aim to have a cluster with similar data points?????(FYI: I did standard scaling on the dataset to equalize the variance of each attribute)

Body:
With susi, this works like the following (taken from susi/SOMClustering.ipynb):

import susi
som = susi.SOMClustering()
som.fit(X) # <- X is your dataset without labels

# to get the clusters
clusters = som.get_clusters(X)

# to plot the clusters
plt.scatter(x=[c[1] for c in clusters], y=[c[0] for c in clusters], c=y, alpha=0.2)
plt.gca().invert_yaxis()
plt.show()

Does that work for you? If not, please give us more information about your data.

Disclaimer: I am the developer of susi.


问:
How to join multiple distinct rows in one column
I have 3 tables

Restaurants table:

restaurant_id
restaurant_name

1
Burger King

2
Coffee shop

Foods table:

food_id
food_title
category_id
restaurant_id

1
Burger with cheese
1
1

2
Beef Burger
2
1

3
Beef Burger with cheese
2
1

4
Iced Coffee
3
2

5
Dark Coffee
3
2

5
Green Tea
4
2

Categories table:

category_id
category_title

1
Normal Burger

2
Beef Burger

3
Coffee

4
Tea

The output I'm looking for:

restaurant_id
restaurant_name
categories_list

1
Burger King
[{category_id: 1, category_title: 'Normal Burger'}, {category_id: 2, category_title: 'Beef Burger'}]

2
Coffee shop
[{category_id: 3, category_title: 'Coffee'}, {category_id: 4, category_title: 'Tea'}]

答:
Join Restaurants to Foods and Categories with LEFT joins and group by restaurant.

Then use JSON_ARRAYAGG() aggregate function to get the lists:

```<code>SELECT r.restaurant_id, r.restaurant_name,
       JSON_ARRAYAGG(JSON_OBJECT('category_id', c.category_id, 'category_title', c.category_title)) categories_list
FROM Restaurants r
LEFT JOIN (SELECT DISTINCT category_id, restaurant_id FROM Foods) f ON f.restaurant_id = r.restaurant_id
LEFT JOIN Categories c ON c.category_id = f.category_id
GROUP BY r.restaurant_id, r.restaurant_name;
</code>```

I use SELECT DISTINCT ... in the table Foods because I see in your expected results that you want distinct categories in each list.

See the demo.

Body:
Join Restaurants to Foods and Categories with LEFT joins and group by restaurant.

Then use JSON_ARRAYAGG() aggregate function to get the lists:

SELECT r.restaurant_id, r.restaurant_name,
       JSON_ARRAYAGG(JSON_OBJECT('category_id', c.category_id, 'category_title', c.category_title)) categories_list
FROM Restaurants r
LEFT JOIN (SELECT DISTINCT category_id, restaurant_id FROM Foods) f ON f.restaurant_id = r.restaurant_id
LEFT JOIN Categories c ON c.category_id = f.category_id
GROUP BY r.restaurant_id, r.restaurant_name;

I use SELECT DISTINCT ... in the table Foods because I see in your expected results that you want distinct categories in each list.

See the demo.


问:
How to return multiple ID’s from a function
I need to return ID’s of a table from a function based on input.

Create or replace function f(v_input nvarchar)
Return v_table
Is
  Select id bulk collect into v_table from table1 where user=v_input ;
  Return v_table
End;
```
<p>And this function will be called in sql queries like</p>
```Select * from table2 where id in (f(abc));
```

This is the concept.

How can we do this programmatically in oracle? How to return multiple record id’s from a function?

答:
You need:

a BEGIN keyword between IS and the start of the main block.

a declaration for a variable to BULK COLLECT INTO between IS and BEGIN.

the return type to be a type not the name of a variable.

a semi-colon to terminate the reutrn statement.

NVARCHAR should be NVARCHAR2.

USER is a reserved word and you should not use this for a column name; if you do it must be as a quoted identifier.

Like this:

Create or replace function f(v_input nvarchar2)
Return t_table
Is
  v_table t_table;
BEGIN
  Select id bulk collect into v_table from table1 where "USER"=v_input ;
  Return v_table;
End;
/
```
<p>Then, if you have created these:</p>
<pre class="lang-sql prettyprint-override"><code>CREATE TYPE t_table IS TABLE OF INTEGER;

CREATE TABLE table1 (id INTEGER, "USER" NVARCHAR2(20));

INSERT INTO table1 (id, "USER")
SELECT 1, N'user1' FROM DUAL UNION ALL
SELECT 2, N'user1' FROM DUAL UNION ALL
SELECT 2, N'user2' FROM DUAL UNION ALL
SELECT 3, N'user3' FROM DUAL;

CREATE TABLE table2 (id) AS
SELECT LEVEL FROM DUAL CONNECT BY LEVEL <= 5;
</code>```

Then:

Select * from table2 where id MEMBER OF f('user1');
```
<p>or</p>
<pre class="lang-sql prettyprint-override"><code>Select * from table2 where id IN (SELECT COLUMN_VALUE FROM TABLE(f('user1')));
</code>```

Outputs:

ID

1

2

db<>fiddle here

Body:
I need to return ID’s of a table from a function based on input.

Create or replace function f(v_input nvarchar)
Return v_table
Is
  Select id bulk collect into v_table from table1 where user=v_input ;
  Return v_table
End;

And this function will be called in sql queries like

Select * from table2 where id in (f(abc));

This is the concept.

How can we do this programmatically in oracle? How to return multiple record id’s from a function?

Body:
You need:

a BEGIN keyword between IS and the start of the main block.

a declaration for a variable to BULK COLLECT INTO between IS and BEGIN.

the return type to be a type not the name of a variable.

a semi-colon to terminate the reutrn statement.

NVARCHAR should be NVARCHAR2.

USER is a reserved word and you should not use this for a column name; if you do it must be as a quoted identifier.

Like this:

Create or replace function f(v_input nvarchar2)
Return t_table
Is
  v_table t_table;
BEGIN
  Select id bulk collect into v_table from table1 where "USER"=v_input ;
  Return v_table;
End;
/

Then, if you have created these:

CREATE TYPE t_table IS TABLE OF INTEGER;

CREATE TABLE table1 (id INTEGER, "USER" NVARCHAR2(20));

INSERT INTO table1 (id, "USER")
SELECT 1, N'user1' FROM DUAL UNION ALL
SELECT 2, N'user1' FROM DUAL UNION ALL
SELECT 2, N'user2' FROM DUAL UNION ALL
SELECT 3, N'user3' FROM DUAL;

CREATE TABLE table2 (id) AS
SELECT LEVEL FROM DUAL CONNECT BY LEVEL <= 5;

Then:

Select * from table2 where id MEMBER OF f('user1');

or

Select * from table2 where id IN (SELECT COLUMN_VALUE FROM TABLE(f('user1')));

Outputs:

ID

1

2

db<>fiddle here


问:
How to detect Rails environment inside whenever
This question will probably only make sense if you know about the whenever gem for creating cron jobs.

For my app, I want to use whenever in all the environments, including testing and development.

My schedule.rb looks like this:

```<code>set :output, {
    :error    => "#{path}/log/error.log",
    :standard => "#{path}/log/cron.log"
}

set :environment, Rails.env.to_sym
every 5.minutes do
  rake 'db:activity:synchronize'
end
</code>```

but it fails on Rails.env.to_sym (and the same stands for RAILS_ENV):

```<code>/home/marius/.rvm/gems/ruby-1.9.2-p290@uxolo/gems/whenever-0.6.8/lib/whenever/job_list.rb:21:in `eval': uninitialized constant Whenever::JobList::Rails (NameError)
    from /home/marius/.rvm/gems/ruby-1.9.2-p290@uxolo/gems/whenever-0.6.8/lib/whenever/job_list.rb:21:in `eval'
    from /home/marius/.rvm/gems/ruby-1.9.2-p290@uxolo/gems/whenever-0.6.8/lib/whenever/job_list.rb:21:in `initialize'
    from /home/marius/.rvm/gems/ruby-1.9.2-p290@uxolo/gems/whenever-0.6.8/lib/whenever.rb:15:in `new'
    from /home/marius/.rvm/gems/ruby-1.9.2-p290@uxolo/gems/whenever-0.6.8/lib/whenever.rb:15:in `cron'
    from /home/marius/.rvm/gems/ruby-1.9.2-p290@uxolo/gems/whenever-0.6.8/lib/whenever/command_line.rb:41:in `run'
    from /home/marius/.rvm/gems/ruby-1.9.2-p290@uxolo/gems/whenever-0.6.8/lib/whenever/command_line.rb:8:in `execute'
    from /home/marius/.rvm/gems/ruby-1.9.2-p290@uxolo/gems/whenever-0.6.8/bin/whenever:38:in `<top (required)>'
    from /home/marius/.rvm/gems/ruby-1.9.2-p290@uxolo/bin/whenever:19:in `load'
    from /home/marius/.rvm/gems/ruby-1.9.2-p290@uxolo/bin/whenever:19:in `<main>'
</code>```

So, my question basically boils down to:

How do I access the current environment, or

What should I do to use whenever in all the environments?

答:
As recommended by the gem author, the solution is to pass in the current environment as a variable:

```$ whenever --set environment=test
0,5,10,15,20,25,30,35,40,45,50,55 * * * * /bin/bash -l -c 'cd /home/marius/uxolo && RAILS_ENV=test rake db:activity:synchronize --silent >> /home/marius/uxolo/log/cron.log 2>> /home/marius/uxolo/log/error.log'

$ whenever --set environment=development
0,5,10,15,20,25,30,35,40,45,50,55 * * * * /bin/bash -l -c 'cd /home/marius/uxolo && RAILS_ENV=development rake db:activity:synchronize --silent >> /home/marius/uxolo/log/cron.log 2>> /home/marius/uxolo/log/error.log'
```

And Chris Bailey is right: Whenever itself doesn't load the Rails environment.

Body:
This question will probably only make sense if you know about the whenever gem for creating cron jobs.

For my app, I want to use whenever in all the environments, including testing and development.

My schedule.rb looks like this:

set :output, {
    :error    => "#{path}/log/error.log",
    :standard => "#{path}/log/cron.log"
}

set :environment, Rails.env.to_sym
every 5.minutes do
  rake 'db:activity:synchronize'
end

but it fails on Rails.env.to_sym (and the same stands for RAILS_ENV):

/home/marius/.rvm/gems/ruby-1.9.2-p290@uxolo/gems/whenever-0.6.8/lib/whenever/job_list.rb:21:in `eval': uninitialized constant Whenever::JobList::Rails (NameError)
    from /home/marius/.rvm/gems/ruby-1.9.2-p290@uxolo/gems/whenever-0.6.8/lib/whenever/job_list.rb:21:in `eval'
    from /home/marius/.rvm/gems/ruby-1.9.2-p290@uxolo/gems/whenever-0.6.8/lib/whenever/job_list.rb:21:in `initialize'
    from /home/marius/.rvm/gems/ruby-1.9.2-p290@uxolo/gems/whenever-0.6.8/lib/whenever.rb:15:in `new'
    from /home/marius/.rvm/gems/ruby-1.9.2-p290@uxolo/gems/whenever-0.6.8/lib/whenever.rb:15:in `cron'
    from /home/marius/.rvm/gems/ruby-1.9.2-p290@uxolo/gems/whenever-0.6.8/lib/whenever/command_line.rb:41:in `run'
    from /home/marius/.rvm/gems/ruby-1.9.2-p290@uxolo/gems/whenever-0.6.8/lib/whenever/command_line.rb:8:in `execute'
    from /home/marius/.rvm/gems/ruby-1.9.2-p290@uxolo/gems/whenever-0.6.8/bin/whenever:38:in `<top (required)>'
    from /home/marius/.rvm/gems/ruby-1.9.2-p290@uxolo/bin/whenever:19:in `load'
    from /home/marius/.rvm/gems/ruby-1.9.2-p290@uxolo/bin/whenever:19:in `'

So, my question basically boils down to:

How do I access the current environment, or

What should I do to use whenever in all the environments?

Body:
As recommended by the gem author, the solution is to pass in the current environment as a variable:

$ whenever --set environment=test
0,5,10,15,20,25,30,35,40,45,50,55 * * * * /bin/bash -l -c 'cd /home/marius/uxolo && RAILS_ENV=test rake db:activity:synchronize --silent >> /home/marius/uxolo/log/cron.log 2>> /home/marius/uxolo/log/error.log'

$ whenever --set environment=development
0,5,10,15,20,25,30,35,40,45,50,55 * * * * /bin/bash -l -c 'cd /home/marius/uxolo && RAILS_ENV=development rake db:activity:synchronize --silent >> /home/marius/uxolo/log/cron.log 2>> /home/marius/uxolo/log/error.log'

And Chris Bailey is right: Whenever itself doesn't load the Rails environment.