问:
why Html.checkboxfor is not sends or changes the boolean value of the model?
I have a simple project that allows the customer to select multiple users and remove them from the DataBase. But the check boxes are not change or sent the isSelected variable which is tells the server that which users are have to be removed.

Client Side:

```<code>@model IEnumerable<WebApplication1.Models.User>

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

@{
    int i;
}
<h2><strong>جدول</strong></h2>
@using (Html.BeginForm())
{
    <p>
        @Html.ActionLink("اضافه کردن کاربر", "Create"
        , null, new { @class = "btn btn-success", @id = "btnCreate" })
        <input type="submit" class="btn btn-danger hidden" id="btnMultipleDelete" value="حذف کاربران" />
    </p>
    <table class="table" border="0" style="user-select: none;">
        <tr>
            <th>
                <strong>نام</strong>
            </th>
            <th>
                <strong>نام خانوادگی</strong>
            </th>
            <th>
                <strong>سنّ</strong>
            </th>
            <th></th>
        </tr>

        @for(i = 0; i < Model.Count(); i++)
        {
            <tr class="mainList" id="tr-@i"
                onmouseover="changeCurrentRow(this.id), mouseIn(true)"
                onmouseout="clearCurrentRow(), mouseIn(false)">
                <td class="IndexInfo">
                    <span class="IndexText">
                        @Html.DisplayFor(modelItem => modelItem.ToList()[i].User_FirstName)
                    </span>
                </td>
                <td class="IndexInfo">
                    <span class="IndexText">
                        @Html.DisplayFor(modelItem => modelItem.ToList()[i].User_LastName)
                    </span>
                </td>
                <td class="IndexInfo">
                    <span class="IndexText persianNumber">
                        @Html.DisplayFor(modelItem => modelItem.ToList()[i].User_Age)
                    </span>
                </td>
                <td align="center" style="flex:3">
                    @Html.ActionLink("ویرایش", "Edit", new { id = Model.ToList()[i].User_Id },
                        new { @class = "btn btn-primary", @id = "btnEdit-" + i })
                    @Html.ActionLink("مشاهده", "Details", new { id = Model.ToList()[i].User_Id },
                        new { @class = "btn btn-secondary", @id = "btnDetail-" + i })
                    @Html.ActionLink("حذف", "Delete", new { id = Model.ToList()[i].User_Id },
                        new { @class = "btn btn-warning", @id = "btnDelete-" + i })
                    @Html.HiddenFor(u => u.ToList()[i].User_Id)
                    @Html.HiddenFor(u => u.ToList()[i].User_FirstName)
                    @Html.HiddenFor(u => u.ToList()[i].User_LastName)
                    @Html.HiddenFor(u => u.ToList()[i].User_Age)
                    @Html.CheckBoxFor(u => u.ToList()[i].IsSelected, new { @class = "", @id = "cb-" + i })
                </td>
            </tr>
        }

    </table>
}

</code>```

Server Side:

```<code>[HttpPost]
        public ActionResult Index(IEnumerable<User> users)
        {
            if (users.Count() == 0)
            {
                return RedirectToAction("Index");
            }
            else
            {
                User user;
                foreach (User u in users)
                {
                    if (u.IsSelected)
                    {
                        user = db.Users.ToList().Find(x => x.User_Id == u.User_Id);
                        db.Users.Remove(user);
                    }
                }
                db.SaveChanges();
                return RedirectToAction("Index");
            }
        }
</code>```

notice that i have tried to put a hidden input for isSelected Variable But that still doesn't work

答:
so, while no one cares about my question i found the solution by my self.
Controller can not receive the IsSelected property from the View because i have changed the identity of the checkbox like id,name and ...
that means if i dont change the the identities of the checkbox, the code will works but even this solution leads us to another problem that you no longer can find the checkbox by JS. so i dont give this answer green tick until someone finds a better way to fix it.

for this solution something that you have to do is change the check box code from this:

```<code>@Html.CheckBoxFor(u => u.ToList()[i].IsSelected, new { @class = "", @id = "cb-" + i })
</code>```

to this:

```<code>@Html.CheckBoxFor(u => u.ToList()[i].IsSelected})
</code>```

and it basically will works.

Body:
I have a simple project that allows the customer to select multiple users and remove them from the DataBase. But the check boxes are not change or sent the isSelected variable which is tells the server that which users are have to be removed.

Client Side:

@model IEnumerable<WebApplication1.Models.User>

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

@{
    int i;
}

جدول

@using (Html.BeginForm())
{

        @Html.ActionLink("اضافه کردن کاربر", "Create"
        , null, new { @class = "btn btn-success", @id = "btnCreate" })
        <input type="submit" class="btn btn-danger hidden" id="btnMultipleDelete" value="حذف کاربران" />

                نام

                نام خانوادگی

                سنّ

        @for(i = 0; i < Model.Count(); i++)
        {

                        @Html.DisplayFor(modelItem => modelItem.ToList()[i].User_FirstName)

                        @Html.DisplayFor(modelItem => modelItem.ToList()[i].User_LastName)

                        @Html.DisplayFor(modelItem => modelItem.ToList()[i].User_Age)

                    @Html.ActionLink("ویرایش", "Edit", new { id = Model.ToList()[i].User_Id },
                        new { @class = "btn btn-primary", @id = "btnEdit-" + i })
                    @Html.ActionLink("مشاهده", "Details", new { id = Model.ToList()[i].User_Id },
                        new { @class = "btn btn-secondary", @id = "btnDetail-" + i })
                    @Html.ActionLink("حذف", "Delete", new { id = Model.ToList()[i].User_Id },
                        new { @class = "btn btn-warning", @id = "btnDelete-" + i })
                    @Html.HiddenFor(u => u.ToList()[i].User_Id)
                    @Html.HiddenFor(u => u.ToList()[i].User_FirstName)
                    @Html.HiddenFor(u => u.ToList()[i].User_LastName)
                    @Html.HiddenFor(u => u.ToList()[i].User_Age)
                    @Html.CheckBoxFor(u => u.ToList()[i].IsSelected, new { @class = "", @id = "cb-" + i })

        }

}

Server Side:

[HttpPost]
        public ActionResult Index(IEnumerable<User> users)
        {
            if (users.Count() == 0)
            {
                return RedirectToAction("Index");
            }
            else
            {
                User user;
                foreach (User u in users)
                {
                    if (u.IsSelected)
                    {
                        user = db.Users.ToList().Find(x => x.User_Id == u.User_Id);
                        db.Users.Remove(user);
                    }
                }
                db.SaveChanges();
                return RedirectToAction("Index");
            }
        }

notice that i have tried to put a hidden input for isSelected Variable But that still doesn't work

Body:
so, while no one cares about my question i found the solution by my self.
Controller can not receive the IsSelected property from the View because i have changed the identity of the checkbox like id,name and ...
that means if i dont change the the identities of the checkbox, the code will works but even this solution leads us to another problem that you no longer can find the checkbox by JS. so i dont give this answer green tick until someone finds a better way to fix it.

for this solution something that you have to do is change the check box code from this:

@Html.CheckBoxFor(u => u.ToList()[i].IsSelected, new { @class = "", @id = "cb-" + i })

to this:

@Html.CheckBoxFor(u => u.ToList()[i].IsSelected})

and it basically will works.


来源: stackexchange

问:
Deleting entire function definition in Vim
I've been trying Vim for any text editing work for almost a week now. I want to know the fastest way to select a C function definition.

For example, if I have a function like this:

void helloworlds( int num )
{
    int n;
    for ( n = 0; n < num; ++n ) {
        printf( "Hello World!\n" );
    }
}
```

How would I be able to delete the whole definition including the function name?

答:
I tried all the top answers here, but none of them works except the one by Nick which suggests to press f{ to get to the opening curly brace. Then V%d to delete the whole function.

Note that, the whole function gets yanked, so you can paste it elsewhere. I come across this use-case frequently, especially when moving if blocks inside another.

ContentLicense: CC BY-SA 4.0

Body:
I've been trying Vim for any text editing work for almost a week now. I want to know the fastest way to select a C function definition.

For example, if I have a function like this:

void helloworlds( int num )
{
    int n;
    for ( n = 0; n < num; ++n ) {
        printf( "Hello World!\n" );
    }
}

How would I be able to delete the whole definition including the function name?


问:
Array with only even number
for X in {18..2500} ; is one line of my script, which means to pick number one by one like: 18,19,20,21,22,23....till 2500

However I find I only need even number right now: 18,20,22,24.....2500

Then what should I do by a slight modify of the line?

Thanks

edit:
It's bash...

My script is now changed to:

```<code>#!/bin/bash

TASK=1101;

NUM=9;

TEND=1100;

for X in {18..2500};{

   if (X % 2 == 0);

   do

     echo "$X      echo \"Wait until $NUM job is done\" $NUM" ;

     NUM=$((NUM+2)) ;

     X=$((X+1)) ;

     TEND=$((TEND+100)) ;

     echo "$X      -t $TASK-$TEND jobs.sh" ;

     TASK=$((TASK+100)) ;}

done
</code>```

but got errors like:
line 15: syntax error near unexpected token `do'

答:
You can specify the increment:

```<code>for X in {18..2500..2}

   A sequence  expression takes the form {x..y[..incr]}, where x and y are
   either integers or single characters, and incr, an optional increment, is
   an integer.
</code>```

Or

```<code>for X in `seq 18 2 2500`
</code>```

ContentLicense: CC BY-SA 3.0

Title: Array with only even number

Body:
for X in {18..2500} ; is one line of my script, which means to pick number one by one like: 18,19,20,21,22,23....till 2500

However I find I only need even number right now: 18,20,22,24.....2500

Then what should I do by a slight modify of the line?

Thanks

edit:
It's bash...

My script is now changed to:

#!/bin/bash

TASK=1101;

NUM=9;

TEND=1100;

for X in {18..2500};{

   if (X % 2 == 0);

   do

     echo "$X      echo \"Wait until $NUM job is done\" $NUM" ;

     NUM=$((NUM+2)) ;

     X=$((X+1)) ;

     TEND=$((TEND+100)) ;

     echo "$X      -t $TASK-$TEND jobs.sh" ;

     TASK=$((TASK+100)) ;}

done

but got errors like:
line 15: syntax error near unexpected token `do'

Body:
You can specify the increment:

for X in {18..2500..2}

   A sequence  expression takes the form {x..y[..incr]}, where x and y are
   either integers or single characters, and incr, an optional increment, is
   an integer.

Or

for X in `seq 18 2 2500`


问:
CORS preflight request doesn't pass access control check: It does not have HTTP ok status
I am trying to make a GET/POST Request to my Wordpress REST API using Authorization Headers but in response i am getting

preflight request doesn't pass access control check: It does not have HTTP ok status.

I am using JWT Authentication for WP-API for Authentication and tried almost every possible option found on the internet but no luck.

Have a look at my current .htaccess configurations

```<code><IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule ^(.*) - [E=HTTP_AUTHORIZATION:%1]
SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1

RewriteCond %{REQUEST_METHOD} OPTIONS
RewriteRule ^(.*)$ $1 [R=200,L]

</IfModule>

<IfModule mod_headers.c>
  Header always set X-Content-Type-Options "nosniff"
  <IfModule mod_setenvif.c>
    SetEnvIf Origin "^(http://localhost:3000)$" CORS=$0
  </IfModule>
  Header set Access-Control-Allow-Origin %{CORS}e env=CORS
  Header set Access-Control-Allow-Credentials "true" env=CORS
  Header set Access-Control-Allow-Methods "GET, POST, OPTIONS, HEAD" env=CORS
  Header set Access-Control-Allow-Headers "*" env=CORS
  Header set Access-Control-Expose-Headers "*" env=CORS
  <FilesMatch "\.(php|html)$">
  </FilesMatch>
</IfModule>
</code>```

I am getting this error when the request is made from axios

Access to XMLHttpRequest at 'HIDDEN_SERVER_ADDRESS' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

In PostMan the calls are working fine and giving desired results.

答:
The solution provided by Azaz Khan worked for me. I searched for why it worked and I found this about request with OPTIONS method

when using Cross-Origin Resource Sharing (CORS), a preflight request with OPTIONS is being automatically sent, so the target resource would respond with acceptable parameters. In normal web development scnario, there is no need to make an OPTION call as it is being issued by browsers.

So I think before the auth request, a request with OPTIONS method has been fired, but the backend API did not give back a 200 OK response. For me the backend sent back a PHP error, maybe a 404 http error, I did not checked, but with this code I am sure the API gives back 200 OK response because of the exit:

```<code><?php
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json; charset=UTF-8');
header('Access-Control-Allow-Methods: GET,POST,PUT,PATCH,DELETE');
header('Access-Control-Allow-Headers: Content-Type,Access-Control-Allow-Headers,Authorization,X-Requested-With');

if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
  header('HTTP/1.1 200 OK');
  exit();
}
</code>```

Body:
I am trying to make a GET/POST Request to my Wordpress REST API using Authorization Headers but in response i am getting

preflight request doesn't pass access control check: It does not have HTTP ok status.

I am using JWT Authentication for WP-API for Authentication and tried almost every possible option found on the internet but no luck.

Have a look at my current .htaccess configurations

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule ^(.*) - [E=HTTP_AUTHORIZATION:%1]
SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1

RewriteCond %{REQUEST_METHOD} OPTIONS
RewriteRule ^(.*)$ $1 [R=200,L]

</IfModule>

<IfModule mod_headers.c>
  Header always set X-Content-Type-Options "nosniff"
  <IfModule mod_setenvif.c>
    SetEnvIf Origin "^(http://localhost:3000)$" CORS=$0
  </IfModule>
  Header set Access-Control-Allow-Origin %{CORS}e env=CORS
  Header set Access-Control-Allow-Credentials "true" env=CORS
  Header set Access-Control-Allow-Methods "GET, POST, OPTIONS, HEAD" env=CORS
  Header set Access-Control-Allow-Headers "*" env=CORS
  Header set Access-Control-Expose-Headers "*" env=CORS
  <FilesMatch "\.(php|html)$">
  </FilesMatch>
</IfModule>

I am getting this error when the request is made from axios

Access to XMLHttpRequest at 'HIDDEN_SERVER_ADDRESS' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

In PostMan the calls are working fine and giving desired results.

Body:
The solution provided by Azaz Khan worked for me. I searched for why it worked and I found this about request with OPTIONS method

when using Cross-Origin Resource Sharing (CORS), a preflight request with OPTIONS is being automatically sent, so the target resource would respond with acceptable parameters. In normal web development scnario, there is no need to make an OPTION call as it is being issued by browsers.

So I think before the auth request, a request with OPTIONS method has been fired, but the backend API did not give back a 200 OK response. For me the backend sent back a PHP error, maybe a 404 http error, I did not checked, but with this code I am sure the API gives back 200 OK response because of the exit:

<?php
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json; charset=UTF-8');
header('Access-Control-Allow-Methods: GET,POST,PUT,PATCH,DELETE');
header('Access-Control-Allow-Headers: Content-Type,Access-Control-Allow-Headers,Authorization,X-Requested-With');

if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
  header('HTTP/1.1 200 OK');
  exit();
}


问:
To get the number of opportunities in an Account
how to count number of opportunities related to account,

total number of opportunities field on account should be increment/decrement when Opportunity is created/deleted.

How to solve it, pl help me with sample code.

答:
```<code>public static void opportunityCount(List<opportunity> oppList) {
    set<id>accountIDs = new set<id>();
    list<Account> accList = new List<Account>();

    for (opportunity eachOppAccId:oppList) {
        accountIDs.add(eachOppAccId.AccountId);
    }

    for (Account eachAccount:[select id,No_Of_Opportunities__c, (select id, AccountID from opportunities) from Account where id In:accountIDs]) {
        eachAccount.No_Of_Opportunities__c=eachAccount.opportunities.size();
        accList.add(eachAccount);
    }

    update accList;
}
</code>```


问:
I cannot open ANACONDA Navigator
I completed all the steps described in the Anaconda troubleshot documantation but I could not accomplish to initialise it. Here is the anaconda prompt traceback code:

```<code>(base) C:\Users\DELL>anaconda navigator

Traceback (most recent call last):

File "C:\Users\DELL\anaconda3\Scripts\anaconda-script.py", line 6, in <module>

from binstar_client.scripts.cli import main

File "C:\Users\DELL\anaconda3\lib\site-packages\binstar_client\__init__.py", line 16, in <module>

from .errors import *

File "C:\Users\DELL\anaconda3\lib\site-packages\binstar_client\errors.py", line 1, in

<module>

from clyent.errors import ClyentError

File "C:\Users\DELL\anaconda3\lib\site-packages\clyent\__init__.py", line 10, in <module>

from pkg_resources import iter_entry_points

File "C:\Users\DELL\anaconda3\lib\site-packages\pkg_resources\__init__.py", line 32, in <module>

import plistlib

File "C:\Users\DELL\anaconda3\lib\plistlib.py", line 61, in <module>

from xml.parsers.expat import ParserCreate

ModuleNotFoundError: No module named 'xml.parsers'
</code>```

I think ı should import the module called xml.parsers however ı could not find out how to do it. I need someone to help me, thank you

答:
You can use the lite, cmd version using conda commands, it is the preferred option to activate environment and install packages.

Reference: https://docs.conda.io/projects/conda/en/latest/commands.html

Title: I cannot open ANACONDA Navigator

Body:
I completed all the steps described in the Anaconda troubleshot documantation but I could not accomplish to initialise it. Here is the anaconda prompt traceback code:

(base) C:\Users\DELL>anaconda navigator

Traceback (most recent call last):

File "C:\Users\DELL\anaconda3\Scripts\anaconda-script.py", line 6, in <module>

from binstar_client.scripts.cli import main

File "C:\Users\DELL\anaconda3\lib\site-packages\binstar_client\__init__.py", line 16, in <module>

from .errors import *

File "C:\Users\DELL\anaconda3\lib\site-packages\binstar_client\errors.py", line 1, in

<module>

from clyent.errors import ClyentError

File "C:\Users\DELL\anaconda3\lib\site-packages\clyent\__init__.py", line 10, in <module>

from pkg_resources import iter_entry_points

File "C:\Users\DELL\anaconda3\lib\site-packages\pkg_resources\__init__.py", line 32, in <module>

import plistlib

File "C:\Users\DELL\anaconda3\lib\plistlib.py", line 61, in <module>

from xml.parsers.expat import ParserCreate

ModuleNotFoundError: No module named 'xml.parsers'

I think ı should import the module called xml.parsers however ı could not find out how to do it. I need someone to help me, thank you


问:
TypeScript - Get ts 7053 error for the created array of objects
I've seen other StackOverflow answers, but none of them seem to be working. Here is the error I am getting:

```<code>Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Paycheck'.
  No index signature with a parameter of type 'string' was found on type 'Paycheck'.
</code>```

I get this when I try to iterate over the Array<Paycheck>, and use their keys to get their value. Is there anything wrong with the way I have created my types?

const seperated: Record<string, Array<string>> = {
    date: [],
    taxes: [],
    benefits: [],
    retirement: [],
    takeHome: [],
    total: [],
  };

type Paycheck = {
  date: string;
  taxes: number;
  benefits: number;
  retirement: number;
  takeHome: number;
  total: number;
};

// removing some code to go straight to forEach loop
// p is of type Paycheck
paychecks.forEach(p => {
    // seperated is pretty much the keys of paycheck
    Object.keys(seperated).forEach(key => {
      // p[key] is throwing the error I mentioned before
      seperated[key].push(p[key]);
    });
  });
```

What am I doing wrong? How do I add an index signature appropriately? I've looked at other solutions and can't get it to work.

答:
What you can do is to get the key from Paycheck via keyof.

let k = key as keyof Paycheck;
```
<p>And since all the properties (value) in <code>seperated</code> is with <code>Array<string></code> type.</p>
<pre class="lang-js prettyprint-override"><code>const seperated: Record<string, Array<string>> = {
  date: [],
  taxes: [],
  benefits: [],
  retirement: [],
  takeHome: [],
  total: [],
};
</code>```

Hence, you need to cast the value from each property in Paycheck as string before the use of push.

seperated[k].push(p[k].toString());
```
<blockquote>
<p>Complete code</p>
</blockquote>
<pre class="lang-js prettyprint-override"><code>paychecks.forEach(p => {
  Object.keys(seperated).forEach(key => {
    let k = key as keyof Paycheck;
    seperated[key].push(p[k].toString());
  });
});
</code>```

Sample Demo on Typescript Playground

Unless you define the indexable key signature for the Type, then you can pass the key as string for index accessing for the Type:

type Paycheck = {
  date: string;
  taxes: number;
  benefits: number;
  retirement: number;
  takeHome: number;
  total: number;
  [key: string]: string | number; // Here to specify key as string and union Value type
};
```
<pre class="lang-js prettyprint-override"><code>seperated[key].push(p[key].toString());
</code>```

Sample Demo (Define Indexable key Signature) on Typescript Playground

Body:
I've seen other StackOverflow answers, but none of them seem to be working. Here is the error I am getting:

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Paycheck'.
  No index signature with a parameter of type 'string' was found on type 'Paycheck'.

I get this when I try to iterate over the Array<Paycheck>, and use their keys to get their value. Is there anything wrong with the way I have created my types?

const seperated: Record<string, Array<string>> = {
    date: [],
    taxes: [],
    benefits: [],
    retirement: [],
    takeHome: [],
    total: [],
  };

type Paycheck = {
  date: string;
  taxes: number;
  benefits: number;
  retirement: number;
  takeHome: number;
  total: number;
};

// removing some code to go straight to forEach loop
// p is of type Paycheck
paychecks.forEach(p => {
    // seperated is pretty much the keys of paycheck
    Object.keys(seperated).forEach(key => {
      // p[key] is throwing the error I mentioned before
      seperated[key].push(p[key]);
    });
  });

What am I doing wrong? How do I add an index signature appropriately? I've looked at other solutions and can't get it to work.

Body:
What you can do is to get the key from Paycheck via keyof.

let k = key as keyof Paycheck;

And since all the properties (value) in seperated is with Array<string> type.

const seperated: Record<string, Array<string>> = {
  date: [],
  taxes: [],
  benefits: [],
  retirement: [],
  takeHome: [],
  total: [],
};

Hence, you need to cast the value from each property in Paycheck as string before the use of push.

seperated[k].push(p[k].toString());

Complete code

paychecks.forEach(p => {
  Object.keys(seperated).forEach(key => {
    let k = key as keyof Paycheck;
    seperated[key].push(p[k].toString());
  });
});

<a href="https://www.typescriptlang.org/play?#code/MYewdgzgLgBBCmAHeAnAhleATAXDASvKClgDzQoCWYA5gDQwCCK6AnuVFbQHzcwC8MAN4AoGOJhYM8PAG0AunTESoaAB7wIcxcvEAjeGHgAzSlC0wFSiTBTwolOwFtDUbdZVoA1vAASIF3ddGCgQVQAbIPEAXwBuEREoVmQYAAU0VmAACyIvAWFlKUw8CmoaePFVDQswAFcnAxQKmAMjU3M8OobUZrsHZ1dO+sbm1R9-QJgukeVQiKHuppE4hPD7GEQM7NyLdMyc4C8FfNkhIpkYACIAJgAGa4BGAFoH26fHy4YqzTwHhlaTGYLNcGH1HPAXGA3DAAMxfbx+AIXAAsXzCaEiMFet2i8niIgA9ATbBCQAA3MpwJEwUBYeAhEAwGiMihoSg0LKwUIwYwgFAAUTQ2Rg4RAIEQhOJiBglAgMBAxhCyXpe22hxEm32OwAdLyBUKsgAKaX8PiiGxEuBIVDSLAyuWIPpJGBOWrCqA5GA+VhyhUbLYHLzBADyegAVkQoNrvRBDQhkOhMFgAJS6vmC7KG70CM3BcRrWB5QTZtBy71+1WB5o2eM2pOyb3ybWIWoQI2IBtN0IAZU4ZUNyeT1Zg0SHylH+PEoEgIDW2tFNDj1sT2DH4iAA" rel="nofollow noreferrer">Sample Demo on Typescript Playground

Unless you define the indexable key signature for the Type, then you can pass the key as string for index accessing for the Type:

type Paycheck = {
  date: string;
  taxes: number;
  benefits: number;
  retirement: number;
  takeHome: number;
  total: number;
  [key: string]: string | number; // Here to specify key as string and union Value type
};

seperated[key].push(p[key].toString());

<a href="https://www.typescriptlang.org/play?#code/MYewdgzgLgBBCmAHeAnAhleATAXDASvKClgDzQoCWYA5gDQwCCK6AnuVFbQHzcwC8MAN4AoGOJhYM8PAG0AunTESoaAB7wIcxcvEAjeGHgAzSlC0wFSiTBTwolOwFtDUbdZVoA1vAASIF3ddGCgQVQAbIPEAXwBuEREoVmQYAAU0VmAACyIvAWFlKUw8CmoaePFVDQswAFcnAxQKmAMjU3M8OobUZrsHZ1dO+sbm1R9-QJgukeVQiKHupuVZH1YSzjL5da4aGAAfKeGekTiE8PsYRAzs3It0zJzgLwV82SEimRgAIgAmAAYfgBGAC0gL+wKBXwYVU0eEBDFaJjMFh+DD6jngLjAbhgAGZod4-AFPgAWaFhNCRGBgv7ReTxEQAekZtkxIAAbmU4MSYKAsPAQiAYDQhRQ0JQaFlYKEYMYQCgAKJobIwcIgECIJksxAwSgQGAgYwhZIC+43J4iK4PW4AOjliuVWQAFDr+HxRDZmXAkKhpFhdfrEH0kjAnLUVVAcjBVvrDZdro8vMEAPJ6ABWRCgNpjToQyHQmCwAEo7fKldknasBO7guI877Cyt4Kx5DbELUIM7EE2WzbQgBlDa0J1FovNGJj5TRSfKUCQEDnG1qmi5n0F7CT8RAA" rel="nofollow noreferrer">Sample Demo (Define Indexable key Signature) on Typescript Playground


问:
DISTINCT combined with CONCAT() not working
I am unable to resolve this issue. The 1st query below works and returns distinct values for the name column:

```<code>SELECT DISTINCT p.name
FROM products AS p
ORDER BY RAND() LIMIT 4;
</code>```

The 2nd query stops filtering DISTINCT values for name - when I use CONCAT() to return an sku:

```<code>SELECT DISTINCT p.name, CONCAT('B', p.id) AS sku
FROM products AS p
ORDER BY RAND() LIMIT 4;
</code>```

EDIT

Here is some sample data to test:

```<code>CREATE TABLE `products` (
`id` MEDIUMINT(8) UNSIGNED NOT NULL AUTO_INCREMENT,
`name` VARCHAR(60) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8;

INSERT INTO `products` VALUES (1, 'Truck');
INSERT INTO `products` VALUES (2, 'Truck');
INSERT INTO `products` VALUES (3, 'Truck');
INSERT INTO `products` VALUES (4, 'Car');
INSERT INTO `products` VALUES (5, 'Car');
INSERT INTO `products` VALUES (6, 'Car');
INSERT INTO `products` VALUES (7, 'Bike');
INSERT INTO `products` VALUES (8, 'Plane');
INSERT INTO `products` VALUES (9, 'Train');
INSERT INTO `products` VALUES (10, 'Canoe');
</code>```

It seems like a simple enough problem, but I am unable to solve it. Any help would be greatly appreciated. Thanks.

答:
Using ROW_NUMBER we can try:

WITH cte AS (
    SELECT *, ROW_NUMBER() OVER (PARTITION BY name ORDER BY RAND()) rn
    FROM products
)

SELECT id, name
FROM cte
WHERE rn = 1
ORDER BY RAND()  -- or whatever order you want here
LIMIT 4;
```

Body:
I am unable to resolve this issue. The 1st query below works and returns distinct values for the name column:

SELECT DISTINCT p.name
FROM products AS p
ORDER BY RAND() LIMIT 4;

The 2nd query stops filtering DISTINCT values for name - when I use CONCAT() to return an sku:

SELECT DISTINCT p.name, CONCAT('B', p.id) AS sku
FROM products AS p
ORDER BY RAND() LIMIT 4;

EDIT

Here is some sample data to test:

CREATE TABLE `products` (
`id` MEDIUMINT(8) UNSIGNED NOT NULL AUTO_INCREMENT,
`name` VARCHAR(60) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8;

INSERT INTO `products` VALUES (1, 'Truck');
INSERT INTO `products` VALUES (2, 'Truck');
INSERT INTO `products` VALUES (3, 'Truck');
INSERT INTO `products` VALUES (4, 'Car');
INSERT INTO `products` VALUES (5, 'Car');
INSERT INTO `products` VALUES (6, 'Car');
INSERT INTO `products` VALUES (7, 'Bike');
INSERT INTO `products` VALUES (8, 'Plane');
INSERT INTO `products` VALUES (9, 'Train');
INSERT INTO `products` VALUES (10, 'Canoe');

It seems like a simple enough problem, but I am unable to solve it. Any help would be greatly appreciated. Thanks.


问:
iOS - how to be notified when a thread (using GCD) ends it's job
I'm start to use GCD, and I need to know when a certain thread has ended it's job.

My code:

```<code>dispatch_queue_t registerDeviceQueue = dispatch_queue_create("RegisterDevice", NULL);
dispatch_async(registerDeviceQueue, ^{
    [self registerDevice];

    dispatch_async(dispatch_get_main_queue(), ^{
        [aiRegisterDevice stopAnimating];
    });
});
dispatch_release(registerDeviceQueue);
</code>```

I need to know when this tread has ended, so that the UIActivityView can stop.
The way it is now, it's stops before the thread ends.

Thanks,

RL

答:
I'd set up a group and use dispatch_group_wait to continue only when the computation has finished. To take your example:

```<code>dispatch_queue_t registerDeviceQueue = dispatch_queue_create("RegisterDevice", NULL);
dispatch_group_t group = dispatch_group_create();

dispatch_group_async(group, registerDeviceQueue, ^{
    [self registerDevice];
});

dispatch_group_wait(group, DISPATCH_TIME_FOREVER); // Block until we're ready
// Now we're good to call it:
[aiRegisterDevice stopAnimating];

dispatch_release(registerDeviceQueue);
dispatch_release(group);
</code>```

Or, if you want to prevent the callback blocking use dispatch_group_notify:

```<code>dispatch_queue_t registerDeviceQueue = dispatch_queue_create("RegisterDevice", NULL);
dispatch_group_t group = dispatch_group_create();

dispatch_group_async(group, registerDeviceQueue, ^{
    [self registerDevice];
}); // In this version, the group won't block

// This block gets called asynchronously when the above code is done:
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
    [aiRegisterDevice stopAnimating];
});

dispatch_release(registerDeviceQueue);
dispatch_release(group);
</code>```

Body:
I'm start to use GCD, and I need to know when a certain thread has ended it's job.

My code:

dispatch_queue_t registerDeviceQueue = dispatch_queue_create("RegisterDevice", NULL);
dispatch_async(registerDeviceQueue, ^{
    [self registerDevice];

    dispatch_async(dispatch_get_main_queue(), ^{
        [aiRegisterDevice stopAnimating];
    });
});
dispatch_release(registerDeviceQueue);

I need to know when this tread has ended, so that the UIActivityView can stop.
The way it is now, it's stops before the thread ends.

Thanks,

RL

Body:
I'd set up a group and use dispatch_group_wait to continue only when the computation has finished. To take your example:

dispatch_queue_t registerDeviceQueue = dispatch_queue_create("RegisterDevice", NULL);
dispatch_group_t group = dispatch_group_create();

dispatch_group_async(group, registerDeviceQueue, ^{
    [self registerDevice];
});

dispatch_group_wait(group, DISPATCH_TIME_FOREVER); // Block until we're ready
// Now we're good to call it:
[aiRegisterDevice stopAnimating];

dispatch_release(registerDeviceQueue);
dispatch_release(group);

Or, if you want to prevent the callback blocking use dispatch_group_notify:

dispatch_queue_t registerDeviceQueue = dispatch_queue_create("RegisterDevice", NULL);
dispatch_group_t group = dispatch_group_create();

dispatch_group_async(group, registerDeviceQueue, ^{
    [self registerDevice];
}); // In this version, the group won't block

// This block gets called asynchronously when the above code is done:
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
    [aiRegisterDevice stopAnimating];
});

dispatch_release(registerDeviceQueue);
dispatch_release(group);


问:
Busybox Bitbake Config does not save
I am trying to add devmem to my yocto image. I do this I run the command

```<code>bitbake -c menuconfig busybox
</code>```

I go to Miscellaneous Utilities and place a * in the devmem menu. Exit and save the config then perform a

```<code>bitbake busybox
</code>```

Followed by

```<code>bitbake core-image-full-cmdline
</code>```

When I boot my device the devmem program is not there, when I re-run the menuconfig for busybox the devmem option is no longer selected! What can I do to fix this?

答:
Busybox is like other projects that are using a .config to define the features needed to be compiled into the final output, just like the Linux kernel and U-boot, etc.

So, here how to deal with them in Yocto:

When you run:

```<code>bitbake busybox -c menuconfig
</code>```

it will run make menuconfig into its working directory and opens the configuration menu for you.

Now, if you save and exit, only the .config in the working directory will be changed, meaning that if the recipe get unpacked again your modification will be lost.

In addition, when you change the .config via menuconfig you need to force the compilation of the busybox recipe, because for bitbake it is already built:

```<code>bitbake busybox -c compile -f
</code>```

But, for the best practices, here what I suggest to you if you want your modification to be a feature that you can easily enable or disable from a recipe:

Run: bitbake busybox -c menuconfig

Edit and save your modification

Run: bitbake busybox -c diffconfig

The diffconfig command will give you a fragment.cfg file that contains the modifications you just did.

The file should contain:

```<code>CONFIG_DEVMEM=y
</code>```

A quick explaination about the fragment:

When you opened menuconfig it backed up .config to .config.old, and then diffconfig will give you the difference between them after saving your modification into .config.

Now, Busybox like other recipes that are using configuration files, they understand that if a .cfg file exists in their working directory, they need to apply it to their main .config file before compilation.

So, what you need to do after getting the fragment.cfg is to create a .bbappend recipe to busybox in your custom recipe and specify your new fragment:

```<code>meta-custom/
     | recipes-core/
         | busybox/
             | busybox_%.bbappend
             | busybox/
                 | devmem.cfg
</code>```

Now, busybox_%.bbappend contains:

```<code>FILESEXTRAPATHS_prepend := "${THISDIR}/${PN}:"
SRC_URI += "file://devmem.cfg"
</code>```

Now, when you re-bitbake Busybox again, it will unpack the fragment and apply it.

To check if the fragment is applied after the bitbake completes, you can check the .config file:

First get the Build directory path of Busybox

```<code>bitbake -e busybox | grep ^B=
</code>```

Grep for CONFIG_DEVMEM

```<code>grep CONFIG_DEVMEM <path_of_previous_command>/.config
</code>```

You should see:

```<code>CONFIG_DEVMEM=y
</code>```

Title: Busybox Bitbake Config does not save

Body:
I am trying to add devmem to my yocto image. I do this I run the command

bitbake -c menuconfig busybox

I go to Miscellaneous Utilities and place a * in the devmem menu. Exit and save the config then perform a

bitbake busybox

Followed by

bitbake core-image-full-cmdline

When I boot my device the devmem program is not there, when I re-run the menuconfig for busybox the devmem option is no longer selected! What can I do to fix this?

Body:
Busybox is like other projects that are using a .config to define the features needed to be compiled into the final output, just like the Linux kernel and U-boot, etc.

So, here how to deal with them in Yocto:

When you run:

bitbake busybox -c menuconfig

it will run make menuconfig into its working directory and opens the configuration menu for you.

Now, if you save and exit, only the .config in the working directory will be changed, meaning that if the recipe get unpacked again your modification will be lost.

In addition, when you change the .config via menuconfig you need to force the compilation of the busybox recipe, because for bitbake it is already built:

bitbake busybox -c compile -f

But, for the best practices, here what I suggest to you if you want your modification to be a feature that you can easily enable or disable from a recipe:

Run: bitbake busybox -c menuconfig

Edit and save your modification

Run: bitbake busybox -c diffconfig

The diffconfig command will give you a fragment.cfg file that contains the modifications you just did.

The file should contain:

CONFIG_DEVMEM=y

A quick explaination about the fragment:

When you opened menuconfig it backed up .config to .config.old, and then diffconfig will give you the difference between them after saving your modification into .config.

Now, Busybox like other recipes that are using configuration files, they understand that if a .cfg file exists in their working directory, they need to apply it to their main .config file before compilation.

So, what you need to do after getting the fragment.cfg is to create a .bbappend recipe to busybox in your custom recipe and specify your new fragment:

meta-custom/
     | recipes-core/
         | busybox/
             | busybox_%.bbappend
             | busybox/
                 | devmem.cfg

Now, busybox_%.bbappend contains:

FILESEXTRAPATHS_prepend := "${THISDIR}/${PN}:"
SRC_URI += "file://devmem.cfg"

Now, when you re-bitbake Busybox again, it will unpack the fragment and apply it.

To check if the fragment is applied after the bitbake completes, you can check the .config file:

First get the Build directory path of Busybox

bitbake -e busybox | grep ^B=

Grep for CONFIG_DEVMEM

grep CONFIG_DEVMEM <path_of_previous_command>/.config

You should see:

CONFIG_DEVMEM=y


问:
Short way to constrain template parameter without boiler plate code for a struct
consider this example:

#include <iostream>
template <typename T, std::size_t I>
struct Foo
{

};

template <typename T>
struct specializes_foo : std::false_type {};

template <typename T, std::size_t I>
struct specializes_foo<Foo<T, I>> : std::true_type {};

template <typename T>
concept foo = specializes_foo<T>::value;

int main()
{
  std::cout << foo<int> << "\n";
  std::cout << foo<Foo<int,3>> << "\n";
}
```
<p>is there a shorter way in C++20? I know that you could do a concept for "specializes template", e.g.:</p>
<pre class="lang-cpp prettyprint-override"><code>// checks if a type T specializes a given template class template_class
// note: This only works with typename template parameters.
// e.g.: specializes<std::array<int, 3>, std::array> will yield a compilation error.
//       workaround: add a specialization for std::array.

namespace specializes_impl
{
template <typename T, template <typename...> typename>
struct is_specialization_of : std::false_type {};

template <typename... Args, template <typename...> typename template_class>
struct is_specialization_of<template_class<Args...>, template_class> : std::true_type {};
}

template <typename T, template <typename...> typename template_class>
inline constexpr bool is_specialization_of_v = specializes_impl::is_specialization_of<T,template_class>::value;

template <typename T, template <typename...> typename template_class>
using is_specialization_of_t = specializes_impl::is_specialization_of<T,template_class>::type;

template<typename T, template <typename...> typename template_class>
concept specializes = is_specialization_of_v<T, template_class>;
</code>```

However, this fails with non-type template parameters such as "size_t". Is there a way so I could, for example just write:

```<code>void test(Foo auto xy);
</code>```

I know that since C++20 there came a couple of other ways to constrain template parameters of a function, however, is there a short way to say "I dont care how it specializes the struct as long as it does"?

答:
Nope.

There's no way to write a generic is_specialization_of that works for both templates with all type parameters and stuff like std::array (i.e. your Foo), because there's no way to write a template that takes a parameter of any kind.

There's a proposal for a language feature that would allow that (P1985), but it's still just a proposal and it won't be in C++23. But it directly allows for a solution for this. Likewise, the reflection proposal (P1240) would allow for a way to do this (except that you'd have to spell the concept Specializes<^Foo> instead of Specializes<Foo>).

Until one of these things happens, you're either writing a bespoke concept for your template, or rewriting your template to only take type parameters.

Body:
consider this example:

#include <iostream>
template <typename T, std::size_t I>
struct Foo
{

};

template <typename T>
struct specializes_foo : std::false_type {};

template <typename T, std::size_t I>
struct specializes_foo<Foo<T, I>> : std::true_type {};

template <typename T>
concept foo = specializes_foo<T>::value;

int main()
{
  std::cout << foo<int> << "\n";
  std::cout << foo<Foo<int,3>> << "\n";
}

is there a shorter way in C++20? I know that you could do a concept for "specializes template", e.g.:

// checks if a type T specializes a given template class template_class
// note: This only works with typename template parameters.
// e.g.: specializes<std::array<int, 3>, std::array> will yield a compilation error.
//       workaround: add a specialization for std::array.

namespace specializes_impl
{
template <typename T, template <typename...> typename>
struct is_specialization_of : std::false_type {};

template <typename... Args, template <typename...> typename template_class>
struct is_specialization_of<template_class<Args...>, template_class> : std::true_type {};
}

template <typename T, template <typename...> typename template_class>
inline constexpr bool is_specialization_of_v = specializes_impl::is_specialization_of<T,template_class>::value;

template <typename T, template <typename...> typename template_class>
using is_specialization_of_t = specializes_impl::is_specialization_of<T,template_class>::type;

template<typename T, template <typename...> typename template_class>
concept specializes = is_specialization_of_v<T, template_class>;

However, this fails with non-type template parameters such as "size_t". Is there a way so I could, for example just write:

void test(Foo auto xy);

I know that since C++20 there came a couple of other ways to constrain template parameters of a function, however, is there a short way to say "I dont care how it specializes the struct as long as it does"?


问:
PyCharm warns about unresolved attribute for dict generated attributes
Consider the following code:

```<code>class SomeClass:
    def __init__(self, config):
        for key, value in config.items():
            self.__setattr__(key, value)

    def foo(self):
        print(self.a)
</code>```

PyCharm 2017.1.1 warns me about unresolved attribute a and I absolutely agree with it. But I don't want to write a blob of attributes in the constructor.

Is there any workaround to write the same functionality without warning? Or at least, how can I notify PyCharm not to warn me about attributes of this particular class?

Update: I don't want to disable PyCharm warnings.

答:
I agree on the fact that dynamic attribute definition is not good idea.
At least, one can use the type definition if the set of to-be-for-sure attributes is known.

```<code>class SomeClass:
    a: str

    def __init__(self, config):
        for key, value in config.items():
            self.__setattr__(key, value)

    def foo(self):
        print(self.a)
</code>```

Nevertheless, in order to disable the PyCharm (at least in the latest versions) warning for all the attribute references for one class you can define the __getattr__ method.

```<code>class SomeClass:
    def __init__(self, config):
        for key, value in config.items():
            self.__setattr__(key, value)

    def __getattr__(self, name: str):
        return self.__dict__[name]
        # return super().__getattr__(name)  # it works but causes a PyCharm warning

    def foo(self):
        print(self.a)

# Verification
config = {"a" : "b"}
instance = SomeClass(config)
print(instance.a)
instance.foo()
</code>```

Body:
Consider the following code:

class SomeClass:
    def __init__(self, config):
        for key, value in config.items():
            self.__setattr__(key, value)

    def foo(self):
        print(self.a)

PyCharm 2017.1.1 warns me about unresolved attribute a and I absolutely agree with it. But I don't want to write a blob of attributes in the constructor.

Is there any workaround to write the same functionality without warning? Or at least, how can I notify PyCharm not to warn me about attributes of this particular class?

Update: I don't want to disable PyCharm warnings.

Body:
I agree on the fact that dynamic attribute definition is not good idea.
At least, one can use the type definition if the set of to-be-for-sure attributes is known.

class SomeClass:
    a: str

    def __init__(self, config):
        for key, value in config.items():
            self.__setattr__(key, value)

    def foo(self):
        print(self.a)

Nevertheless, in order to disable the PyCharm (at least in the latest versions) warning for all the attribute references for one class you can define the __getattr__ method.

class SomeClass:
    def __init__(self, config):
        for key, value in config.items():
            self.__setattr__(key, value)

    def __getattr__(self, name: str):
        return self.__dict__[name]
        # return super().__getattr__(name)  # it works but causes a PyCharm warning

    def foo(self):
        print(self.a)

# Verification
config = {"a" : "b"}
instance = SomeClass(config)
print(instance.a)
instance.foo()


问:
How do I capture the output of a script if it is being ran by the task scheduler?
Using Windows Server 2008, how do I go about capturing the output of a script that is being ran with the windows task scheduler?

I'm testing a rather long custom printing batch-script, and for debugging purposes, I would like to see all of the output from it every night.

答:
Combining the other answers, which each had some useful tips, but none of them captured every nuance:

In the Task Scheduler > Actions:

Action: Start a program

Program/script: cmd

Add arguments: /c ""C:\my path\my task.cmd" >> "C:\my path\my task.log" 2>&1"

The above example demonstrates these features:

Allows spaces in the path/filename. If there are no spaces in the path, then you can eliminate the nested quotes: /c "C:\path\task.cmd >> C:\path\task.log 2>&1"

Appends to the log. If you want to overwrite the log each time, then use > instead of >>

Includes both STDOUT and STDERR in the log. If you only want STDOUT, then remove 2>&1


问:
Set the location in iPhone Simulator
How can I set the location (as it's picked up in CoreLocation services) in the iPhone Simulator? </p>

答:
As of iOS 15.2 and Xcode 13.2.2, the simulator has a configurable location.

Under the Features menu, the last entry is "Location"; this gives you a sub menu with:

None

Custom Location

City Run

City Bicycle Ride

Freeway Drive

Apple

Custom Location lets you enter a Lat/Long value. Bicycle ride, City Run, and Freeway Drive are simulation of a moving location (in Cupertino, of course).

OwnerDisplayName: Cliff

Title: Set the location in iPhone Simulator


问:
How to remove entire substring from '<' to '>' in Java
I have a program that takes an input string. I want to delete anything inside the characters '<' and '>'. For example if the string says

```<code>"P.S.<!--
BODY
   {
   color:white;
   background-color: transparent;
   font-family:sans-serif;
   }
--> Hello how are you today?"
</code>```

I want the output string to only contain "P.S. Hello how are you today?". Is there a simple way to do this in Java? Thanks

答:
Use a regular expression:

```<code>newstr = str.replaceAll("<[^>]*>", "");
</code>```

What this means is to find every substring beginning with <, then any number of characters that are not >, and then the character >. Then replace all these substrings with the empty string, "".

Reference: java.lang.String.replaceAll()

Body:
I have a program that takes an input string. I want to delete anything inside the characters '<' and '>'. For example if the string says

"P.S. Hello how are you today?"

I want the output string to only contain "P.S. Hello how are you today?". Is there a simple way to do this in Java? Thanks

Body:
Use a regular expression:

newstr = str.replaceAll("<[^>]*>", "");

What this means is to find every substring beginning with <, then any number of characters that are not >, and then the character >. Then replace all these substrings with the empty string, "".

Reference: java.lang.String.replaceAll()


问:
Vue Watcher not working on component created with Vue.extend
I have a Parent component with a select input which is bound through v-model to a variable in data.

Besides, I create child components dynamically using Vue.extend, which i pass the propsData which also includes the value of the select.

This components have a watcher for the prop that is related to the select input.

When i create the component it receives the props succesfully, The problem comes when I update the value of the select input that doesn't trigger the watcher on the child component.

I've been looking for similar situations but have not found something that helps me solve this problem, i don't know why it doesn't trigger the watcher on the child component when the select input changes.

Any help would be very preciated.

Here i create the component dynamically:

```<code>let PresupuestoFormularioVue = Vue.extend(PresupuestoFormulario)
let instance = new PresupuestoFormularioVue({
  propsData: {
    //The prop related to select input
    seguro: this.seguro,
  }
})
instance.$mount()
this.$refs.formularioContenedor.appendChild(instance.$el)
</code>```

And this is the watcher in the component which isn't working:

```<code>watch:{
  seguro:{
    handler: function( newVal ){
      console.log(newVal)
    },
  },
},
</code>```

答:
It's not the watch that doesn't work. It's the bindings. You're assigning the current value of this.seguro, not the reactive object itself. However, a new Vue() can add this binding for you.

As a sidenote, whether PresupuestoFormulario is a Vue.extend() doesn't matter. It can be any valid VueConstructor: a Vue.extend(), Vue.component() or a valid SFC (with name and template): export default {...}.

Here's how to do it:

```<code>methods: {
  addPresupuestoFormulario() {
    const div = document.createElement('div');
    this.$el.appendChild(div);
    new Vue({
      components: { PresupuestoFormulario },
      render: h => h("presupuesto-formulario", {
        props: {
          seguro: this.seguro
        }
      })
    }).$mount(div)
  }
}
</code>```

The
 initially appended to the parent will get replaced upon mounting with the actual template of PresupuestoFormulario and the bindings will be set, exactly as if you had <presupuesto-formulario :seguro="seguro" /> in the parent template from the start.

The really cool part about it is that the parent component doesn't need to have PresupuestoFormulario declared in its components.

Here's a working example:

const Test = Vue.component('test', {
  template: `<div>message: {{message}}</div>`,
  props: ['message'],
  watch: {
    message: console.log
  }
})

new Vue({
  el: '#app',
  data: () => ({
    msg: "¯\\_(ツ)_/¯"
  }),
  methods: {
    addComponent() {
      const div = document.createElement("div");
      this.$el.appendChild(div);
      new Vue({
        components: {
          Test
        },
        render: h => h("test", {
          props: {
            message: this.msg
          }
        })
      }).$mount(div);
    }
  }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
<div id="app">
  <input v-model="msg">
  <button @click="addComponent">Add dynamic child</button>
</div></code>```

A separate note, about using this.$el.appendChild(). While this works when you're using a root Vue instance (a so-called Vue app), it will likely fail when using a normal Vue component, as Vue2 components are limited to having only 1 root element.

It's probably a good idea to have an empty container (e.g:
) in the parent, and use this.$refs.container.appendChild() instead.

Body:
I have a Parent component with a select input which is bound through v-model to a variable in data.

Besides, I create child components dynamically using Vue.extend, which i pass the propsData which also includes the value of the select.

This components have a watcher for the prop that is related to the select input.

When i create the component it receives the props succesfully, The problem comes when I update the value of the select input that doesn't trigger the watcher on the child component.

I've been looking for similar situations but have not found something that helps me solve this problem, i don't know why it doesn't trigger the watcher on the child component when the select input changes.

Any help would be very preciated.

Here i create the component dynamically:

let PresupuestoFormularioVue = Vue.extend(PresupuestoFormulario)
let instance = new PresupuestoFormularioVue({
  propsData: {
    //The prop related to select input
    seguro: this.seguro,
  }
})
instance.$mount()
this.$refs.formularioContenedor.appendChild(instance.$el)

And this is the watcher in the component which isn't working:

watch:{
  seguro:{
    handler: function( newVal ){
      console.log(newVal)
    },
  },
},

Body:
It's not the watch that doesn't work. It's the bindings. You're assigning the current value of this.seguro, not the reactive object itself. However, a new Vue() can add this binding for you.

As a sidenote, whether PresupuestoFormulario is a Vue.extend() doesn't matter. It can be any valid VueConstructor: a Vue.extend(), Vue.component() or a valid SFC (with name and template): export default {...}.

Here's how to do it:

methods: {
  addPresupuestoFormulario() {
    const div = document.createElement('div');
    this.$el.appendChild(div);
    new Vue({
      components: { PresupuestoFormulario },
      render: h => h("presupuesto-formulario", {
        props: {
          seguro: this.seguro
        }
      })
    }).$mount(div)
  }
}

The <div> initially appended to the parent will get replaced upon mounting with the actual template of PresupuestoFormulario and the bindings will be set, exactly as if you had <presupuesto-formulario :seguro="seguro" /> in the parent template from the start.

The really cool part about it is that the parent component doesn't need to have PresupuestoFormulario declared in its components.

Here's a working example:

const Test = Vue.component('test', {
  template: `<div>message: {{message}}</div>`,
  props: ['message'],
  watch: {
    message: console.log
  }
})

new Vue({
  el: '#app',
  data: () => ({
    msg: "¯\\_(ツ)_/¯"
  }),
  methods: {
    addComponent() {
      const div = document.createElement("div");
      this.$el.appendChild(div);
      new Vue({
        components: {
          Test
        },
        render: h => h("test", {
          props: {
            message: this.msg
          }
        })
      }).$mount(div);
    }
  }
})

<script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
<div id="app">
  <input v-model="msg">
  <button @click="addComponent">Add dynamic child</button>
</div>

A separate note, about using this.$el.appendChild(). While this works when you're using a root Vue instance (a so-called Vue app), it will likely fail when using a normal Vue component, as Vue2 components are limited to having only 1 root element.

It's probably a good idea to have an empty container (e.g: <div ref="container" />) in the parent, and use this.$refs.container.appendChild() instead.


问:
Extend Register Form
Does anyone have any experience with extending the registration form in Shopware 6 with additional required fields?
I'm having a hard time getting this to work properly, since the registration form can be submitted even if all the required fields I added are empty.

What is the proper way to implement form violations my own?
I already made sure to add required="required" to the input.
I've seen it done two seperate ways in the twig templates regarding registration but none of them work for me.

答:
I tried if by myself, adding a form component with required="required" is enough for the frontend validation:

added (for testing) at the top of vendor/shopware/storefront/Resources/views/storefront/component/address/address-personal-company.html.twig

```<code>  <div class="form-now">
      {% block component_address_form_company_legal_label %}
          <label class="form-label"
                 for="{{ prefix }}legal">
              {{ "address.companyLegalLabel"|trans|sw_sanitize }}{% if accountTypeRequired %}{{ "general.required"|trans|sw_sanitize }}{% endif %}
          </label>
      {% endblock %}

      {% block component_address_form_company_legal_input %}
          <input type="text"
                 class="form-control{% if violationPath %} is-invalid{% endif %}"
                 id="{{ prefix }}company"
                 placeholder="{{ "address.companyLegalPlaceholder"|trans|striptags }}"
                 name="{{ prefix }}[company]"
                 value="{{ address.get('legal') }}"
                 required="required">
      {% endblock %}

      {% block component_address_form_company_legal_input_error %}
          {% if violationPath %}
              {% sw_include '@Storefront/storefront/utilities/form-violation.html.twig' %}
          {% endif %}
      {% endblock %}
  </div>
</code>```

The field is validated and I cannot submit the form (if I filled all but the custom field)

Make sure you have the _input_error_component

In addition, you should always validate your data in the backend as well, so that nobody who can use the browsers dev-tools to delete required fields can override your validation.

Such a validation could be added by decorating \Shopware\Core\Checkout\Customer\SalesChannel\RegisterRoute::register and pass additional fields to the parameter $additionalValidationDefinitions and calling the original function.

Title: Extend Register Form

Body:
I tried if by myself, adding a form component with required="required" is enough for the frontend validation:

added (for testing) at the top of vendor/shopware/storefront/Resources/views/storefront/component/address/address-personal-company.html.twig

  <div class="form-now">
      {% block component_address_form_company_legal_label %}
          <label class="form-label"
                 for="{{ prefix }}legal">
              {{ "address.companyLegalLabel"|trans|sw_sanitize }}{% if accountTypeRequired %}{{ "general.required"|trans|sw_sanitize }}{% endif %}
          </label>
      {% endblock %}

      {% block component_address_form_company_legal_input %}
          <input type="text"
                 class="form-control{% if violationPath %} is-invalid{% endif %}"
                 id="{{ prefix }}company"
                 placeholder="{{ "address.companyLegalPlaceholder"|trans|striptags }}"
                 name="{{ prefix }}[company]"
                 value="{{ address.get('legal') }}"
                 required="required">
      {% endblock %}

      {% block component_address_form_company_legal_input_error %}
          {% if violationPath %}
              {% sw_include '@Storefront/storefront/utilities/form-violation.html.twig' %}
          {% endif %}
      {% endblock %}
  </div>

The field is validated and I cannot submit the form (if I filled all but the custom field)

Make sure you have the _input_error_component

In addition, you should always validate your data in the backend as well, so that nobody who can use the browsers dev-tools to delete required fields can override your validation.

Such a validation could be added by decorating \Shopware\Core\Checkout\Customer\SalesChannel\RegisterRoute::register and pass additional fields to the parameter $additionalValidationDefinitions and calling the original function.


问:
Flutter bottomNavigator with indexed stack
Question regarding navigating between tabs using indexed stack to display relevant page. I'm doing this in order to keep scroll/state of pages. This works fine. I can change the current page displayed by clicking tab - and can also navigate inside each page  (each page is wrapped with it's own Navigator). This is the code for rendering the pages.

```<code>Widget build(BuildContext context) {
return IndexedStack(
    index: widget.selectedIndex,
    children: List.generate(widget._size, (index) {
  return _buildNavigator(index);
}));
</code>```

}

Mu problem is that IndexedStack builds all pages at once. In some of my pages I want to load data from an API, I want to do it when the widget first time built and only if the page is currently visible. Is there a way to do so? in my current implementation all widgets build at once and so all my API calls are called even for the pages that are not currently painted.

Not sure if i'm missing something here, or there is a better way to implement bottom navigation bar. BTW i'm also using Provider for state management.

答:
Use a PageView instead of an IndexedStack

```<code> PageView(
            physics: const NeverScrollableScrollPhysics(),
            controller: _pageController,
            children: const [
              Page1(),
              Page2(),
              Page3(),
            ],
          ),
</code>```

you can switch pages using the pageController

```<code>_pageController.jumpToPage(0);
</code>```

Body:
Question regarding navigating between tabs using indexed stack to display relevant page. I'm doing this in order to keep scroll/state of pages. This works fine. I can change the current page displayed by clicking tab - and can also navigate inside each page  (each page is wrapped with it's own Navigator). This is the code for rendering the pages.

Widget build(BuildContext context) {
return IndexedStack(
    index: widget.selectedIndex,
    children: List.generate(widget._size, (index) {
  return _buildNavigator(index);
}));

}

Mu problem is that IndexedStack builds all pages at once. In some of my pages I want to load data from an API, I want to do it when the widget first time built and only if the page is currently visible. Is there a way to do so? in my current implementation all widgets build at once and so all my API calls are called even for the pages that are not currently painted.

Not sure if i'm missing something here, or there is a better way to implement bottom navigation bar. BTW i'm also using Provider for state management.

Body:
Use a PageView instead of an IndexedStack

 PageView(
            physics: const NeverScrollableScrollPhysics(),
            controller: _pageController,
            children: const [
              Page1(),
              Page2(),
              Page3(),
            ],
          ),

you can switch pages using the pageController

_pageController.jumpToPage(0);


问:
for-loop confusion
I'm supposed to write a code that will ask the user to input their names and the number of times they want it printed but I'm facing challenges. Kindly find my code below.</p>
```<code>name = input('What is your name:\n ')
print('How many times do you want your name printed?')
answer = input(int())
for times in answer:
    print(name)
</code>```

答:
The statement should be int(input()) and not the reverse. The int function casts the input to expect an integer value so that mathematical operations can be performed. Hence we need to convert the input() to int

Also, for i in answer should be changed to for i in range(answer)
Thank you @AbhyudayVaish for reminding me.

Title: for-loop confusion

Body:
I'm supposed to write a code that will ask the user to input their names and the number of times they want it printed but I'm facing challenges. Kindly find my code below.

name = input('What is your name:\n ')
print('How many times do you want your name printed?')
answer = input(int())
for times in answer:
    print(name)


问:
Java Jar run as Daemon cant issue exec()
I have a java socket server I wrote to allow me to keep a web clusters code base in sync. When I run the init.d script from a shell login like so

```<code>[root@web11 www]# /etc/init.d/servermngr start
</code>```

Logout and all will work fine but if the server reboots or I run the init.d using services like so

```<code>[root@web11 www]# service servermngr start
</code>```

Any of the exec() commands passed to the socket server will not get executed on the linux box. I am assuming it has to do with the JVM having no real shell.  If I login and run

```<code>[root@web11 www]# /etc/init.d/servermngr start
</code>```

...and logout all runs nice all CVS commands are executed.

Another note when run as a service the socket server responds to status checks so it is running

Here is the init.d script

```<code>#!/bin/sh
# chkconfig: 2345 95 1
# description: Starts Daemon Using ServerManager.jar.
#
# Source function library.
. /etc/init.d/functions

start () {
    echo -n $"Starting ServerManager: "

    # start daemon
    cd /www/servermanager/
    daemon java -jar ServerManager.jar > /www/logs/ServerManager.log &
    RETVAL=$?
    echo
    [ $RETVAL = 0 ] && touch /var/lock/subsys/cups
    echo "";
    return $RETVAL
}

stop () {
    # stop daemon
    echo -n $"Stopping $prog: "
    kill `ps uax | grep -i "java -jar ServerManager.ja[r]" | head -n 1 | awk '{print $2}'`
    RETVAL=$?
    echo "";
    return $RETVAL
}

restart() {
    stop
    start
}

case $1 in
    start)
        start
    ;;
    stop)
        stop
    ;;
    *)

    echo $"Usage: servermngr {start|stop}"
    exit 3
esac

exit $RETVAL
</code>```

And the Java responsible for actually executing the code:

```<code>// Build cmd Array of Strings
            String[] cmd = {"/bin/sh", "-c", "cd /www;cvs up -d htdocs/;cvs up -d phpinclude/"};
            final Process process;
            try {
                process = Runtime.getRuntime().exec(cmd);

                BufferedReader buf = new BufferedReader(new InputStreamReader(
                        process.getInputStream()));

                // Since this is a CVS UP we return the Response to PHP
                if(input.matches(".*(cvs up).*")){
                    String line1;
                    out.println("cvsupdate-start");
                    System.out.println("CVS Update" + input);
                    while ((line1 = buf.readLine()) != null) {
                        out.println(line1);
                        System.out.println("CVS:" + line1);
                    }
                    out.println("cvsupdate-end");
                }

            } catch (IOException ex) {
                System.out.println("IOException on Run cmd " + CommandFactory.class.getName() + " " + ex);
                Logger.getLogger(CommandFactory.class.getName()).log(Level.SEVERE, null, ex);
            }
</code>```

Thx for any help

答: You might be happier using http://akuma.kohsuke.org/ to help you with this stuff, or at least Apache Commons Exec.</p>

Body:
I have a java socket server I wrote to allow me to keep a web clusters code base in sync. When I run the init.d script from a shell login like so

[root@web11 www]# /etc/init.d/servermngr start

Logout and all will work fine but if the server reboots or I run the init.d using services like so

[root@web11 www]# service servermngr start

Any of the exec() commands passed to the socket server will not get executed on the linux box. I am assuming it has to do with the JVM having no real shell.  If I login and run

[root@web11 www]# /etc/init.d/servermngr start

...and logout all runs nice all CVS commands are executed.

Another note when run as a service the socket server responds to status checks so it is running

Here is the init.d script

#!/bin/sh
# chkconfig: 2345 95 1
# description: Starts Daemon Using ServerManager.jar.
#
# Source function library.
. /etc/init.d/functions

start () {
    echo -n $"Starting ServerManager: "

    # start daemon
    cd /www/servermanager/
    daemon java -jar ServerManager.jar > /www/logs/ServerManager.log &
    RETVAL=$?
    echo
    [ $RETVAL = 0 ] && touch /var/lock/subsys/cups
    echo "";
    return $RETVAL
}

stop () {
    # stop daemon
    echo -n $"Stopping $prog: "
    kill `ps uax | grep -i "java -jar ServerManager.ja[r]" | head -n 1 | awk '{print $2}'`
    RETVAL=$?
    echo "";
    return $RETVAL
}

restart() {
    stop
    start
}

case $1 in
    start)
        start
    ;;
    stop)
        stop
    ;;
    *)

    echo $"Usage: servermngr {start|stop}"
    exit 3
esac

exit $RETVAL

And the Java responsible for actually executing the code:

// Build cmd Array of Strings
            String[] cmd = {"/bin/sh", "-c", "cd /www;cvs up -d htdocs/;cvs up -d phpinclude/"};
            final Process process;
            try {
                process = Runtime.getRuntime().exec(cmd);

                BufferedReader buf = new BufferedReader(new InputStreamReader(
                        process.getInputStream()));

                // Since this is a CVS UP we return the Response to PHP
                if(input.matches(".*(cvs up).*")){
                    String line1;
                    out.println("cvsupdate-start");
                    System.out.println("CVS Update" + input);
                    while ((line1 = buf.readLine()) != null) {
                        out.println(line1);
                        System.out.println("CVS:" + line1);
                    }
                    out.println("cvsupdate-end");
                }

            } catch (IOException ex) {
                System.out.println("IOException on Run cmd " + CommandFactory.class.getName() + " " + ex);
                Logger.getLogger(CommandFactory.class.getName()).log(Level.SEVERE, null, ex);
            }

Thx for any help


问:
Multiply string - [Leetcode] Problem with Java
Question is:

Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string.

Note: You must not use any built-in BigInteger library or convert the inputs to integer directly.

Code:

```<code>class Solution {
    public String multiply(String num1, String num2) {
        long n1=0, n2=0, res;
        n1 =  Long.parseLong(num1);
        n2 =  Long.parseLong(num2);
        res = n1 * n2;
        String str = Long.toString(res);
        return str;
    }
}
</code>```

Question is:

Its working properly when I give smaller number is like:

Input :40,
90

Output:3600

Input :100,
2099

Output:209900

If i give input like this:

Input :498828660196, 840477629533

Output:"-3269442614257959980"

But the Actual output is : 419254329864656431168468. I don't know why answer coming like this. am also using long datatype. Anyone explain me and give solution for this problem.

答:
Thank you guys!

I find the Solution.

```<code>class Solution {
    public String multiply(String num1, String num2) {
         if (num1.equals("0") || num2.equals("0")) return "0";
        int l1 = num1.length(), l2 = num2.length(), l = l1 + l2;
        char[] ans = new char[l];
        char[] c1 = num1.toCharArray();
        char[] c2 = num2.toCharArray();
        for (int i = l1 - 1; i >= 0; --i) {
            int c = c1[i] - '0';
            for (int j = l2 - 1; j >= 0; --j) {
                ans[i + j + 1] +=  c * (c2[j] - '0');
            }
        }
        for (int i = l - 1; i > 0; --i) {
            if (ans[i] > 9) {
                ans[i - 1] += ans[i] / 10;
                ans[i] %= 10;
            }
        }
        StringBuilder sb = new StringBuilder();
        int i = 0;
        for (; ; ++i) if (ans[i] != 0) break;
        for (; i < ans.length; ++i) sb.append((char) (ans[i] + '0'));
        return sb.toString();
    }
}
</code>```

Body:
Question is:

Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string.

Note: You must not use any built-in BigInteger library or convert the inputs to integer directly.

Code:

class Solution {
    public String multiply(String num1, String num2) {
        long n1=0, n2=0, res;
        n1 =  Long.parseLong(num1);
        n2 =  Long.parseLong(num2);
        res = n1 * n2;
        String str = Long.toString(res);
        return str;
    }
}

Question is:

Its working properly when I give smaller number is like:

Input :40,
90

Output:3600

Input :100,
2099

Output:209900

If i give input like this:

Input :498828660196, 840477629533

Output:"-3269442614257959980"

But the Actual output is : 419254329864656431168468. I don't know why answer coming like this. am also using long datatype. Anyone explain me and give solution for this problem.

Body:
Thank you guys!

I find the Solution.

class Solution {
    public String multiply(String num1, String num2) {
         if (num1.equals("0") || num2.equals("0")) return "0";
        int l1 = num1.length(), l2 = num2.length(), l = l1 + l2;
        char[] ans = new char[l];
        char[] c1 = num1.toCharArray();
        char[] c2 = num2.toCharArray();
        for (int i = l1 - 1; i >= 0; --i) {
            int c = c1[i] - '0';
            for (int j = l2 - 1; j >= 0; --j) {
                ans[i + j + 1] +=  c * (c2[j] - '0');
            }
        }
        for (int i = l - 1; i > 0; --i) {
            if (ans[i] > 9) {
                ans[i - 1] += ans[i] / 10;
                ans[i] %= 10;
            }
        }
        StringBuilder sb = new StringBuilder();
        int i = 0;
        for (; ; ++i) if (ans[i] != 0) break;
        for (; i < ans.length; ++i) sb.append((char) (ans[i] + '0'));
        return sb.toString();
    }
}


问:
What is the usage of * as an argument in discord.py API functions?
I referenced the code in this answer about an avatar command for Discord Python bots:

@commands.command()
async def avatar(self, ctx, *,  avamember : discord.Member=None):
    userAvatarUrl = avamember.avatar_url
    await ctx.send(userAvatarUrl)
```

What is the function of * as its own argument? I expect to see it as *args or **kwargs

答:
They are called keyword-only arguments. They restrict all the parameters that come after the * to accept keyword-only arguments.

With your given example:

```<code>@commands.command()
async def avatar(self, ctx, *,  avamember : discord.Member=None):
    userAvatarUrl = avamember.avatar_url
    await ctx.send(userAvatarUrl)
</code>```

If you invoke the avatar function with positional arguments only:

```<code>avatar(ctx_value, "member_value")
</code>```

It will throw an error. TypeError: avatar() takes 1 positional argument but 2 were given.

The function will only accept a positional argument as the first argument, and a keyword-only argument as a second argument. To avoid the error, you must invoke the avatar  function with a keyword-only argument as a second argument:

```<code>avatar(ctx_value, avamember="member_value")
</code>```

Note. Am using strings for "member_value" because I don't know the discord.Member type hint. So you must replace it with the appropriate type.

Body:
I referenced the code in this answer about an avatar command for Discord Python bots:

@commands.command()
async def avatar(self, ctx, *,  avamember : discord.Member=None):
    userAvatarUrl = avamember.avatar_url
    await ctx.send(userAvatarUrl)

What is the function of * as its own argument? I expect to see it as *args or **kwargs

Body:
They are called keyword-only arguments. They restrict all the parameters that come after the * to accept keyword-only arguments.

With your given example:

@commands.command()
async def avatar(self, ctx, *,  avamember : discord.Member=None):
    userAvatarUrl = avamember.avatar_url
    await ctx.send(userAvatarUrl)

If you invoke the avatar function with positional arguments only:

avatar(ctx_value, "member_value")

It will throw an error. TypeError: avatar() takes 1 positional argument but 2 were given.

The function will only accept a positional argument as the first argument, and a keyword-only argument as a second argument. To avoid the error, you must invoke the avatar  function with a keyword-only argument as a second argument:

avatar(ctx_value, avamember="member_value")

Note. Am using strings for "member_value" because I don't know the discord.Member type hint. So you must replace it with the appropriate type.


问:
Sum for array with While loop JS
I have tried to make a while loop where I add all the numbers of the array to one sum. I keep on getting an endless loop. I've also tried to do (array.length) (array.length --) (array.length>numbers)
But nothing I tried worked... any suggestions? :)</p>
```<code>function sumNumbersWhileLoop(array, sum) {
  array = [1, 5, 4, 6, 7];
  sum = 0;
  for (let numbers of array) {
    while (array.length>0) {
      sum += numbers;

      console.log(sum);
    }
  }
}
</code>```

答:
You don't need the while loop. The for...of loop is going to iterate over the array till its length.

function sumNumbersWhileLoop(array, sum) {
  array = [1, 5, 4, 6, 7];
  sum = 0;
  for (let numbers of array) {
      sum += numbers;
  }
  console.log(sum)
}

sumNumbersWhileLoop();```
</div>
</div>
</p>
<p>If you want to use while, or <code>reduce</code>, then you can do the following:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function sumNumbersWhileLoop() {
  const array = [1, 5, 4, 6, 7];
  let len = array.length - 1;
  let sum = 0;
  while (len >=0) {
    sum += array[len--];
  }
  console.log(sum);

  // Or use reduce :
  const reduceSum = array.reduce((acc, item) => acc + item, 0);
  console.log(reduceSum);
}

sumNumbersWhileLoop();</code>```

Title: Sum for array with While loop JS

Body:
I have tried to make a while loop where I add all the numbers of the array to one sum. I keep on getting an endless loop. I've also tried to do (array.length) (array.length --) (array.length>numbers)
But nothing I tried worked... any suggestions? :)

function sumNumbersWhileLoop(array, sum) {
  array = [1, 5, 4, 6, 7];
  sum = 0;
  for (let numbers of array) {
    while (array.length>0) {
      sum += numbers;

      console.log(sum);
    }
  }
}

Body:
You don't need the while loop. The for...of loop is going to iterate over the array till its length.

function sumNumbersWhileLoop(array, sum) {
  array = [1, 5, 4, 6, 7];
  sum = 0;
  for (let numbers of array) {
      sum += numbers;
  }
  console.log(sum)
}

sumNumbersWhileLoop();

If you want to use while, or reduce, then you can do the following:

function sumNumbersWhileLoop() {
  const array = [1, 5, 4, 6, 7];
  let len = array.length - 1;
  let sum = 0;
  while (len >=0) {
    sum += array[len--];
  }
  console.log(sum);

  // Or use reduce :
  const reduceSum = array.reduce((acc, item) => acc + item, 0);
  console.log(reduceSum);
}

sumNumbersWhileLoop();


问:
Python Selenium - pressing javascript src button
I'm trying to click on a button that is generated using this javascript code

```<code><script type='text/javascript' value name ="clickme"
src='//examplecode.com/example.js>
</code>```

I'm using driver.findelement and it says "selenium.common.exceptions.ElementNotInteractableException: Message: element not interactable", heres my python code:

```<code>from webdriver_manager.chrome import ChromeDriverManager
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
import time

options = webdriver.ChromeOptions()  # Initializing Chrome Options from the Webdriver
options.add_experimental_option("useAutomationExtension", False)  # Adding Argument to Not Use Automation Extension
options.add_experimental_option('excludeSwitches', ['enable-logging'])
options.add_experimental_option("excludeSwitches", ["enable-automation"])  # Excluding enable-automation Switch

#options.add_argument("disable-popup-blocking")
#options.add_argument("disable-notifications")
options.add_argument("--enable-infobars")
options.add_argument("--enable-extensions")
options.add_argument("disable-gpu")
options.add_argument("start-maximized")
prefs = {"profile.default_content_setting_values.notifications" : 1}
options.add_experimental_option("prefs",prefs)

driver = webdriver.Chrome(options=options,executable_path=ChromeDriverManager().install())
driver.get("http://examplesite.com/")

tabName = driver.find_element(By.NAME, "clickme")
tabName.click()

time.sleep(200)
driver.quit()
</code>```

答:
maybe have some element layer upper than click() element

try this code:

```<code>tabname=WebDriverWait(driver, 2).until(EC.element_to_be_clickable((By.CLASS_NAME, 'balabala')))
driver.execute_script("arguments[0].click();", tabname)
</code>```

Body:
maybe have some element layer upper than click() element

try this code:

tabname=WebDriverWait(driver, 2).until(EC.element_to_be_clickable((By.CLASS_NAME, 'balabala')))
driver.execute_script("arguments[0].click();", tabname)


问:
Selenium keeps opening "data;." tab when I want it to be headless
I created a bot to scan usernames and pull up people's stats in the game Warzone, but I am having a problem, every time I run my code everything works but it keeps opening that "data;." tab of chrome and I don't want it to open anything. How do I fix this? I think I got myself into a deep hole of not understanding this whole chromedriver side of Selenium and I probably have more stuff on my code causing this that I don't need. Below is the part of my code running the Selenium tasks. Like I said, everything works fine but I hate how it opens a chrome tab every time I run the code and I have to manually close it. Thank you!</p>
```<code>from pathlib import Path

from tkinter import Tk, Canvas, Entry, Text, Button, PhotoImage
import tkinter as tk
import threading
import pyautogui
import time
import cv2
from pytesseract import *
from PIL import Image
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.service import Service
ser = Service(executable_path=ChromeDriverManager().install())
driver = webdriver.Chrome(service=ser)
from selenium.webdriver.common.by import By
import mss
import mss.tools

pytesseract.tesseract_cmd = r'...tesseract.exe'

OUTPUT_PATH = Path(__file__).parent
ASSETS_PATH = OUTPUT_PATH / Path("./assets")

def relative_to_assets(path: str) -> Path:
    return ASSETS_PATH / Path(path)

if __name__ == "__main__":

    window = tk.Tk()
    window.geometry("431x550")
    window.configure(bg = "#ECECEC")
    window.title("BOT")
    window.iconbitmap("icon.ico")

    def webscrape(username, original):
        t = time.time()

        options = webdriver.ChromeOptions()
        options.headless = True
        driver = webdriver.Chrome(options=options)
        driver.get(f'https://cod.tracker.gg/warzone/profile/atvi/{username}/overview')
        page_title = driver.find_elements(By.CLASS_NAME, 'lead')

        if not page_title or page_title[0] == "WARZONE STATS NOT FOUND":
            print("WARZONE STATS NOT FOUND - Private profile")
            usernameBox.delete(0, tk.END)
            usernameBox.insert(0, "WARZONE STATS NOT FOUND - Private profile")

        else:
            usernameBox.delete(0, tk.END)
            usernameBox.insert(0, original)
            search = driver.find_elements(By.CLASS_NAME, 'value')

            if len(search) > 4:
                print("Wins:", search[0].text)
                winsBox.delete(0, tk.END)
                winsBox.insert(0, search[0].text)

                print("Win %:", search[1].text)
                winPercentageBox.delete(0, tk.END)
                winPercentageBox.insert(0, search[1].text)

                print("Kills:", search[2].text)
                killsBox.delete(0, tk.END)
                killsBox.insert(0, search[2].text)

                print("K/D:", search[3].text)
                KDBox.delete(0, tk.END)
                KDBox.insert(0, search[3].text)

                print("Score/min:", search[4].text)
                scoreMinBox.delete(0, tk.END)
                scoreMinBox.insert(0, search[4].text)

            else:
                print("Incorrect name or private profile")

                usernameBox.delete(0, tk.END)
                usernameBox.insert(0, original)

                winsBox.delete(0, tk.END)
                winsBox.insert(0, "-----")

                winPercentageBox.delete(0, tk.END)
                winPercentageBox.insert(0, "-----")

                killsBox.delete(0, tk.END)
                killsBox.insert(0, "-----")

                KDBox.delete(0, tk.END)
                KDBox.insert(0, "-----")

                scoreMinBox.delete(0, tk.END)
                scoreMinBox.insert(0, "-----")

        elapsed = time.time() - t
        print(elapsed, "Time to webscrape")
        webscrapeBox.delete(0, tk.END)
        webscrapeBox.insert(0, str(round(elapsed, 2)) + " seconds")

        driver.close()
</code>```

答: Replace options.headless = True with options.add_argument('--headless').

Body:
I created a bot to scan usernames and pull up people's stats in the game Warzone, but I am having a problem, every time I run my code everything works but it keeps opening that "data;." tab of chrome and I don't want it to open anything. How do I fix this? I think I got myself into a deep hole of not understanding this whole chromedriver side of Selenium and I probably have more stuff on my code causing this that I don't need. Below is the part of my code running the Selenium tasks. Like I said, everything works fine but I hate how it opens a chrome tab every time I run the code and I have to manually close it. Thank you!

from pathlib import Path

from tkinter import Tk, Canvas, Entry, Text, Button, PhotoImage
import tkinter as tk
import threading
import pyautogui
import time
import cv2
from pytesseract import *
from PIL import Image
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.service import Service
ser = Service(executable_path=ChromeDriverManager().install())
driver = webdriver.Chrome(service=ser)
from selenium.webdriver.common.by import By
import mss
import mss.tools

pytesseract.tesseract_cmd = r'...tesseract.exe'

OUTPUT_PATH = Path(__file__).parent
ASSETS_PATH = OUTPUT_PATH / Path("./assets")

def relative_to_assets(path: str) -> Path:
    return ASSETS_PATH / Path(path)

if __name__ == "__main__":

    window = tk.Tk()
    window.geometry("431x550")
    window.configure(bg = "#ECECEC")
    window.title("BOT")
    window.iconbitmap("icon.ico")

    def webscrape(username, original):
        t = time.time()

        options = webdriver.ChromeOptions()
        options.headless = True
        driver = webdriver.Chrome(options=options)
        driver.get(f'https://cod.tracker.gg/warzone/profile/atvi/{username}/overview')
        page_title = driver.find_elements(By.CLASS_NAME, 'lead')

        if not page_title or page_title[0] == "WARZONE STATS NOT FOUND":
            print("WARZONE STATS NOT FOUND - Private profile")
            usernameBox.delete(0, tk.END)
            usernameBox.insert(0, "WARZONE STATS NOT FOUND - Private profile")

        else:
            usernameBox.delete(0, tk.END)
            usernameBox.insert(0, original)
            search = driver.find_elements(By.CLASS_NAME, 'value')

            if len(search) > 4:
                print("Wins:", search[0].text)
                winsBox.delete(0, tk.END)
                winsBox.insert(0, search[0].text)

                print("Win %:", search[1].text)
                winPercentageBox.delete(0, tk.END)
                winPercentageBox.insert(0, search[1].text)

                print("Kills:", search[2].text)
                killsBox.delete(0, tk.END)
                killsBox.insert(0, search[2].text)

                print("K/D:", search[3].text)
                KDBox.delete(0, tk.END)
                KDBox.insert(0, search[3].text)

                print("Score/min:", search[4].text)
                scoreMinBox.delete(0, tk.END)
                scoreMinBox.insert(0, search[4].text)

            else:
                print("Incorrect name or private profile")

                usernameBox.delete(0, tk.END)
                usernameBox.insert(0, original)

                winsBox.delete(0, tk.END)
                winsBox.insert(0, "-----")

                winPercentageBox.delete(0, tk.END)
                winPercentageBox.insert(0, "-----")

                killsBox.delete(0, tk.END)
                killsBox.insert(0, "-----")

                KDBox.delete(0, tk.END)
                KDBox.insert(0, "-----")

                scoreMinBox.delete(0, tk.END)
                scoreMinBox.insert(0, "-----")

        elapsed = time.time() - t
        print(elapsed, "Time to webscrape")
        webscrapeBox.delete(0, tk.END)
        webscrapeBox.insert(0, str(round(elapsed, 2)) + " seconds")

        driver.close()


问:
What is the decoded output of a video codec?
Folks,

I am wondering if someone can explain to me what exactly is the output of video decoding. Let's say it is a H.264 stream in an MP4 container.

From displaying something on the screen, I guess decoder can provider two different types of output:

Point - (x, y) coordinate of the location and the (R, G, B) color for the pixel

Rectangle (x, y, w, h) units for the rectangle and the (R, G, B) color to display

There is also the issue of time stamp.

Can you please enlighten me or point me the right link on what is generated out of a decoder and how a video client can use this information to display something on screen?

I intend to download VideoLAN source and examine it but some explanation would be helpful.

Thank you in advance for your help.

Regards,
Peter

答:
None of the above.

Usually the output will be a stream of bytes that contains just the color data.  The X,Y location is implied by the dimensions of the video.

In other words, the first three bytes might encode the color value at (0, 0), the second three byte the value at (0, 1), and so on.  Some formats might use four bytes groups, or even a number of bits that doesn't add up to one byte -- for example, if you use 5 bits for each color component and you have three color components, that's 15 bits per pixel.  This might be padded to 16 bits (exactly two bytes) for efficiency, since that will align data in a way that CPUs can better process it.

When you've processed exactly as many values as the video is wide, you've reached the end of that row.  When you've processed exactly as many rows as the video is high, you've reached the end of that frame.

As for the interpretation of those bytes, that depends on the color space used by the codec.  Common color spaces are YUV, RGB, and HSL/HSV.

It depends strongly on the codec in use and what input format(s) it supports; the output format is usually restricted to the set of formats that are acceptable inputs.

Timestamp data is a bit more complex, since that can be encoded in the video stream itself, or in the container.  At a minimum, the stream would need a framerate; from that, the time of each frame can be determined by counting how many frames have been decoded already.  Other approaches, like the one taken by AVI, is to include a byte-offset for every Nth frame (or just the keyframes) at the end of the file to enable rapid seeking.  (Otherwise, you would need to decode every frame up to the timestamp you're looking for in order to determine where in the file that frame is.)

And if you're considering audio data too, note that with most codecs and containers, the audio and video streams are independent and know nothing about each other.  During encoding, the software that writes both streams into the container format does a process called muxing.  It will write out the data in chunks of N seconds each, alternating between streams.  This allows whoever is reading the stream to get N seconds of video, then N seconds of audio, then another N seconds of video, and so on.  (More than one audio stream might be included too -- this technique is frequently used to mux together video, and English and Spanish audio tracks into a single file that contains three streams.)  In fact, even subtitles can be muxed in with the other streams.


问:
Pattern attribute not working as expected?
So I'm trying to make a form for my assignment, and I am using the pattern attribute in html so only certain characters are required to be typed on the text box. But for some reason, the form is saying using that I'm using an incorrect format even though I made my pattern attribute that way.

Here's an example of the code and a picture of the problem.

<form>
  Mobile Number:
  <input type="text" required id="mnumber" pattern="[0-9]">

  <input type="submit" value="submit">
</form>```

答: you just need to change type="text" to type="number"


问:
How to avoid tearing with pygame on Linux/X11
I've been playing with pygame (on Debian/Lenny).
It seems to work nicely, except for annoying tearing of blits (fullscreen or windowed mode).

I'm using the default SDL X11 driver.  Googling suggests that it's a known issue with SDL that X11 provides no vsync facility (even with a display created with FULLSCREEN|DOUBLEBUF|HWSURFACE flags), and I should use the "dga" driver instead.

However, running

```<code>SDL_VIDEODRIVER=dga ./mygame.py
</code>```

throws in pygame initialisation with

```<code>pygame.error: No available video device
</code>```

(despite xdpyinfo showing an XFree86-DGA extension present).

So: what's the trick to getting tear-free vsynced flips ?  Either by getting this dga thing working or some other mechanism ?

答: Use the SCALED flag and vsync=True when calling set_mode and you should be all set (at least on any systems which actually support this; in some scenarios SDL still can't give you a VSync-capable surface but they are increasingly rare).

ContentLicense: CC BY-SA 2.5

Body:
I've been playing with pygame (on Debian/Lenny).
It seems to work nicely, except for annoying tearing of blits (fullscreen or windowed mode).

I'm using the default SDL X11 driver.  Googling suggests that it's a known issue with SDL that X11 provides no vsync facility (even with a display created with FULLSCREEN|DOUBLEBUF|HWSURFACE flags), and I should use the "dga" driver instead.

However, running

SDL_VIDEODRIVER=dga ./mygame.py

throws in pygame initialisation with

pygame.error: No available video device

(despite xdpyinfo showing an XFree86-DGA extension present).

So: what's the trick to getting tear-free vsynced flips ?  Either by getting this dga thing working or some other mechanism ?


问:
How to destruct array of numbers in an object and combine to one in javascript?
I have this object:

```<code>const memorized = [
 {
  verses: [1, 2, 3, 4, 5],
  when: '2022 Jan 14'
 },
 {
  verses: [6, 7, 8, 9]
  when: '2022 Jan 15'
 },
 {
  verses: [10, 11, 12, 13, 14, 15]
  when: '2022 Jan 16'
 },
...
]
</code>```

and how can I get the total verses like this:

```<code>const total_verses = [1, 2, 3, 4, 5, ..., 15]
</code>```

My possible solution would be:

```<code>let total_verses = []
memorized.map(ar => total_verses.push(...ar.verses))
</code>```

But I would like to do it by just filtering or mapping.

答:
No need to push when you map - that is wasting an array

EITHER push in a forEach or just flatMap the array

const memorized = [ { verses: [1, 2, 3, 4, 5], when: '2022 Jan 14' }, { verses: [6, 7, 8, 9], when: '2022 Jan 15' }, { verses: [10, 11, 12, 13, 14, 15], when: '2022 Jan 16'  } ];

const total_verses = memorized.flatMap(({ verses }) => verses)

console.log(total_verses);```

Body:
I have this object:

const memorized = [
 {
  verses: [1, 2, 3, 4, 5],
  when: '2022 Jan 14'
 },
 {
  verses: [6, 7, 8, 9]
  when: '2022 Jan 15'
 },
 {
  verses: [10, 11, 12, 13, 14, 15]
  when: '2022 Jan 16'
 },
...
]

and how can I get the total verses like this:

const total_verses = [1, 2, 3, 4, 5, ..., 15]

My possible solution would be:

let total_verses = []
memorized.map(ar => total_verses.push(...ar.verses))

But I would like to do it by just filtering or mapping.