问:
Kube-VIP unable to find Namespace
I am exploring the kube-vip, following the doc => https://kube-vip.io/control-plane/ for a multi-master (HA) cluster setup

```<code>sudo docker run --network host --rm ghcr.io/kube-vip/kube-vip:main manifest pod \
--vip 192.168.0.75 \
--arp \
--leaderElection | sudo tee /etc/kubernetes/manifests/vip.yaml

sudo kubeadm init --kubernetes-version 1.17.0 --control-plane-endpoint 192.168.0.75 --upload-certs
</code>```

I have been trying to perform kubeadm init but it always times out with a reason kubelet unhealthy

On further debugging, I found that one kubevip container is failing with the message :

```<code>time="2022-02-11T06:21:54Z" level=info msg="No interface is specified for VIP in config, auto-detecting default Interface"
time="2022-02-11T06:21:54Z" level=info msg="kube-vip will bind to interface [eth0]"
time="2022-02-11T06:21:54Z" level=info msg="server started"
time="2022-02-11T06:21:54Z" level=info msg="Starting Kube-vip Manager with the ARP engine"
time="2022-02-11T06:21:54Z" level=info msg="Namespace [kube-system], Hybrid mode [false]"
time="2022-02-11T06:21:54Z" level=fatal msg="starting new Manager error -> unable to find Namespace"
</code>```

I tried the same with BGP protocol (using the --bgp option in docker run), which leads me to a different error

```<code>time="2022-02-12T07:35:33Z" level=info msg="No interface is specified for VIP in config, auto-detecting default Interface"
time="2022-02-12T07:35:33Z" level=info msg="kube-vip will bind to interface [eth0]"
time="2022-02-12T07:35:33Z" level=info msg="server started"
time="2022-02-12T07:35:33Z" level=info msg="Starting Kube-vip Manager with the BGP engine"
time="2022-02-12T07:35:33Z" level=info msg="Namespace [kube-system], Hybrid mode [false]"
time="2022-02-12T07:35:33Z" level=info msg="Starting the BGP server to advertise VIP routes to BGP peers"
time="2022-02-12T07:35:33Z" level=fatal msg="starting new Manager error -> You need to provide at least one peer"
</code>```

What is these error suggesting ?

答:
You are missing the --controlplane flag to start the kube-vip manager as the control plane. Otherwise it will try to connect to another non-existing control plane.

```<code>sudo docker run --network host --rm ghcr.io/kube-vip/kube-vip:main manifest pod \
--vip 192.168.0.75 \
--arp \
--controlplane \
--leaderElection | sudo tee /etc/kubernetes/manifests/vip.yaml
</code>```

If this doesn't resolve your issue please increase the log level --log 5.

Title: Kube-VIP unable to find Namespace

Body:
I am exploring the kube-vip, following the doc => https://kube-vip.io/control-plane/ for a multi-master (HA) cluster setup

sudo docker run --network host --rm ghcr.io/kube-vip/kube-vip:main manifest pod \
--vip 192.168.0.75 \
--arp \
--leaderElection | sudo tee /etc/kubernetes/manifests/vip.yaml

sudo kubeadm init --kubernetes-version 1.17.0 --control-plane-endpoint 192.168.0.75 --upload-certs

I have been trying to perform kubeadm init but it always times out with a reason kubelet unhealthy

On further debugging, I found that one kubevip container is failing with the message :

time="2022-02-11T06:21:54Z" level=info msg="No interface is specified for VIP in config, auto-detecting default Interface"
time="2022-02-11T06:21:54Z" level=info msg="kube-vip will bind to interface [eth0]"
time="2022-02-11T06:21:54Z" level=info msg="server started"
time="2022-02-11T06:21:54Z" level=info msg="Starting Kube-vip Manager with the ARP engine"
time="2022-02-11T06:21:54Z" level=info msg="Namespace [kube-system], Hybrid mode [false]"
time="2022-02-11T06:21:54Z" level=fatal msg="starting new Manager error -> unable to find Namespace"

I tried the same with BGP protocol (using the --bgp option in docker run), which leads me to a different error

time="2022-02-12T07:35:33Z" level=info msg="No interface is specified for VIP in config, auto-detecting default Interface"
time="2022-02-12T07:35:33Z" level=info msg="kube-vip will bind to interface [eth0]"
time="2022-02-12T07:35:33Z" level=info msg="server started"
time="2022-02-12T07:35:33Z" level=info msg="Starting Kube-vip Manager with the BGP engine"
time="2022-02-12T07:35:33Z" level=info msg="Namespace [kube-system], Hybrid mode [false]"
time="2022-02-12T07:35:33Z" level=info msg="Starting the BGP server to advertise VIP routes to BGP peers"
time="2022-02-12T07:35:33Z" level=fatal msg="starting new Manager error -> You need to provide at least one peer"

What is these error suggesting ?

Body:
You are missing the --controlplane flag to start the kube-vip manager as the control plane. Otherwise it will try to connect to another non-existing control plane.

sudo docker run --network host --rm ghcr.io/kube-vip/kube-vip:main manifest pod \
--vip 192.168.0.75 \
--arp \
--controlplane \
--leaderElection | sudo tee /etc/kubernetes/manifests/vip.yaml

If this doesn't resolve your issue please increase the log level --log 5.


来源: stackexchange

问:
Why does summation of string and number output a string but multiplication of them output a number in javascript?
string + number

```<code>const a = "5";
const b = 7;

console.log(a + b);
</code>```

Output is -
57

string * number

```<code>const a = "5";
const b = 7;

console.log(a * b);
</code>```

Output is -
35

答: it's based on what the creators of JS thought would be more useful. In every other language you can concatenate the strings, numbers and other stuff using the +. So in JS they thought that would be a nice solution as well. But then... what does it mean to multiply a string? The creators of JS had no answer, so assumed this must be a mathematical operation.

ContentLicense: CC BY-SA 4.0

Body:
string + number

const a = "5";
const b = 7;

console.log(a + b);

Output is -
57

string * number

const a = "5";
const b = 7;

console.log(a * b);

Output is -
35


问:
Visual Studio Code source control not showing changes
Visual Studio Code source control panel is empty when I click on it.  Nothing to expand and nothing to click on.

Things I've tried:

Uninstalled/Reinstalled Git

Uninstall/Reinstalled VS Code

Removed extensions folder

答:
I had this problem, because I was changing files one folder down from where I opened Visual Studio Code.

Solution- open Visual Studio Code without a location, File/Open Folder - open the folder I am directly working out of.

Unstaged changes now show in the direct folder I'm working in. Unstage changes previously auto-staged by Visual Studio Code when working on a nested project directory to see them (open a Terminal and run git reset).


问:
I cannot understand why this code is wrong
```<code>class Solution:

    def firstRepeated(self,A, n):

        #arr : given array
        #n : size of the array

        D={}
        for i in range(n):
            if A[i] not in D:
                D[A[i]]=[i]
            else:
                D[A[i]].append(i)
        c=0
        for i in D:
            if(len(D[i])>1):
                c+=1
                return (D[i][0]+1)

        if(c==0): return -1

A=[1 ,5 ,3, 4, 3, 5, 6]

n=len(A)

M=Solution()

print(M.firstRepeated(A,n))
</code>```

this is a problem from geeks for geeks.
" Given an array arr[] of size n, find the first repeating element. The element should occurs more than once and the index of its first occurrence should be the smallest"

the index positions(returned) are assumed to start from 1. If there is no
such element that has frequency more than 1 , we gotta return -1

This code is actually working correctly in VS code, but whenever I use
it in GFG IDE, it's failing(shows 3 as output instead of 2)

Kindly help, as I have no idea what's wrong here.

答:
Your code is returning the index of the repeating element based on the order that keys are stored in the dictionary. After having collected all values in a dictionary keyed by number, your code iterates that dictionary like this:

```<code>    for i in D:
</code>```

The order in which this loop will visit the dictionary keys (indexes), depends on the Python version. See Are dictionaries ordered in Python 3.6+?.

At the time of writing Geeks for Geeks uses version 3.5.2, and so the order the keys are visited is undefined, which means that sometimes your function will not return the expected answer on their web site, while on your own environment it will always be correct (if you have a more recent version).

Correction

You can change your code so it does not rely on the order of the dictionary. Instead, during insertion, check which is the dictionary key with the least value. Here is your code corrected just with that change in mind:

```<code>class Solution:
    def firstRepeated(self,A, n):
        D = {}
        c = len(A)
        for i in range(n):
            if A[i] not in D:
                D[A[i]] = i  # No need to maintain a list
            elif D[A[i]] < c: # When the dupe's first index is earlier...
                c = D[A[i]]

        if c == len(A):
            return -1
        return c + 1
</code>```

This will do the trick.

Body:
class Solution:

    def firstRepeated(self,A, n):

        #arr : given array
        #n : size of the array

        D={}
        for i in range(n):
            if A[i] not in D:
                D[A[i]]=[i]
            else:
                D[A[i]].append(i)
        c=0
        for i in D:
            if(len(D[i])>1):
                c+=1
                return (D[i][0]+1)

        if(c==0): return -1

A=[1 ,5 ,3, 4, 3, 5, 6]

n=len(A)

M=Solution()

print(M.firstRepeated(A,n))

this is a problem from geeks for geeks.
" Given an array arr[] of size n, find the first repeating element. The element should occurs more than once and the index of its first occurrence should be the smallest"

the index positions(returned) are assumed to start from 1. If there is no
such element that has frequency more than 1 , we gotta return -1

This code is actually working correctly in VS code, but whenever I use
it in GFG IDE, it's failing(shows 3 as output instead of 2)

Kindly help, as I have no idea what's wrong here.

Body:
Your code is returning the index of the repeating element based on the order that keys are stored in the dictionary. After having collected all values in a dictionary keyed by number, your code iterates that dictionary like this:

    for i in D:

The order in which this loop will visit the dictionary keys (indexes), depends on the Python version. See Are dictionaries ordered in Python 3.6+?.

At the time of writing Geeks for Geeks uses version 3.5.2, and so the order the keys are visited is undefined, which means that sometimes your function will not return the expected answer on their web site, while on your own environment it will always be correct (if you have a more recent version).

Correction

You can change your code so it does not rely on the order of the dictionary. Instead, during insertion, check which is the dictionary key with the least value. Here is your code corrected just with that change in mind:

class Solution:
    def firstRepeated(self,A, n):
        D = {}
        c = len(A)
        for i in range(n):
            if A[i] not in D:
                D[A[i]] = i  # No need to maintain a list
            elif D[A[i]] < c: # When the dupe's first index is earlier...
                c = D[A[i]]

        if c == len(A):
            return -1
        return c + 1

This will do the trick.


问:
Election Polls Query
I have SQL tables below.

```<code>Candidates
ID Name Position
1 Pacquio President
2 Leni    President
3 Herbert Senator
4 Tulfo   Senator
5 Marcoleta Senator

Voters
ID  Name Candidates
1  Noel 1,3,4
2 Mar   2,4,5
3 Dan.  2,4,3
</code>```

The result should be below

```<code>Results
Position Name Votes
President Leni 2
President Pacquio 1
Senator Tulfo 2
Senator Herbert 1
Senator Marcoleta 1
</code>```

What should be my SQL Query

Thanks very much
Noel

答:
Show the number of votes and who voted them.

```<code>;WITH CastedVotes(VoterID,CandidateID) as
(
SELECT ID, value
FROM Voters
CROSS APPLY STRING_SPLIT(Candidates, ',')
)
SELECT Position, C.Name, COUNT (C.Name) as Votes
, STRING_AGG(CONVERT(NVARCHAR(max), ISNULL(V.Name,'N/A')), ',') AS
Voters
FROM CastedVotes CV
INNER JOIN Voters V ON VoterID=V.ID
INNER JOIN Candidates C ON CandidateID=C.ID
group by Position, C.Name
ORDER BY Position, Votes DESC
</code>```

Title: Election Polls Query

Body:
I have SQL tables below.

Candidates
ID Name Position
1 Pacquio President
2 Leni    President
3 Herbert Senator
4 Tulfo   Senator
5 Marcoleta Senator

Voters
ID  Name Candidates
1  Noel 1,3,4
2 Mar   2,4,5
3 Dan.  2,4,3

The result should be below

Results
Position Name Votes
President Leni 2
President Pacquio 1
Senator Tulfo 2
Senator Herbert 1
Senator Marcoleta 1

What should be my SQL Query

Thanks very much
Noel

Body:
Show the number of votes and who voted them.

;WITH CastedVotes(VoterID,CandidateID) as
(
SELECT ID, value
FROM Voters
CROSS APPLY STRING_SPLIT(Candidates, ',')
)
SELECT Position, C.Name, COUNT (C.Name) as Votes
, STRING_AGG(CONVERT(NVARCHAR(max), ISNULL(V.Name,'N/A')), ',') AS
Voters
FROM CastedVotes CV
INNER JOIN Voters V ON VoterID=V.ID
INNER JOIN Candidates C ON CandidateID=C.ID
group by Position, C.Name
ORDER BY Position, Votes DESC


问:
why does the program exit without taking any input?
I am trying to write a code to find the lowest grade among 10 quizzes and calculate the final grade of quiz, midterm and final exam.

This is the code. When i run it, it just says program finished with exit code 0.

```<code>
#include <stdio.h>
#include <math.h>
int main(void)
{
    int i, quiz[i], min, QUIZ, final_grade;
    double MID, FINAL;

    /*loop store quiz grades*/
    for (i=1; i<=10; ++i)
    {
        printf ("Enter quiz%d grade:", i);
        scanf ("%d", &quiz[i]);
    }

    /*store midterm and final value*/
    printf ("Enter midterm grade:");
    scanf ("%lf", &MID);
    printf ("Enter final exam grade:");
    scanf ("%lf", &FINAL);

    /*find sum of quiz score*/
    QUIZ=0;

    for (i=1; i<=10; ++i)
    {
        QUIZ += quiz[i];
    }
    printf ("%d",QUIZ);

    /*find min quiz score*/
    for (i=1; i<=10; ++i)
    {
        min=quiz[1];
        if (quiz[i]<min);
            min=quiz[i];
    }
    printf ("\n%d",min);

    /*calculate quiz pecent score*/
    QUIZ = 2.5*(QUIZ-min)/9;
    printf ("\n%d",QUIZ);

    /*calculate final grade*/
    if (MID>=FINAL)
    {
        final_grade=MID*.35+FINAL*.4+QUIZ;
    }
    else
    {
        final_grade=MID*.25+FINAL*.5+QUIZ;
    }
    printf ("\nThe final grade is:%d", final_grade);

    return 0;
}
</code>```

It works fine in this part

```<code>{
    int i, quiz[i];
    /*loop store quiz grades*/
    for (i=1; i<=10; ++i)
    {
        printf ("Enter quiz%d grade:", i);
        scanf ("%d", &quiz[i]);
    }
    int min;
    min=1;
    /*find min quiz grade*/
    if (quiz[i]<quiz[min])
        {
            min=i;
        }
    quiz[min]=0;
    printf ("%d", quiz[min]);

    return (0);
}
</code>```

But when I add more work to the program it doesnt take input anymore.

答:
In your code

```<code> int i, quiz[i], min, QUIZ, final_grade;
</code>```

you are using i uninitialized. The value of i at that point is indeterminate. Your program behaviour is undefined, therefore.

You need to ensure to populate i with a valid value, before you can use that to define the VLA size.

Body:
I am trying to write a code to find the lowest grade among 10 quizzes and calculate the final grade of quiz, midterm and final exam.

This is the code. When i run it, it just says program finished with exit code 0.

#include <stdio.h>
#include <math.h>
int main(void)
{
    int i, quiz[i], min, QUIZ, final_grade;
    double MID, FINAL;

    /*loop store quiz grades*/
    for (i=1; i<=10; ++i)
    {
        printf ("Enter quiz%d grade:", i);
        scanf ("%d", &quiz[i]);
    }

    /*store midterm and final value*/
    printf ("Enter midterm grade:");
    scanf ("%lf", &MID);
    printf ("Enter final exam grade:");
    scanf ("%lf", &FINAL);

    /*find sum of quiz score*/
    QUIZ=0;

    for (i=1; i<=10; ++i)
    {
        QUIZ += quiz[i];
    }
    printf ("%d",QUIZ);

    /*find min quiz score*/
    for (i=1; i<=10; ++i)
    {
        min=quiz[1];
        if (quiz[i]<min);
            min=quiz[i];
    }
    printf ("\n%d",min);

    /*calculate quiz pecent score*/
    QUIZ = 2.5*(QUIZ-min)/9;
    printf ("\n%d",QUIZ);

    /*calculate final grade*/
    if (MID>=FINAL)
    {
        final_grade=MID*.35+FINAL*.4+QUIZ;
    }
    else
    {
        final_grade=MID*.25+FINAL*.5+QUIZ;
    }
    printf ("\nThe final grade is:%d", final_grade);

    return 0;
}

It works fine in this part

{
    int i, quiz[i];
    /*loop store quiz grades*/
    for (i=1; i<=10; ++i)
    {
        printf ("Enter quiz%d grade:", i);
        scanf ("%d", &quiz[i]);
    }
    int min;
    min=1;
    /*find min quiz grade*/
    if (quiz[i]<quiz[min])
        {
            min=i;
        }
    quiz[min]=0;
    printf ("%d", quiz[min]);

    return (0);
}

But when I add more work to the program it doesnt take input anymore.

Body:
In your code

 int i, quiz[i], min, QUIZ, final_grade;

you are using i uninitialized. The value of i at that point is indeterminate. Your program behaviour is undefined, therefore.

You need to ensure to populate i with a valid value, before you can use that to define the VLA size.


问:
XML update a set of nodes in PHP
I have this PHP code that adds a set of nodes to an XML file. It does most of what it should do, it finds where to make the additions, but then it doesn't make the update.

I have an xml file of this structure.

```<code><COMMUNITIES>
  <COMMUNITY ID="c001">
       <URLS>
           <URL ID="u001">
              <NAME>Google.com</NAME>
              <URL>http://www.google.com</URL>
           </URL>
       </URLS>
  </COMMUNITY>
</COMMUNITIES>
</code>```

The updates are being made to the URLS node.  The user clicks an "Add URL" link and I add the new URL to this node like this.

```<code>       <URL ID="u002">
          <NAME>Yahoo.com</NAME>
          <URL>http://www.yahoo.com</URL>
       </URL>
</code>```

If the URLS node exists, I append the new url node. If the URLS node does not exist, I create it, then append the new url node.

There are no errors, everything seems to work, but the URLS node is empty.  Here is the PHP script.

```<code>function add_url( $nodeid, $urlid, $urlname, $urllink ) {

$dom = new DOMDocument();
$dom->load('communities.xml');

$dom->formatOutput = true;
$dom->preserveWhiteSpace = false;

// get document element

$xpath = new DOMXPath($dom);
$nodes = $xpath->query("//COMMUNITY[@ID='$nodeid']");

if ($nodes->length) {
   $node = $nodes->item(0);

   $xurl = $dom->createElement("URL");
   $xurl->setAttribute("ID", $urlid);

   $xuname     = $dom->createElement("NAME");
   $xunameText = $dom->createTextNode(mysql_escape_mimic($urlname));
   $xuname->appendChild($xunameText);

   $xulink     = $dom->createElement("URL");
   $xulinkText = $dom->createTextNode(mysql_escape_mimic($urllink));
   $xulink->appendChild($xulinkText);

   $xurl->appendChild($xuname);
   $xurl->appendChild($xulink);

   $xurls = $xpath->query("//COMMUNITY[@ID='$nodeid']/URLS");

   if ($xurls->length) {
   }
   else {
      $xurls = $dom->createElement("URLS");
   }

   $xurls->appendChild($xurl);

   /* $node->appendChild($xurls); */

}

$dom->save('communities.xml');
}
</code>```

I thought the problem was that I was appending the URLS node when it already existed.  But I commented out that line.  I am sure the problem is simple, but I am new at this.  I looked on the site and did not find that specific situation.

Edit

Removed return statement before if ($xurls->length).

Fixed function.

答:
The problem was that I was attempting to add nodes to a node which was already in the XML file as empty.

Instead of the node having data like this.

```<code><URLS>
   <URL ID="u001">
      <NAME>Google.com</NAME>
   </URL>
</URLS>
</code>```

I had a node like this.

```<code><URLS/>
</code>```

Common sense says that this should not be a problem. If the node is empty then appendChild should just add the data and rewrite the node as.

```<code><URLS>
   <URL ID="u002">
      <NAME>Yahoo.com</NAME>
   </URL>
</URLS>
</code>```

Here is the PHP script that worked.  You will note that I created a new node instead of appending to <URLS/>.  I also reordered the appendChild to start from the top node instead of the creating the child nodes first then appending a set of nodes to the top node.

```<code>function add_url( $nodeid, $urlid, $urlname, $urllink ) {

$dom = new DOMDocument();
$dom->load('communities.xml');

$dom->formatOutput = true;
$dom->preserveWhiteSpace = true;

// get document element

$xpath = new DOMXPath($dom);
$nodes = $xpath->query("//COMMUNITY[@ID='$nodeid']");

if ($nodes->length) {

   $node = $nodes->item(0);

   $xurls = $xpath->query("//COMMUNITY[@ID='$nodeid']/URLS");

   if ($xurls->length) {
   }
   else {
      $xurls = $dom->createElement("URLS");
      $node->appendChild($xurls);
   }

      $xurls = $dom->createElement("URLSC");
      $node->appendChild($xurls);

   $xurl = $dom->createElement("URL");
   $xurl->setAttribute("ID", $urlid);
   $xurls->appendChild($xurl);

   $xuname     = $dom->createElement("NAME");
   $xunameText = $dom->createTextNode(mysql_escape_mimic($urlname));
   $xuname->appendChild($xunameText);
   $xurl->appendChild($xuname);

   $xulink     = $dom->createElement("URLC");
   $xulinkText = $dom->createTextNode(mysql_escape_mimic($urllink));
   $xulink->appendChild($xulinkText);
   $xurl->appendChild($xulink);

}

$dom->save('communities.xml');
}
</code>```

So I must modify the function that creates the empty node <URLS/>.  I should not create the node in that function but create it here in the add_url function only when it doesn't exist.

ContentLicense: CC BY-SA 3.0

Title: XML update a set of nodes in PHP

Body:
I have this PHP code that adds a set of nodes to an XML file. It does most of what it should do, it finds where to make the additions, but then it doesn't make the update.

I have an xml file of this structure.

<COMMUNITIES>
  <COMMUNITY ID="c001">
       <URLS>
           <URL ID="u001">
              <NAME>Google.com</NAME>
              <URL>http://www.google.com</URL>
           </URL>
       </URLS>
  </COMMUNITY>
</COMMUNITIES>

The updates are being made to the URLS node.  The user clicks an "Add URL" link and I add the new URL to this node like this.

       <URL ID="u002">
          <NAME>Yahoo.com</NAME>
          <URL>http://www.yahoo.com</URL>
       </URL>

If the URLS node exists, I append the new url node. If the URLS node does not exist, I create it, then append the new url node.

There are no errors, everything seems to work, but the URLS node is empty.  Here is the PHP script.

function add_url( $nodeid, $urlid, $urlname, $urllink ) {

$dom = new DOMDocument();
$dom->load('communities.xml');

$dom->formatOutput = true;
$dom->preserveWhiteSpace = false;

// get document element

$xpath = new DOMXPath($dom);
$nodes = $xpath->query("//COMMUNITY[@ID='$nodeid']");

if ($nodes->length) {
   $node = $nodes->item(0);

   $xurl = $dom->createElement("URL");
   $xurl->setAttribute("ID", $urlid);

   $xuname     = $dom->createElement("NAME");
   $xunameText = $dom->createTextNode(mysql_escape_mimic($urlname));
   $xuname->appendChild($xunameText);

   $xulink     = $dom->createElement("URL");
   $xulinkText = $dom->createTextNode(mysql_escape_mimic($urllink));
   $xulink->appendChild($xulinkText);

   $xurl->appendChild($xuname);
   $xurl->appendChild($xulink);

   $xurls = $xpath->query("//COMMUNITY[@ID='$nodeid']/URLS");

   if ($xurls->length) {
   }
   else {
      $xurls = $dom->createElement("URLS");
   }

   $xurls->appendChild($xurl);

   /* $node->appendChild($xurls); */

}

$dom->save('communities.xml');
}

I thought the problem was that I was appending the URLS node when it already existed.  But I commented out that line.  I am sure the problem is simple, but I am new at this.  I looked on the site and did not find that specific situation.

Edit

Removed return statement before if ($xurls->length).

Fixed function.

Body:
The problem was that I was attempting to add nodes to a node which was already in the XML file as empty.

Instead of the node having data like this.

<URLS>
   <URL ID="u001">
      <NAME>Google.com</NAME>
   </URL>
</URLS>

I had a node like this.

<URLS/>

Common sense says that this should not be a problem. If the node is empty then appendChild should just add the data and rewrite the node as.

<URLS>
   <URL ID="u002">
      <NAME>Yahoo.com</NAME>
   </URL>
</URLS>

Here is the PHP script that worked.  You will note that I created a new node instead of appending to <URLS/>.  I also reordered the appendChild to start from the top node instead of the creating the child nodes first then appending a set of nodes to the top node.

function add_url( $nodeid, $urlid, $urlname, $urllink ) {

$dom = new DOMDocument();
$dom->load('communities.xml');

$dom->formatOutput = true;
$dom->preserveWhiteSpace = true;

// get document element

$xpath = new DOMXPath($dom);
$nodes = $xpath->query("//COMMUNITY[@ID='$nodeid']");

if ($nodes->length) {

   $node = $nodes->item(0);

   $xurls = $xpath->query("//COMMUNITY[@ID='$nodeid']/URLS");

   if ($xurls->length) {
   }
   else {
      $xurls = $dom->createElement("URLS");
      $node->appendChild($xurls);
   }

      $xurls = $dom->createElement("URLSC");
      $node->appendChild($xurls);

   $xurl = $dom->createElement("URL");
   $xurl->setAttribute("ID", $urlid);
   $xurls->appendChild($xurl);

   $xuname     = $dom->createElement("NAME");
   $xunameText = $dom->createTextNode(mysql_escape_mimic($urlname));
   $xuname->appendChild($xunameText);
   $xurl->appendChild($xuname);

   $xulink     = $dom->createElement("URLC");
   $xulinkText = $dom->createTextNode(mysql_escape_mimic($urllink));
   $xulink->appendChild($xulinkText);
   $xurl->appendChild($xulink);

}

$dom->save('communities.xml');
}

So I must modify the function that creates the empty node <URLS/>.  I should not create the node in that function but create it here in the add_url function only when it doesn't exist.


问:
VBA Class Inheritance
I am working on a script to help me create geometry in 3D software based on user input and I wanted to approach the problem with classes. I have 3 levels of structures, points, curves and surfaces so I want to create a class for each, where the next level structure inherits the lower one.
So for example class cPoint have 4 properties: x,y,z,id. Further, the class cCurve has only 2 properties: id and points, and the same for surfaces.
Now my question is: I implemented class cPoint as follows:

```<code>Private x_ As Double
Private y_ As Double
Private z_ As Double
Private id_ As Long

Public Property Let X(ByVal value As Double)
    x_ = value
End Property
Public Property Let Y(ByVal value As Double)
    y_ = value
End Property
Public Property Let Z(ByVal value As Double)
    z_ = value
End Property
Public Property Let ID(ByVal value As Long)
    id_ = value
End Property
Public Property Get X() As Double
    X = x_
End Property
Public Property Get Y() As Double
    Y = y_
End Property
Public Property Get Z() As Double
    Z = z_
End Property
Public Property Get ID() As Long
    ID = id_
End Property
</code>```

and everything is fine here. And here I have class cCurve implemented:

```<code>Implements cPoint

Private id_ As Long
Private point_ As Collection

Public Property Let ID(ByVal value As Long)
    id_ = value
End Property
Public Property Set point(ByVal value As Collection)
    Set point_ = value
End Property
Public Property Get ID() As Long
    ID = id_
End Property
Public Property Get point() As Collection
    Set point = point_
End Property
</code>```

But here, when I try to run the code I get prompted with the following error:
Object module needs to implement 'X' for interface 'cPoint'
I think I know what it means, but I have no clue how to implement it. Is my approach even correct?
I'd highly appreciate any guidance in this manner.

答:
VBA does not support inheritance. The only way to mimic inheritance is to implement your Point class and at the same time have a private instance of the Point class in your curve class. This is what your "Point" class would look like (I used "GeometryPoint" as the name of the class because Excel already has a "Point" class created):

```<code>Option Explicit

Private Type TState
    ID  As Long
    X   As Double
    Y   As Double
    Z   As Double
End Type

Private This As TState

Public Property Let ID(ByVal Value As Long)
    This.ID = Value
End Property
Public Property Get ID() As Long
    ID = This.ID
End Property

Public Property Let X(ByVal Value As Double)
    This.X = Value
End Property
Public Property Get X() As Double
    X = This.X
End Property

Public Property Let Y(ByVal Value As Double)
    This.Y = Value
End Property
Public Property Get Y() As Double
    Y = This.Y
End Property

Public Property Let Z(ByVal Value As Double)
    This.Z = Value
End Property
Public Property Get Z() As Double
    Z = This.Z
End Property
</code>```

And this is what your "Curve" class would look like:

```<code>Option Explicit
Implements GeometryPoint

Private Type TState
    Base        As GeometryPoint
    ID          As Long
    Points      As Collection
    X           As Double
    Y           As Double
    Z           As Double
End Type

Private This As TState

Public Property Let GeometryPoint_ID(ByVal Value As Long)
    This.Base.ID = Value
End Property
Public Property Get GeometryPoint_ID() As Long
    GeometryPoint_ID = This.Base.ID
End Property

Public Property Let GeometryPoint_X(ByVal Value As Double)
    This.Base.X = Value
End Property
Public Property Get GeometryPoint_X() As Double
    GeometryPoint_X = This.Base.X
End Property

Public Property Let GeometryPoint_Y(ByVal Value As Double)
    This.Base.Y = Value
End Property
Public Property Get GeometryPoint_Y() As Double
    GeometryPoint_Y = This.Base.Y
End Property

Public Property Let GeometryPoint_Z(ByVal Value As Double)
    This.Base.Z = Value
End Property
Public Property Get GeometryPoint_Z() As Double
    GeometryPoint_Z = This.Base.Z
End Property

Public Property Set Points(ByVal Value As Collection)
    Set This.Points = Value
End Property
Public Property Get Points() As Collection
    Set Points = This.Points
End Property

Private Sub Class_Initialize()
    Set This.Base = New GeometryPoint
End Sub

Private Sub Class_Terminate()
    Set This.Base = Nothing
End Sub
</code>```

In VBA, when you "Implement" a class you need to list all of the members (properties, methods) of that class. In your case you received an error because you didn't list the X,Y,Z properties of the cPoint class that you were implementing.
Is the "Curve" class supposed to have X,Y,Z properties as well?  If not then you shouldn't implement the Point class. If the Curve class is just a class that stores a collection of Points then your Curve class should look like this:

**Note: This code was edited to include the "Class_Initialize" method which sets the "Points" member as a new collection once the Curve class is instantiated.

```<code>Option Explicit

Private Type TState
    ID          As Long
    Points      As Collection
End Type

Private This As TState

Public Property Let ID(ByVal Value As Long)
    This.ID = Value
End Property
Public Property Get ID() As Long
    ID = This.ID
End Property

Public Property Set Points(ByVal Value As Collection)
    Set This.Points = Value
End Property
Public Property Get Points() As Collection
    Set Points = This.Points
End Property

Private Sub Class_Initialize()
    Set This.Points = New Collection
End Sub

Private Sub Class_Terminate()
    Set This.Points = Nothing
End Sub
</code>```

Finally, adding a new Point object to the "Points" member in the Curve class would look something like this:

```<code>Dim NewPoint As GeometryPoint
Dim NewCurve As Curve

Set NewPoint = New GeometryPoint
With NewPoint
    .X = 1
    .Y = 2
    .Z = 3
End With

Set NewCurve = New Curve
With NewCurve.Points
    .Add NewPoint
End With
</code>```

Title: VBA Class Inheritance

Body:
I am working on a script to help me create geometry in 3D software based on user input and I wanted to approach the problem with classes. I have 3 levels of structures, points, curves and surfaces so I want to create a class for each, where the next level structure inherits the lower one.
So for example class cPoint have 4 properties: x,y,z,id. Further, the class cCurve has only 2 properties: id and points, and the same for surfaces.
Now my question is: I implemented class cPoint as follows:

Private x_ As Double
Private y_ As Double
Private z_ As Double
Private id_ As Long

Public Property Let X(ByVal value As Double)
    x_ = value
End Property
Public Property Let Y(ByVal value As Double)
    y_ = value
End Property
Public Property Let Z(ByVal value As Double)
    z_ = value
End Property
Public Property Let ID(ByVal value As Long)
    id_ = value
End Property
Public Property Get X() As Double
    X = x_
End Property
Public Property Get Y() As Double
    Y = y_
End Property
Public Property Get Z() As Double
    Z = z_
End Property
Public Property Get ID() As Long
    ID = id_
End Property

and everything is fine here. And here I have class cCurve implemented:

Implements cPoint

Private id_ As Long
Private point_ As Collection

Public Property Let ID(ByVal value As Long)
    id_ = value
End Property
Public Property Set point(ByVal value As Collection)
    Set point_ = value
End Property
Public Property Get ID() As Long
    ID = id_
End Property
Public Property Get point() As Collection
    Set point = point_
End Property

But here, when I try to run the code I get prompted with the following error:
Object module needs to implement 'X' for interface 'cPoint'
I think I know what it means, but I have no clue how to implement it. Is my approach even correct?
I'd highly appreciate any guidance in this manner.

Body:
VBA does not support inheritance. The only way to mimic inheritance is to implement your Point class and at the same time have a private instance of the Point class in your curve class. This is what your "Point" class would look like (I used "GeometryPoint" as the name of the class because Excel already has a "Point" class created):

Option Explicit

Private Type TState
    ID  As Long
    X   As Double
    Y   As Double
    Z   As Double
End Type

Private This As TState

Public Property Let ID(ByVal Value As Long)
    This.ID = Value
End Property
Public Property Get ID() As Long
    ID = This.ID
End Property

Public Property Let X(ByVal Value As Double)
    This.X = Value
End Property
Public Property Get X() As Double
    X = This.X
End Property

Public Property Let Y(ByVal Value As Double)
    This.Y = Value
End Property
Public Property Get Y() As Double
    Y = This.Y
End Property

Public Property Let Z(ByVal Value As Double)
    This.Z = Value
End Property
Public Property Get Z() As Double
    Z = This.Z
End Property

And this is what your "Curve" class would look like:

Option Explicit
Implements GeometryPoint

Private Type TState
    Base        As GeometryPoint
    ID          As Long
    Points      As Collection
    X           As Double
    Y           As Double
    Z           As Double
End Type

Private This As TState

Public Property Let GeometryPoint_ID(ByVal Value As Long)
    This.Base.ID = Value
End Property
Public Property Get GeometryPoint_ID() As Long
    GeometryPoint_ID = This.Base.ID
End Property

Public Property Let GeometryPoint_X(ByVal Value As Double)
    This.Base.X = Value
End Property
Public Property Get GeometryPoint_X() As Double
    GeometryPoint_X = This.Base.X
End Property

Public Property Let GeometryPoint_Y(ByVal Value As Double)
    This.Base.Y = Value
End Property
Public Property Get GeometryPoint_Y() As Double
    GeometryPoint_Y = This.Base.Y
End Property

Public Property Let GeometryPoint_Z(ByVal Value As Double)
    This.Base.Z = Value
End Property
Public Property Get GeometryPoint_Z() As Double
    GeometryPoint_Z = This.Base.Z
End Property

Public Property Set Points(ByVal Value As Collection)
    Set This.Points = Value
End Property
Public Property Get Points() As Collection
    Set Points = This.Points
End Property

Private Sub Class_Initialize()
    Set This.Base = New GeometryPoint
End Sub

Private Sub Class_Terminate()
    Set This.Base = Nothing
End Sub

In VBA, when you "Implement" a class you need to list all of the members (properties, methods) of that class. In your case you received an error because you didn't list the X,Y,Z properties of the cPoint class that you were implementing.
Is the "Curve" class supposed to have X,Y,Z properties as well?  If not then you shouldn't implement the Point class. If the Curve class is just a class that stores a collection of Points then your Curve class should look like this:

**Note: This code was edited to include the "Class_Initialize" method which sets the "Points" member as a new collection once the Curve class is instantiated.

Option Explicit

Private Type TState
    ID          As Long
    Points      As Collection
End Type

Private This As TState

Public Property Let ID(ByVal Value As Long)
    This.ID = Value
End Property
Public Property Get ID() As Long
    ID = This.ID
End Property

Public Property Set Points(ByVal Value As Collection)
    Set This.Points = Value
End Property
Public Property Get Points() As Collection
    Set Points = This.Points
End Property

Private Sub Class_Initialize()
    Set This.Points = New Collection
End Sub

Private Sub Class_Terminate()
    Set This.Points = Nothing
End Sub

Finally, adding a new Point object to the "Points" member in the Curve class would look something like this:

Dim NewPoint As GeometryPoint
Dim NewCurve As Curve

Set NewPoint = New GeometryPoint
With NewPoint
    .X = 1
    .Y = 2
    .Z = 3
End With

Set NewCurve = New Curve
With NewCurve.Points
    .Add NewPoint
End With


问:
Learning about Computer Vision
I am really intrigued by the field of computer vision and the potential it has. Are there any examples (preferably implemented in .NET) which I can study along with a reference book?</p>

答: There is the OpenCV project on sourceforge with a book that you can get as well.  You can see it here. However, that is not a .NET solution it is C</p>

OwnerDisplayName: Ali Kazmi

ContentLicense: CC BY-SA 2.5

Title: Learning about Computer Vision

LastEditorDisplayName: Gortok

OwnerDisplayName: Mitchel Sellers


答:
```<code>def merge_lists(*args):
   new_list = sorted(list(heapq.merge(*args)))
   print(new_list)
</code>```

Title: python combine multiple sorted lists into one big sorted list one by one

Body:
I have several sorted lists, and I want to add them together into one big sorted list. What is the most efficient way to do this?

Here is what I would do, but it is too inefficient:

big_list=[]
for slist in sorted_lists: # sorted_lists is a generator, so lists have to be added one by one
    big_list.extend(slist)
big_list.sort()

Here is an example for sorted_lists:

The size of sorted_lists =200

Size of first element of sorted_lists=1668

sorted_lists=[
['000008.htm_181_0040_0009', '000008.htm_181_0040_0037', '000008.htm_201_0041_0031', '000008.htm_213_0029_0004', '000008.htm_263_0015_0011', '000018.htm_116_0071_0002', '000018.htm_147_0046_0002', '000018.htm_153_0038_0015', '000018.htm_160_0060_0001', '000018.htm_205_0016_0002', '000031.htm_4_0003_0001', '000032.htm_4_0003_0001', '000065.htm_5_0013_0005', '000065.htm_8_0008_0006', '000065.htm_14_0038_0036', '000065.htm_127_0016_0006', '000065.htm_168_0111_0056', '000072.htm_97_0016_0012', '000072.htm_175_0028_0020', '000072.htm_188_0035_0004'….],
['000018.htm_68_0039_0030', '000018.htm_173_0038_0029', '000018.htm_179_0042_0040', '000018.htm_180_0054_0021', '000018.htm_180_0054_0031', '000018.htm_182_0025_0023', '000018.htm_191_0041_0010', '000065.htm_5_0013_0007', '000072.htm_11_0008_0002', '000072.htm_14_0015_0002', '000072.htm_75_0040_0021', '000079.htm_11_0005_0000', '000079.htm_14_0006_0000', '000079.htm_16_0054_0006', '000079.htm_61_0018_0012', '000079.htm_154_0027_0011', '000086.htm_8_0003_0000', '000086.htm_9_0030_0005', '000086.htm_11_0038_0004', '000086.htm_34_0031_0024'….],
['000001.htm_13_0037_0004', '000008.htm_48_0025_0006', '000008.htm_68_0025_0008', '000008.htm_73_0024_0014', '000008.htm_122_0034_0026', '000008.htm_124_0016_0005', '000008.htm_144_0046_0030', '000059.htm_99_0022_0012', '000065.htm_69_0045_0017', '000065.htm_383_0026_0020', '000072.htm_164_0030_0002', '000079.htm_122_0030_0009', '000079.htm_123_0049_0015', '000086.htm_13_0037_0004', '000109.htm_71_0054_0029', '000109.htm_73_0035_0005', '000109.htm_75_0018_0004', '000109.htm_76_0027_0013', '000109.htm_101_0030_0008', '000109.htm_134_0036_0030']]

EDIT

Thank you for the answers. I think I should have made it more clear that I do not have the sorted lists simulateneosly but I am iterating over some large files to get them. So, I need to add them one by one, as I am showing in my crude code above.


答:
well stright off this is wrong

```<code>int i, quiz[i]
</code>```

since you havent given i a value how big do you expect quiz to be

I changed to

```<code>int i, quiz[10]
</code>```

after that it runs and gives me output, not sure if its the correct ouput though.

```<code>Enter quiz1 grade:3
Enter quiz2 grade:4
Enter quiz3 grade:5
Enter quiz4 grade:
5
Enter quiz5 grade:5
Enter quiz6 grade:5
Enter quiz7 grade:5
Enter quiz8 grade:5
Enter quiz9 grade:5
Enter quiz10 grade:5
Enter midterm grade:5
Enter final exam grade:6
47
5
11
The final grade is:15
</code>```

Title: why does the program exit without taking any input?

Body:
well stright off this is wrong

int i, quiz[i]

since you havent given i a value how big do you expect quiz to be

I changed to

int i, quiz[10]

after that it runs and gives me output, not sure if its the correct ouput though.

Enter quiz1 grade:3
Enter quiz2 grade:4
Enter quiz3 grade:5
Enter quiz4 grade:
5
Enter quiz5 grade:5
Enter quiz6 grade:5
Enter quiz7 grade:5
Enter quiz8 grade:5
Enter quiz9 grade:5
Enter quiz10 grade:5
Enter midterm grade:5
Enter final exam grade:6
47
5
11
The final grade is:15


问:
.NET Core / EF : how to avoid performance issue with Linq query?
I have a few questions on lambda filtering performance.

This is my code:

```<code>public class supplier
{
    public Guid supplier_id { get; set; }
    public string supplier_name { get; set; }
    public Guid township_id { get; set; }
}

public class township
{
    public Guid township_id { get; set; }
    public string township { get; set; }
}
</code>```

This is my dto class:

```<code>public class supplier_dto
{
    public Guid supplier_id { get; set; }
    public string suppliername { get; set; }
    public Township township { get; set; }
}
</code>```

So why I filter for list using Linq:

```<code>var supplier_list = (from sup on _dbcontext.suppliers
                     join twn on _dbcontext.townships on sup.township_id equals twn.township_id
                     select new supplier_dto
                                {
                                    supplier_id = sup.supplier_id,
                                    suppliername = sup.supplier_name,
                                    township = getTownshipById(twn.township_id)
                                }).ToList();
</code>```

If there are many suppliers, will this affect the performance? Is there a way to do without using getTownshipById function?

BR,
jm

答:
There are several issues with your classes.
First, I assume you have one-to-many relationship between township and suppliers, which is typically represented by foreign key in the database. Therefore you have to have similar relationship in the model:

```<code>public class supplier
{
    public Guid supplier_id { get; set; }
    public string supplier_name { get; set; }
    public Guid TownshipId { get; set; }
    public Township township { get; set; }
}

public class Township
{
    public Guid TownshipId { get; set; }
    public string name { get; set; }
    public ICollection<supplier> suppliers { get; set; }
}
</code>```

If that is the case, you can rewrite you LINQ statement:

```<code>var supplier_list = (from sup in _dbcontext.suppliers
                     select new supplier_dto
                                {
                                    supplier_id = sup.supplier_id,
                                    suppliername = sup.supplier_name,
                                    township = sup.township
                                }).ToList();
</code>```

Just make sure that township is actually loaded either through eager or explicit loading. In general, I consider it code smell if you need to use join in LINQ statement.

Second, the performance of LINQ query depends on the query that it generates. You put a label of .NET 3.1. In .NET 5 you can use an easy API ToQueryString() to get the resultant query; but even in 3.1 you can generate it with a little more effort.

Finally, your question doesn't have anything to do with lambda

Body:
I have a few questions on lambda filtering performance.

This is my code:

public class supplier
{
    public Guid supplier_id { get; set; }
    public string supplier_name { get; set; }
    public Guid township_id { get; set; }
}

public class township
{
    public Guid township_id { get; set; }
    public string township { get; set; }
}

This is my dto class:

public class supplier_dto
{
    public Guid supplier_id { get; set; }
    public string suppliername { get; set; }
    public Township township { get; set; }
}

So why I filter for list using Linq:

var supplier_list = (from sup on _dbcontext.suppliers
                     join twn on _dbcontext.townships on sup.township_id equals twn.township_id
                     select new supplier_dto
                                {
                                    supplier_id = sup.supplier_id,
                                    suppliername = sup.supplier_name,
                                    township = getTownshipById(twn.township_id)
                                }).ToList();

If there are many suppliers, will this affect the performance? Is there a way to do without using getTownshipById function?

BR,
jm

Body:
There are several issues with your classes.
First, I assume you have one-to-many relationship between township and suppliers, which is typically represented by foreign key in the database. Therefore you have to have similar relationship in the model:

public class supplier
{
    public Guid supplier_id { get; set; }
    public string supplier_name { get; set; }
    public Guid TownshipId { get; set; }
    public Township township { get; set; }
}

public class Township
{
    public Guid TownshipId { get; set; }
    public string name { get; set; }
    public ICollection<supplier> suppliers { get; set; }
}

If that is the case, you can rewrite you LINQ statement:

var supplier_list = (from sup in _dbcontext.suppliers
                     select new supplier_dto
                                {
                                    supplier_id = sup.supplier_id,
                                    suppliername = sup.supplier_name,
                                    township = sup.township
                                }).ToList();

Just make sure that township is actually loaded either through eager or explicit loading. In general, I consider it code smell if you need to use join in LINQ statement.

Second, the performance of LINQ query depends on the query that it generates. You put a label of .NET 3.1. In .NET 5 you can use an easy API ToQueryString() to get the resultant query; but even in 3.1 you can generate it with a little more effort.

Finally, your question doesn't have anything to do with lambda


问:
How regularly is the cached content updated from origin server in CDN?
Since most of CDNs update the cache data only after it reaches an expiry, what if the origin server is updated before that. Does the CDN serve the old data until updated upon expiry?</p>

答:
Generally they have a callback method for you to let them know if a content changed and needs to be updated/re-cached. So it won't serve the old content until the next refresh.

You can see the documentation for Cloudflare-Purge Cache and Azure.


问:
Need for try catch within a constructor
The link http://gotw.ca/gotw/066.htm states that

Moral #1: Constructor function-try-block handlers have only one purpose -- to translate an exception. (And maybe to do logging or some other side effects.) They are not useful for any other purpose.

While http://www.parashift.com/c++-faq-lite/exceptions.html#faq-17.8

If a constructor throws an exception, the object's destructor is not run. If your object has already done something that needs to be undone (such as allocating some memory, opening a file, or locking a semaphore), this "stuff that needs to be undone" must be remembered by a data member inside the object.

Are these 2 statements not contradictory?  The first one kind of implies that the try catch within a constructor is pretty much useless while the second says that it is needed to free resources.  What am i missing here?

答:
They refer to different things.

The first one is related to the function-try block, i.e. a try block that includes a whole function, and, in the case of constructors, includes also the calls to the constructors of the base classes and of the member objects, i.e. stuff that is executed before the actual constructor body is run.

The morale is that, if a base class or a class member fails to constructs correctly, the object construction must fail with an exception, because otherwise your newly constructed object is left in an inconsistent state, with the base object/member objects half constructed. So, the purpose of such try block must be only to translate/rethrow such exception, maybe logging the incident. You can't do in any other way: if you don't explicitly throw inside your catch, an implicit throw; is added by the compiler to prevent the "half-constructed object" eventuality.

The second one refers to exceptions that are risen inside the body of your constructor; in this case, it says that you should use a "regular" try block to catch the exception, free the resources you have allocated up to now and then rethrow, because the destructor won't be called.

Notice that this behavior makes sense, since the implicit contract for the destructor, as for any other member function that is not the constructor, is that it expects to work on an object in a consistent state; but an exception thrown from the constructor means that the object hasn't been fully constructed yet, so this contract would be violated.

Title: Need for try catch within a constructor


问:
Node.js heap out of memory
Today I ran my script for filesystem indexing to refresh RAID files index and after 4h it crashed with following error:

```<code>[md5:]  241613/241627 97.5%
[md5:]  241614/241627 97.5%
[md5:]  241625/241627 98.1%
Creating missing list... (79570 files missing)
Creating new files list... (241627 new files)

<--- Last few GCs --->

11629672 ms: Mark-sweep 1174.6 (1426.5) -> 1172.4 (1418.3) MB, 659.9 / 0 ms [allocation failure] [GC in old space requested].
11630371 ms: Mark-sweep 1172.4 (1418.3) -> 1172.4 (1411.3) MB, 698.9 / 0 ms [allocation failure] [GC in old space requested].
11631105 ms: Mark-sweep 1172.4 (1411.3) -> 1172.4 (1389.3) MB, 733.5 / 0 ms [last resort gc].
11631778 ms: Mark-sweep 1172.4 (1389.3) -> 1172.4 (1368.3) MB, 673.6 / 0 ms [last resort gc].

<--- JS stacktrace --->

==== JS stack trace =========================================

Security context: 0x3d1d329c9e59 <JS Object>
1: SparseJoinWithSeparatorJS(aka SparseJoinWithSeparatorJS) [native array.js:~84] [pc=0x3629ef689ad0] (this=0x3d1d32904189 <undefined>,w=0x2b690ce91071 <JS Array[241627]>,L=241627,M=0x3d1d329b4a11 <JS Function ConvertToString (SharedFunctionInfo 0x3d1d3294ef79)>,N=0x7c953bf4d49 <String[4]\: ,\n  >)
2: Join(aka Join) [native array.js:143] [pc=0x3629ef616696] (this=0x3d1d32904189 <undefin...

FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory
 1: node::Abort() [/usr/bin/node]
 2: 0xe2c5fc [/usr/bin/node]
 3: v8::Utils::ReportApiFailure(char const*, char const*) [/usr/bin/node]
 4: v8::internal::V8::FatalProcessOutOfMemory(char const*, bool) [/usr/bin/node]
 5: v8::internal::Factory::NewRawTwoByteString(int, v8::internal::PretenureFlag) [/usr/bin/node]
 6: v8::internal::Runtime_SparseJoinWithSeparator(int, v8::internal::Object**, v8::internal::Isolate*) [/usr/bin/node]
 7: 0x3629ef50961b
</code>```

Server is equipped with 16gb RAM and 24gb SSD swap. I highly doubt my script exceeded 36gb of memory. At least it shouldn't

Script creates index of files stored as Array of Objects with files metadata (modification dates, permissions, etc, no big data)

Here's full script code:
http://pastebin.com/mjaD76c3

I've already experiend weird node issues in the past with this script what forced me eg. split index into multiple files as node was glitching when working on such big files as String. Is there any way to improve nodejs memory management with huge datasets?

答:
Unix (Mac OS)

Open a terminal and open our .zshrc file using nano like so (this will create one, if one doesn't exist):

nano ~/.zshrc

Update our NODE_OPTIONS environment variable by adding the following line into our currently open .zshrc file:

export NODE_OPTIONS=--max-old-space-size=8192 # increase node memory limit

Please note that we can set the number of megabytes passed in to whatever we like, provided our system has enough memory (here we are passing in 8192 megabytes which is roughly 8 GB).

Save and exit nano by pressing: ctrl + x, then y to agree and finally enter to save the changes.

Close and reopen the terminal to make sure our changes have been recognised.

We can print out the contents of our .zshrc file to see if our changes were saved like so: cat ~/.zshrc.

Linux (Ubuntu)

Open a terminal and open the .bashrc file using nano like so:

nano ~/.bashrc

The remaining steps are similar with the Mac steps from above, except we would most likely be using ~/.bashrc by default (as opposed to ~/.zshrc). So these values would need to be substituted!

Link to Nodejs Docs

Title: Node.js heap out of memory

Body:
Today I ran my script for filesystem indexing to refresh RAID files index and after 4h it crashed with following error:

[md5:]  241613/241627 97.5%
[md5:]  241614/241627 97.5%
[md5:]  241625/241627 98.1%
Creating missing list... (79570 files missing)
Creating new files list... (241627 new files)

<--- Last few GCs --->

11629672 ms: Mark-sweep 1174.6 (1426.5) -> 1172.4 (1418.3) MB, 659.9 / 0 ms [allocation failure] [GC in old space requested].
11630371 ms: Mark-sweep 1172.4 (1418.3) -> 1172.4 (1411.3) MB, 698.9 / 0 ms [allocation failure] [GC in old space requested].
11631105 ms: Mark-sweep 1172.4 (1411.3) -> 1172.4 (1389.3) MB, 733.5 / 0 ms [last resort gc].
11631778 ms: Mark-sweep 1172.4 (1389.3) -> 1172.4 (1368.3) MB, 673.6 / 0 ms [last resort gc].

<--- JS stacktrace --->

==== JS stack trace =========================================

Security context: 0x3d1d329c9e59 <JS Object>
1: SparseJoinWithSeparatorJS(aka SparseJoinWithSeparatorJS) [native array.js:~84] [pc=0x3629ef689ad0] (this=0x3d1d32904189 <undefined>,w=0x2b690ce91071 <JS Array[241627]>,L=241627,M=0x3d1d329b4a11 <JS Function ConvertToString (SharedFunctionInfo 0x3d1d3294ef79)>,N=0x7c953bf4d49 <String[4]\: ,\n  >)
2: Join(aka Join) [native array.js:143] [pc=0x3629ef616696] (this=0x3d1d32904189 <undefin...

FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory
 1: node::Abort() [/usr/bin/node]
 2: 0xe2c5fc [/usr/bin/node]
 3: v8::Utils::ReportApiFailure(char const*, char const*) [/usr/bin/node]
 4: v8::internal::V8::FatalProcessOutOfMemory(char const*, bool) [/usr/bin/node]
 5: v8::internal::Factory::NewRawTwoByteString(int, v8::internal::PretenureFlag) [/usr/bin/node]
 6: v8::internal::Runtime_SparseJoinWithSeparator(int, v8::internal::Object**, v8::internal::Isolate*) [/usr/bin/node]
 7: 0x3629ef50961b

Server is equipped with 16gb RAM and 24gb SSD swap. I highly doubt my script exceeded 36gb of memory. At least it shouldn't

Script creates index of files stored as Array of Objects with files metadata (modification dates, permissions, etc, no big data)

Here's full script code:
http://pastebin.com/mjaD76c3

I've already experiend weird node issues in the past with this script what forced me eg. split index into multiple files as node was glitching when working on such big files as String. Is there any way to improve nodejs memory management with huge datasets?


问:
Is it possible to put binary image data into html markup and then get the image displayed as usual in any browser?
It's an important security issue and I'm sure this should be possible.

A simple example:

You run a community portal. Users are registered and upload their pictures.
Your application gives security rules whenever a picture is allowed to be displayed. For example users must be friends on each sides by the system, in order that you can view someone else's uploaded pictures.

Here comes the problem: it is possible that someone crawls the image directories of your server. But you want to protect your users from such attacks.

If it's possible to put the binary data of an image directly into the HTML markup, you can restrict the user access of your image dirs to the user and group your web application runs of and pass the image data to your Apache user and group directly in the HTML.

The only possible weakness then is the password of the user that your web app runs as.

Is there already a possibility?

答:
https://www.base64-image.de/

I used this website to generate base64 code fir given image, and then this website provide code to directly paste . It worked.


问:
net::ERR_ACCESS_DENIED Android error while opening WebPage in Android Activity
Android WebPage showing net::ERR_ACCESS_DENIED while opening Android activity
Embedded with with WebPage Tag

I tried to provide permission in Android Manifest.

```<code><uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
</code>```

webview:

```<code>    WebView webView;
    webView = (WebView)findViewById(R.id.webbrowser);
    webView.setWebViewClient(new WebViewClient());
    webView.getSettings().setJavaScriptEnabled(true);
    webView.getSettings().setDomStorageEnabled(true);
    webView.getSettings().setLoadWithOverviewMode(true);
    webView.getSettings().setUseWideViewPort(true);
    webView.getSettings().setBuiltInZoomControls(true);
    webView.getSettings().setPluginState(WebSettings.PluginState.ON);
    webView.loadUrl("http://basic-testing-faq.blogspot.com/");
</code>```

I getting net::ERR_ACCESS_DENIED

答:
I also wanted to add my observations on file access denied.

1. It can happens when you try to used files from storage i.e. internal memory or external memory.

Here you can do-

a)Declare tags in the manifest:

```<code><uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
</code>```

b)  First you need to put these two lines when working with webview

```<code>webView.settings.allowContentAccess = true
webView.settings.allowFileAccess = true

In the last line of the webview you must use below statement

webView.loadUrl("file///....")

This is because, when you tried to loadUrl before allowContentAccess and
allowFileAccess it is not able to read the storage. So, first allow access
and the use loadurl. it will work perfectly fine every time.
</code>```

2. When you are working with online urls-

a) Put <uses-permission android:name="android.permission.INTERNET"/>
in manifest.

b) Use android:usesCleartextTraffic="true" inside application tag in manifest.

c) Also this snippet need to be added-

```<code>webView.settings.allowContentAccess= true
   webView.settings.allowFileAccess = true
   webView.loadUrl("file///....")
</code>```

Hope your code works. Cheers :)

Body:
Android WebPage showing net::ERR_ACCESS_DENIED while opening Android activity
Embedded with with WebPage Tag

I tried to provide permission in Android Manifest.

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

webview:

    WebView webView;
    webView = (WebView)findViewById(R.id.webbrowser);
    webView.setWebViewClient(new WebViewClient());
    webView.getSettings().setJavaScriptEnabled(true);
    webView.getSettings().setDomStorageEnabled(true);
    webView.getSettings().setLoadWithOverviewMode(true);
    webView.getSettings().setUseWideViewPort(true);
    webView.getSettings().setBuiltInZoomControls(true);
    webView.getSettings().setPluginState(WebSettings.PluginState.ON);
    webView.loadUrl("http://basic-testing-faq.blogspot.com/");

I getting net::ERR_ACCESS_DENIED

Body:
I also wanted to add my observations on file access denied.

1. It can happens when you try to used files from storage i.e. internal memory or external memory.

Here you can do-

a)Declare tags in the manifest:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

b)  First you need to put these two lines when working with webview

webView.settings.allowContentAccess = true
webView.settings.allowFileAccess = true

In the last line of the webview you must use below statement

webView.loadUrl("file///....")

This is because, when you tried to loadUrl before allowContentAccess and
allowFileAccess it is not able to read the storage. So, first allow access
and the use loadurl. it will work perfectly fine every time.

2. When you are working with online urls-

a) Put <uses-permission android:name="android.permission.INTERNET"/>
in manifest.

b) Use android:usesCleartextTraffic="true" inside application tag in manifest.

c) Also this snippet need to be added-

webView.settings.allowContentAccess= true
   webView.settings.allowFileAccess = true
   webView.loadUrl("file///....")

Hope your code works. Cheers :)


问:
Code syntax explaination help
I am learning WPF and there's a piece of code which I don't quite understand the method declared with constraints:

```<code>public static T FindAncestor<T>(DependencyObject dependencyObject)
    where T : class // Need help to interpret this method declaration
</code>```

I understand this is a shared method and T has be a class but what is what is 'static T FindAncestor'? Having troubles interpreting it as a whole. Thanks!

Code:

```<code>public static class VisualTreeHelperExtensions
{
    public static T FindAncestor<T>(DependencyObject dependencyObject)
        where T : class // Need help to interpret this method
    {
        DependencyObject target = dependencyObject;
        do
        {
            target = VisualTreeHelper.GetParent(target);
        }
        while (target != null && !(target is T));
        return target as T;
    }
}
</code>```

答: The T is a placeholder for a type - what is known as a generic. The where clause is a generic constraint that requires reference types.

Title: Code syntax explaination help

Body:
I am learning WPF and there's a piece of code which I don't quite understand the method declared with constraints:

public static T FindAncestor<T>(DependencyObject dependencyObject)
    where T : class // Need help to interpret this method declaration

I understand this is a shared method and T has be a class but what is what is 'static T FindAncestor'? Having troubles interpreting it as a whole. Thanks!

Code:

public static class VisualTreeHelperExtensions
{
    public static T FindAncestor<T>(DependencyObject dependencyObject)
        where T : class // Need help to interpret this method
    {
        DependencyObject target = dependencyObject;
        do
        {
            target = VisualTreeHelper.GetParent(target);
        }
        while (target != null && !(target is T));
        return target as T;
    }
}


问:
Flutter is not able to install the apk into the real device suddenly
I am working with flutter currently and everything was fine suddenly when I uninstalled the app from the device and rerun flutter run from the terminal it's suddenly not able to install the apk into a real device. It's not even giving any error just getting stopped at the installation process.

What led to this problem

I was working with sqflite and everything was fine. So I had to change the schema and added another table which was failing. Searching on SO answerer suggested to uninstall the app then reinstall it (was accepted answer). So I did that but after every time when I am running flutter run it is not installing the APK.

I am running Mac Os High Sierra 10.13.6 and running flutter doctor is giving everything right as I said it was working fine but not reinstalling after uninstalling.

答: I too faced a similar issue, Your device may have multiple user profiles, so go through them and uninstall from them as well, then this problem will be solved!</p>


问:
JS TypeError showing on click for unrelated code
I am stumped as to why I am getting the following error message:

```<code>Uncaught TypeError: e.target.className.includes is not a function
  <anonymous> https://domain/jco/v2022-main.1.2.js:978
  EventListener.handleEvent* https://domain/jco/v2022-main.1.2.js:855

  <anonymous> https://domain/jco/v2022-main.1.2.js:978
  (Async: EventListener.handleEvent)
  <anonymous> https://domain/jco/v2022-main.1.2.js:855
</code>```

The lines in question are part of a large event delegation section, that we use because we are using JS to replace just the content on page changes rather than reloading the entire page.  The code below is the event delegation minus all of the href code (which is rather long).  The numbers in the error message correspond to:

855 - $('mstrwrap').addEventListener('click', function(e) {

978 - else if (e.target.className.includes('closeit')) {

```<code>$('mstrwrap').addEventListener('click', function(e) {

  // set eventlisteners for all A HREF links
  if (e.target.nodeName === 'A') {
    // actions for clicks on href links
  }
  // end if 'A' link

  // clicks of divs, svg, other non-href
  // check if is myList link
  else if (e.target.id.includes('add2lst')) {
    // add tourid to MyList
    addToMyList();
  }
  else if (e.target.id.includes('svd2lst')) {
    // remove tourid from MyList
    removeFromMyList();
  }

  else if (e.target.id.includes('mlPhnDiv')) {
    // toggle myList on phones
    $('mlPhnDiv').classList.toggle('mlrvl');
  }

  // check if is close nav button
  else if (e.target.className.includes('closeit')) {
    var thisNav = e.target.parentNode.id;
    var thisNvBtn = 'nvbtn' + thisNav.match(/\d+/g);
    // manually close nav panels
    $(thisNav).style.maxHeight = '0';
    $(thisNvBtn).classList.remove('nvopen');
  }

  // show hide nav more trips functions
  else if (e.target.id.includes('showtrips')) {
    showTrips();
  }
  else if (e.target.id.includes('hidetrips')) {
    hideTrips();
  }

  // phone nav menu open close
  // show hide phone nav
  else if (e.target.id.includes('phNav')) {
    tglPhnNav();
  }

  // any other click ignore
  else {
    return;
  }
  // end set eventListeners
});
</code>```

The thing that is stumping me is that the error message is generated when I click on the #phNav button which should target else if (e.target.id.includes('phNav')) { which is further down the code and not the .closeit code.

Everything works as expected, including the .closeit section as well as the hidetrips / showtrips functions in between closeit and phNav.  The click target for phNav is an svg.

Are there any quirks of JS that might explain this or can anyone see something I missed?

Some additional bits, we are not using jQuery just a snippet that saves characters by setting $ = document.getElementById.  And the tglPhnNav code is below:

```<code>// phone nav buttons
function tglPhnNav() {
  if ($('phmenu').style.display === 'flex') {
    $('phmenu').style.display = 'none';
  } else {
    $('phmenu').style.display = 'flex';
  }
}
</code>```

As requested by NiceBooks in the comments, the svg link that when clicked is having the error

```<code><div id="btmnvbar" class="horz">
  <svg width="35" height="35">removed for brevity</svg>
  <svg width="35" height="35">removed for brevity</svg>
  <svg viewBox="0 0 100 80" width="32" height="32" fill="#ffe" id="phNav"><rect width="100" height="12" rx="8"></rect><rect y="30" width="100" height="12" rx="8"></rect><rect y="60" width="100" height="12" rx="8"></rect></svg>
</div>
</code>```

Update: The earlier issue of not firing the phNav code has been resolved, but the primary issue of the unrelated error message remains.

答:
Make sure you are using the proper selector. Try console logging the selected element to check if it is available in the document.

console.log('tag', $('mstrwrap'));
console.log('id', $('#mstrwrap'));
console.log('class', $('.mstrwrap'));
```
<p>Also you should use <code>e.target.classList.contains('closeit')</code> instead of <code>e.target.className.includes('closeit')</code>.</p>
<p>EDIT: As the #phNav is child of another element that has multiple child elements try doing this. I might solve the problem.</p>
<pre class="lang-js prettyprint-override"><code>  // phone nav menu open close
  // show hide phone nav
  else if (e.target.parentNode.id == 'btmnvbar') {
    tglPhnNav();
  }
</code>```

instead of

  // phone nav menu open close
  // show hide phone nav
  else if (e.target.id.includes('phNav')) {
    tglPhnNav();
  }
```

Body:
I am stumped as to why I am getting the following error message:

Uncaught TypeError: e.target.className.includes is not a function
  <anonymous> https://domain/jco/v2022-main.1.2.js:978
  EventListener.handleEvent* https://domain/jco/v2022-main.1.2.js:855

  <anonymous> https://domain/jco/v2022-main.1.2.js:978
  (Async: EventListener.handleEvent)
  <anonymous> https://domain/jco/v2022-main.1.2.js:855

The lines in question are part of a large event delegation section, that we use because we are using JS to replace just the content on page changes rather than reloading the entire page.  The code below is the event delegation minus all of the href code (which is rather long).  The numbers in the error message correspond to:

855 - $('mstrwrap').addEventListener('click', function(e) {

978 - else if (e.target.className.includes('closeit')) {

$('mstrwrap').addEventListener('click', function(e) {

  // set eventlisteners for all A HREF links
  if (e.target.nodeName === 'A') {
    // actions for clicks on href links
  }
  // end if 'A' link

  // clicks of divs, svg, other non-href
  // check if is myList link
  else if (e.target.id.includes('add2lst')) {
    // add tourid to MyList
    addToMyList();
  }
  else if (e.target.id.includes('svd2lst')) {
    // remove tourid from MyList
    removeFromMyList();
  }

  else if (e.target.id.includes('mlPhnDiv')) {
    // toggle myList on phones
    $('mlPhnDiv').classList.toggle('mlrvl');
  }

  // check if is close nav button
  else if (e.target.className.includes('closeit')) {
    var thisNav = e.target.parentNode.id;
    var thisNvBtn = 'nvbtn' + thisNav.match(/\d+/g);
    // manually close nav panels
    $(thisNav).style.maxHeight = '0';
    $(thisNvBtn).classList.remove('nvopen');
  }

  // show hide nav more trips functions
  else if (e.target.id.includes('showtrips')) {
    showTrips();
  }
  else if (e.target.id.includes('hidetrips')) {
    hideTrips();
  }

  // phone nav menu open close
  // show hide phone nav
  else if (e.target.id.includes('phNav')) {
    tglPhnNav();
  }

  // any other click ignore
  else {
    return;
  }
  // end set eventListeners
});

The thing that is stumping me is that the error message is generated when I click on the #phNav button which should target else if (e.target.id.includes('phNav')) { which is further down the code and not the .closeit code.

Everything works as expected, including the .closeit section as well as the hidetrips / showtrips functions in between closeit and phNav.  The click target for phNav is an svg.

Are there any quirks of JS that might explain this or can anyone see something I missed?

Some additional bits, we are not using jQuery just a snippet that saves characters by setting $ = document.getElementById.  And the tglPhnNav code is below:

// phone nav buttons
function tglPhnNav() {
  if ($('phmenu').style.display === 'flex') {
    $('phmenu').style.display = 'none';
  } else {
    $('phmenu').style.display = 'flex';
  }
}

As requested by NiceBooks in the comments, the svg link that when clicked is having the error

  <svg width="35" height="35">removed for brevity</svg>
  <svg width="35" height="35">removed for brevity</svg>
  <svg viewBox="0 0 100 80" width="32" height="32" fill="#ffe" id="phNav"><rect width="100" height="12" rx="8"></rect><rect y="30" width="100" height="12" rx="8"></rect><rect y="60" width="100" height="12" rx="8"></rect></svg>

Update: The earlier issue of not firing the phNav code has been resolved, but the primary issue of the unrelated error message remains.

Body:
Make sure you are using the proper selector. Try console logging the selected element to check if it is available in the document.

console.log('tag', $('mstrwrap'));
console.log('id', $('#mstrwrap'));
console.log('class', $('.mstrwrap'));

Also you should use e.target.classList.contains('closeit') instead of e.target.className.includes('closeit').

EDIT: As the #phNav is child of another element that has multiple child elements try doing this. I might solve the problem.

  // phone nav menu open close
  // show hide phone nav
  else if (e.target.parentNode.id == 'btmnvbar') {
    tglPhnNav();
  }

instead of

  // phone nav menu open close
  // show hide phone nav
  else if (e.target.id.includes('phNav')) {
    tglPhnNav();
  }


问:
Axios get request with web.php in laravel 8
I am new to Axios and API. I was trying to get data from a table with laravel 8 and React js and it works fine with

```<code>const res = await axios.get('http://127.0.0.1:8081/api/students');
</code>```

When I try to do the same with

```<code>const res = await axios.get('http://127.0.0.1:8081/web/students');
</code>```

with web.php access, it shows the error in the console

Access to XMLHttpRequest at 'http://127.0.0.1:8081/web/students' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.  GET http://127.0.0.1:8081/web/students net::ERR_FAILED 404.

Thanks.

答:
As specified in boot() method in app/Providers/RouteServiceProvider.php, web routes have no prefix.
https://github.com/laravel/laravel/blob/8.x/app/Providers/RouteServiceProvider.php

```<code>Route::middleware('web')
   ->namespace($this->namespace)
   ->group(base_path('routes/web.php'));
</code>```

So your endpoint should be http://127.0.0.1:8081/students instead of http://127.0.0.1:8081/web/students

Body:
I am new to Axios and API. I was trying to get data from a table with laravel 8 and React js and it works fine with

const res = await axios.get('http://127.0.0.1:8081/api/students');

When I try to do the same with

const res = await axios.get('http://127.0.0.1:8081/web/students');

with web.php access, it shows the error in the console

Access to XMLHttpRequest at 'http://127.0.0.1:8081/web/students' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.  GET http://127.0.0.1:8081/web/students net::ERR_FAILED 404.

Thanks.

Body:
As specified in boot() method in app/Providers/RouteServiceProvider.php, web routes have no prefix.
https://github.com/laravel/laravel/blob/8.x/app/Providers/RouteServiceProvider.php

Route::middleware('web')
   ->namespace($this->namespace)
   ->group(base_path('routes/web.php'));

So your endpoint should be http://127.0.0.1:8081/students instead of http://127.0.0.1:8081/web/students


问:
how i can change the background color of the datatable based on the result
hi i am using Datatable in laravel

```<code>$(document).ready(function () {
    // Setup - add a text input to each footer cell
    $('#example thead tr')
        .clone(true)
        .addClass('filters')
        .appendTo('#example thead');

    var table = $('#example').DataTable({
        orderCellsTop: true,
        fixedHeader: true,
        initComplete: function () {
            var api = this.api();

            // For each column
            api
                .columns()
                .eq(0)
                .each(function (colIdx) {
                    // Set the header cell to contain the input element
                    var cell = $('.filters th').eq(
                        $(api.column(colIdx).header()).index()
                    );
                    var title = $(cell).text();
                    $(cell).html('<input type="text" placeholder="' + title + '" />');

                    // On every keypress in this input
                    $(
                        'input',
                        $('.filters th').eq($(api.column(colIdx).header()).index())
                    )
                        .off('keyup change')
                        .on('keyup change', function (e) {
                            e.stopPropagation();

                            // Get the search value
                            $(this).attr('title', $(this).val());
                            var regexr = '({search})'; //$(this).parents('th').find('select').val();

                            var cursorPosition = this.selectionStart;
                            // Search the column for that value
                            api
                                .column(colIdx)
                                .search(
                                    this.value != ''
                                        ? regexr.replace('{search}', '(((' + this.value + ')))')
                                        : '',
                                    this.value != '',
                                    this.value == ''
                                )
                                .draw();

                            $(this)
                                .focus()[0]
                                .setSelectionRange(cursorPosition, cursorPosition);
                        });
                });
        },
    });

});
</code>```

it is working fine but i want to change the background field of the data such as

```<code><table id="example" class="display" style="width:10px;">
            <thead>
                <tr>
                    <th>Code</th>
                    <th>Employee</th>
                    <th>Date</th>
                    <th>Arrival time </th>
                    <th>Departure Time</th>
                    <th>Total</th>
                </tr>
            </thead>
            <tbody>
                @foreach($attandance as $attandances)
                <tr>

                    <td>{{$attandances->code}}</td>
                    <td>{{$attandances->employee}}</td>
                    <td>{{$attandances->date}}</td>
                    <td>{{$attandances->start_time}}</td>
                    <td>{{$attandances->end_time}}</td>
                    <td>{{$attandances->total_hours}}</td>

                </tr>
                @endforeach
            </tbody>

        </table>
</code>```

i want to change the background color of the table such as if the total hours are less than the 9 hours the background color of that field should change to red ..or if there is any better way i can use datatables i am new to programming and doesn't know jquery well. kindly need your help

答:
This has nothing to do with the fact that you're using DataTables. You want to add a class conditionally: if ( $attandances->total_hours < 9 ), add a class name to that  which is styled to be red.

HTML:

```<code><td class="{{ ( $attandances->total_hours < 9 ) ? 'danger' : '' }}">
    {{$attandances->total_hours}}
</td>
</code>```

CSS:

```<code>.danger {
  color: red;
}
</code>```

Body:
hi i am using Datatable in laravel

$(document).ready(function () {
    // Setup - add a text input to each footer cell
    $('#example thead tr')
        .clone(true)
        .addClass('filters')
        .appendTo('#example thead');

    var table = $('#example').DataTable({
        orderCellsTop: true,
        fixedHeader: true,
        initComplete: function () {
            var api = this.api();

            // For each column
            api
                .columns()
                .eq(0)
                .each(function (colIdx) {
                    // Set the header cell to contain the input element
                    var cell = $('.filters th').eq(
                        $(api.column(colIdx).header()).index()
                    );
                    var title = $(cell).text();
                    $(cell).html('<input type="text" placeholder="' + title + '" />');

                    // On every keypress in this input
                    $(
                        'input',
                        $('.filters th').eq($(api.column(colIdx).header()).index())
                    )
                        .off('keyup change')
                        .on('keyup change', function (e) {
                            e.stopPropagation();

                            // Get the search value
                            $(this).attr('title', $(this).val());
                            var regexr = '({search})'; //$(this).parents('th').find('select').val();

                            var cursorPosition = this.selectionStart;
                            // Search the column for that value
                            api
                                .column(colIdx)
                                .search(
                                    this.value != ''
                                        ? regexr.replace('{search}', '(((' + this.value + ')))')
                                        : '',
                                    this.value != '',
                                    this.value == ''
                                )
                                .draw();

                            $(this)
                                .focus()[0]
                                .setSelectionRange(cursorPosition, cursorPosition);
                        });
                });
        },
    });

});

it is working fine but i want to change the background field of the data such as

                    Code
                    Employee
                    Date
                    Arrival time
                    Departure Time
                    Total

                @foreach($attandance as $attandances)

                    {{$attandances->code}}
                    {{$attandances->employee}}
                    {{$attandances->date}}
                    {{$attandances->start_time}}
                    {{$attandances->end_time}}
                    {{$attandances->total_hours}}

                @endforeach

i want to change the background color of the table such as if the total hours are less than the 9 hours the background color of that field should change to red ..or if there is any better way i can use datatables i am new to programming and doesn't know jquery well. kindly need your help

Body:
This has nothing to do with the fact that you're using DataTables. You want to add a class conditionally: if ( $attandances->total_hours < 9 ), add a class name to that <td> which is styled to be red.

HTML:

<td class="{{ ( $attandances->total_hours < 9 ) ? 'danger' : '' }}">
    {{$attandances->total_hours}}
</td>

CSS:

.danger {
  color: red;
}


问:
Plotting Maxwellian Distribution in Julia
I have a list of positive and negative values and a single temperature. I am trying to plot the Maxwell-Boltzmann Distribution using the equation for particles moving in only one direction.

```<code>m_e = 9.11E-28 # electron mass [g]
k = 1.38E-16 # boltzmann constant [erg*K^-1]
v = range(1e10, -1e10, step=-1e8) # velocity [cm/s]

T_M = 1e6 # temperature of Maxwellian [K]

function Maxwellian(v_Max, T_Max)
    normal = (m_e/(2*pi*k*T_Max))^1.5
    exp_term = exp(-((m_e).*v_Max.*v_Max)/(3*k*T_Max))
    return normal*exp_term
end

# Initially comparing chosen distribution f_s to Maxwellian F_s
plot(v, Maxwellian.(v, T_M), label= L"F_s" * " (Maxwellian)")
xlabel!("velocity (cm/s)")
ylabel!("probability density")
</code>```

However, when, plotting this, my whole function is 0:

I tested out if I wrote my function correctly by replacing return normal*exp_term with return exp_term (i.e. ignoring any normalization constants) and this seems to produce the distinct of the bell curve:

Yet, without the normalization constant, this will not preserve the area under the curve. I was wondering what may I be doing incorrectly with setting up my Maxwellian function and the constant in front of the exponential.

答:
If you print the normalization term on its own:

```<code>julia> (m_e/(2*pi*k*T_M))^1.5
1.0769341115495682e-27
</code>```

you can see that it is 10 orders of magnitude smaller than the Y-axis scale used for the plot. You can set the Y-axis limits during the plots with ylims argument, or after the plot with:

```<code>julia> ylims!(-1e-28, 2e-27)
</code>```

which changes the plot to:

Body:
I have a list of positive and negative values and a single temperature. I am trying to plot the Maxwell-Boltzmann Distribution using the equation for particles moving in only one direction.

m_e = 9.11E-28 # electron mass [g]
k = 1.38E-16 # boltzmann constant [erg*K^-1]
v = range(1e10, -1e10, step=-1e8) # velocity [cm/s]

T_M = 1e6 # temperature of Maxwellian [K]

function Maxwellian(v_Max, T_Max)
    normal = (m_e/(2*pi*k*T_Max))^1.5
    exp_term = exp(-((m_e).*v_Max.*v_Max)/(3*k*T_Max))
    return normal*exp_term
end

# Initially comparing chosen distribution f_s to Maxwellian F_s
plot(v, Maxwellian.(v, T_M), label= L"F_s" * " (Maxwellian)")
xlabel!("velocity (cm/s)")
ylabel!("probability density")

However, when, plotting this, my whole function is 0:

I tested out if I wrote my function correctly by replacing return normal*exp_term with return exp_term (i.e. ignoring any normalization constants) and this seems to produce the distinct of the bell curve:

Yet, without the normalization constant, this will not preserve the area under the curve. I was wondering what may I be doing incorrectly with setting up my Maxwellian function and the constant in front of the exponential.

Body:
If you print the normalization term on its own:

julia> (m_e/(2*pi*k*T_M))^1.5
1.0769341115495682e-27

you can see that it is 10 orders of magnitude smaller than the Y-axis scale used for the plot. You can set the Y-axis limits during the plots with ylims argument, or after the plot with:

julia> ylims!(-1e-28, 2e-27)

which changes the plot to:


问:
Easy_install and Pip doesn't work
Easy_install and Pip doesn't work anymore on python 2.7, when I try to do:

```<code>sudo easy_install pip
</code>```

I get:

```<code>Traceback (most recent call last):
  File "/usr/bin/easy_install", line 5, in <module>
    from pkg_resources import load_entry_point
  File "/usr/bin/lib/python2.7/site-packages/distribute-0.6.19-py2.7.egg/pkg_resources.py", line 2713, in <module>
    parse_requirements(__requires__), Environment()
  File "/usr/bin/lib/python2.7/site-packages/distribute-0.6.19-py2.7.egg/pkg_resources.py", line 584, in resolve
    raise DistributionNotFound(req)
pkg_resources.DistributionNotFound: distribute==0.6.15
</code>```

And when I try:

```<code>sudo pip install [package]
</code>```

I get:

```<code>Traceback (most recent call last):
  File "/usr/bin/pip", line 5, in <module>
    from pkg_resources import load_entry_point
  File "/usr/bin/lib/python2.7/site-packages/distribute-0.6.19-py2.7.egg/pkg_resources.py", line 2713, in <module>
    parse_requirements(__requires__), Environment()
  File "/usr/bin/lib/python2.7/site-packages/distribute-0.6.19-py2.7.egg/pkg_resources.py", line 584, in resolve
    raise DistributionNotFound(req)
pkg_resources.DistributionNotFound: pip==0.8.2
</code>```

I've already install both of them (and yes, first deleted them), but no result...

Thanks!

(I tried already this post)

答:
If you installed a new version of easy_install through Distribute, the new command may have been installed in another directory, most likely /usr/local/bin/.  But the traceback shows you were using /usr/bin/easy_install.   Try this:

```<code>sudo /usr/local/bin/easy_install ...
</code>```

Title: Easy_install and Pip doesn't work

Body:
Easy_install and Pip doesn't work anymore on python 2.7, when I try to do:

sudo easy_install pip

I get:

Traceback (most recent call last):
  File "/usr/bin/easy_install", line 5, in <module>
    from pkg_resources import load_entry_point
  File "/usr/bin/lib/python2.7/site-packages/distribute-0.6.19-py2.7.egg/pkg_resources.py", line 2713, in <module>
    parse_requirements(__requires__), Environment()
  File "/usr/bin/lib/python2.7/site-packages/distribute-0.6.19-py2.7.egg/pkg_resources.py", line 584, in resolve
    raise DistributionNotFound(req)
pkg_resources.DistributionNotFound: distribute==0.6.15

And when I try:

sudo pip install [package]

I get:

Traceback (most recent call last):
  File "/usr/bin/pip", line 5, in <module>
    from pkg_resources import load_entry_point
  File "/usr/bin/lib/python2.7/site-packages/distribute-0.6.19-py2.7.egg/pkg_resources.py", line 2713, in <module>
    parse_requirements(__requires__), Environment()
  File "/usr/bin/lib/python2.7/site-packages/distribute-0.6.19-py2.7.egg/pkg_resources.py", line 584, in resolve
    raise DistributionNotFound(req)
pkg_resources.DistributionNotFound: pip==0.8.2

I've already install both of them (and yes, first deleted them), but no result...

Thanks!

(I tried already this post)

Body:
If you installed a new version of easy_install through Distribute, the new command may have been installed in another directory, most likely /usr/local/bin/.  But the traceback shows you were using /usr/bin/easy_install.   Try this:

sudo /usr/local/bin/easy_install ...


问:
Applying 'transition' effect to  elements not working properly
Below is some HTML code that I have for a website I'm working on:

.container {
    display: flex;
    flex-direction: row;
    position: relative;
    top: 10%;
    width: 25vw;
    min-width: 428px;
    height: auto;
    padding: 15px;

    justify-content: left;
    align-items: center;

    background-color: white;
}

.container a {
  color: black;
  margin-left: 10px;
  text-decoration: none;
  transition: all ease-in-out 0.25s;
}

.container a h2:hover {
  text-decoration: underline;
}

.container a img {
    width: 100px;
    height: auto;
}

.container + .container {
  margin-top: 20px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <div class="main">
      <h1>Contact</h1>
      <p>In need of a commission? Do you just want to talk? Let me know by shooting me an email or DMing me on Instagram.</p>
      <div class="container">
        <img src="./insta.png">
        <h2>@bellapfisterphotography</h2>
      </div>
      <div class="container">
        <img src="./email.png">
        <h2>mail@gmail.com</h2>
      </div>
  </div></code>```

For some reason, the underline transition I'm applying to the containers  elements is not functioning as intended. Any help on fixing this or explaining why this happens would be greatly appreciated.

答:
The hover element must be the one with transition property.

I would also advise you to move the :hover to the  tag.

Try this:

.container a h2 {
  transition: all ease-in-out 0.25s;
}

.container a:hover h2 {
  text-decoration: underline;
}
```

Title: Applying 'transition' effect to <a> elements not working properly

Body:
Below is some HTML code that I have for a website I'm working on:

.container {
    display: flex;
    flex-direction: row;
    position: relative;
    top: 10%;
    width: 25vw;
    min-width: 428px;
    height: auto;
    padding: 15px;

    justify-content: left;
    align-items: center;

    background-color: white;
}

.container a {
  color: black;
  margin-left: 10px;
  text-decoration: none;
  transition: all ease-in-out 0.25s;
}

.container a h2:hover {
  text-decoration: underline;
}

.container a img {
    width: 100px;
    height: auto;
}

.container + .container {
  margin-top: 20px;
}

Contact

In need of a commission? Do you just want to talk? Let me know by shooting me an email or DMing me on Instagram.

@bellapfisterphotography

mail@gmail.com

For some reason, the underline transition I'm applying to the containers  elements is not functioning as intended. Any help on fixing this or explaining why this happens would be greatly appreciated.

Body:
The hover element must be the one with transition property.

I would also advise you to move the :hover to the <a> tag.

Try this:

.container a h2 {
  transition: all ease-in-out 0.25s;
}

.container a:hover h2 {
  text-decoration: underline;
}


问:
OpenGl error Validation Failed: No vertex array object bound
Mesh class longer unbinds vao, though it still doesn't work. Everything seems like it should be in order. I bind vao, then vbo, I create the shader, but then it screws up validating it cause the vao isn't bound? How? I bind it when I make the mesh and never unbind it. I don't understand this program. What am I doing wrong

```<code>public boolean create(float vertices[]) {
    vCount=vertices.length/3;
    //generate vao id
    vao=glGenVertexArrays();

    glBindVertexArray(vao);

    vbo=glGenBuffers();
    glBindBuffer(GL_ARRAY_BUFFER, vbo);

    //static draw stores data in GPU
    //GL_DYNAMIC_DRAW stores it in ram to be more accessible
    glBufferData(GL_ARRAY_BUFFER, vertices, GL_STATIC_DRAW);//pass vertex data
    /*glEnableVertexAttribArray(0);
    glEnableVertexAttribArray(1);
    glVertexAttribPointer(0, 3, GL_FLOAT, false, VERTEX_SIZE * 4, 0);
    glVertexAttribPointer(1, 2, GL_FLOAT, false, VERTEX_SIZE * 4, 12);*/
    glVertexAttribPointer(0,3,GL_FLOAT,false,0,0);//allocates 3 spaces for x,y,z floats

    return true;
}
</code>```

Simple draw function.

```<code>public void draw() {

    glDrawArrays(GL_TRIANGLES,0,vCount);

}
</code>```

I shouldn't need to make a buffer or something for camera/object transform, should I? This method just initializes is

```<code>    glUniformMatrix4fv(uniOProjectionMat,true,obj);

    with my shader
    #version 330 core
    layout(location=0) in vec3 position;
    uniform mat4 worldTransform;
    uniform mat4 objectTransform;
    uniform mat4 projection;

    void main(){
        gl_Position=projection*worldTransform *
</code>```

objectTransform* vec4(position,1);
}

答:
glValidateProgram checks whether the program can execute with the current OpenGL state. Because there is no standard vertex array object in a core profile context, you must bind a named VAO before validating the program.

Bind your VAO before the program is validated or don't call unBindVAO(). There is no need to unbind the VAO at all.

Body:
Mesh class longer unbinds vao, though it still doesn't work. Everything seems like it should be in order. I bind vao, then vbo, I create the shader, but then it screws up validating it cause the vao isn't bound? How? I bind it when I make the mesh and never unbind it. I don't understand this program. What am I doing wrong

public boolean create(float vertices[]) {
    vCount=vertices.length/3;
    //generate vao id
    vao=glGenVertexArrays();

    glBindVertexArray(vao);

    vbo=glGenBuffers();
    glBindBuffer(GL_ARRAY_BUFFER, vbo);

    //static draw stores data in GPU
    //GL_DYNAMIC_DRAW stores it in ram to be more accessible
    glBufferData(GL_ARRAY_BUFFER, vertices, GL_STATIC_DRAW);//pass vertex data
    /*glEnableVertexAttribArray(0);
    glEnableVertexAttribArray(1);
    glVertexAttribPointer(0, 3, GL_FLOAT, false, VERTEX_SIZE * 4, 0);
    glVertexAttribPointer(1, 2, GL_FLOAT, false, VERTEX_SIZE * 4, 12);*/
    glVertexAttribPointer(0,3,GL_FLOAT,false,0,0);//allocates 3 spaces for x,y,z floats

    return true;
}

Simple draw function.

public void draw() {

    glDrawArrays(GL_TRIANGLES,0,vCount);

}

I shouldn't need to make a buffer or something for camera/object transform, should I? This method just initializes is

    glUniformMatrix4fv(uniOProjectionMat,true,obj);

    with my shader
    #version 330 core
    layout(location=0) in vec3 position;
    uniform mat4 worldTransform;
    uniform mat4 objectTransform;
    uniform mat4 projection;

    void main(){
        gl_Position=projection*worldTransform *

objectTransform* vec4(position,1);
}