问:
Python Textacy pos_regex_matches vs matches
I'm trying to find verbs in a sentence with python for a NLP problem. I found an old answer here on stackoverflow and it works with the deprecated pos_regex_matches. Using the new matches function I have a pretty boring problem. The new function returns any match and not only the longest match (which pos_regex_matches does).

```<code>pattern = r'<VERB>*<ADV>*<VERB>+<PART>*'
verb_pattern = [{"POS": "VERB", "OP": "*"},{"POS": "ADV", "OP": "*"},{"POS": "VERB", "OP": "+"},{"POS": "PART", "OP": "*"}]

t_list_1 = textacy.extract.pos_regex_matches(text, pattern)
t_list_2 = textacy.extract.matches(text, verb_pattern)
</code>```

As you can see the pattern is the same, but the matches function's one is in the new format.
The old pos_regex_matches returns, for example, was celebrating while the new matches returns both was and was celebrating.
Does someone has encountered the same problem? Is a pattern problem or a textacy problem?

Thanks in advance

答:
I have had the same issue. A quick solution maybe is the filter_spans from spacy utilities.

Specifically, I am posting below a try to fix your example.

```<code>from spacy.util import filter_spans

t_list_2 = filter_spans(t_list_2)
</code>```

I hope it will help you.

Body:
I'm trying to find verbs in a sentence with python for a NLP problem. I found an old answer here on stackoverflow and it works with the deprecated pos_regex_matches. Using the new matches function I have a pretty boring problem. The new function returns any match and not only the longest match (which pos_regex_matches does).

pattern = r'<VERB>*<ADV>*<VERB>+<PART>*'
verb_pattern = [{"POS": "VERB", "OP": "*"},{"POS": "ADV", "OP": "*"},{"POS": "VERB", "OP": "+"},{"POS": "PART", "OP": "*"}]

t_list_1 = textacy.extract.pos_regex_matches(text, pattern)
t_list_2 = textacy.extract.matches(text, verb_pattern)

As you can see the pattern is the same, but the matches function's one is in the new format.
The old pos_regex_matches returns, for example, was celebrating while the new matches returns both was and was celebrating.
Does someone has encountered the same problem? Is a pattern problem or a textacy problem?

Thanks in advance

Body:
I have had the same issue. A quick solution maybe is the filter_spans from spacy utilities.

Specifically, I am posting below a try to fix your example.

from spacy.util import filter_spans

t_list_2 = filter_spans(t_list_2)

I hope it will help you.


来源: stackexchange

问:
Dataframe recursively calculate values with conditions [complicated logic]
It seems like I cannot solve this on my own even though I already tried hard so I would like to seek your support in this matter. Thanks and appreciated in advance for your help.

Input Pandas dataframe:

```<code>day   a
1     1000
2     0
3     0
4     -1200
5     0
6     0
7     -50
8     0
9     0
10    0
11    -150
</code>```

Output:

```<code>day   a     b    c   d
1     1000  1000 100 100
2     0     1000 100 200
3     0     1000 100 300
4     -1200 100  10  10
5     0     100  10  20
6     0     100  10  30
7     -50   50   5   35
8     0     50   5   40
9     0     50   5   45
10    0     50   5   50
11    -100  -50  0   0
</code>```

Explain:

a is daily amount.

b is accumulated sum of a, but with a condition, explained below.

c = b * 10%

d = accumulated sum of c

The problem here is the logic for column B. At the day when there is a minus amount in column a:

if a + b(of previous day) + d(of previous day) is > 0, then b = the result, d = c (previous d already been added to b, so remove previous d);
e.g. line day = 4

if a + b(of previous day) > 0, then b = previous b + a; d = previous d + c ; e.g. line day = 7

if a + b(of previous day) + d(of previous day) <= 0, then c, d turn to 0; e.g. line day = 11

I have been stuck for days so your help is really appreciated! If there is any questions please let me know.

答:
This is way too complex to be achieved with vectorized methods. So IMHO, the best way is to forget Pandas and simply process arrays. As in the end we use the results to feed the dataframe, I would use numpy arrays instead of plain lists. Code could be:

```<code># prepare the numpy arrays for the existing column and the new ones
A = df['a'].to_numpy()
B = np.ndarray(A.shape)
C = np.ndarray(A.shape)
D = np.ndarray(A.shape)

# initialize initial values of b, c and d to 0
b = c = d = 0

# loop over A and compute b, c, and d according to the requirements
for i, a in enumerate(A):
    if a + b > 0:
        b += a
        c = b // 10
        d += c
    elif a + b + d > 0:
        b += a + d
        c = b // 10
        d = c
    else:
        b += a
        c = d = 0
    # feed the arrays
    B[i], C[i], D[i] = b, c, d

# add the new columns to the DataFrame
df['B'] = B
df['C'] = C
df['D'] = D
</code>```

It gives as expected:

```<code>    day     a       B      C      D
0     1  1000  1000.0  100.0  100.0
1     2     0  1000.0  100.0  200.0
2     3     0  1000.0  100.0  300.0
3     4 -1200   100.0   10.0   10.0
4     5     0   100.0   10.0   20.0
5     6     0   100.0   10.0   30.0
6     7   -50    50.0    5.0   35.0
7     8     0    50.0    5.0   40.0
8     9     0    50.0    5.0   45.0
9    10     0    50.0    5.0   50.0
10   11  -100   -50.0    0.0    0.0
</code>```

ContentLicense: CC BY-SA 4.0

Body:
It seems like I cannot solve this on my own even though I already tried hard so I would like to seek your support in this matter. Thanks and appreciated in advance for your help.

Input Pandas dataframe:

day   a
1     1000
2     0
3     0
4     -1200
5     0
6     0
7     -50
8     0
9     0
10    0
11    -150

Output:

day   a     b    c   d
1     1000  1000 100 100
2     0     1000 100 200
3     0     1000 100 300
4     -1200 100  10  10
5     0     100  10  20
6     0     100  10  30
7     -50   50   5   35
8     0     50   5   40
9     0     50   5   45
10    0     50   5   50
11    -100  -50  0   0

Explain:

a is daily amount.

b is accumulated sum of a, but with a condition, explained below.

c = b * 10%

d = accumulated sum of c

The problem here is the logic for column B. At the day when there is a minus amount in column a:

if a + b(of previous day) + d(of previous day) is > 0, then b = the result, d = c (previous d already been added to b, so remove previous d);
e.g. line day = 4

if a + b(of previous day) > 0, then b = previous b + a; d = previous d + c ; e.g. line day = 7

if a + b(of previous day) + d(of previous day) <= 0, then c, d turn to 0; e.g. line day = 11

I have been stuck for days so your help is really appreciated! If there is any questions please let me know.

Body:
This is way too complex to be achieved with vectorized methods. So IMHO, the best way is to forget Pandas and simply process arrays. As in the end we use the results to feed the dataframe, I would use numpy arrays instead of plain lists. Code could be:

# prepare the numpy arrays for the existing column and the new ones
A = df['a'].to_numpy()
B = np.ndarray(A.shape)
C = np.ndarray(A.shape)
D = np.ndarray(A.shape)

# initialize initial values of b, c and d to 0
b = c = d = 0

# loop over A and compute b, c, and d according to the requirements
for i, a in enumerate(A):
    if a + b > 0:
        b += a
        c = b // 10
        d += c
    elif a + b + d > 0:
        b += a + d
        c = b // 10
        d = c
    else:
        b += a
        c = d = 0
    # feed the arrays
    B[i], C[i], D[i] = b, c, d

# add the new columns to the DataFrame
df['B'] = B
df['C'] = C
df['D'] = D

It gives as expected:

    day     a       B      C      D
0     1  1000  1000.0  100.0  100.0
1     2     0  1000.0  100.0  200.0
2     3     0  1000.0  100.0  300.0
3     4 -1200   100.0   10.0   10.0
4     5     0   100.0   10.0   20.0
5     6     0   100.0   10.0   30.0
6     7   -50    50.0    5.0   35.0
7     8     0    50.0    5.0   40.0
8     9     0    50.0    5.0   45.0
9    10     0    50.0    5.0   50.0
10   11  -100   -50.0    0.0    0.0


问:
Turn off display of header dashes in SQL Server Management Studio query results?
How can I tell SQL Server 2008 Management Studio to turn off printing of header dashes when displaying text results in a query window?

Examples of header dashes being produced are:

selectId, count(*) ContentCount from Table group by Id order by count(*) desc produces:

```<code>Id                   ContentCount
-------------------- ------------------
622                  5
623                  1
</code>```

select 'Person Info' produces:

```<code>------------
Person Info
</code>```

Those dashes are not conducive to all situations so I expect there is way to turn them off.

答:
this is an incorrect SQL statement.

set head off
set und off

ContentLicense: CC BY-SA 2.5

Body:
How can I tell SQL Server 2008 Management Studio to turn off printing of header dashes when displaying text results in a query window?

Examples of header dashes being produced are:

selectId, count(*) ContentCount from Table group by Id order by count(*) desc produces:

Id                   ContentCount
-------------------- ------------------
622                  5
623                  1

select 'Person Info' produces:

------------
Person Info

Those dashes are not conducive to all situations so I expect there is way to turn them off.


问:
unity (Android bild), i have problem "We can't assign a new GUID because the asset is in an immutable folder. The asset will be ignored."
I have unity 2019.3.7f1,
2 sided libraries:

```<code>GooglePlayGamesPlugin-0.10.08
GoogleMobileAds-v3.18.3
</code>```

(it also installed "latest External Dependency Manager for Unity")

And everything compiled perfectly on Android (apk)

I added a library Firebase 6.13.0 and got the following errors:

I read that you need to delete them and restart the project, it did not help, I also reinstalled all the libraries, it did not help.

Has anyone had similar problems? Please help solve it.

答:
Installing Unity Ads
To ensure the latest version of Unity Ads, download it through the Asset store, or through the Unity Package Manager in the Editor.

Important: You must choose either the Asset or the package. Installing both may lead to build errors.
source

Body:
I have unity 2019.3.7f1,
2 sided libraries:

GooglePlayGamesPlugin-0.10.08
GoogleMobileAds-v3.18.3

(it also installed "latest External Dependency Manager for Unity")

And everything compiled perfectly on Android (apk)

I added a library Firebase 6.13.0 and got the following errors:

I read that you need to delete them and restart the project, it did not help, I also reinstalled all the libraries, it did not help.

Has anyone had similar problems? Please help solve it.


问:
Error message from server side is not displaying in front end
When login gets failed in server side res.status(403).json({ fail: "Login failed" }); message from server side is passing into front end setHelperText(failMessage); How can i get the 'Login Failed' message in front end ?

It is displaying error in chrome console >> Error: Request failed with status code 403
    at createError (createError.js:16)
    at settle (settle.js:17)

server.js

```<code>app.post('/service/login', async (req, res) => {
  try {
    const userEmail = req.body.email;
    const userPassword = req.body.password;
    const loginData = await UserModel.findAll({ where: { email: userEmail} });
    const password = loginData[0].password;
    const email = loginData[0].email;
    if(password === userPassword && email === userEmail){
     const privilege  = loginData[0].privilege;
      res.status(200).json({ success: true, privilege, email });
    }else{
      res.status(403).json({ fail: "Login failed" });
    }
  } catch (e) {
    res.status(500).json({ message: e.message });
  }
});
</code>```

Login.js

```<code>const fetchData = async () => {
  try {
    const res = await axios.post('http://localhost:8000/service/login', { email , password });
    console.log("Front End success message:"+res.data.success);
    if(res.data.success){
      setHelperText("Login successfully");
      setValue(res.data.privilege);
      setError(true);
    }
    else{
      const failMessage = res.data.fail;
      setHelperText(failMessage);
    }
  } catch (e) {
    console.log(e);
  }
}
</code>```

答:
If the response is not success, (403 in your case), catch block will be executed, so move your logic inside the else block to catch block in the Login.js</p>

```<code>catch(e) {
const failMessage = e.response.data.fail;
setHelperText(failMessage);
// console.log(e.data.response); -> to print the server response
}
</code>```

Body:
When login gets failed in server side res.status(403).json({ fail: "Login failed" }); message from server side is passing into front end setHelperText(failMessage); How can i get the 'Login Failed' message in front end ?

It is displaying error in chrome console >> Error: Request failed with status code 403
    at createError (createError.js:16)
    at settle (settle.js:17)

server.js

app.post('/service/login', async (req, res) => {
  try {
    const userEmail = req.body.email;
    const userPassword = req.body.password;
    const loginData = await UserModel.findAll({ where: { email: userEmail} });
    const password = loginData[0].password;
    const email = loginData[0].email;
    if(password === userPassword && email === userEmail){
     const privilege  = loginData[0].privilege;
      res.status(200).json({ success: true, privilege, email });
    }else{
      res.status(403).json({ fail: "Login failed" });
    }
  } catch (e) {
    res.status(500).json({ message: e.message });
  }
});

Login.js

const fetchData = async () => {
  try {
    const res = await axios.post('http://localhost:8000/service/login', { email , password });
    console.log("Front End success message:"+res.data.success);
    if(res.data.success){
      setHelperText("Login successfully");
      setValue(res.data.privilege);
      setError(true);
    }
    else{
      const failMessage = res.data.fail;
      setHelperText(failMessage);
    }
  } catch (e) {
    console.log(e);
  }
}

Body:
If the response is not success, (403 in your case), catch block will be executed, so move your logic inside the else block to catch block in the Login.js

catch(e) {
const failMessage = e.response.data.fail;
setHelperText(failMessage);
// console.log(e.data.response); -> to print the server response
}


问:
How can I get Python to recognize comma as the decimal point in user input?
Super beginner here.

I'm following along the Automate the Boring Stuff With Python book and I decided to make a little script to help me out with some basic percentage checking. I didn't want to open Excel everytime I wanted to do this.

So the script gets two inputs, an old price and a new price and then calculates the percentage change in price. I think I got that right.

The problem occurs once I try to enter a float (that's the right term, yeah?) and I use the comma here in Europe.

I found a topic here where a similar question was answered, but there seems to be an issue on whether or not to call setlocale and (as far as I understand it) it does not deal with how to convert an input?

My code is below:

```<code>    def izracun_odstotkov():    #function to calculate the difference in % between original price and new price
    while True:
        try:
            prvotna_cena = float(input('Prosim vnesi prvotno ceno:')) #original price
        except ValueError:
            print('Oprosti, to ni veljavni podatek. Vnesi stevilko.')
            continue

        if prvotna_cena == 0:
                print('Prvotna cena ne more biti 0.')
        else:
            break

    while True:
        try:
            nova_cena = float(input('Prosim vnesi novo ceno:')) #new price
        except ValueError:
            print('Oprosti, to ni veljavni podatek. Vnesi stevilko.')
            continue
        else:
            break

    print(round((float (nova_cena)- float (prvotna_cena))/ float (prvotna_cena)*100, 2), '%')

while True:
    izracun_odstotkov() #This makes the script run over and over so the user can just keep checking the % changes.
</code>```

答:
You can use the replace method:</p>

```<code>prvotna_cena = float(input('Prosim vnesi prvotno ceno:').replace(',','.'))
</code>```

Body:
Super beginner here.

I'm following along the Automate the Boring Stuff With Python book and I decided to make a little script to help me out with some basic percentage checking. I didn't want to open Excel everytime I wanted to do this.

So the script gets two inputs, an old price and a new price and then calculates the percentage change in price. I think I got that right.

The problem occurs once I try to enter a float (that's the right term, yeah?) and I use the comma here in Europe.

I found a topic here where a similar question was answered, but there seems to be an issue on whether or not to call setlocale and (as far as I understand it) it does not deal with how to convert an input?

My code is below:

    def izracun_odstotkov():    #function to calculate the difference in % between original price and new price
    while True:
        try:
            prvotna_cena = float(input('Prosim vnesi prvotno ceno:')) #original price
        except ValueError:
            print('Oprosti, to ni veljavni podatek. Vnesi stevilko.')
            continue

        if prvotna_cena == 0:
                print('Prvotna cena ne more biti 0.')
        else:
            break

    while True:
        try:
            nova_cena = float(input('Prosim vnesi novo ceno:')) #new price
        except ValueError:
            print('Oprosti, to ni veljavni podatek. Vnesi stevilko.')
            continue
        else:
            break

    print(round((float (nova_cena)- float (prvotna_cena))/ float (prvotna_cena)*100, 2), '%')

while True:
    izracun_odstotkov() #This makes the script run over and over so the user can just keep checking the % changes.

Body:
You can use the replace method:

prvotna_cena = float(input('Prosim vnesi prvotno ceno:').replace(',','.'))


问:
In laravel, how can I echo out form results in json format, after submitting?
In laravel, how can I echo out form results in JSON format, after submitting; without saving to the database first? This is to check the data the form is holding.</p>

答:
assume you have already done form submit code with form. below one line code you can use in controller

```<code>public function store(Request $request)
{
   echo json_encode($request);
   // below you can store data after validation if need then
}
</code>```

if you are using a post method to submit a form then above one line code will you to echo form data as json format

you can also check form data with Dump and Die like dd($request->all()); but this will not return json format

Note: if it's not working then please explain which php and Laravel version you are using.

Official  Laravel docs

Body:
assume you have already done form submit code with form. below one line code you can use in controller

public function store(Request $request)
{
   echo json_encode($request);
   // below you can store data after validation if need then
}

if you are using a post method to submit a form then above one line code will you to echo form data as json format

you can also check form data with Dump and Die like dd($request->all()); but this will not return json format

Note: if it's not working then please explain which php and Laravel version you are using.

Official  Laravel docs


问:
Is there a way to store in a PHP array the selected <option> from a HTML <select>?
My idea is to store in a PHP array the selected <option> from different html <select> ' s.

In a form I generate using a php function called from a Jquery function a
 containing each list element text and a <select>

Like so:

Part of the form where the list elements are added:

    Productos de este pedido:

```

<hr>

<h2>JQuery function that calls the PHP function:</h2>

<pre class="lang-js prettyprint-override"><code>$("#pedidos").on("input", function() {
    $.get("cambio_cliente.php", { idPedido: $("#pedidos").val()}, function (data) {
        $("#lineaPedidos").empty();
        $("#lineaPedidos").append(data);

        $("#asignarBdto").show();
        $("#lineaPedidos").show();
    });
});
</code>```

PHP function:

// Si llegamos a este script por haber seleccionado un pedido
if(isset($_GET["idPedido"])){
    // Abrimos una conexión con la BD y consultamos la lista de productos dado un pedido
    $conexion = crearConexionBD();
    $resultado = listarProductos($conexion, $_GET["idPedido"]);

    if($resultado != NULL){
        // Para cada producto del listado devuelto
        foreach($resultado as $lineaPedido) {
            //Listamos los productos de cada pedido
            echo "
" . $lineaPedido["NUM_LINEA_P"] .": cantidad= ". $lineaPedido["CANTIDAD"] .", importe= ". $lineaPedido["IMPORTE"] ."
Base de dto: <select class=\"linPed\" required><option value=\"\" hidden disabled selected>% DTO</option> <option value=\"21\">21%</option> <option value=\"16\">16%</option> <option value=\"8\">8%</option></select>
";
        }
    }
    // Cerramos la conexión y borramos de la sesión la variable "idPedido"
    cerrarConexionBD($conexion);
    unset($_GET["idPedido"]);
}
```

<hr>

<p>So far so good.</p>

<p>The form display this fields without problems:</p>

<p><img src="https://i.stack.imgur.com/D7bIU.jpg" alt="form alta factura"></p>

<hr>

<h1>The problem starts here</h1>

<p>I need to store each selected <code><option></code> into the array I mentioned in the very begining. I don't know how many <code><select></code> ' s will be created, so I can't create id's for each of them. I decided to create a class (linPed) for this selects, and tried this JS function:</p>

<pre class="lang-js prettyprint-override"><code>$(".linPed").on("input", function(){
   alert("all good");
});
</code>```

I first tried do some 'logging' to see if the function executes correctly, but doesn't show the alert.
Despite of that, even if the function executed correctly, how do I add in the array the selected .linPed value? Or maybe there is an easier way to do it?

EDIT 1:

alert("hello");
    $("select.linPed").on("change", function(){
       alert("this works");
    });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<ul>
    <div>
        <li>
            Hello
        </li>
        <select class="linPed">
            <option value="21">
                21%
            </option>
            <option value="16">
                16%
            </option>
            <option value="8">
                8%
            </option>
        </select>
    </div>
   <div>
        <li>
            bye
        </li>
        <select class="linPed">
            <option value="21">
                21%
            </option>
            <option value="16">
                16%
            </option>
            <option value="8">
                8%
            </option>
        </select>
    </div>
</ul>
<select class="linPed">
            <option value="21">
                21%
            </option>
            <option value="16">
                16%
            </option>
            <option value="8">
                8%
            </option>
</select></code>```

I have created an snippet testing if the problem was that the <select> 's were inside the
.

EDIT 2:

I still don't know why, but if I try to acces the <option> 's value from a separated script, doesn't work. I tried adding an onchange field to the <select>'s and finally works.

答:
Personaly I would use change in stead of input in the .on() function for detecting a change like:

$('.linPed').on('change', function() {
  alert( this.value );
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<select class='linPed'>
    <option value="1"><li>One</li></option>
    <option value="2">Two</option>
</select></code>```

For getting al the value I would use the .each() function like:

```<code>var arr = [];
$('.linPed').each(function(){
  arr.push($(this).val())
})
</code>```

If I'm correct this gives you al the selected values in the array arr.

Edit:

I executed echo myself and lookt at it. It is there where lays the problem. Your class is't linPed it's \"linPed"\.

In your code replece al the \ with nothing.

Edit 2:

Having a look at your snippet and saw it instantly. You js ran before the html is loaded. Put your JavaScript at the end of your code. Or put an ready function around your code like

```<code>$(function () {
  //Code ..
});
</code>```

Body:
My idea is to store in a PHP array the selected <option> from different html <select> ' s.

In a form I generate using a php function called from a Jquery function a
 containing each list element text and a <select>

Like so:

Part of the form where the list elements are added:

    Productos de este pedido:

JQuery function that calls the PHP function:

$("#pedidos").on("input", function() {
    $.get("cambio_cliente.php", { idPedido: $("#pedidos").val()}, function (data) {
        $("#lineaPedidos").empty();
        $("#lineaPedidos").append(data);

        $("#asignarBdto").show();
        $("#lineaPedidos").show();
    });
});

PHP function:

// Si llegamos a este script por haber seleccionado un pedido
if(isset($_GET["idPedido"])){
    // Abrimos una conexión con la BD y consultamos la lista de productos dado un pedido
    $conexion = crearConexionBD();
    $resultado = listarProductos($conexion, $_GET["idPedido"]);

    if($resultado != NULL){
        // Para cada producto del listado devuelto
        foreach($resultado as $lineaPedido) {
            //Listamos los productos de cada pedido
            echo "
" . $lineaPedido["NUM_LINEA_P"] .": cantidad= ". $lineaPedido["CANTIDAD"] .", importe= ". $lineaPedido["IMPORTE"] ."
Base de dto: <select class=\"linPed\" required><option value=\"\" hidden disabled selected>% DTO</option> <option value=\"21\">21%</option> <option value=\"16\">16%</option> <option value=\"8\">8%</option></select>
";
        }
    }
    // Cerramos la conexión y borramos de la sesión la variable "idPedido"
    cerrarConexionBD($conexion);
    unset($_GET["idPedido"]);
}

So far so good.

The form display this fields without problems:

The problem starts here

I need to store each selected <option> into the array I mentioned in the very begining. I don't know how many <select> ' s will be created, so I can't create id's for each of them. I decided to create a class (linPed) for this selects, and tried this JS function:

$(".linPed").on("input", function(){
   alert("all good");
});

I first tried do some 'logging' to see if the function executes correctly, but doesn't show the alert.
Despite of that, even if the function executed correctly, how do I add in the array the selected .linPed value? Or maybe there is an easier way to do it?

EDIT 1:

alert("hello");
    $("select.linPed").on("change", function(){
       alert("this works");
    });

            Hello

        <select class="linPed">
            <option value="21">
                21%
            </option>
            <option value="16">
                16%
            </option>
            <option value="8">
                8%
            </option>
        </select>

            bye

        <select class="linPed">
            <option value="21">
                21%
            </option>
            <option value="16">
                16%
            </option>
            <option value="8">
                8%
            </option>
        </select>

<select class="linPed">
            <option value="21">
                21%
            </option>
            <option value="16">
                16%
            </option>
            <option value="8">
                8%
            </option>
</select>

I have created an snippet testing if the problem was that the <select> 's were inside the
.

EDIT 2:

I still don't know why, but if I try to acces the <option> 's value from a separated script, doesn't work. I tried adding an onchange field to the <select>'s and finally works.

Body:
Personaly I would use change in stead of input in the .on() function for detecting a change like:

$('.linPed').on('change', function() {
  alert( this.value );
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<select class='linPed'>
    <option value="1"><li>One</li></option>
    <option value="2">Two</option>
</select>

For getting al the value I would use the .each() function like:

var arr = [];
$('.linPed').each(function(){
  arr.push($(this).val())
})

If I'm correct this gives you al the selected values in the array arr.

Edit:

I executed echo myself and lookt at it. It is there where lays the problem. Your class is't linPed it's \"linPed"\.

In your code replece al the \ with nothing.

Edit 2:

Having a look at your snippet and saw it instantly. You js ran before the html is loaded. Put your JavaScript at the end of your code. Or put an ready function around your code like

$(function () {
  //Code ..
});


问:
Python, loops with changeable parts of filenames
I have a bunch of very similar commands which all look like this (df means pandas dataframe):

```<code>df1_part1=...
df1_part2=...
...
df1_part5=...
df2_part1=...
</code>```

I would like to make a loop for it, as follows:

```<code>for i in range(1,5):
for j in range(1,5):
df%i_part%j=...
</code>```

Of course, it doesn't work with %. But is has to be some easy way to do it, I suppose.
Could You help me please?

答:
One way would be to collect your pandas dataframes in a list of lists and iterate over that list instead of trying dynamically parse your python code.</p>

```<code>df1_part1=...
df1_part2=...
...
df1_part5=...
df2_part1=...

dflist = [[df1_part1, df1_part2, df1_part3, df1_part4, df1_part5],
          [df2_part1, df2_part2, df2_part3, df2_part4, df2_part5]]
for df in dflist:
    for df_part in df:
        # do something with df_part
</code>```

Body:
I have a bunch of very similar commands which all look like this (df means pandas dataframe):

df1_part1=...
df1_part2=...
...
df1_part5=...
df2_part1=...

I would like to make a loop for it, as follows:

for i in range(1,5):
for j in range(1,5):
df%i_part%j=...

Of course, it doesn't work with %. But is has to be some easy way to do it, I suppose.
Could You help me please?

Body:
One way would be to collect your pandas dataframes in a list of lists and iterate over that list instead of trying dynamically parse your python code.

df1_part1=...
df1_part2=...
...
df1_part5=...
df2_part1=...

dflist = [[df1_part1, df1_part2, df1_part3, df1_part4, df1_part5],
          [df2_part1, df2_part2, df2_part3, df2_part4, df2_part5]]
for df in dflist:
    for df_part in df:
        # do something with df_part


问:
Ignore images when converting word document to text using Interop in C#
Currently my code successfully converts all the text in a word document (.docx) into plain text in a .txt file but wherever there is a image in the word doc it gets replaced by a '/' in my output file. How can I ignore the images?

My code stub:

```<code>Word.Application app = new Word.Application();
Word.Document doc;
object missing = Type.Missing;
object readOnly = true;
doc = app.Documents.Open(ref path, ref missing, ref readOnly, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
string text = doc.Content.Text;
System.IO.File.WriteAllText(txtPath, text);
Console.WriteLine("File converted to .txt!");
</code>```

答:
Here my solution. This class read a Word document, remove all images and then convert it to a RTF file.

```<code>using Microsoft.Office.Interop.Word;
using System.IO;
using OW = Microsoft.Office.Interop.Word;

namespace WordImagesCruncher
{
    public class WordImagesCruncher
    {
        public string SourceFilePath { private set; get; }

        public WordImagesCruncher(string sourceFilePath)
        {
            SourceFilePath = sourceFilePath;
        }

        public void DoWork()
        {
            var wordApp = new OW.Application();
            OW.Document doc = wordApp.Documents.Open(SourceFilePath);

            for (int i = doc.InlineShapes.Count; i > 0; i--)
            {
                doc.InlineShapes[1].Delete();
            }

            for (int i = doc.Shapes.Count; i >0 ; i--)
            {
                doc.Shapes[1].Delete();
            }

            doc.SaveAs(Path.GetFileNameWithoutExtension(SourceFilePath) + "_tmp.rtf", OW.WdSaveFormat.wdFormatRTF);
            doc.Close();
            wordApp.Quit();
        }
    }
}
</code>```

Don't forget to add the Interop reference

and change the property Embed Interop Types to Yes.

Body:
Currently my code successfully converts all the text in a word document (.docx) into plain text in a .txt file but wherever there is a image in the word doc it gets replaced by a '/' in my output file. How can I ignore the images?

My code stub:

Word.Application app = new Word.Application();
Word.Document doc;
object missing = Type.Missing;
object readOnly = true;
doc = app.Documents.Open(ref path, ref missing, ref readOnly, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
string text = doc.Content.Text;
System.IO.File.WriteAllText(txtPath, text);
Console.WriteLine("File converted to .txt!");

Body:
Here my solution. This class read a Word document, remove all images and then convert it to a RTF file.

using Microsoft.Office.Interop.Word;
using System.IO;
using OW = Microsoft.Office.Interop.Word;

namespace WordImagesCruncher
{
    public class WordImagesCruncher
    {
        public string SourceFilePath { private set; get; }

        public WordImagesCruncher(string sourceFilePath)
        {
            SourceFilePath = sourceFilePath;
        }

        public void DoWork()
        {
            var wordApp = new OW.Application();
            OW.Document doc = wordApp.Documents.Open(SourceFilePath);

            for (int i = doc.InlineShapes.Count; i > 0; i--)
            {
                doc.InlineShapes[1].Delete();
            }

            for (int i = doc.Shapes.Count; i >0 ; i--)
            {
                doc.Shapes[1].Delete();
            }

            doc.SaveAs(Path.GetFileNameWithoutExtension(SourceFilePath) + "_tmp.rtf", OW.WdSaveFormat.wdFormatRTF);
            doc.Close();
            wordApp.Quit();
        }
    }
}

Don't forget to add the Interop reference

and change the property Embed Interop Types to Yes.


问:
How to pass a boost asio tcp socket to a thread for sending heartbeat to client or server
I am writing a client/server program in boost TCP in which I want to send a HEARTBEAT message to the client every 2 seconds for which I am trying to create a new thread by which I can send it easily but unable to solve it. I am creating thread using boost::thread t(hearbeatSender,sock); this. but giving lots of errors. I also use bind to bind function name with the socket but not resolved the error.

```<code>void process(boost::asio::ip::tcp::socket & sock);
std::string read_data(boost::asio::ip::tcp::socket & sock);
void write_data(boost::asio::ip::tcp::socket & sock,std::string);
void hearbeatSender(boost::asio::ip::tcp::socket & sock);
int main()
{

    unsigned short port_num = 3333;
    boost::asio::ip::tcp::endpoint ep(boost::asio::ip::address_v4::any(), port_num);
    boost::asio::io_service io;
    try
    {
        boost::asio::ip::tcp::acceptor acceptor(io, ep.protocol());
        acceptor.bind(ep);
        acceptor.listen();
        boost::asio::ip::tcp::socket sock(io);
        acceptor.accept(sock);
        boost::thread t(hearbeatSender,sock);
        process(sock);
        t.join();

    }
    catch (boost::system::system_error &e)
    {
        std::cout << "Error occured! Error code = " << e.code()
        << ". Message: " << e.what();

        return e.code().value();
    }
  return 0;

}
void process(boost::asio::ip::tcp::socket & sock)
{
    while(1){
    std::string data = read_data(sock);
    std::cout<<"Client's request is: "<<data<<std::endl;
    write_data(sock,data);
    }
}
std::string read_data(boost::asio::ip::tcp::socket & sock)
{
    boost::asio::streambuf buf;
    boost::asio::read_until(sock, buf, "\n");
    std::string data = boost::asio::buffer_cast<const char*>(buf.data());
    return data;
}
void write_data(boost::asio::ip::tcp::socket & sock,std::string data)
{
    boost::system::error_code error;
    std::string msg;
    int ch = data[0]-'0';
    switch(ch)
    {
        case 1: msg = "Case 1\n"; break;
        case 2: msg = "Case 2\n"; break;
        case 3: msg = "Case 3\n"; break;
        case 4: msg = "Case 4\n"; break;
        default: msg  = "Case default\n"; break;
    }
    boost::asio::write( sock, boost::asio::buffer(msg+ "\n"), error );
     if( !error ) {
        std::cout << "Server sent hello message!" << std::endl;
     }
     else {
        std::cout << "send failed: " << error.message() << std::endl;
     }
}
void hearbeatSender(boost::asio::ip::tcp::socket & sock)
{
    boost::system::error_code error;
    std::string msg = "HEARTBEAT";
    while(1)
    {
        sleep(2);
        std::cout<<msg<<std::endl;
        boost::asio::write( sock, boost::asio::buffer(msg+ "\n"), error );
        if( !error ) {
        std::cout << "Server sent HEARTBEAT message!" << std::endl;
        }
        else {
            std::cout << "send failed: " << error.message() << std::endl;
        }
    }
}

</code>```

This is a server-side code for responding to the message of the client and sending heartbeat to the client. This is a synchronous TCP server.

答:
Instead of this:

```<code>    boost::asio::ip::tcp::socket sock(io);
    acceptor.accept(sock);
    boost::thread t(hearbeatSender,sock);
</code>```

this:

```<code>    auto sock = acceptor.accept();
    std::thread t([&sock]() {
        hearbeatSender(sock);
    });
</code>```

And instead of sleep, just used std::this_thread::sleep for compiling universally.

Here's the complete program that compiles and runs

```<code>#include <boost/asio.hpp>
#include <iostream>

void process(boost::asio::ip::tcp::socket& sock);
std::string read_data(boost::asio::ip::tcp::socket& sock);
void write_data(boost::asio::ip::tcp::socket& sock, std::string);
void hearbeatSender(boost::asio::ip::tcp::socket& sock);
int main()
{

    unsigned short port_num = 3333;
    boost::asio::ip::tcp::endpoint ep(boost::asio::ip::address_v4::any(), port_num);
    boost::asio::io_service io;
    try
    {
        boost::asio::ip::tcp::acceptor acceptor(io, ep.protocol());
        acceptor.bind(ep);
        acceptor.listen();
        auto sock = acceptor.accept();
        std::thread t([&sock]() {
            hearbeatSender(sock);
        });
        process(sock);
        t.join();

    }
    catch (boost::system::system_error& e)
    {
        std::cout << "Error occured! Error code = " << e.code()
            << ". Message: " << e.what();

        return e.code().value();
    }
    return 0;

}
void process(boost::asio::ip::tcp::socket& sock)
{
    while (1) {
        std::string data = read_data(sock);
        std::cout << "Client's request is: " << data << std::endl;
        write_data(sock, data);
    }
}
std::string read_data(boost::asio::ip::tcp::socket& sock)
{
    boost::asio::streambuf buf;
    boost::asio::read_until(sock, buf, "\n");
    std::string data = boost::asio::buffer_cast<const char*>(buf.data());
    return data;
}
void write_data(boost::asio::ip::tcp::socket& sock, std::string data)
{
    boost::system::error_code error;
    std::string msg;
    int ch = data[0] - '0';
    switch (ch)
    {
    case 1: msg = "Case 1\n"; break;
    case 2: msg = "Case 2\n"; break;
    case 3: msg = "Case 3\n"; break;
    case 4: msg = "Case 4\n"; break;
    default: msg = "Case default\n"; break;
    }
    boost::asio::write(sock, boost::asio::buffer(msg + "\n"), error);
    if (!error) {
        std::cout << "Server sent hello message!" << std::endl;
    }
    else {
        std::cout << "send failed: " << error.message() << std::endl;
    }
}
void hearbeatSender(boost::asio::ip::tcp::socket& sock)
{
    boost::system::error_code error;
    std::string msg = "HEARTBEAT";
    while (1)
    {
        std::this_thread::sleep_for(std::chrono::seconds(2));
        std::cout << msg << std::endl;
        boost::asio::write(sock, boost::asio::buffer(msg + "\n"), error);
        if (!error) {
            std::cout << "Server sent HEARTBEAT message!" << std::endl;
        }
        else {
            std::cout << "send failed: " << error.message() << std::endl;
        }
    }
}
</code>```

Body:
I am writing a client/server program in boost TCP in which I want to send a HEARTBEAT message to the client every 2 seconds for which I am trying to create a new thread by which I can send it easily but unable to solve it. I am creating thread using boost::thread t(hearbeatSender,sock); this. but giving lots of errors. I also use bind to bind function name with the socket but not resolved the error.

void process(boost::asio::ip::tcp::socket & sock);
std::string read_data(boost::asio::ip::tcp::socket & sock);
void write_data(boost::asio::ip::tcp::socket & sock,std::string);
void hearbeatSender(boost::asio::ip::tcp::socket & sock);
int main()
{

    unsigned short port_num = 3333;
    boost::asio::ip::tcp::endpoint ep(boost::asio::ip::address_v4::any(), port_num);
    boost::asio::io_service io;
    try
    {
        boost::asio::ip::tcp::acceptor acceptor(io, ep.protocol());
        acceptor.bind(ep);
        acceptor.listen();
        boost::asio::ip::tcp::socket sock(io);
        acceptor.accept(sock);
        boost::thread t(hearbeatSender,sock);
        process(sock);
        t.join();

    }
    catch (boost::system::system_error &e)
    {
        std::cout << "Error occured! Error code = " << e.code()
        << ". Message: " << e.what();

        return e.code().value();
    }
  return 0;

}
void process(boost::asio::ip::tcp::socket & sock)
{
    while(1){
    std::string data = read_data(sock);
    std::cout<<"Client's request is: "<<data<<std::endl;
    write_data(sock,data);
    }
}
std::string read_data(boost::asio::ip::tcp::socket & sock)
{
    boost::asio::streambuf buf;
    boost::asio::read_until(sock, buf, "\n");
    std::string data = boost::asio::buffer_cast<const char*>(buf.data());
    return data;
}
void write_data(boost::asio::ip::tcp::socket & sock,std::string data)
{
    boost::system::error_code error;
    std::string msg;
    int ch = data[0]-'0';
    switch(ch)
    {
        case 1: msg = "Case 1\n"; break;
        case 2: msg = "Case 2\n"; break;
        case 3: msg = "Case 3\n"; break;
        case 4: msg = "Case 4\n"; break;
        default: msg  = "Case default\n"; break;
    }
    boost::asio::write( sock, boost::asio::buffer(msg+ "\n"), error );
     if( !error ) {
        std::cout << "Server sent hello message!" << std::endl;
     }
     else {
        std::cout << "send failed: " << error.message() << std::endl;
     }
}
void hearbeatSender(boost::asio::ip::tcp::socket & sock)
{
    boost::system::error_code error;
    std::string msg = "HEARTBEAT";
    while(1)
    {
        sleep(2);
        std::cout<<msg<<std::endl;
        boost::asio::write( sock, boost::asio::buffer(msg+ "\n"), error );
        if( !error ) {
        std::cout << "Server sent HEARTBEAT message!" << std::endl;
        }
        else {
            std::cout << "send failed: " << error.message() << std::endl;
        }
    }
}

This is a server-side code for responding to the message of the client and sending heartbeat to the client. This is a synchronous TCP server.

Body:
Instead of this:

    boost::asio::ip::tcp::socket sock(io);
    acceptor.accept(sock);
    boost::thread t(hearbeatSender,sock);

this:

    auto sock = acceptor.accept();
    std::thread t([&sock]() {
        hearbeatSender(sock);
    });

And instead of sleep, just used std::this_thread::sleep for compiling universally.

Here's the complete program that compiles and runs

#include <boost/asio.hpp>
#include <iostream>

void process(boost::asio::ip::tcp::socket& sock);
std::string read_data(boost::asio::ip::tcp::socket& sock);
void write_data(boost::asio::ip::tcp::socket& sock, std::string);
void hearbeatSender(boost::asio::ip::tcp::socket& sock);
int main()
{

    unsigned short port_num = 3333;
    boost::asio::ip::tcp::endpoint ep(boost::asio::ip::address_v4::any(), port_num);
    boost::asio::io_service io;
    try
    {
        boost::asio::ip::tcp::acceptor acceptor(io, ep.protocol());
        acceptor.bind(ep);
        acceptor.listen();
        auto sock = acceptor.accept();
        std::thread t([&sock]() {
            hearbeatSender(sock);
        });
        process(sock);
        t.join();

    }
    catch (boost::system::system_error& e)
    {
        std::cout << "Error occured! Error code = " << e.code()
            << ". Message: " << e.what();

        return e.code().value();
    }
    return 0;

}
void process(boost::asio::ip::tcp::socket& sock)
{
    while (1) {
        std::string data = read_data(sock);
        std::cout << "Client's request is: " << data << std::endl;
        write_data(sock, data);
    }
}
std::string read_data(boost::asio::ip::tcp::socket& sock)
{
    boost::asio::streambuf buf;
    boost::asio::read_until(sock, buf, "\n");
    std::string data = boost::asio::buffer_cast<const char*>(buf.data());
    return data;
}
void write_data(boost::asio::ip::tcp::socket& sock, std::string data)
{
    boost::system::error_code error;
    std::string msg;
    int ch = data[0] - '0';
    switch (ch)
    {
    case 1: msg = "Case 1\n"; break;
    case 2: msg = "Case 2\n"; break;
    case 3: msg = "Case 3\n"; break;
    case 4: msg = "Case 4\n"; break;
    default: msg = "Case default\n"; break;
    }
    boost::asio::write(sock, boost::asio::buffer(msg + "\n"), error);
    if (!error) {
        std::cout << "Server sent hello message!" << std::endl;
    }
    else {
        std::cout << "send failed: " << error.message() << std::endl;
    }
}
void hearbeatSender(boost::asio::ip::tcp::socket& sock)
{
    boost::system::error_code error;
    std::string msg = "HEARTBEAT";
    while (1)
    {
        std::this_thread::sleep_for(std::chrono::seconds(2));
        std::cout << msg << std::endl;
        boost::asio::write(sock, boost::asio::buffer(msg + "\n"), error);
        if (!error) {
            std::cout << "Server sent HEARTBEAT message!" << std::endl;
        }
        else {
            std::cout << "send failed: " << error.message() << std::endl;
        }
    }
}


问:
Implementation of ceil() and floor()
Just curious how are these implemented. I can't see where I would start. Do they work directly on the float's/double's bits?

Also where can I find the source code of functions from math.h? All I find are either headers with prototypes or files with functions that call other functions from somewhere else.

EDIT: Part of the message was lost after editing the title. What I meant in particular were the ceil() and floor() functions.

答:
A lot of it is done on processors these days.
The chip I cut my teeth on didn't even have a multiply instruction (z80)

We had to approximate stuff using the concept of the Taylor Series.

About 1/2 the way down this page, you can see how sin and cos are approximated.

ContentLicense: CC BY-SA 3.0

Title: Implementation of ceil() and floor()


问:
Does cleaning the user yarn cache will affect docker image?
While building the docker images, after the below steps

Installing dependencies (RUN yarn install)

generate build (RUN ng build --prod)

If I clean the yarn cache from usr location using below command in docker file, will it affect afterward when I run the docker image?

RUN rm -rf /usr/local/share/.cache/yarn/*

as the docker images size was huge 1.2 GB so I have clean the above location that has close to 450+ MB.

I am using a lower version of docker (for a specific reason) which doesn't support multistage build.

Also, is the above command is equivalent to RUN yarn clean cache?

```<code>FROM node:10-alpine

WORKDIR /app

COPY . /app

RUN apk --no-cache add yarn \
    && yarn install \
    && ng build --prod \
    && rm -rf /var/cache/apk/* \
    && rm -rf /usr/local/share/.cache/yarn/*

EXPOSE 3000

CMD ["npm", "run", "start"]
</code>```

答:
yarn Version 1

You can safely remove cache files, it will not affect your application. There's even a dedicated command for that:

```<code>$ yarn cache clean
</code>```

yarn Version 2

With Plug'n'Play, however, clearing the cache will very likely break your application because dependencies are no longer placed in node_modules. Here's what the documentation says:

In this install mode (now the default starting from Yarn v2), Yarn generates a single .pnp.js file instead of the usual node_modules. Instead of containing the source code of the installed packages, the .pnp.js file contains a map linking a package name and version to a location on the disk, and another map linking a package name and version to its set of dependencies. Thanks to this efficient system, Yarn can tell Node exactly where to look for files being required - regardless of who asks for them!

The location on the disk is cache.

You can get the old behavior back by placing this in your .yarnrc.yml file.

```<code>nodeLinker: node-modules
</code>```

Read more about Plug'n'Play here

Body:
While building the docker images, after the below steps

Installing dependencies (RUN yarn install)

generate build (RUN ng build --prod)

If I clean the yarn cache from usr location using below command in docker file, will it affect afterward when I run the docker image?

RUN rm -rf /usr/local/share/.cache/yarn/*

as the docker images size was huge 1.2 GB so I have clean the above location that has close to 450+ MB.

I am using a lower version of docker (for a specific reason) which doesn't support multistage build.

Also, is the above command is equivalent to RUN yarn clean cache?

FROM node:10-alpine

WORKDIR /app

COPY . /app

RUN apk --no-cache add yarn \
    && yarn install \
    && ng build --prod \
    && rm -rf /var/cache/apk/* \
    && rm -rf /usr/local/share/.cache/yarn/*

EXPOSE 3000

CMD ["npm", "run", "start"]

Body:
yarn Version 1

You can safely remove cache files, it will not affect your application. There's even a dedicated command for that:

$ yarn cache clean

yarn Version 2

With Plug'n'Play, however, clearing the cache will very likely break your application because dependencies are no longer placed in node_modules. Here's what the documentation says:

In this install mode (now the default starting from Yarn v2), Yarn generates a single .pnp.js file instead of the usual node_modules. Instead of containing the source code of the installed packages, the .pnp.js file contains a map linking a package name and version to a location on the disk, and another map linking a package name and version to its set of dependencies. Thanks to this efficient system, Yarn can tell Node exactly where to look for files being required - regardless of who asks for them!

The location on the disk is cache.

You can get the old behavior back by placing this in your .yarnrc.yml file.

nodeLinker: node-modules

Read more about Plug'n'Play here


问:
Find nearest location coordinates in Land using python
A geocode api returns no location information for coordinates in ocean/sea. For those records, I would like to find the nearest possible coordinates that has a valid location information (that is closest land coordinates)
Below is the code for fetching location information by passing coordinates

```<code>import requests
request_url = "https://api.mapbox.com/geocoding/v5/mapbox.places/{0}%2C{1}.json?access_token={2}&types=country&limit=1".format(lng,lat,key)
response = requests.get(request_url)
output = response.json()
</code>```

I have no clue in finding the nearest location. I'm also new to Python

Sample output:

```<code>{'type': 'FeatureCollection',
 'query': [32.12, 54.21],
 'features': [{'id': 'country.10008046970720960',
   'type': 'Feature',
   'place_type': ['country'],
   'relevance': 1,
   'properties': {'short_code': 'ru', 'wikidata': 'Q159'},
   'text': 'Russia',
   'place_name': 'Russia',
   'bbox': [19.608673, 41.185353, 179.9, 81.961618],
   'center': [37.61667, 55.75],
   'geometry': {'type': 'Point', 'coordinates': [37.61667, 55.75]}}],
 'attribution': 'NOTICE: © 2020 Mapbox and its suppliers. All rights reserved. Use of this data is subject to the Mapbox Terms of Service (https://www.mapbox.com/about/maps/). This response and the information it contains may not be retained. POI(s) provided by Foursquare.'}
</code>```

Output when the coordinates are ocean:

```<code>{'type': 'FeatureCollection',
 'query': [0, 0],
 'features': [],
 'attribution': 'NOTICE: © 2020 Mapbox and its suppliers. All rights reserved. Use of this data is subject to the Mapbox Terms of Service (https://www.mapbox.com/about/maps/). This response and the information it contains may not be retained. POI(s) provided by Foursquare.'}
</code>```

答:
Use reverse_geocode library in python to get nearest city with country.

Example:

```<code>import reverse_geocode

coordinates = (-37.81, 144.96), (31.76, 35.21)

reverse_geocode.search(coordinates)
</code>```

Result:

[{'city': 'Melbourne', 'code': 'AU', 'country': 'Australia'},
  {'city': 'Jerusalem', 'code': 'IL', 'country': 'Israel'}]

Body:
A geocode api returns no location information for coordinates in ocean/sea. For those records, I would like to find the nearest possible coordinates that has a valid location information (that is closest land coordinates)
Below is the code for fetching location information by passing coordinates

import requests
request_url = "https://api.mapbox.com/geocoding/v5/mapbox.places/{0}%2C{1}.json?access_token={2}&types=country&limit=1".format(lng,lat,key)
response = requests.get(request_url)
output = response.json()

I have no clue in finding the nearest location. I'm also new to Python

Sample output:

{'type': 'FeatureCollection',
 'query': [32.12, 54.21],
 'features': [{'id': 'country.10008046970720960',
   'type': 'Feature',
   'place_type': ['country'],
   'relevance': 1,
   'properties': {'short_code': 'ru', 'wikidata': 'Q159'},
   'text': 'Russia',
   'place_name': 'Russia',
   'bbox': [19.608673, 41.185353, 179.9, 81.961618],
   'center': [37.61667, 55.75],
   'geometry': {'type': 'Point', 'coordinates': [37.61667, 55.75]}}],
 'attribution': 'NOTICE: © 2020 Mapbox and its suppliers. All rights reserved. Use of this data is subject to the Mapbox Terms of Service (https://www.mapbox.com/about/maps/). This response and the information it contains may not be retained. POI(s) provided by Foursquare.'}

Output when the coordinates are ocean:

{'type': 'FeatureCollection',
 'query': [0, 0],
 'features': [],
 'attribution': 'NOTICE: © 2020 Mapbox and its suppliers. All rights reserved. Use of this data is subject to the Mapbox Terms of Service (https://www.mapbox.com/about/maps/). This response and the information it contains may not be retained. POI(s) provided by Foursquare.'}

Body:
Use reverse_geocode library in python to get nearest city with country.

Example:

import reverse_geocode

coordinates = (-37.81, 144.96), (31.76, 35.21)

reverse_geocode.search(coordinates)

Result:

[{'city': 'Melbourne', 'code': 'AU', 'country': 'Australia'},
  {'city': 'Jerusalem', 'code': 'IL', 'country': 'Israel'}]


问:
Is there a way to convert Hlist to an appropriate case class in a generic way?
I have looked at the cool solution presented by Travis Brown which allows converting case classes between each other in a generic way. I tried to use it to convert HList to a case class but did not managed to get it worked. Here is my attempt:

```<code>import shapeless._, ops.hlist.Align
import syntax.std.tuple._

object Shplss  extends App {
  class SameFieldsConverter[T] {
    def apply[S, SR <: HList, TR <: HList](s: S)(implicit
                                                 genS: LabelledGeneric.Aux[S, SR],
                                                 genT: LabelledGeneric.Aux[T, TR],
                                                 align: Align[SR, TR]
    ) = genT.from(align(genS.to(s)))
  }

  def convertTo[T] = new SameFieldsConverter[T]

  type SomeType = Int :: Int :: String :: Boolean :: Int :: Int :: HNil
  final case class SomeProductType(f1: Int, f2: Int, f3: String, f4: Boolean, f5: Int, f6: Int)

  val some: SomeType = (4, 4, "ssdf", true, 2, 4).productElements

  convertTo[SomeProductType](some)
}
</code>```

Unfortunately it fails with the error:

```<code>Error:(22, 29) could not find implicit value for parameter genS: shapeless.LabelledGeneric.Aux[com.test.Shplss.SomeType,SR]
  convertTo[SomeProductType](some)

Error:(22, 29) not enough arguments for method apply: (implicit genS: shapeless.LabelledGeneric.Aux[com.test.Shplss.SomeType,SR], implicit genT: shapeless.LabelledGeneric.Aux[com.test.Shplss.SomeProductType,TR], implicit align: shapeless.ops.hlist.Align[SR,TR])com.test.Shplss.SomeProductType in class SameFieldsConverter.
Unspecified value parameters genS, genT, align.
  convertTo[SomeProductType](some)
</code>```

Is there a way to enhance the converTo[B] function so it can convert between HLists as well?

答:
Shapeless's Generic and LabelledGeneric are type classes that provide a generic representation for case classes and sealed trait hierarchies using hlists and coproducts. If you already have an hlist, you don't really need a Generic instance, and Shapeless doesn't provide one. In your case this means you can actually skip the genS and SR parts:

```<code>import shapeless._, ops.hlist.Align
import syntax.std.tuple._

object Shplss  extends App {
  class SameFieldsConverter[T] {
    def apply[S <: HList, TR <: HList](s: S)(implicit
      genT: Generic.Aux[T, TR],
      align: Align[S, TR]
    ) = genT.from(align(s))
  }

  def convertTo[T] = new SameFieldsConverter[T]

  type SomeType = Int :: Int :: String :: Boolean :: Int :: Int :: HNil
  final case class SomeProductType(f1: Int, f2: Int, f3: String, f4: Boolean, f5: Int, f6: Int)

  val some: SomeType = (4, 4, "ssdf", true, 2, 4).productElements

  convertTo[SomeProductType](some)
}
</code>```

This will give you SomeProductType(4,4,ssdf,true,2,4), as you'd expect.

Note that I've changed genT from LabelledGeneric to Generic, since we no longer have labels to align on the input side. I guess you could add some extra machinery to "inject" the unlabeled input into a Shapeless record to match the LabelledGeneric type, but in this specific use case at least there's not really any point.

Body:
I have looked at the cool solution presented by Travis Brown which allows converting case classes between each other in a generic way. I tried to use it to convert HList to a case class but did not managed to get it worked. Here is my attempt:

import shapeless._, ops.hlist.Align
import syntax.std.tuple._

object Shplss  extends App {
  class SameFieldsConverter[T] {
    def apply[S, SR <: HList, TR <: HList](s: S)(implicit
                                                 genS: LabelledGeneric.Aux[S, SR],
                                                 genT: LabelledGeneric.Aux[T, TR],
                                                 align: Align[SR, TR]
    ) = genT.from(align(genS.to(s)))
  }

  def convertTo[T] = new SameFieldsConverter[T]

  type SomeType = Int :: Int :: String :: Boolean :: Int :: Int :: HNil
  final case class SomeProductType(f1: Int, f2: Int, f3: String, f4: Boolean, f5: Int, f6: Int)

  val some: SomeType = (4, 4, "ssdf", true, 2, 4).productElements

  convertTo[SomeProductType](some)
}

Unfortunately it fails with the error:

Error:(22, 29) could not find implicit value for parameter genS: shapeless.LabelledGeneric.Aux[com.test.Shplss.SomeType,SR]
  convertTo[SomeProductType](some)

Error:(22, 29) not enough arguments for method apply: (implicit genS: shapeless.LabelledGeneric.Aux[com.test.Shplss.SomeType,SR], implicit genT: shapeless.LabelledGeneric.Aux[com.test.Shplss.SomeProductType,TR], implicit align: shapeless.ops.hlist.Align[SR,TR])com.test.Shplss.SomeProductType in class SameFieldsConverter.
Unspecified value parameters genS, genT, align.
  convertTo[SomeProductType](some)

Is there a way to enhance the converTo[B] function so it can convert between HLists as well?

Body:
Shapeless's Generic and LabelledGeneric are type classes that provide a generic representation for case classes and sealed trait hierarchies using hlists and coproducts. If you already have an hlist, you don't really need a Generic instance, and Shapeless doesn't provide one. In your case this means you can actually skip the genS and SR parts:

import shapeless._, ops.hlist.Align
import syntax.std.tuple._

object Shplss  extends App {
  class SameFieldsConverter[T] {
    def apply[S <: HList, TR <: HList](s: S)(implicit
      genT: Generic.Aux[T, TR],
      align: Align[S, TR]
    ) = genT.from(align(s))
  }

  def convertTo[T] = new SameFieldsConverter[T]

  type SomeType = Int :: Int :: String :: Boolean :: Int :: Int :: HNil
  final case class SomeProductType(f1: Int, f2: Int, f3: String, f4: Boolean, f5: Int, f6: Int)

  val some: SomeType = (4, 4, "ssdf", true, 2, 4).productElements

  convertTo[SomeProductType](some)
}

This will give you SomeProductType(4,4,ssdf,true,2,4), as you'd expect.

Note that I've changed genT from LabelledGeneric to Generic, since we no longer have labels to align on the input side. I guess you could add some extra machinery to "inject" the unlabeled input into a Shapeless record to match the LabelledGeneric type, but in this specific use case at least there's not really any point.


问:
How to convert nested array of object into arraylist in javascript?
i have a nested array of object and i want to convert in arraylist like this :
this is my data array of object :

```<code>{
    "status": true,
    "message": "",
    "data": [{
            "pasien_docs": [{
                    "ecg": null,
                    "date": "2020-01-21T05:22:01.901Z"
                }, {
                    "ecg": 1.03,
                    "date": "2020-01-21T05:22:02.979Z"
                }, {
                    "ecg": 1.04,
                    "date": "2020-01-21T05:22:04.053Z"
                }, {
                    "ecg": 1.04,
                    "date": "2020-01-21T05:22:05.126Z"
                },
            ]
        }
    ]
}
</code>```

and i want change convert to array like this :

```<code>{
    "status": true,
    "message": "",
    "data": [
        [
            "2020-01-21T05:22:01.901Z",
            null
        ],
        [
            "2020-01-21T05:22:01.901Z",
            1, 03
        ]
        [
            "2020-01-21T05:22:01.901Z",
            1.04
        ]
        [
            "2020-01-21T05:22:01.901Z",
            1.04
        ]
    ]
 }
</code>```

i try using map to convert on result like this :

```<code>result = result.map((u, i) => [
            u.pasien_docs[i].date,
            u.pasien_docs[i].ecg,
        ]);
</code>```

but why i only get result data of one array not four data ? help me please, thankyou..

```<code>{
    "status": true,
    "message": "",
    "data": [
        [
            "2020-01-21T05:22:01.901Z",
            null
        ]
    ]
}
</code>```

答:
If you dont wanna use spread operator, this can also do the trick for you </p>

```<code>const source = {"status":true,"message":"","data":[{"pasien_docs":[{"ecg":null,"date":"2020-01-21T05:22:01.901Z"},{"ecg":1.03,"date":"2020-01-21T05:22:02.979Z"},{"ecg":1.04,"date":"2020-01-21T05:22:04.053Z"},{"ecg":1.04,"date":"2020-01-21T05:22:05.126Z"},]}]}

const result = Object.assign({}, source, {
  data: source.data[0].pasien_docs.map(Object.values)
})

console.log(result)
</code>```

Body:
i have a nested array of object and i want to convert in arraylist like this :
this is my data array of object :

{
    "status": true,
    "message": "",
    "data": [{
            "pasien_docs": [{
                    "ecg": null,
                    "date": "2020-01-21T05:22:01.901Z"
                }, {
                    "ecg": 1.03,
                    "date": "2020-01-21T05:22:02.979Z"
                }, {
                    "ecg": 1.04,
                    "date": "2020-01-21T05:22:04.053Z"
                }, {
                    "ecg": 1.04,
                    "date": "2020-01-21T05:22:05.126Z"
                },
            ]
        }
    ]
}

and i want change convert to array like this :

{
    "status": true,
    "message": "",
    "data": [
        [
            "2020-01-21T05:22:01.901Z",
            null
        ],
        [
            "2020-01-21T05:22:01.901Z",
            1, 03
        ]
        [
            "2020-01-21T05:22:01.901Z",
            1.04
        ]
        [
            "2020-01-21T05:22:01.901Z",
            1.04
        ]
    ]
 }

i try using map to convert on result like this :

result = result.map((u, i) => [
            u.pasien_docs[i].date,
            u.pasien_docs[i].ecg,
        ]);

but why i only get result data of one array not four data ? help me please, thankyou..

{
    "status": true,
    "message": "",
    "data": [
        [
            "2020-01-21T05:22:01.901Z",
            null
        ]
    ]
}

Body:
If you dont wanna use spread operator, this can also do the trick for you

const source = {"status":true,"message":"","data":[{"pasien_docs":[{"ecg":null,"date":"2020-01-21T05:22:01.901Z"},{"ecg":1.03,"date":"2020-01-21T05:22:02.979Z"},{"ecg":1.04,"date":"2020-01-21T05:22:04.053Z"},{"ecg":1.04,"date":"2020-01-21T05:22:05.126Z"},]}]}

const result = Object.assign({}, source, {
  data: source.data[0].pasien_docs.map(Object.values)
})

console.log(result)


问:
How to collect a coroutine flow in java?
I'm developing an Android library,

When the user receives a push notification it may contain deep links, that I need to return to the app.

I did in kotlin with no problem.

This is the function that is called when it needs to send the deep links

```<code>fun getDeepLinkFlow(): Flow<HashMap<String, String>?> = flow {
    emit(deepLinks)
}
</code>```

And in my kotlin test app I managed to use with no problems as well, using like this.

```<code>GlobalScope.launch(coroutineContext) {
    SDK.getDeepLinkFlow().collect { deepLinks ->
        println(deepLinks)
    }
}
</code>```

But now, there's a RN project that whant to use the lib, in order to do that we are doing a RN module that joins the iOS code and the Android code. But it uses java.

So, how can I use the collect from Coroutines on a Java code? or what could I do differently?

答: I've decided to change the way deep links were used and start using the ViewModel with a liveData instead.</p>

Body:
I'm developing an Android library,

When the user receives a push notification it may contain deep links, that I need to return to the app.

I did in kotlin with no problem.

This is the function that is called when it needs to send the deep links

fun getDeepLinkFlow(): Flow<HashMap<String, String>?> = flow {
    emit(deepLinks)
}

And in my kotlin test app I managed to use with no problems as well, using like this.

GlobalScope.launch(coroutineContext) {
    SDK.getDeepLinkFlow().collect { deepLinks ->
        println(deepLinks)
    }
}

But now, there's a RN project that whant to use the lib, in order to do that we are doing a RN module that joins the iOS code and the Android code. But it uses java.

So, how can I use the collect from Coroutines on a Java code? or what could I do differently?


问:
Why does rails.bat work but rails does not?
When attempting to create a new Ruby on Rails app in Windows the command

```<code>rails new test_app
</code>```

returns an error

```<code>'rails' is not recognized as an internal or external command, operable program
or batch  file
</code>```

but the command

```<code>rails.bat new test_app
</code>```

works just fine. I have added the ..\ruby\bin directory to my PATH variable but it doesn't seem to change anything. A similar problem occurs for all other 'rails' commands as well as for 'rake' vs 'rake.bat'.

Running type rails.bat returns:

```<code>@ECHO OFF
IF NOT "%~f0" == "~f0" GOTO :WinNT
@"ruby.exe" "C:/_LOCALdata/Ruby192/bin/rails" %1 %2 %3 %4 %5 %6 %7 %8 %9
GOTO :EOF
:WinNT
@"ruby.exe" "%~dpn0" %*
</code>```

答:
you have to download railsinstaller for windows this would help you solve all conflicts
download it from rubyforge</p>

Body:
When attempting to create a new Ruby on Rails app in Windows the command

rails new test_app

returns an error

'rails' is not recognized as an internal or external command, operable program
or batch  file

but the command

rails.bat new test_app

works just fine. I have added the ..\ruby\bin directory to my PATH variable but it doesn't seem to change anything. A similar problem occurs for all other 'rails' commands as well as for 'rake' vs 'rake.bat'.

Running type rails.bat returns:

@ECHO OFF
IF NOT "%~f0" == "~f0" GOTO :WinNT
@"ruby.exe" "C:/_LOCALdata/Ruby192/bin/rails" %1 %2 %3 %4 %5 %6 %7 %8 %9
GOTO :EOF
:WinNT
@"ruby.exe" "%~dpn0" %*


问:
Is it possible to use internal load balancer with backend on App Engine Flexible instances?
We need this to use non standard TCP port. From what I can see Load balancers need instance groups to be defined, and instance groups are compute engine thing. So I wonder if it's possible at all.</p>

答:
App Engine is a managed service, this means that it has it's own load balancer and manages the requests in a very specific way which you can check over here.

As mentioned by @guillaume blaquiere, you would be mixing 2 concepts completely different which are IaaS and PaaS. If you need to set up a specific load balancer with certain behaviour for your App to run, you may be better off using Managed instance groups rather than App Engine so you have more control on everything rather than relying on GCP's management.

I hope you find this information useful.


问:
Check for duplicates in particular column after joining two datatables
I am trying to add more functionality to my existing code.

This part is responsible for joining two datatables:

```<code>                var results = from table1 in t2.AsEnumerable()
                              join table2 in t1.AsEnumerable()
                                  on (string)table1["SNAME"] equals (string)table2["SNAME"] into temp
                              from table2 in temp.DefaultIfEmpty()
                              select new
                              {
                                  NRO = (string)table1["NRO"],
                                  NRO1 = table2 != null ? (string)table2["NRO"] : string.Empty,
                                  SNAME = (string)table1["SNAME"],
                                  NAMEA = (string)table1["NAMEA"],
                                  NAMEB = (string)table1["NAMEB"],
                                  ADDRESS = (string)table1["ADDRESS"],
                                  POSTS = (string)table1["POSTS"],
                                  POSTNRO = (string)table1["POSTNRO"],
                                  POSTTP = (string)table1["POSTTP"],
                                  COMPANY = (string)table1["COMPANY"],
                                  COUNTRY = (string)table1["COUNTRY"],
                                  BID = (string)table1["BID"]
                              };
</code>```

Now I have tried with below code to check for duplicate records in column COMPANY but it says:

Severity  Code    Description Project File    Line    Suppression State
  Error CS1929  '' does not contain a definition for 'Field' and the best
  extension method overload 'DataRowExtensions.Field(DataRow,
  string)' requires a receiver of type 'DataRow'

```<code>                var duplicates = results.AsEnumerable()
               .Select(dr => dr.Field<string>("COMPANY"))
               .GroupBy(x => x)
               .Where(g => g.Count() > 1)
               .Select(g => g.Key)
               .ToList();
</code>```

What I am doing wrong?

答:
To everyone new like I am. While using Visual Studio I highly recommend in case of error delete all parameters to the right and type a dot. Like in this case dr.Field<string>("COMPANY") -> remove .Field<string>("COMPANY") and Visual Studio will automatically suggest you available parameters, in this case it should be dr.COMPANY.

```<code>var duplicates = results.AsEnumerable()
.Select(dr => dr.COMPANY)
.GroupBy(x => x)
.Where(g => g.Count() > 1)
.Select(g => g.Key)
.ToList();

duplicates.ForEach(i => Console.Write("{0}\t", i));
</code>```

Body:
I am trying to add more functionality to my existing code.

This part is responsible for joining two datatables:

                var results = from table1 in t2.AsEnumerable()
                              join table2 in t1.AsEnumerable()
                                  on (string)table1["SNAME"] equals (string)table2["SNAME"] into temp
                              from table2 in temp.DefaultIfEmpty()
                              select new
                              {
                                  NRO = (string)table1["NRO"],
                                  NRO1 = table2 != null ? (string)table2["NRO"] : string.Empty,
                                  SNAME = (string)table1["SNAME"],
                                  NAMEA = (string)table1["NAMEA"],
                                  NAMEB = (string)table1["NAMEB"],
                                  ADDRESS = (string)table1["ADDRESS"],
                                  POSTS = (string)table1["POSTS"],
                                  POSTNRO = (string)table1["POSTNRO"],
                                  POSTTP = (string)table1["POSTTP"],
                                  COMPANY = (string)table1["COMPANY"],
                                  COUNTRY = (string)table1["COUNTRY"],
                                  BID = (string)table1["BID"]
                              };

Now I have tried with below code to check for duplicate records in column COMPANY but it says:

Severity  Code    Description Project File    Line    Suppression State
  Error CS1929  '' does not contain a definition for 'Field' and the best
  extension method overload 'DataRowExtensions.Field(DataRow,
  string)' requires a receiver of type 'DataRow'

                var duplicates = results.AsEnumerable()
               .Select(dr => dr.Field<string>("COMPANY"))
               .GroupBy(x => x)
               .Where(g => g.Count() > 1)
               .Select(g => g.Key)
               .ToList();

What I am doing wrong?

Body:
To everyone new like I am. While using Visual Studio I highly recommend in case of error delete all parameters to the right and type a dot. Like in this case dr.Field<string>("COMPANY") -> remove .Field<string>("COMPANY") and Visual Studio will automatically suggest you available parameters, in this case it should be dr.COMPANY.

var duplicates = results.AsEnumerable()
.Select(dr => dr.COMPANY)
.GroupBy(x => x)
.Where(g => g.Count() > 1)
.Select(g => g.Key)
.ToList();

duplicates.ForEach(i => Console.Write("{0}\t", i));


问:
Not getting server response when passed as bean
I have a controller where I pass direct Bean and @valid annotation to validate.  I have created a custom annotation and added it to each field in the bean. It validates but doesn't give messages from a custom exception handler. Next, if I don't pass bean and pass request param in for every field then it gives proper response from a custom exception handler.

Adding screenshots.

You can see /group gives the response of validation when passed as @RequestParam and /check doesn't give a response message just gives 400 request code.

I have added a response message in custom exception handler

You can see the message passed in constraints violation exception. I Have created custom annotation which just validates special characters nothing else. It works for RequestParam.

答:
So here I resolved the issue with removing the @Valid annotation and added this code</p>

```<code>Set<ConstraintViolation<ProcessDefination>> violations = validator.validate(processDefination);
            if (!violations.isEmpty()) {
              throw new ConstraintViolationException(violations);
            }
</code>```

Body:
So here I resolved the issue with removing the @Valid annotation and added this code

Set<ConstraintViolation<ProcessDefination>> violations = validator.validate(processDefination);
            if (!violations.isEmpty()) {
              throw new ConstraintViolationException(violations);
            }


问:
Why is the textarea value always empty when log it in a function?
I’m trying to get the textarea value using JavaScript after it is rendered in the document, I used:

```<code>let input = document.getElementById("input").value;
let btn = document.getElementById("btn");

btn.addEventListener("click", () => {
  console.log(input);
};
</code>```

But it keeps on showing an empty string in the console.

答:
You need to use preventDefault method for solving this issue against your button event, as for some control default behavior preventing the execution of the event logic. see the solution below.Hope it will work.</p>

```<code>let input = document.getElementById("input").value;
let btn = document.getElementById("btn");

btn.addEventListener("click", (event) => {
  event.preventDefault();
  console.log(input);
})
</code>```

Body:
I’m trying to get the textarea value using JavaScript after it is rendered in the document, I used:

let input = document.getElementById("input").value;
let btn = document.getElementById("btn");

btn.addEventListener("click", () => {
  console.log(input);
};

But it keeps on showing an empty string in the console.

Body:
You need to use preventDefault method for solving this issue against your button event, as for some control default behavior preventing the execution of the event logic. see the solution below.Hope it will work.

let input = document.getElementById("input").value;
let btn = document.getElementById("btn");

btn.addEventListener("click", (event) => {
  event.preventDefault();
  console.log(input);
})


答:
Please add your HTML as well next time.

That said, in your code the value of your input is read only once when the page is loaded. If you want to read and display the updated input value you have to read it every time the button is pressed. A simple example here below:

let btn = document.getElementById("btn");
btn.addEventListener("click", () => {
  let input = document.getElementById("input").value;
  console.log(input);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input id="input"></input>
<button id="btn">PressMe</button></code>```

Title: Why is the textarea value always empty when log it in a function?

Body:
Please add your HTML as well next time.

That said, in your code the value of your input is read only once when the page is loaded. If you want to read and display the updated input value you have to read it every time the button is pressed. A simple example here below:

let btn = document.getElementById("btn");
btn.addEventListener("click", () => {
  let input = document.getElementById("input").value;
  console.log(input);
});

<input id="input"></input>
<button id="btn">PressMe</button>


问:
If StartMenuInternet is not set, where else can I look for the default browser?
```<code>key = Registry.CurrentUser.OpenSubKey(@"Software\Clients\StartMenuInternet", false);
if (key == null)
{
    key = Registry.LocalMachine.OpenSubKey(@"Software\Clients\StartMenuInternet", false);
}
</code>```

On a very few machines this is coming up blank.  When regedit is probed, the key is found to be (value not found).  What are my options?

答:
I needed </p>

```<code>if (key == null || key.ValueCount == 0)
                {
                    key = Registry.LocalMachine.OpenSubKey(@"Software\Clients\StartMenuInternet", false);
                }
</code>```

Body:
key = Registry.CurrentUser.OpenSubKey(@"Software\Clients\StartMenuInternet", false);
if (key == null)
{
    key = Registry.LocalMachine.OpenSubKey(@"Software\Clients\StartMenuInternet", false);
}

On a very few machines this is coming up blank.  When regedit is probed, the key is found to be (value not found).  What are my options?

Body:
I needed

if (key == null || key.ValueCount == 0)
                {
                    key = Registry.LocalMachine.OpenSubKey(@"Software\Clients\StartMenuInternet", false);
                }


问:
What is _UITemporaryLayoutWidth and why does it break my constraints?
I have a storyboard with Autolayout and Size Classes. Pretty complicated layout, and unfortunately I can't really pin down how to reproduce the problem in a new project.

But the view in question is pinned to the left and right edge of the screen with a constraint that has 750 priority (i.e. |-(0@750)-[myView]-(0@750)-|, additionally it has a greater or equal than constraint with a priority of 1000 (i.e. |-(>=0)-[myView]-(>=0)-|). That is done to limit the width on an iPad, so there is a width constraint of width <= 600 @1000, and a center horizontal in container constraint as well. On top of that the view has a aspect ratio constraint of 3:1. As I said, rather complicated.

Interface Builder doesn't show any problems with the constraints. The Xcode layout preview renders correct for all devices.

When I run the app iOS tells me that it has conflicting constraints.

```<code>Unable to simultaneously satisfy constraints.
    Probably at least one of the constraints in the following list is one you don't want. Try this: (1) look at each constraint and try to figure out which you don't expect; (2) find the code that added the unwanted constraint or constraints and fix it. (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints)
(
    "<NSLayoutConstraint:0x7fd72853ff80 DMXKit.DipSwitchAssembly:0x7fd72990d0e0.width == 3*DMXKit.DipSwitchAssembly:0x7fd72990d0e0.height>",
    "<NSLayoutConstraint:0x7fd728574e50 '_UITemporaryLayoutWidth' H:[DMXKit.DipSwitchAssembly:0x7fd72990d0e0(400)]>",
    "<NSLayoutConstraint:0x7fd72856e9c0 V:[DMXKit.DipSwitchAssembly:0x7fd72990d0e0(133)]>"
)

Will attempt to recover by breaking constraint
<NSLayoutConstraint:0x7ffb19798000 DMXKit.DipSwitchAssembly:0x7ffb1979a000.width == 3*DMXKit.DipSwitchAssembly:0x7ffb1979a000.height>
</code>```

This is repeated a couple of times, with the exact same (i.e. same pointer) constraints. That is strange as well, looks like the constraint isn't really broken. When run, the app looks 100% correct. When I look at the app in the Xcode view debugger, the constraint with the address 0x7ffb19798000 is still there, so it was never broken.

Where does the _UITemporaryLayoutWidth constaint comes from? Obviously I didn't add it. Google doesn't spit out anything useful about _UITemporaryLayoutWidth. Did anyone encounter a problem like this?

答:
I think the issue is adding constraint to a view before adding it as subview to another view. If you assign constraints when there is no superview it automatically adds _TemporaryLayout constraints.To prevent that make translatesAutoResizingMaskIntoConstraints false.

In my case I was adding a view controller as another view controllers child. Even I set translatesAutoResizingMaskIntroConstraints flag to false from where I add it to parent view controller the warnings were still there.

Then I found loadView method of childViewController called when the view of childViewController is first called. Therefore it does not work when you set autoresizing flag outside of the childViewController since it would already set their constraints.

ParentViewController

```<code>let childViewController = CustomViewController()
//childViewController.view.translatesAutoResizingMaskIntoConstraints = false
// This does not work since before this line executes loadView

parentViewController.addChild(childViewController)
parentViewController.view.addSubview(childViewContoller.view)
// `childViewContoller.view` triggers loadView method of childViewController
// It sets up constraints before adding as subview.
</code>```

solution is making translatesAutoResizingMaskIntoConstraints false in childViewController

```<code>override func loadView() {

     super.loadView() // If you used storyboard call this to set those views
     // view = UIView() // call this if you layout views programatically
    view.translatesAutoResizingMaskIntoConstraints = false
}
</code>```

Body:
I have a storyboard with Autolayout and Size Classes. Pretty complicated layout, and unfortunately I can't really pin down how to reproduce the problem in a new project.

But the view in question is pinned to the left and right edge of the screen with a constraint that has 750 priority (i.e. |-(0@750)-[myView]-(0@750)-|, additionally it has a greater or equal than constraint with a priority of 1000 (i.e. |-(>=0)-[myView]-(>=0)-|). That is done to limit the width on an iPad, so there is a width constraint of width <= 600 @1000, and a center horizontal in container constraint as well. On top of that the view has a aspect ratio constraint of 3:1. As I said, rather complicated.

Interface Builder doesn't show any problems with the constraints. The Xcode layout preview renders correct for all devices.

When I run the app iOS tells me that it has conflicting constraints.

Unable to simultaneously satisfy constraints.
    Probably at least one of the constraints in the following list is one you don't want. Try this: (1) look at each constraint and try to figure out which you don't expect; (2) find the code that added the unwanted constraint or constraints and fix it. (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints)
(
    "<NSLayoutConstraint:0x7fd72853ff80 DMXKit.DipSwitchAssembly:0x7fd72990d0e0.width == 3*DMXKit.DipSwitchAssembly:0x7fd72990d0e0.height>",
    "<NSLayoutConstraint:0x7fd728574e50 '_UITemporaryLayoutWidth' H:[DMXKit.DipSwitchAssembly:0x7fd72990d0e0(400)]>",
    "<NSLayoutConstraint:0x7fd72856e9c0 V:[DMXKit.DipSwitchAssembly:0x7fd72990d0e0(133)]>"
)

Will attempt to recover by breaking constraint
<NSLayoutConstraint:0x7ffb19798000 DMXKit.DipSwitchAssembly:0x7ffb1979a000.width == 3*DMXKit.DipSwitchAssembly:0x7ffb1979a000.height>

This is repeated a couple of times, with the exact same (i.e. same pointer) constraints. That is strange as well, looks like the constraint isn't really broken. When run, the app looks 100% correct. When I look at the app in the Xcode view debugger, the constraint with the address 0x7ffb19798000 is still there, so it was never broken.

Where does the _UITemporaryLayoutWidth constaint comes from? Obviously I didn't add it. Google doesn't spit out anything useful about _UITemporaryLayoutWidth. Did anyone encounter a problem like this?

Body:
I think the issue is adding constraint to a view before adding it as subview to another view. If you assign constraints when there is no superview it automatically adds _TemporaryLayout constraints.To prevent that make translatesAutoResizingMaskIntoConstraints false.

In my case I was adding a view controller as another view controllers child. Even I set translatesAutoResizingMaskIntroConstraints flag to false from where I add it to parent view controller the warnings were still there.

Then I found loadView method of childViewController called when the view of childViewController is first called. Therefore it does not work when you set autoresizing flag outside of the childViewController since it would already set their constraints.

ParentViewController

let childViewController = CustomViewController()
//childViewController.view.translatesAutoResizingMaskIntoConstraints = false
// This does not work since before this line executes loadView

parentViewController.addChild(childViewController)
parentViewController.view.addSubview(childViewContoller.view)
// `childViewContoller.view` triggers loadView method of childViewController
// It sets up constraints before adding as subview.

solution is making translatesAutoResizingMaskIntoConstraints false in childViewController

override func loadView() {

     super.loadView() // If you used storyboard call this to set those views
     // view = UIView() // call this if you layout views programatically
    view.translatesAutoResizingMaskIntoConstraints = false
}


问:
Angular Dynamic Form with Dynamic Event Binding With Dynamic Function
Hi I am new to angular and i need to make something that renders a form using JSON and that JSON also has all the events and functions too.
This is my Html Component

```<code>    <div *ngFor="let form of forms; index as i ">
    <div *ngIf="form.type == 'input'">
        <input  type="text" value="{{ form.value }}" ("{{form.event}}") = "{{form.function}}"/>

    </div>
</div>
</code>```

This is my TS file,

```<code>    @Component({
      selector: 'app-form',
      templateUrl: './form.component.html',
      styleUrls: ['./form.component.scss']
    })
    export class FormComponent implements OnInit {

      forms: any
      constructor() { }

  ngOnInit(): void {
      this.forms = [
        {
          'type' : 'input',
          'value' : '123',
          'event' : 'click',
          'function' : 'show',
        },

      ]

  }
   show(a,b){
    console.log('hello');
  }

}
</code>```

I can not find a way to generate the HTML with the events and function from my JSON Array.

答:
I did reach to a solution.

Working Stackblitz :- https://stackblitz.com/edit/angular-kecqvt

I took a dummy JSON for my example.

```<code>[{
   "type":"input",
   "value":"3",
   "event":"change",
   "function":"/Function(function (value) { console.log(value); })/"
}]
</code>```

I converted json into js object like :-

```<code>public forms = JSON.parse(this.formJSON, function(key, value) {
  if (typeof value === "string" &&
      value.startsWith("/Function(") &&
      value.endsWith(")/")) {
    value = value.substring(10, value.length - 2);
    return (0, eval)("(" + value + ")");
  }
  return value;
});
</code>```

My HTML :-

```<code><div *ngFor="let form of forms; index as i ">
    <div *ngIf="form.type == 'input'">
        <input  type="text" [value]="form.value" (change) = "form['event'] === 'change' && form['function']($event.target.value)"
        (blur) = "form['event'] === 'blur' && form['function']($event.target.value)"/>
    </div>
</div>
</code>```

Body:
Hi I am new to angular and i need to make something that renders a form using JSON and that JSON also has all the events and functions too.
This is my Html Component

        <input  type="text" value="{{ form.value }}" ("{{form.event}}") = "{{form.function}}"/>

This is my TS file,

    @Component({
      selector: 'app-form',
      templateUrl: './form.component.html',
      styleUrls: ['./form.component.scss']
    })
    export class FormComponent implements OnInit {

      forms: any
      constructor() { }

  ngOnInit(): void {
      this.forms = [
        {
          'type' : 'input',
          'value' : '123',
          'event' : 'click',
          'function' : 'show',
        },

      ]

  }
   show(a,b){
    console.log('hello');
  }

}

I can not find a way to generate the HTML with the events and function from my JSON Array.

Body:
I did reach to a solution.

Working Stackblitz :- https://stackblitz.com/edit/angular-kecqvt

I took a dummy JSON for my example.

[{
   "type":"input",
   "value":"3",
   "event":"change",
   "function":"/Function(function (value) { console.log(value); })/"
}]

I converted json into js object like :-

public forms = JSON.parse(this.formJSON, function(key, value) {
  if (typeof value === "string" &&
      value.startsWith("/Function(") &&
      value.endsWith(")/")) {
    value = value.substring(10, value.length - 2);
    return (0, eval)("(" + value + ")");
  }
  return value;
});

My HTML :-

<div *ngFor="let form of forms; index as i ">
    <div *ngIf="form.type == 'input'">
        <input  type="text" [value]="form.value" (change) = "form['event'] === 'change' && form['function']($event.target.value)"
        (blur) = "form['event'] === 'blur' && form['function']($event.target.value)"/>
    </div>
</div>