问:
Get parent element of nested child by class or name
I have html elements like follows with unknown hierarchy:

          Nested Child 1

```

<pre class="lang-html prettyprint-override"><code><div class="parent" name="parent">
  <div>
    <div onclick="get_parent(this)">
      Nested Child 2
    </div>
  </div>
</div>
</code>```

Is there any easy way to get parent of nested child by class or name?

Maybe there is some alternative to child.parentElement or child.parentNode I am not aware of which may help me?

Or looping through all parents until I get needed class or name is the only possible choice?

答:
The pure JS only solution you can try!

function getParent(ele, parentClass="parent"){
   var e = ele;
   while(!e.classList.contains(parentClass)){
      e=e.parentElement;
   }
   console.log(e);
   return e;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent">
   <div>
      <div>
         <div>
            <div onclick="getParent(this)">CHILD 1</div>
         </div>
      </div>
   </div>
</div>

<div class="second_parent">
    <div>
        <div onclick="getParent(this,'second_parent')">CHILD 2</div>
    </div>
</div></code>```

Body:
I have html elements like follows with unknown hierarchy:

          Nested Child 1

      Nested Child 2

Is there any easy way to get parent of nested child by class or name?

Maybe there is some alternative to child.parentElement or child.parentNode I am not aware of which may help me?

Or looping through all parents until I get needed class or name is the only possible choice?

Body:
The pure JS only solution you can try!

function getParent(ele, parentClass="parent"){
   var e = ele;
   while(!e.classList.contains(parentClass)){
      e=e.parentElement;
   }
   console.log(e);
   return e;
}

<div class="parent">
   <div>
      <div>
         <div>
            <div onclick="getParent(this)">CHILD 1</div>
         </div>
      </div>
   </div>
</div>

<div class="second_parent">
    <div>
        <div onclick="getParent(this,'second_parent')">CHILD 2</div>
    </div>
</div>


来源: stackexchange

问:
Finding the Longest Path in a Binary Tree
I want to find the longest path in a Binary Tree. I plan to add them to a list, that way I can tell my enemy character to take the long path on easy mode.

```<code>private static <T> ArrayList<T> depthFirstSearch(BinaryNode<T> node)
{
    if(node != null)
    {
        Stack<BinaryNode<T>> stack = new Stack<BinaryNode<T>>();

        stack.push(node);

        while(!stack.isEmpty())
        {
            BinaryNode<T> currentNode = stack.pop();

            if(currentNode.right != null)
                stack.push(currentNode.right);

            // We want to visit left child first, so push left node last.
            if(currentNode.left != null)
                stack.push(currentNode.left);
        }
    }
}
</code>```

I have written that code, but it is a mess. I am trying to use DFS to find the longest path to take. Any suggestions?

EDIT: I do have the height of the tree, I can get it using this.

```<code>public static <T> int height(BinaryNode<T> t)
{
    if (t == null)
        return -1;

    else
        return 1 + Math.max(height(t.left), height(t.right));
}
</code>```

My issue is: when do I know that I have found the longest path using DFS so that I can add nodes to my list?

答:
I will leave this answer in case any one need it. Here is my solution in c++.
The function Get_Max_Path() returns a vector with the longest path itself so you got the path, it's length and it's sum if needed:

vector<int> Max_Path(vector<int>rightpath, vector<int>leftpath)
{
    return (rightpath.size() > leftpath.size()) ? rightpath : leftpath;
}

vector<int> GetPath(node* N, vector<int> v)
{
    v.push_back(N->Data);
    return v;
}
vector<int> Get_Max_Path(node* root)
{
    if (!root) return
        vector<int>(0);
    return Max_Path(GetPath( root, Get_Max_Path(root->Right)),
                    GetPath( root, Get_Max_Path(root->Left)) );
}
```

<p>And here is the tree structure</p>

<pre class="lang-cpp prettyprint-override"><code>
class node
{
public:
    node* Right = NULL;
    node* Left = NULL;
    int Data;
};

class Tree
{
private:
    node* Root = NULL;

public:

    void Insert_Node(int Data)
    {
        node* DataNode = (node*)malloc(sizeof(node));
        DataNode->Data = Data;
        DataNode->Left = DataNode->Right = NULL;

        if (Root == NULL) {
            Root = DataNode;
            return;
        }

        node* tmp_root = Root, * prev = NULL;
        while (tmp_root != NULL)
        {
            prev = tmp_root;
            tmp_root = (tmp_root->Data < Data) ?
                tmp_root->Right :
                tmp_root->Left;
        }
        (prev->Data < Data) ? (prev->Right = DataNode) : (prev->Left = DataNode);
    }

    vector<int> Max_Path(vector<int>rightpath, vector<int>leftpath)
    {
        return (rightpath.size() > leftpath.size()) ? rightpath : leftpath;
    }
    vector<int> Update_Path(node* N, vector<int> v)
    {
        v.push_back(N->Data);
        return v;
    }
    vector<int> Get_Max_length_Path(node* root)
    {
        if (!root) return
            vector<int>(0);
        return Max_Path(
            Update_Path(root, Get_Max_length_Path(root->Right)),
            Update_Path(root, Get_Max_length_Path(root->Left)));
    }

    vector<int> Get_Max_length_Path()
    {
        return Get_Max_length_Path(Root);
    }
};
</code>```

This is the driver Code

int main()
{
    Tree T;

    int nodes[] = { 11, 6, 8, 19, 4, 13, 5, 17, 43, 49, 16, 31, 32};
    int length = sizeof(nodes) / sizeof(nodes[0]);

    for (size_t i = 0; i < length; i++)
        T.Insert_Node(nodes[i]);

    int sum = 0;

    vector<int> path = T.Get_Max_length_Path();
    cout << "The path length is : " << path.size() <<endl;
    cout << "The path from the leaf to the root is : ";
    for (int i = 0; i < path.size(); i++)
    {
        cout << path[i] << " ";
        sum += path[i] ;
    }
    cout << endl;
    cout << "the path sum is :" << sum << endl;
    return 0;
}
```

<p>Test Case</p>

<p>BST sample
<img src="https://i.stack.imgur.com/9Dale.png" alt="BST sample"></p>

<p>Output</p>

```The path length is : 5 The path from the leaf to the root is : 16 17
13 19 11 the path sum is :76
```

ContentLicense: CC BY-SA 3.0

Body:
I want to find the longest path in a Binary Tree. I plan to add them to a list, that way I can tell my enemy character to take the long path on easy mode.

private static <T> ArrayList<T> depthFirstSearch(BinaryNode<T> node)
{
    if(node != null)
    {
        Stack<BinaryNode<T>> stack = new Stack<BinaryNode<T>>();

        stack.push(node);

        while(!stack.isEmpty())
        {
            BinaryNode<T> currentNode = stack.pop();

            if(currentNode.right != null)
                stack.push(currentNode.right);

            // We want to visit left child first, so push left node last.
            if(currentNode.left != null)
                stack.push(currentNode.left);
        }
    }
}

I have written that code, but it is a mess. I am trying to use DFS to find the longest path to take. Any suggestions?

EDIT: I do have the height of the tree, I can get it using this.

public static <T> int height(BinaryNode<T> t)
{
    if (t == null)
        return -1;

    else
        return 1 + Math.max(height(t.left), height(t.right));
}

My issue is: when do I know that I have found the longest path using DFS so that I can add nodes to my list?

Body:
I will leave this answer in case any one need it. Here is my solution in c++.
The function Get_Max_Path() returns a vector with the longest path itself so you got the path, it's length and it's sum if needed:

vector<int> Max_Path(vector<int>rightpath, vector<int>leftpath)
{
    return (rightpath.size() > leftpath.size()) ? rightpath : leftpath;
}

vector<int> GetPath(node* N, vector<int> v)
{
    v.push_back(N->Data);
    return v;
}
vector<int> Get_Max_Path(node* root)
{
    if (!root) return
        vector<int>(0);
    return Max_Path(GetPath( root, Get_Max_Path(root->Right)),
                    GetPath( root, Get_Max_Path(root->Left)) );
}

And here is the tree structure

class node
{
public:
    node* Right = NULL;
    node* Left = NULL;
    int Data;
};

class Tree
{
private:
    node* Root = NULL;

public:

    void Insert_Node(int Data)
    {
        node* DataNode = (node*)malloc(sizeof(node));
        DataNode->Data = Data;
        DataNode->Left = DataNode->Right = NULL;

        if (Root == NULL) {
            Root = DataNode;
            return;
        }

        node* tmp_root = Root, * prev = NULL;
        while (tmp_root != NULL)
        {
            prev = tmp_root;
            tmp_root = (tmp_root->Data < Data) ?
                tmp_root->Right :
                tmp_root->Left;
        }
        (prev->Data < Data) ? (prev->Right = DataNode) : (prev->Left = DataNode);
    }

    vector<int> Max_Path(vector<int>rightpath, vector<int>leftpath)
    {
        return (rightpath.size() > leftpath.size()) ? rightpath : leftpath;
    }
    vector<int> Update_Path(node* N, vector<int> v)
    {
        v.push_back(N->Data);
        return v;
    }
    vector<int> Get_Max_length_Path(node* root)
    {
        if (!root) return
            vector<int>(0);
        return Max_Path(
            Update_Path(root, Get_Max_length_Path(root->Right)),
            Update_Path(root, Get_Max_length_Path(root->Left)));
    }

    vector<int> Get_Max_length_Path()
    {
        return Get_Max_length_Path(Root);
    }
};

This is the driver Code

int main()
{
    Tree T;

    int nodes[] = { 11, 6, 8, 19, 4, 13, 5, 17, 43, 49, 16, 31, 32};
    int length = sizeof(nodes) / sizeof(nodes[0]);

    for (size_t i = 0; i < length; i++)
        T.Insert_Node(nodes[i]);

    int sum = 0;

    vector<int> path = T.Get_Max_length_Path();
    cout << "The path length is : " << path.size() <<endl;
    cout << "The path from the leaf to the root is : ";
    for (int i = 0; i < path.size(); i++)
    {
        cout << path[i] << " ";
        sum += path[i] ;
    }
    cout << endl;
    cout << "the path sum is :" << sum << endl;
    return 0;
}

Test Case

BST sample

Output

The path length is : 5 The path from the leaf to the root is : 16 17
13 19 11 the path sum is :76

ContentLicense: CC BY-SA 4.0


问:
How to make local home network on Ubuntu
so I wanna be able to access my files on my Ubuntu 18.04 LTS machine from my other windows machine by typing its local IP address like this image

but I don't know how to setup apache to display the folders I want, all I'm getting when I type my IP address in the other machine is the apache Ubuntu default page, so how can I make this.

thanks in advance.

答:
To access file system on remote server you can use SFTP to transfer file between systems.

Download Winscp : https://winscp.net/eng/download.php

Type your local ip address including username and password into setup then you can access your remote folders.


问:
Get deltas from an array using foreach in PHP
I am trying to show some values using json api. It returns a date and some density value in numbers. Successfully, I have printed all return values from url. Now, I want to find the difference between one density value to previous day density value.

I know how to calculate the difference in normal static numbers. But, I am not sure how do I achieve this inside a foreach loop.

PHP Code:

```<code>$json_url = "https://www.example.com/api";

$json = file_get_contents($json_url);
$obj  = json_decode($json,true);
$data = $obj["data"];

foreach(array_slice($data, 0, 10) as $k) {

    echo $k["date"]." - ".$k["density"]."<br/><br/>";

}
</code>```

Current Output:

```
14-02-2020 - 110

13-02-2020 - 114

12-02-2020 - 112

11-02-2020 - 110

10-02-2020 - 105

07-02-2020 - 125

06-02-2020 - 122

05-02-2020 - 118

04-02-2020 - 119

03-02-2020 - 119
```

Expected Output:

```
14-02-2020 - 110 - Diff is -4 from Previous Date

13-02-2020 - 114 - Diff is +2 from Previous Date

12-02-2020 - 112 - Diff is +2 from Previous Date

11-02-2020 - 110 - Diff is +5 from Previous Date

10-02-2020 - 105 - Diff is -20 from Previous Date

07-02-2020 - 125 - Diff is +3 from Previous Date

06-02-2020 - 122 - Diff is +4 from Previous Date

05-02-2020 - 118 - Diff is -1 from Previous Date

04-02-2020 - 119 - No Difference - Same

03-02-2020 - 119 - No Difference - Same
```

答:
Just an alternative, shorter version.  This just works on a straight for() loop, working with the current and next items.  The loop stops at the second from last one as the last one will always be the same as the next one...

```<code>$end = count($array)-1;
for ( $i = 0; $i < $end; $i++ ) {
    if ( $array[$i]["density"] == $array[$i+1]["density"] )    {
        echo "No Difference - Same".PHP_EOL;
    }
    else    {
        echo "Diff is ".($array[$i]["density"]-$array[$i+1]["density"])." from Previous Date".PHP_EOL;
    }

}
echo "No Difference - Same".PHP_EOL;
</code>```

Body:
I am trying to show some values using json api. It returns a date and some density value in numbers. Successfully, I have printed all return values from url. Now, I want to find the difference between one density value to previous day density value.

I know how to calculate the difference in normal static numbers. But, I am not sure how do I achieve this inside a foreach loop.

PHP Code:

$json_url = "https://www.example.com/api";

$json = file_get_contents($json_url);
$obj  = json_decode($json,true);
$data = $obj["data"];

foreach(array_slice($data, 0, 10) as $k) {

    echo $k["date"]." - ".$k["density"]."

";

}

Current Output:

14-02-2020 - 110

13-02-2020 - 114

12-02-2020 - 112

11-02-2020 - 110

10-02-2020 - 105

07-02-2020 - 125

06-02-2020 - 122

05-02-2020 - 118

04-02-2020 - 119

03-02-2020 - 119

Expected Output:

14-02-2020 - 110 - Diff is -4 from Previous Date

13-02-2020 - 114 - Diff is +2 from Previous Date

12-02-2020 - 112 - Diff is +2 from Previous Date

11-02-2020 - 110 - Diff is +5 from Previous Date

10-02-2020 - 105 - Diff is -20 from Previous Date

07-02-2020 - 125 - Diff is +3 from Previous Date

06-02-2020 - 122 - Diff is +4 from Previous Date

05-02-2020 - 118 - Diff is -1 from Previous Date

04-02-2020 - 119 - No Difference - Same

03-02-2020 - 119 - No Difference - Same

Body:
Just an alternative, shorter version.  This just works on a straight for() loop, working with the current and next items.  The loop stops at the second from last one as the last one will always be the same as the next one...

$end = count($array)-1;
for ( $i = 0; $i < $end; $i++ ) {
    if ( $array[$i]["density"] == $array[$i+1]["density"] )    {
        echo "No Difference - Same".PHP_EOL;
    }
    else    {
        echo "Diff is ".($array[$i]["density"]-$array[$i+1]["density"])." from Previous Date".PHP_EOL;
    }

}
echo "No Difference - Same".PHP_EOL;


问:
How can web developer see user console errors?
I was wondering what is the best way (or different options) for a web developer to be alerted to console errors that are logged by other users (who are logged in). I'm using Express / Passport connected to MongoDB. The errors could be on the client or server side. I was guessing I could somehow send the error to the database and access it through there. Alternately I could use something like mailgun to email them to myself, but I was wondering if there were better ways of doing this?

Thanks

答:
I think there are different ways to do this. But the important point is that you must classify the system errors and consider an information system for each. For example, for critical errors that cause the system to crash, you need to have a module for sending SMS directly, or use modules to send messages to one of your social networks.

Good for second-rate errors with less priority for email and error storage.

For low-priority errors and warnings, you need to have a log storage system that stores logged records and monitors relevant processing and error processing from your stored information. Graylog is OK! :)

The Winston module is usually used to display errors in Express.
 And in the first layer, if you use PM2, it automatically saves the logs in a text file.


问:
Trying to group an array of objects under same keys resulting in a new array of objects
I have an array of messages consisting of objects, where each object represents a single message and the created_at key representing the date of the message. I am receiving this data from the API. Here is the structure that I get:

```<code>let messages = [
  {text: "A", status: 'r', created_at: "2020-02-06"},
  {text: "B", status: 's', created_at: "2020-02-06"},
  {text: "C", status: 'r', created_at: "2020-02-06"},
  {text: "D", status: 's', created_at: "2020-02-07"},
  {text: "E", status: 's', created_at: "2020-02-07"},
  {text: "F", status: 'r', created_at: "2020-02-09"},
  {text: "G", status: 's', created_at: "2020-02-09"},
  {text: "H", status: 's', created_at: "2020-02-10"}
]
</code>```

I am using vuejs to render these messages in a chat application (similar to WhatsApp), where I want to display the date on top and the messages under that date in chronological order, just like WhatsApp. I am receiving the messages from the API in chronological order like the messages array I pasted above.
I would like to have the following output, so that I can use v-for directive in vuejs to loop through the messages and render them according to the date they were created:

```<code>  output:
    [
      {
        dt: "2020-02-06",
        arr: [
            {text: "A", status: 'r', created_at: "2020-02-06"},
            {text: "B", status: 's', created_at: "2020-02-06"},
            {text: "C", status: 'r', created_at: "2020-02-06"},
        ]
      },
      {
        dt: "2020-02-07",
        arr: [
            {text: "D", status: 's', created_at: "2020-02-06"},
            {text: "E", status: 's', created_at: "2020-02-06"},
        ]
      },
      {
        dt: "2020-02-09",
        arr: [
            {text: "F", status: 'r', created_at: "2020-02-09"},
            {text: "G", status: 's', created_at: "2020-02-09"},
        ]
      },
        {
        dt: "2020-02-10",
        arr: [
           {text: "H", status: 's', created_at: "2020-02-10"}
        ]
      },
    ]
</code>```

Is there a library in lodash that can achieve this directly?

What I have tried so far:

I was able to group the dates in an array without the dates repeating, like so:

```<code>let dates = messages.map((item => {
    return item.created_at
}))
let uniq = [...new Set(dates)];
console.log(uniq)
</code>```

...which gives the following output:

```<code>uniq = ["2020-02-06", "2020-02-07", "2020-02-09", "2020-02-10"]
</code>```

I am not able to move ahead of this.

Thanks in advance!

答:
I found the solution without using any external library:

const messages = [
  {text: "A", status: 'r', created_at: "2020-02-06"},
  {text: "B", status: 's', created_at: "2020-02-06"},
  {text: "C", status: 'r', created_at: "2020-02-06"},
  {text: "D", status: 's', created_at: "2020-02-07"},
  {text: "E", status: 's', created_at: "2020-02-07"},
  {text: "F", status: 'r', created_at: "2020-02-09"},
  {text: "G", status: 's', created_at: "2020-02-09"},
  {text: "H", status: 's', created_at: "2020-02-10"}
]

let dupDates = messages.map((item => {
 return item.created_at
}))
let uniq = [...new Set(dupDates)];
let grouping = uniq.map(uniqItem => {
 let ret = messages.filter(msg => {
   return msg.created_at === uniqItem
  })
  return {
    dt: uniqItem,
         arr: ret
  }
})
console.log(grouping)
 ```

Body:
I have an array of messages consisting of objects, where each object represents a single message and the created_at key representing the date of the message. I am receiving this data from the API. Here is the structure that I get:

let messages = [
  {text: "A", status: 'r', created_at: "2020-02-06"},
  {text: "B", status: 's', created_at: "2020-02-06"},
  {text: "C", status: 'r', created_at: "2020-02-06"},
  {text: "D", status: 's', created_at: "2020-02-07"},
  {text: "E", status: 's', created_at: "2020-02-07"},
  {text: "F", status: 'r', created_at: "2020-02-09"},
  {text: "G", status: 's', created_at: "2020-02-09"},
  {text: "H", status: 's', created_at: "2020-02-10"}
]

I am using vuejs to render these messages in a chat application (similar to WhatsApp), where I want to display the date on top and the messages under that date in chronological order, just like WhatsApp. I am receiving the messages from the API in chronological order like the messages array I pasted above.
I would like to have the following output, so that I can use v-for directive in vuejs to loop through the messages and render them according to the date they were created:

  output:
    [
      {
        dt: "2020-02-06",
        arr: [
            {text: "A", status: 'r', created_at: "2020-02-06"},
            {text: "B", status: 's', created_at: "2020-02-06"},
            {text: "C", status: 'r', created_at: "2020-02-06"},
        ]
      },
      {
        dt: "2020-02-07",
        arr: [
            {text: "D", status: 's', created_at: "2020-02-06"},
            {text: "E", status: 's', created_at: "2020-02-06"},
        ]
      },
      {
        dt: "2020-02-09",
        arr: [
            {text: "F", status: 'r', created_at: "2020-02-09"},
            {text: "G", status: 's', created_at: "2020-02-09"},
        ]
      },
        {
        dt: "2020-02-10",
        arr: [
           {text: "H", status: 's', created_at: "2020-02-10"}
        ]
      },
    ]

Is there a library in lodash that can achieve this directly?

What I have tried so far:

I was able to group the dates in an array without the dates repeating, like so:

let dates = messages.map((item => {
    return item.created_at
}))
let uniq = [...new Set(dates)];
console.log(uniq)

...which gives the following output:

uniq = ["2020-02-06", "2020-02-07", "2020-02-09", "2020-02-10"]

I am not able to move ahead of this.

Thanks in advance!


答:
We can use ave here :

```<code>df$timestamp <- with(df, ave(timestamp, label, FUN = function(x) (x - x[1])/10E8))
</code>```

With dplyr

```<code>library(dplyr)

df %>%
  group_by(label) %>%
  mutate(timestamp = (timestamp - first(timestamp))/10E8)
</code>```

Or data.table

```<code>library(data.table)
setDT(df)[, timestamp := (timestamp - first(timestamp))/10E8, label]
</code>```

This subtracts timestamp with first timestamp in each label dividing by 10E8.

Title: How to set time equal to zero by group?

Body:
If I have a data frame that has many rows like this:

  subject-id activity label    timestamp          x         y          z
1       1600              A 2.522077e+14 -0.3647613  8.793503  1.0550842
2       1600              A 2.522077e+14 -0.8797302  9.768784  1.0169983
3       1600              A 2.522078e+14  2.0014954 11.109070   2.619156
4       1600              A 2.522078e+14  0.4506226 12.651642 0.18455505
5       1600              A 2.522079e+14 -2.1643524 13.928436 -4.4224854
6       1600              A 2.522079e+14 -4.3327790 13.361191 -0.7188721
.
.
.
  subject-id activity label    timestamp           x          y          z
991      1600             B 2.519876e+14  1.37554930 15.3750460  2.9716187
992      1600             B 2.519877e+14 -3.93443300 17.5387880  2.1100159
993      1600             B 2.519877e+14 -0.08773804 12.7915650 -1.4541016
994      1600             B 2.519878e+14  2.03874200  3.0771484 -1.0537262
995      1600             B 2.519878e+14 -2.55847170 -2.7386780 -2.0985107
996      1600             B 2.519879e+14 -1.35530090  0.3884125 -0.6598511

How can I set the time equal to zero by group "subject-id"? I want to subtract off the first time for every instance of that group. Like this:

  subject-id activity label    timestamp          x         y          z
1       1600              A            0 -0.3647613  8.793503  1.0550842
2       1600              A      .050354 -0.8797302  9.768784  1.0169983
3       1600              A      .100708  2.0014954 11.109070   2.619156
4       1600              A      .151062  0.4506226 12.651642 0.18455505
.
.
.
  subject-id activity label    timestamp           x          y          z
991      1600             B            0  1.37554930 15.3750460  2.9716187
992      1600             B      .049355 -3.93443300 17.5387880  2.1100159
993      1600             B      .100601 -0.08773804 12.7915650 -1.4541016

Note: I made up some number for activity B to demonstrate what I mean.

What I have tried:
I tried making a function and applying the function with aggregate:

time_zero <- function(vec){
  result <- (vec$timestamp - vec$timestamp[1])/10E8
  return(result)
}
test <- aggregate(pa, list(pa$`activity label`), FUN = time_zero)

Body:
We can use ave here :

df$timestamp <- with(df, ave(timestamp, label, FUN = function(x) (x - x[1])/10E8))

With dplyr

library(dplyr)

df %>%
  group_by(label) %>%
  mutate(timestamp = (timestamp - first(timestamp))/10E8)

Or data.table

library(data.table)
setDT(df)[, timestamp := (timestamp - first(timestamp))/10E8, label]

This subtracts timestamp with first timestamp in each label dividing by 10E8.


问:
How can I make timediff functions returned negative time to positive?
I have query where I have to find the difference between two times , it works well when the first time is greater than the second time .

But when the first one is smaller than the second one it returns a negative time; Just wondering is there any way to make it positive?

Below is the query that returns negative time.

```<code>SELECT TIMEDIFF("13:10:11", "13:20:10");
</code>```

output

```<code>-00:09:59
</code>```

expected output

```<code>00:09:59
</code>```

答:
Use DateDiff with MINUTE difference:    </p>

```<code> SELECT DATEDIFF(MINUTE, '11:10:10' , '11:20:00') AS MinuteDiff
</code>```

Body:
I have query where I have to find the difference between two times , it works well when the first time is greater than the second time .

But when the first one is smaller than the second one it returns a negative time; Just wondering is there any way to make it positive?

Below is the query that returns negative time.

SELECT TIMEDIFF("13:10:11", "13:20:10");

output

-00:09:59

expected output

00:09:59

Body:
Use DateDiff with MINUTE difference:

 SELECT DATEDIFF(MINUTE, '11:10:10' , '11:20:00') AS MinuteDiff


问:
Challenge for realm in HttpUnit
The HttpUnit API for webclient says that "Will only send the authorization header when challenged for the specified realm." What does challenged mean in this case? How does HttpUnit recognize a challenge?</p>

答:
This refers to the way HTTP Authentication works:

When accessing a protected URL (for the first time, with no credentials included in the request), the server will send back a response that has a status code of 401 Unauthorized  and a WWW-Authenticate header set to something like Basic realm="My Realm". This indicates that Basic authentication is needed for the given URL and the realm is named 'My Realm'. This is the challenge - the user agent is being informed by the server that the URL it tried to access requires authentication and it should send back the user credentials. The user agent will typically prompt the user for credentials and then retry the request, this time with a Authorization header set to something like Basic rXflcjMwYXxz where the second part is the Base64 encoded username and password pair.

In case of the HttpUnit method you've linked to, you'll see that it requires a realm, username and password. I imagine that when the a URL is accessed, if it gets back a 401 (the challenge) from the server, it'll compare the realm you passed it with the realm in the response; if it matches, it'll attempt to authenticate with the username and password supplied.

References:

RFC entry for 401

Headers for authentication

Basic access authentication

Title: Challenge for realm in HttpUnit


问:
Angular - Redirect based on user's login Id
I am working on an Application with Laravel backend and Angular frontend. Each table has user_id that is related to id in users table, that is User Model class. Apart from admin that has user Id as 1, that will see everything. I want it that any user that logs in, it should redirect based on login Id.

Angular: auth.service.ts

```<code>import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { HttpHeaders } from '@angular/common/http';
import { Router } from '@angular/router';
import { Observable, throwError } from 'rxjs';
import { catchError, map, tap } from 'rxjs/operators';

// App imports
import { environment } from '../../environments/environment.prod';
import { User } from '../models/user';
// Setup headers
const httpOptions = {
  headers: new HttpHeaders({
'Content-Type': 'application/json'
})
};

@Injectable({
providedIn: 'root'
})
export class AuthService {
 public currentUser: User;
 private readonly apiUrl = environment.apiUrl;
 private registerUrl = this.apiUrl + '/register';
 private loginUrl = this.apiUrl + '/login';

 constructor(
 private http: HttpClient,
 private router: Router) {}

 onRegister(user: User): Observable<User> {

const request = JSON.stringify(
  { name: user.name, username: user.username, email: user.email, password: user.password }
);

return this.http.post(this.registerUrl, request, httpOptions)
  .pipe(
    map((response: User) => {
      // Receive jwt token in the response
      const token: string = response['access_token'];
      // If we have a token, proceed
      if (token) {
        this.setToken(token);
        this.getUser().subscribe();
      }
      return response;
    }),
    catchError(error => this.handleError(error))
  );
  }

  onLogin(user: User): Observable<User> {

const request = JSON.stringify(
  { email: user.email, password: user.password }
);

return this.http.post(this.loginUrl, request, httpOptions)
  .pipe(
    map((response: User) => {
      // Receive jwt token in the response
      const token: string = response['access_token'];
      // If we have a token, proceed
      if (token) {
        this.setToken(token);
        this.getUser().subscribe();
      }
      return response;
    }),
    catchError(error => this.handleError(error))
  );
  }

  onLogout(): Observable<User> {
return this.http.post(this.apiUrl + '/logout', httpOptions).pipe(
  tap(
    () => {
      localStorage.removeItem('token');
      this.router.navigate(['/']);
    }
   )
 );
 }

setToken(token: string): void {
return localStorage.setItem('token', token );
}

getToken(): string {
return localStorage.getItem('token');
}

getUser(): Observable<User> {
return this.http.get(this.apiUrl + '/me').pipe(
  tap(
    (user: User) => {
      this.currentUser = user;
    }
  )
 );
}

isAuthenticated(): boolean {
// get the token
const token: string = this.getToken();
if (token) {
  return true;
}
return false;
}

private handleError(error: HttpErrorResponse) {
if (error.error instanceof ErrorEvent) {
  // A client-side error.
  console.error('An error occurred:', error.error.message);
} else {
  // The backend error.
    return throwError(error);
}
// return a custom error message
return throwError('Ohps something wrong happen here; please try again
later.');
  }
}
</code>```

login.component.ts

```<code> public function indexShortcode(Request $request)
{
if(Auth::user()->id == 1)
    $shortcodes = Shortcode::all();
import { Component, OnInit } from '@angular/core';
import { FormGroup,  FormBuilder,  Validators } from '@angular/forms';
import { FlashMessagesService } from 'angular2-flash-messages';
import { ActivatedRoute, Router } from '@angular/router';
import {UserService} from '../../services/user.service';
import { SnotifyService } from 'ng-snotify';

// App imports
import { AuthService } from '../../services/auth.service';
import { User } from '../../models/user';

@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {
user: User = new User();
error: any;
returnUrl: string;

constructor(
private authService: AuthService,
private router: Router,
private route: ActivatedRoute,
private notify: SnotifyService
) { }

 ngOnInit() {
 //  Set the return url
 this.returnUrl = this.route.snapshot.queryParams['returnUrl'] || '/home';
}

onSubmit(loginForm): void {
this.authService.onLogin(this.user).subscribe(
  (response) => {
    // get return url from route parameters or default to '/'
    this.notify.success('Done, you have successfully logged in.', {timeout:2000, position: "rightTop"})
    this.router.navigate([this.returnUrl]);
  },
  (error) => {
    this.error = error.error;
  }
);
// Clear form fields
loginForm.reset();
}
}
}
</code>```

login.component.ts

```<code> public function login(Request $request)
{
$validator = Validator::make($request->all(), [
    'email' => 'required|string|email|max:255',
    'password'=> 'required'
]);

if ($validator->fails()) {
    return response()->json($validator->errors(), 422);
}

$credentials = $request->only(['email', 'password']);

if (!$token = auth()->attempt($credentials)) {
    return response()->json(['error' => 'Invalid Credentials'], 400);
}

$current_user = $request->email;

return response()->json([
'access_token' => $token,
'token_type' => 'bearer',
'current_user' => $current_user,
'expires_in' => auth()->factory()->getTTL() * 60
], 200);
}
</code>```

auth.guard.ts

```<code>import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router }
from '@angular/router';
import { Observable } from 'rxjs';
import { AuthService } from '../services/auth.service';

@Injectable()
export class AuthGuard implements CanActivate {

 constructor(
private router: Router,
private auth: AuthService) {}

canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> |
 boolean {

  if (this.auth.isAuthenticated()) {
    // logged in so return true
    return true;
  }

  // not logged in so redirect to login page with the return url
  this.router.navigate(['/login'], { queryParams: { returnUrl: state.url
}});

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

auth.guard.spec.ts

```<code>import { RouterTestingModule } from '@angular/router/testing';
import { TestBed, async, inject } from '@angular/core/testing';
import { HttpClient, HttpHandler } from '@angular/common/http';
import { Router } from '@angular/router';

//  App imports
import { AuthGuard } from './auth.guard';
import { AuthService } from '../services/auth.service';

describe('AuthGuard Tests: ', () => {
const router = {
  navigate: jasmine.createSpy('navigate')
 };

beforeEach(async(() => {
TestBed.configureTestingModule({
  imports: [
    RouterTestingModule.withRoutes([
      {path: 'shortcode:id'}
    ])
  ],
  providers: [AuthGuard, AuthService, HttpClient, HttpHandler, { provide:
Router, useValue: router } ]
});
 }));

   it('should AuthGuartd to be defined', inject([AuthGuard], (guard: AuthGuard)
=> {
expect(guard).toBeTruthy();
}));

it('should AuthService to be defined', inject([AuthService], (auth:
AuthService) => {
expect(auth).toBeTruthy();
}));

});
</code>```

If login user()->id is 1 it should redirect to admindashboard, but if not 1 it should redirect to userdashboard.

答:
From your login function in laravel, you are returning a field current_user which holds just the current users email. It is advisable and more flexible to rather return every important detail of that user to the frontend, for a more robust application. If your email field in the user table is unique, you should send a query to search for the user and assign the value to a variable, like:

$user = User::where('email',$request['email'])->get()->first();
```

<p>and assign that <code>$user</code> to <code>current_user</code>:</p>

<pre class="lang-php prettyprint-override"><code>return response()->json([
    'access_token' => $token,
    'token_type' => 'bearer',
    'current_user' => $user,
    'expires_in' => auth()->factory()->getTTL() * 60
], 200);
</code>```

Then in your onSubmit(loginForm) function, before you redirect, you can specify a condition from your response:

if(response.current_user.role_id==1){
    this.route.navigate(['admindashboard'],response.current_user.id);
} else {
    this.route.navigate(['userdashboard'],response.current_user.id);
}
```

I hope this is the answer to the question, or gives you a logic on how to solve it.

Body:
I am working on an Application with Laravel backend and Angular frontend. Each table has user_id that is related to id in users table, that is User Model class. Apart from admin that has user Id as 1, that will see everything. I want it that any user that logs in, it should redirect based on login Id.

Angular: auth.service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { HttpHeaders } from '@angular/common/http';
import { Router } from '@angular/router';
import { Observable, throwError } from 'rxjs';
import { catchError, map, tap } from 'rxjs/operators';

// App imports
import { environment } from '../../environments/environment.prod';
import { User } from '../models/user';
// Setup headers
const httpOptions = {
  headers: new HttpHeaders({
'Content-Type': 'application/json'
})
};

@Injectable({
providedIn: 'root'
})
export class AuthService {
 public currentUser: User;
 private readonly apiUrl = environment.apiUrl;
 private registerUrl = this.apiUrl + '/register';
 private loginUrl = this.apiUrl + '/login';

 constructor(
 private http: HttpClient,
 private router: Router) {}

 onRegister(user: User): Observable<User> {

const request = JSON.stringify(
  { name: user.name, username: user.username, email: user.email, password: user.password }
);

return this.http.post(this.registerUrl, request, httpOptions)
  .pipe(
    map((response: User) => {
      // Receive jwt token in the response
      const token: string = response['access_token'];
      // If we have a token, proceed
      if (token) {
        this.setToken(token);
        this.getUser().subscribe();
      }
      return response;
    }),
    catchError(error => this.handleError(error))
  );
  }

  onLogin(user: User): Observable<User> {

const request = JSON.stringify(
  { email: user.email, password: user.password }
);

return this.http.post(this.loginUrl, request, httpOptions)
  .pipe(
    map((response: User) => {
      // Receive jwt token in the response
      const token: string = response['access_token'];
      // If we have a token, proceed
      if (token) {
        this.setToken(token);
        this.getUser().subscribe();
      }
      return response;
    }),
    catchError(error => this.handleError(error))
  );
  }

  onLogout(): Observable<User> {
return this.http.post(this.apiUrl + '/logout', httpOptions).pipe(
  tap(
    () => {
      localStorage.removeItem('token');
      this.router.navigate(['/']);
    }
   )
 );
 }

setToken(token: string): void {
return localStorage.setItem('token', token );
}

getToken(): string {
return localStorage.getItem('token');
}

getUser(): Observable<User> {
return this.http.get(this.apiUrl + '/me').pipe(
  tap(
    (user: User) => {
      this.currentUser = user;
    }
  )
 );
}

isAuthenticated(): boolean {
// get the token
const token: string = this.getToken();
if (token) {
  return true;
}
return false;
}

private handleError(error: HttpErrorResponse) {
if (error.error instanceof ErrorEvent) {
  // A client-side error.
  console.error('An error occurred:', error.error.message);
} else {
  // The backend error.
    return throwError(error);
}
// return a custom error message
return throwError('Ohps something wrong happen here; please try again
later.');
  }
}

login.component.ts

 public function indexShortcode(Request $request)
{
if(Auth::user()->id == 1)
    $shortcodes = Shortcode::all();
import { Component, OnInit } from '@angular/core';
import { FormGroup,  FormBuilder,  Validators } from '@angular/forms';
import { FlashMessagesService } from 'angular2-flash-messages';
import { ActivatedRoute, Router } from '@angular/router';
import {UserService} from '../../services/user.service';
import { SnotifyService } from 'ng-snotify';

// App imports
import { AuthService } from '../../services/auth.service';
import { User } from '../../models/user';

@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {
user: User = new User();
error: any;
returnUrl: string;

constructor(
private authService: AuthService,
private router: Router,
private route: ActivatedRoute,
private notify: SnotifyService
) { }

 ngOnInit() {
 //  Set the return url
 this.returnUrl = this.route.snapshot.queryParams['returnUrl'] || '/home';
}

onSubmit(loginForm): void {
this.authService.onLogin(this.user).subscribe(
  (response) => {
    // get return url from route parameters or default to '/'
    this.notify.success('Done, you have successfully logged in.', {timeout:2000, position: "rightTop"})
    this.router.navigate([this.returnUrl]);
  },
  (error) => {
    this.error = error.error;
  }
);
// Clear form fields
loginForm.reset();
}
}
}

login.component.ts

 public function login(Request $request)
{
$validator = Validator::make($request->all(), [
    'email' => 'required|string|email|max:255',
    'password'=> 'required'
]);

if ($validator->fails()) {
    return response()->json($validator->errors(), 422);
}

$credentials = $request->only(['email', 'password']);

if (!$token = auth()->attempt($credentials)) {
    return response()->json(['error' => 'Invalid Credentials'], 400);
}

$current_user = $request->email;

return response()->json([
'access_token' => $token,
'token_type' => 'bearer',
'current_user' => $current_user,
'expires_in' => auth()->factory()->getTTL() * 60
], 200);
}

auth.guard.ts

import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router }
from '@angular/router';
import { Observable } from 'rxjs';
import { AuthService } from '../services/auth.service';

@Injectable()
export class AuthGuard implements CanActivate {

 constructor(
private router: Router,
private auth: AuthService) {}

canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> |
 boolean {

  if (this.auth.isAuthenticated()) {
    // logged in so return true
    return true;
  }

  // not logged in so redirect to login page with the return url
  this.router.navigate(['/login'], { queryParams: { returnUrl: state.url
}});

  return true;
 }
}

auth.guard.spec.ts

import { RouterTestingModule } from '@angular/router/testing';
import { TestBed, async, inject } from '@angular/core/testing';
import { HttpClient, HttpHandler } from '@angular/common/http';
import { Router } from '@angular/router';

//  App imports
import { AuthGuard } from './auth.guard';
import { AuthService } from '../services/auth.service';

describe('AuthGuard Tests: ', () => {
const router = {
  navigate: jasmine.createSpy('navigate')
 };

beforeEach(async(() => {
TestBed.configureTestingModule({
  imports: [
    RouterTestingModule.withRoutes([
      {path: 'shortcode:id'}
    ])
  ],
  providers: [AuthGuard, AuthService, HttpClient, HttpHandler, { provide:
Router, useValue: router } ]
});
 }));

   it('should AuthGuartd to be defined', inject([AuthGuard], (guard: AuthGuard)
=> {
expect(guard).toBeTruthy();
}));

it('should AuthService to be defined', inject([AuthService], (auth:
AuthService) => {
expect(auth).toBeTruthy();
}));

});

If login user()->id is 1 it should redirect to admindashboard, but if not 1 it should redirect to userdashboard.

Body:
From your login function in laravel, you are returning a field current_user which holds just the current users email. It is advisable and more flexible to rather return every important detail of that user to the frontend, for a more robust application. If your email field in the user table is unique, you should send a query to search for the user and assign the value to a variable, like:

$user = User::where('email',$request['email'])->get()->first();

and assign that $user to current_user:

return response()->json([
    'access_token' => $token,
    'token_type' => 'bearer',
    'current_user' => $user,
    'expires_in' => auth()->factory()->getTTL() * 60
], 200);

Then in your onSubmit(loginForm) function, before you redirect, you can specify a condition from your response:

if(response.current_user.role_id==1){
    this.route.navigate(['admindashboard'],response.current_user.id);
} else {
    this.route.navigate(['userdashboard'],response.current_user.id);
}

I hope this is the answer to the question, or gives you a logic on how to solve it.


问:
Build an SQL query dynamically based on columns' datatype
In my app, i have a feature where the user can enter multiple search fields and these will be used to query the db, for example, the user enters:

smith 123456 london 12/01/2020

These fields will be passed to a stored procedure as a table-valued parameter (consisting of one column as varchar). The sp uses a view as its datasource. For example for the above custom search, there will be a view with the following columns:

```<code>number, int
firstname, varchar
lastname, varchar
dob, datetime
address, varchar
</code>```

The sp needs to build the sql query dynamically and this query should look like

```<code>select * from customersview
where 'smith' in (firstname, lastname, address)
and 123456 in (number)
and 'london' in (firstname, lastname, address)
and '12/01/2029' in (dob)
</code>```

So basically, what the sp does is:

Take the search filters and determine what datatype they are

Map the filters' datatype with columns' datatype, so that, for example, an int filter is mapped to all int columns, etc.

So I started off with the following:

```<code>select COLUMN_NAME, DATA_TYPE
from INFORMATION_SCHEMA.VIEWS v
join INFORMATION_SCHEMA.COLUMNS c on c.TABLE_SCHEMA = v.TABLE_SCHEMA
and c.TABLE_NAME = v.TABLE_NAME
where c.TABLE_NAME = 'customersview'
</code>```

which will give me the view's columns and their datatype.

But how can I match the data types (because the filters come in a TVP) so that I can build the various conditions?

Alternatively, I can change the TableType so that it has 3 unique columns (int, varchar, datetime) and the app determines the data type and adds the value in the correct column.

答:
I just tried to build the query using a while loop and checking the datatype as following.

I have added comments in the query itself for easy understanding.

TODO:

1- You need to add other datatypes the below query.

2- You need to parameterized the query and use sp_executesql instead of execute to avoid any sql injection attack.

```<code>--Table to Store search inputs, which will be your table type parameter.
DECLARE @v TABLE (searchString VARCHAR(100))
--Sample Inputs
INSERT INTO @v
SELECT *
FROM (
    VALUES ('smith')
        ,('1234')
        ,('london')
        ,('12/01/2020')
    ) t(v)

IF OBJECT_ID('tempdb..#Temp') IS NOT NULL
    DROP TABLE #Temp
--Create a temporary table to loop the serach inputs
SELECT *
    ,0 AS IsProcessed
INTO #Temp
FROM @v

DECLARE @query NVARCHAR(max) = 'SELECT * FROM customersview WHERE 1 = 1 '
DECLARE @searchString VARCHAR(100)
--Loop through each search input
WHILE (
        SELECT Count(*)
        FROM #Temp
        ) > 0
BEGIN
    SELECT TOP 1 @searchString = searchString
    FROM #Temp

    SELECT @searchString

    --Check if input is int/bigint type
    IF (ISNUMERIC(@searchString) = 1)
    BEGIN

        SET @query = @query + 'AND ' + @searchString + ' IN (' + Stuff((
                    SELECT DISTINCT ', ' + Quotename(COLUMN_NAME)
                    FROM (
                        SELECT COLUMN_NAME
                            ,DATA_TYPE
                        FROM INFORMATION_SCHEMA.VIEWS v
                        JOIN INFORMATION_SCHEMA.COLUMNS c ON c.TABLE_SCHEMA = v.TABLE_SCHEMA
                            AND c.TABLE_NAME = v.TABLE_NAME
                        WHERE c.TABLE_NAME = 'customersview'
                            AND DATA_TYPE IN ('int', 'bigint')
                        ) t
                    FOR XML path('')
                        ,type
                    ).value('.', 'NVARCHAR(MAX)'), 1, 1, '') + ')'
    END
    --Check if input is date type
    ELSE IF (ISDATE(@searchString) = 1)
    BEGIN

        SET @query = @query + ' AND ''' + @searchString + ''' IN (' + Stuff((
                    SELECT DISTINCT ', ' + Quotename(COLUMN_NAME)
                    FROM (
                        SELECT COLUMN_NAME
                            ,DATA_TYPE
                        FROM INFORMATION_SCHEMA.VIEWS v
                        JOIN INFORMATION_SCHEMA.COLUMNS c ON c.TABLE_SCHEMA = v.TABLE_SCHEMA
                            AND c.TABLE_NAME = v.TABLE_NAME
                        WHERE c.TABLE_NAME = 'customersview'
                            AND DATA_TYPE IN ('date', 'datetime')
                        ) t
                    FOR XML path('')
                        ,type
                    ).value('.', 'NVARCHAR(MAX)'), 1, 1, '') + ')'
    END
    ELSE
    BEGIN
    --Check if input is VARCHAR/NVARCHAR type
        SET @query = @query + ' AND ''' + @searchString + ''' IN (' + Stuff((
                    SELECT DISTINCT ', ' + Quotename(COLUMN_NAME)
                    FROM (
                        SELECT COLUMN_NAME
                            ,DATA_TYPE
                        FROM INFORMATION_SCHEMA.VIEWS v
                        JOIN INFORMATION_SCHEMA.COLUMNS c ON c.TABLE_SCHEMA = v.TABLE_SCHEMA
                            AND c.TABLE_NAME = v.TABLE_NAME
                        WHERE c.TABLE_NAME = 'customersview'
                            AND DATA_TYPE IN ('VARCHAR', 'NVARCHAR')
                        ) t
                    FOR XML path('')
                        ,type
                    ).value('.', 'NVARCHAR(MAX)'), 1, 1, '') + ')'
    END

    DELETE #Temp
    WHERE searchString = @searchString
END

SELECT @query
--Execute the query
--EXEC(@Query)
</code>```

Body:
In my app, i have a feature where the user can enter multiple search fields and these will be used to query the db, for example, the user enters:

smith 123456 london 12/01/2020

These fields will be passed to a stored procedure as a table-valued parameter (consisting of one column as varchar). The sp uses a view as its datasource. For example for the above custom search, there will be a view with the following columns:

number, int
firstname, varchar
lastname, varchar
dob, datetime
address, varchar

The sp needs to build the sql query dynamically and this query should look like

select * from customersview
where 'smith' in (firstname, lastname, address)
and 123456 in (number)
and 'london' in (firstname, lastname, address)
and '12/01/2029' in (dob)

So basically, what the sp does is:

Take the search filters and determine what datatype they are

Map the filters' datatype with columns' datatype, so that, for example, an int filter is mapped to all int columns, etc.

So I started off with the following:

select COLUMN_NAME, DATA_TYPE
from INFORMATION_SCHEMA.VIEWS v
join INFORMATION_SCHEMA.COLUMNS c on c.TABLE_SCHEMA = v.TABLE_SCHEMA
and c.TABLE_NAME = v.TABLE_NAME
where c.TABLE_NAME = 'customersview'

which will give me the view's columns and their datatype.

But how can I match the data types (because the filters come in a TVP) so that I can build the various conditions?

Alternatively, I can change the TableType so that it has 3 unique columns (int, varchar, datetime) and the app determines the data type and adds the value in the correct column.

Body:
I just tried to build the query using a while loop and checking the datatype as following.

I have added comments in the query itself for easy understanding.

TODO:

1- You need to add other datatypes the below query.

2- You need to parameterized the query and use sp_executesql instead of execute to avoid any sql injection attack.

--Table to Store search inputs, which will be your table type parameter.
DECLARE @v TABLE (searchString VARCHAR(100))
--Sample Inputs
INSERT INTO @v
SELECT *
FROM (
    VALUES ('smith')
        ,('1234')
        ,('london')
        ,('12/01/2020')
    ) t(v)

IF OBJECT_ID('tempdb..#Temp') IS NOT NULL
    DROP TABLE #Temp
--Create a temporary table to loop the serach inputs
SELECT *
    ,0 AS IsProcessed
INTO #Temp
FROM @v

DECLARE @query NVARCHAR(max) = 'SELECT * FROM customersview WHERE 1 = 1 '
DECLARE @searchString VARCHAR(100)
--Loop through each search input
WHILE (
        SELECT Count(*)
        FROM #Temp
        ) > 0
BEGIN
    SELECT TOP 1 @searchString = searchString
    FROM #Temp

    SELECT @searchString

    --Check if input is int/bigint type
    IF (ISNUMERIC(@searchString) = 1)
    BEGIN

        SET @query = @query + 'AND ' + @searchString + ' IN (' + Stuff((
                    SELECT DISTINCT ', ' + Quotename(COLUMN_NAME)
                    FROM (
                        SELECT COLUMN_NAME
                            ,DATA_TYPE
                        FROM INFORMATION_SCHEMA.VIEWS v
                        JOIN INFORMATION_SCHEMA.COLUMNS c ON c.TABLE_SCHEMA = v.TABLE_SCHEMA
                            AND c.TABLE_NAME = v.TABLE_NAME
                        WHERE c.TABLE_NAME = 'customersview'
                            AND DATA_TYPE IN ('int', 'bigint')
                        ) t
                    FOR XML path('')
                        ,type
                    ).value('.', 'NVARCHAR(MAX)'), 1, 1, '') + ')'
    END
    --Check if input is date type
    ELSE IF (ISDATE(@searchString) = 1)
    BEGIN

        SET @query = @query + ' AND ''' + @searchString + ''' IN (' + Stuff((
                    SELECT DISTINCT ', ' + Quotename(COLUMN_NAME)
                    FROM (
                        SELECT COLUMN_NAME
                            ,DATA_TYPE
                        FROM INFORMATION_SCHEMA.VIEWS v
                        JOIN INFORMATION_SCHEMA.COLUMNS c ON c.TABLE_SCHEMA = v.TABLE_SCHEMA
                            AND c.TABLE_NAME = v.TABLE_NAME
                        WHERE c.TABLE_NAME = 'customersview'
                            AND DATA_TYPE IN ('date', 'datetime')
                        ) t
                    FOR XML path('')
                        ,type
                    ).value('.', 'NVARCHAR(MAX)'), 1, 1, '') + ')'
    END
    ELSE
    BEGIN
    --Check if input is VARCHAR/NVARCHAR type
        SET @query = @query + ' AND ''' + @searchString + ''' IN (' + Stuff((
                    SELECT DISTINCT ', ' + Quotename(COLUMN_NAME)
                    FROM (
                        SELECT COLUMN_NAME
                            ,DATA_TYPE
                        FROM INFORMATION_SCHEMA.VIEWS v
                        JOIN INFORMATION_SCHEMA.COLUMNS c ON c.TABLE_SCHEMA = v.TABLE_SCHEMA
                            AND c.TABLE_NAME = v.TABLE_NAME
                        WHERE c.TABLE_NAME = 'customersview'
                            AND DATA_TYPE IN ('VARCHAR', 'NVARCHAR')
                        ) t
                    FOR XML path('')
                        ,type
                    ).value('.', 'NVARCHAR(MAX)'), 1, 1, '') + ')'
    END

    DELETE #Temp
    WHERE searchString = @searchString
END

SELECT @query
--Execute the query
--EXEC(@Query)


问:
Android 9 App or MDM shutdown and restart, timeout screen or sleep
Good morning, everyone,
we're considering an application that will be installed outside the meeting rooms.
Our tablets are Galaxy Tab A 2019 version of Android 9.
We realized that we would like to have these features on the tablets:

Turning off the screen and turning it back on at a certain time (or even turning off the entire tablet and starting up) - typically these are office hours: turning on at 08:00 in the morning and turning off at 8:00 in the evening.

Avoid timeout after a few minutes...

We have MAAS360 and we can manage the Kiosk mode of this application.

Do you have suggestions?

答:
As far as I know, the screen can be managed by any Android application.

To prevent the device from turning off screen, you need to add a flag FLAG_KEEP_SCREEN_ON to your Activity:

```<code>getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
</code>```

To turn off the screen, just clear this flag when you need to turn off (use AlarmManager to schedule the event), the screen will turn off in some minutes.

To turn screen back on, send a pending intent to your Activity using the AlarmManager, then use the following code to turn screen on in your Activity:

```<code>setTurnScreenOn(true);
</code>```

To wake the device up from the sleeping mode, use WakeLock and add the android.permission.WAKE_LOCK permission.

Body:
As far as I know, the screen can be managed by any Android application.

To prevent the device from turning off screen, you need to add a flag FLAG_KEEP_SCREEN_ON to your Activity:

getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

To turn off the screen, just clear this flag when you need to turn off (use AlarmManager to schedule the event), the screen will turn off in some minutes.

To turn screen back on, send a pending intent to your Activity using the AlarmManager, then use the following code to turn screen on in your Activity:

setTurnScreenOn(true);

To wake the device up from the sleeping mode, use WakeLock and add the android.permission.WAKE_LOCK permission.


问:
How to call another function's results
```<code>def most_frequency_occ(chars,inputString):
    count = 0
    for ind_char in inputString:
        ind_char = ind_char.lower()
        if chars == ind_char:
             count += 1
    return count

def general(inputString):
    maxOccurences = 0
    for chars in inputString:
        most_frequency_occ(chars, inputString)
</code>```

This is my current code. I'm trying to find the most frequent occurring letter in general. I created another function called most_frequency_occ that finds a specific character in the string that occurs the most often, but how do I generalize it into finding the frequent letter in a string without specifying a specific character and only using loops, without any build in string functions either.

For example:

```<code>print(general('aqweasdaza'))
</code>```

should print 4 as "a" occurs the most frequently, occurring 4 times.

答:
The other answers have suggested alternative ways of counting the letters in a string, some of which may be better than what you've come up with on your own. But I think it may be worth answering your question about how to call your most_frequency_occ function from your general function even if the algorithm isn't great, since you'll need to understand how functions work in other contexts.

The thing to understand about function calls is that the call expression will be evaluated to the value returned by the function. In this case, that's the count. Often you may want to assign the return value to a variable so you can reference it multiple times. Here's what that might look like:

```<code>count = most_frequency_occ(chars, inputString)
</code>```

Now you can do a comparsion between the count and the previously best count to see if you've just checked the most common letter so far:

```<code>maxOccurences = 0
for chars in inputString:
    count = most_frequency_occ(chars, inputString)
    if count > maxOccurences:  # check if chars is more common than the previous best
        maxOccurences = count
return maxOccurences
</code>```

One final note: Some of your variable and function names are a bit misleading. That often happens when you're changing your code around from one design to another, but not changing the variable names at the same time. You may want to occasionally reread your code and double check to make sure that the variable names still match what you're doing with them. If not, you should "refactor" your code by renaming the variables to better match their actual uses.

To be specific, your most_frequency_occ function isn't actually finding the most frequent character itself, it's only doing a small step in that process, counting how often a single character occurs. So I'd call it count_char or something similar. The general function might be named something more descriptive like find_most_frequent_character.

And the variable chars (which exists in both functions) is also misleading since it represents a single character, but the name chars implies something plural (like a list or a string that contains several characters). Renaming it to char might be better, as that seems more like a singular name.

Title: How to call another function's results

Body:
def most_frequency_occ(chars,inputString):
    count = 0
    for ind_char in inputString:
        ind_char = ind_char.lower()
        if chars == ind_char:
             count += 1
    return count

def general(inputString):
    maxOccurences = 0
    for chars in inputString:
        most_frequency_occ(chars, inputString)

This is my current code. I'm trying to find the most frequent occurring letter in general. I created another function called most_frequency_occ that finds a specific character in the string that occurs the most often, but how do I generalize it into finding the frequent letter in a string without specifying a specific character and only using loops, without any build in string functions either.

For example:

print(general('aqweasdaza'))

should print 4 as "a" occurs the most frequently, occurring 4 times.

Body:
The other answers have suggested alternative ways of counting the letters in a string, some of which may be better than what you've come up with on your own. But I think it may be worth answering your question about how to call your most_frequency_occ function from your general function even if the algorithm isn't great, since you'll need to understand how functions work in other contexts.

The thing to understand about function calls is that the call expression will be evaluated to the value returned by the function. In this case, that's the count. Often you may want to assign the return value to a variable so you can reference it multiple times. Here's what that might look like:

count = most_frequency_occ(chars, inputString)

Now you can do a comparsion between the count and the previously best count to see if you've just checked the most common letter so far:

maxOccurences = 0
for chars in inputString:
    count = most_frequency_occ(chars, inputString)
    if count > maxOccurences:  # check if chars is more common than the previous best
        maxOccurences = count
return maxOccurences

One final note: Some of your variable and function names are a bit misleading. That often happens when you're changing your code around from one design to another, but not changing the variable names at the same time. You may want to occasionally reread your code and double check to make sure that the variable names still match what you're doing with them. If not, you should "refactor" your code by renaming the variables to better match their actual uses.

To be specific, your most_frequency_occ function isn't actually finding the most frequent character itself, it's only doing a small step in that process, counting how often a single character occurs. So I'd call it count_char or something similar. The general function might be named something more descriptive like find_most_frequent_character.

And the variable chars (which exists in both functions) is also misleading since it represents a single character, but the name chars implies something plural (like a list or a string that contains several characters). Renaming it to char might be better, as that seems more like a singular name.


问:
Mongoose $lookup aggregate doesn't work as expected
I am writing this mean stack application and here I have a company schema and vehicle schema for that company.

company details schema

```<code>var CompanyDetailsSchema = new Schema({
    companyName: String,
    createdAt: { type: Date, default: Date.now },
    ...............
    ...............

});
module.exports = mongoose.model('Company-details', CompanyDetailsSchema);
</code>```

vehicle schema

```<code>var VehicleDetailsSchema = new Schema({
    companyId:{
        type:mongoose.Schema.ObjectId,
        ref: 'Company-details'
    },
    createdAt: { type: Date, default: Date.now },
    ....................
    ....................
});

module.exports = mongoose.model('Vehicle-details', VehicleDetailsSchema);
</code>```

what I need is to get all the company details also when I get vehicle details. like in an SQL join query, for that I am using this  $lookup aggregate. this code sample returns all the vehicles but the company details are empty. how to get all the company details also in mongoose.

```<code>getVehciles:() =>{
        return new Promise((resolve, reject) => {
            VehicleDetailsSchema.aggregate([{
                $lookup: {
                    from: "Company-details", // collection name in db
                    localField: "companyId",
                    foreignField: "_id",
                    as: "companyDetails"
                }
            }]).exec(function(err, vehicles){
                if(err) {
                    reject(err)
                } else {
                    resolve(vehicles)
                }
            });
        })
    },
</code>```

答:
try this code works for me.</p>

```<code> getVehciles:() =>{
    return new Promise((resolve, reject) => {
        VehicleDetailsSchema.aggregate([{
            $lookup: {
                from: "company-details", // pass the callection name in small letters
                localField: "companyId",
                foreignField: "_id",
                as: "companyDetails"
            }
        }]).exec(function(err, vehicles){
            if(err) {
                reject(err)
            } else {
                resolve(vehicles)
            }
        });
    })
},
</code>```

Body:
I am writing this mean stack application and here I have a company schema and vehicle schema for that company.

company details schema

var CompanyDetailsSchema = new Schema({
    companyName: String,
    createdAt: { type: Date, default: Date.now },
    ...............
    ...............

});
module.exports = mongoose.model('Company-details', CompanyDetailsSchema);

vehicle schema

var VehicleDetailsSchema = new Schema({
    companyId:{
        type:mongoose.Schema.ObjectId,
        ref: 'Company-details'
    },
    createdAt: { type: Date, default: Date.now },
    ....................
    ....................
});

module.exports = mongoose.model('Vehicle-details', VehicleDetailsSchema);

what I need is to get all the company details also when I get vehicle details. like in an SQL join query, for that I am using this  $lookup aggregate. this code sample returns all the vehicles but the company details are empty. how to get all the company details also in mongoose.

getVehciles:() =>{
        return new Promise((resolve, reject) => {
            VehicleDetailsSchema.aggregate([{
                $lookup: {
                    from: "Company-details", // collection name in db
                    localField: "companyId",
                    foreignField: "_id",
                    as: "companyDetails"
                }
            }]).exec(function(err, vehicles){
                if(err) {
                    reject(err)
                } else {
                    resolve(vehicles)
                }
            });
        })
    },

Body:
try this code works for me.

 getVehciles:() =>{
    return new Promise((resolve, reject) => {
        VehicleDetailsSchema.aggregate([{
            $lookup: {
                from: "company-details", // pass the callection name in small letters
                localField: "companyId",
                foreignField: "_id",
                as: "companyDetails"
            }
        }]).exec(function(err, vehicles){
            if(err) {
                reject(err)
            } else {
                resolve(vehicles)
            }
        });
    })
},


问:
Modelling message queues
I've this system that consists of lots of different stages piped together.
Specifically, I've got lots of different processes that communicate via tcp-ip; messages are exchanged
via a packet oriented protocol (more messages can be stuffed together in a single wire-protocol data unit
if certains conditions are met); I've control flow queues too - sockets are non blocking, if I fail to send
I queue messages or even coalesce them in the send queue;
of course what happens at runtime depends on tcp ip control flow underneath, so I'd like to model the tcp ip queues, too.
So the question is - can anyone share their thoughts on how to make a simulation for my system?
I've thought to make a simulator for it - that is: a program with a queue data structure for every queue
I have in my model, for each time tick I make the model evolve according to my understanding of the sytstem
i.e. if the data structure for the tcp buffer in my model says it has space enough I decrement the message number
in the output queue and decrease the available space counter in the tcp buffer model by the size of the message, and so on - then I make the
tcp buffer empty at a rate based on the bandwidth for the tcp link
(of course I'm making the hypothesis that I'm pumping lots of data and that the only parameter for the tcp link
is bandwidth).
Building such a thing seems a lot of effort and I'm not sure it is what I need.
Maybe I'd better off with some kind of excel spreadsheet model, but I'm not sure how to structure it.</p>

答: You could use Ronald Szeto's TCP Simulator.  It has a Java interface to it.  I wouldn't try to get so complicated with paired queues.  Just model your system, and then use this simulator to model the underlying network conditions, and link them together as you would have in your OS.  I'm assuming you probably don't have separate network queues on your real system for every one in your application.</p>

OwnerDisplayName: vlvlvlvlvl

ContentLicense: CC BY-SA 2.5

Title: Modelling message queues

OwnerDisplayName: John Ellinwood


问:
Expect script to su to root and perform sed
I've never used expect before but need a script to do the following for a large list of hosts

ssh into a machine

su to root and enter the root password

sed a file in /etc/passwd to replace some text with some other text, for this example lets just say the original text is TEXT and the text to replace it with is NEWTEXT

Can anyone help?

答:
Understandably, executing a script to process commands as root is a huge security issue, and is generally not allowed.

However, Expect has the ability to run a pseudo terminal, so it can act just like a human typing away at a keyboard.

This is more or less what you asked, but is untested.

```<code>#!/bin/sh
# if run from shell, restart with wish \
exec wish "$0" "$@"

package require Expect

proc fix_a_host {host usrname password root_password} {
        # open session to host, wait for a username prompt
        spawn ssh $host
        expect "username:"

        # send username, wait for a password prompt
        send "$usrname\r"
        expect "password:"

        # send password, wait for shell prompt
        send "$password\r"
        expect "%"

        # become root, wait for prompt
        send "su\r"
        expect "#"

        # change TEXT to NEWTEXT in password file
        send "sed 's/TEXT/NEWTEXT'" /etc/passwd
        expect "#"

        # exit root, exit host connection
        send "exit\r"
        expect "%"

        send "exit\r"
        expect eof
}

fix_a_host {"host1" "someuser" "user_password"  "root_password"}
fix_a_host {"host2" "someuser" "user_password"  "root_password"}
</code>```

If it were me, I'd change the sed command to something far less destructive, like grep TEXT /etc/passwd until confident it works well.  For a remote command which display output you want to see, use

```<code>set results $expect_out(buffer)
send "some_command\r"
expect "#"    # use the command prompt to indicate output is complete
puts "command output is got `$buffer`"
</code>```

Body:
Understandably, executing a script to process commands as root is a huge security issue, and is generally not allowed.

However, Expect has the ability to run a pseudo terminal, so it can act just like a human typing away at a keyboard.

This is more or less what you asked, but is untested.

#!/bin/sh
# if run from shell, restart with wish \
exec wish "$0" "$@"

package require Expect

proc fix_a_host {host usrname password root_password} {
        # open session to host, wait for a username prompt
        spawn ssh $host
        expect "username:"

        # send username, wait for a password prompt
        send "$usrname\r"
        expect "password:"

        # send password, wait for shell prompt
        send "$password\r"
        expect "%"

        # become root, wait for prompt
        send "su\r"
        expect "#"

        # change TEXT to NEWTEXT in password file
        send "sed 's/TEXT/NEWTEXT'" /etc/passwd
        expect "#"

        # exit root, exit host connection
        send "exit\r"
        expect "%"

        send "exit\r"
        expect eof
}

fix_a_host {"host1" "someuser" "user_password"  "root_password"}
fix_a_host {"host2" "someuser" "user_password"  "root_password"}

If it were me, I'd change the sed command to something far less destructive, like grep TEXT /etc/passwd until confident it works well.  For a remote command which display output you want to see, use

set results $expect_out(buffer)
send "some_command\r"
expect "#"    # use the command prompt to indicate output is complete
puts "command output is got `$buffer`"


答:
I would do this in a single loop and use the printf() function to format the signed values.

I'm writing \n\n in place of your

 so that my demo renders properly.

I find this snippet easy to read and manage.

Code: (Demo)

```<code>$prev = null;
foreach ($data as $row) {
    if ($prev !== null) {
        $diff = $prev - $row['density'];
        if (!$diff) {
            echo " - No Difference - Same\n\n";
        } else {
            printf(" - Diff is %+d from Next Date\n\n", $diff);
        }
    }
    echo "{$row['date']} - {$row['density']}";
    $prev = $row['density'];
}
</code>```

Output:

```<code>14-02-2020 - 110 - Diff is -4 from Next Date

13-02-2020 - 114 - Diff is +2 from Next Date

12-02-2020 - 112 - Diff is +2 from Next Date

11-02-2020 - 110 - Diff is +5 from Next Date

10-02-2020 - 105 - Diff is -20 from Next Date

07-02-2020 - 125 - Diff is +3 from Next Date

06-02-2020 - 122 - Diff is +4 from Next Date

05-02-2020 - 118 - Diff is -1 from Next Date

04-02-2020 - 119 - No Difference - Same

03-02-2020 - 119
</code>```

Title: Get deltas from an array using foreach in PHP

Body:
I am trying to show some values using json api. It returns a date and some density value in numbers. Successfully, I have printed all return values from url. Now, I want to find the difference between one density value to previous day density value.

I know how to calculate the difference in normal static numbers. But, I am not sure how do I achieve this inside a foreach loop.

PHP Code:

$json_url = "https://www.example.com/api";

$json = file_get_contents($json_url);
$obj  = json_decode($json,true);
$data = $obj["data"];

foreach(array_slice($data, 0, 10) as $k) {

    echo $k["date"]." - ".$k["density"]."

";

}

Current Output:

14-02-2020 - 110

13-02-2020 - 114

12-02-2020 - 112

11-02-2020 - 110

10-02-2020 - 105

07-02-2020 - 125

06-02-2020 - 122

05-02-2020 - 118

04-02-2020 - 119

03-02-2020 - 119

Expected Output:

14-02-2020 - 110 - Diff is -4 from Previous Date

13-02-2020 - 114 - Diff is +2 from Previous Date

12-02-2020 - 112 - Diff is +2 from Previous Date

11-02-2020 - 110 - Diff is +5 from Previous Date

10-02-2020 - 105 - Diff is -20 from Previous Date

07-02-2020 - 125 - Diff is +3 from Previous Date

06-02-2020 - 122 - Diff is +4 from Previous Date

05-02-2020 - 118 - Diff is -1 from Previous Date

04-02-2020 - 119 - No Difference - Same

03-02-2020 - 119 - No Difference - Same

Body:
I would do this in a single loop and use the printf() function to format the signed values.

I'm writing \n\n in place of your <br><br> so that my demo renders properly.

I find this snippet easy to read and manage.

Code: (Demo)

$prev = null;
foreach ($data as $row) {
    if ($prev !== null) {
        $diff = $prev - $row['density'];
        if (!$diff) {
            echo " - No Difference - Same\n\n";
        } else {
            printf(" - Diff is %+d from Next Date\n\n", $diff);
        }
    }
    echo "{$row['date']} - {$row['density']}";
    $prev = $row['density'];
}

Output:

14-02-2020 - 110 - Diff is -4 from Next Date

13-02-2020 - 114 - Diff is +2 from Next Date

12-02-2020 - 112 - Diff is +2 from Next Date

11-02-2020 - 110 - Diff is +5 from Next Date

10-02-2020 - 105 - Diff is -20 from Next Date

07-02-2020 - 125 - Diff is +3 from Next Date

06-02-2020 - 122 - Diff is +4 from Next Date

05-02-2020 - 118 - Diff is -1 from Next Date

04-02-2020 - 119 - No Difference - Same

03-02-2020 - 119


问:
URL join of two URIs
I am trying to join these two URIs

```<code>from urllib.parse import urljoin
# baskslash is not a mistake
r = urljoin(r"https:/\\corrlinks.blob.core.windows.net", r"videofaq")
print(r)
</code>```

I am getting

```<code>https:///videofaq
</code>```

How can I get

```<code>https:/\\corrlinks.blob.core.windows.net/videofaq
</code>```

This one would be Ok too:

```<code>https://corrlinks.blob.core.windows.net/videofaq
</code>```

Note. Browsers handle the link above just fine.

答:
python treats backslash(\) as an escape character.

using r'string' goes handy many times.

r just means raw string. This is useful when we want to have a string that contains backslash and don’t want it to be treated as an escape character.
In this case

```<code>from urllib.parse import urljoin
r = urljoin(r"https://corrlinks.blob.core.windows.net", "videofaq")
print(r)
# returns https://corrlinks.blob.core.windows.net/videofaq
</code>```

This should do the work.

Title: URL join of two URIs

Body:
I am trying to join these two URIs

from urllib.parse import urljoin
# baskslash is not a mistake
r = urljoin(r"https:/\\corrlinks.blob.core.windows.net", r"videofaq")
print(r)

I am getting

https:///videofaq

How can I get

https:/\\corrlinks.blob.core.windows.net/videofaq

This one would be Ok too:

https://corrlinks.blob.core.windows.net/videofaq

Note. Browsers handle the link above just fine.

Body:
python treats backslash(\) as an escape character.

using r'string' goes handy many times.

r just means raw string. This is useful when we want to have a string that contains backslash and don’t want it to be treated as an escape character.
In this case

from urllib.parse import urljoin
r = urljoin(r"https://corrlinks.blob.core.windows.net", "videofaq")
print(r)
# returns https://corrlinks.blob.core.windows.net/videofaq

This should do the work.


问:
Append text to product title if product has product-tag on cart in WooCommerce
I'm trying to append text to WooCommerce product title in the cart if products has a specific tag.

This is what i have. I mis the conditional code.

add_filter( 'woocommerce_cart_item_name', 'add_udstilling_below_cart_item_name', 10, 3);
function add_udstilling_below_cart_item_name( $item_name, $cart_item, $cart_item_key ) {
    echo $item_name . ' (test)';
}
```

<p>I tried something like this:</p>

<pre class="lang-php prettyprint-override"><code>if ( has_term( 'udstillingsmodel', 'product_tag' ) ) {

}
</code>```

But i need help getting it to work with products in cart.

答:
function add_udstilling_below_cart_item_name( $item_name, $cart_item, $cart_item_key ) {
    $product_id = $cart_item['product_id'];

    /* Uncomment for debug purposes
    $terms = wp_get_post_terms( $product_id, 'product_tag' );
    echo '```', print_r($terms, 1), '```';
    */

    if ( has_term( 'udstillingsmodel', 'product_tag', $product_id ) ) {
        $item_name = $item_name . ' (test)';
    }

    return $item_name;
}
add_filter( 'woocommerce_cart_item_name', 'add_udstilling_below_cart_item_name', 10, 3 );
```

Body:
I'm trying to append text to WooCommerce product title in the cart if products has a specific tag.

This is what i have. I mis the conditional code.

add_filter( 'woocommerce_cart_item_name', 'add_udstilling_below_cart_item_name', 10, 3);
function add_udstilling_below_cart_item_name( $item_name, $cart_item, $cart_item_key ) {
    echo $item_name . ' (test)';
}

I tried something like this:

if ( has_term( 'udstillingsmodel', 'product_tag' ) ) {

}

But i need help getting it to work with products in cart.

Body:
function add_udstilling_below_cart_item_name( $item_name, $cart_item, $cart_item_key ) {
    $product_id = $cart_item['product_id'];

    /* Uncomment for debug purposes
    $terms = wp_get_post_terms( $product_id, 'product_tag' );
    echo '<pre>', print_r($terms, 1), '</pre>';
    */

    if ( has_term( 'udstillingsmodel', 'product_tag', $product_id ) ) {
        $item_name = $item_name . ' (test)';
    }

    return $item_name;
}
add_filter( 'woocommerce_cart_item_name', 'add_udstilling_below_cart_item_name', 10, 3 );


问:
How to get correct day number in my country?
I'm using date('j') function in calendar. The problem is that it returns not correct day. For example in my country today is day 17 and this function return day 16. How to fix this?

答: Tell your system which timezone you're in by setting the timezone.</p>


问:
How to parse a complicated nested JSON string in C#?
I have an ugly JSON string that is getting returned from an API that looks like this (this is the result of Console.Write on the string):

```<code>{"d":"\"\\\"\\\\\\\"[{\\\\\\\\\\\\\\\"foo\\\\\\\\\\\\\\\":15,\\\\\\\\\\\\\\\"bar\\\\\\\\\\\\\\\":null}]\\\\\\\"\\\"\\n\""}
</code>```

I am trying to parse this into a C# object in the simplest way possible, so I can access properties like foo and bar. But I am having a difficult time doing this.

I have tried parsing it a number of ways, including:

```<code>// code to get the response string
client.Headers.Add(HttpRequestHeader.ContentType, "application/json");
var serializedData = "{data: 'data'}";
var responseString = client.UploadString(url, "POST", serializedData);

// parse the response string
dynamic obj = Newtonsoft.Json.JsonConvert.DeserializeObject(jsonString);
</code>```

This allows me to access the value of d, which is the actual string I need to parse. I then tried to parse that separately using JArray.Parse(obj["d"]), but I get an error saying that obj["d"] is not an array.

Unfortunately, I have no access to the API itself so can't modify how it's serializing the data it's returning.

Any suggestions?

答:
You can replace all New Line, Backslash, Double quotes to format the JSON

```<code>var formattedJson =  jsonString.Replace(@"\n", string.Empty)
                               .Replace(@"\", string.Empty)
                               .Replace("\"\"", string.Empty);
Console.WriteLine(formattedJson);
</code>```

OUTPUT

```<code>{
    "d": [
        {
            "foo": 15,
            "bar": null
        }
    ]
}
</code>```

Convert to JArray.

```<code>var jArray = JArray.Parse(JObject.Parse(formattedJson)["d"].ToString());
Console.WriteLine($"{jArray[0]["foo"]} {jArray[0]["bar"]}");
</code>```

OUTPUT

```<code>15
</code>```

Body:
I have an ugly JSON string that is getting returned from an API that looks like this (this is the result of Console.Write on the string):

{"d":"\"\\\"\\\\\\\"[{\\\\\\\\\\\\\\\"foo\\\\\\\\\\\\\\\":15,\\\\\\\\\\\\\\\"bar\\\\\\\\\\\\\\\":null}]\\\\\\\"\\\"\\n\""}

I am trying to parse this into a C# object in the simplest way possible, so I can access properties like foo and bar. But I am having a difficult time doing this.

I have tried parsing it a number of ways, including:

// code to get the response string
client.Headers.Add(HttpRequestHeader.ContentType, "application/json");
var serializedData = "{data: 'data'}";
var responseString = client.UploadString(url, "POST", serializedData);

// parse the response string
dynamic obj = Newtonsoft.Json.JsonConvert.DeserializeObject(jsonString);

This allows me to access the value of d, which is the actual string I need to parse. I then tried to parse that separately using JArray.Parse(obj["d"]), but I get an error saying that obj["d"] is not an array.

Unfortunately, I have no access to the API itself so can't modify how it's serializing the data it's returning.

Any suggestions?

Body:
You can replace all New Line, Backslash, Double quotes to format the JSON

var formattedJson =  jsonString.Replace(@"\n", string.Empty)
                               .Replace(@"\", string.Empty)
                               .Replace("\"\"", string.Empty);
Console.WriteLine(formattedJson);

OUTPUT

{
    "d": [
        {
            "foo": 15,
            "bar": null
        }
    ]
}

Convert to JArray.

var jArray = JArray.Parse(JObject.Parse(formattedJson)["d"].ToString());
Console.WriteLine($"{jArray[0]["foo"]} {jArray[0]["bar"]}");

OUTPUT

15


问:
Symfony2/Monolog: Log Level - only show app.INFO?
I am using Symfony2 and monolog to write in specific logs in a defined logfile (mylogfile.log):

```<code>#config_dev.yml
monolog:
    handlers:
        main:
           type:  stream
           path:  %kernel.logs_dir%/%kernel.environment%.log
           level: debug
       file:
           type:   stream
           path:   %kernel.logs_dir%/mylogfile.log
           level:  info
</code>```

I am accessing the logfile in my controller via:

```<code>    $logger = $this->get('logger'); // Log
    $logger->info('somelogcontent');
</code>```

Now my issue is that my log file contains the whole info level, meaning it gives me all  app.INFO logs (which is what I want) and request.INFO (which I don't really need):

```<code>[2012-04-04 11:13:17] request.INFO: Matched route ... blablabla
[2012-04-04 11:13:17] app.INFO: somelogcontent
...
</code>```

Is there any way not to log the Request.INFO?

Mike

答:
Add in your config\packages\monolog.yaml file the "app" spécific channel

```<code>monolog:
    handlers:
        info:
            type:  rotating_file
            path:  '%kernel.logs_dir%/info_%kernel.environment%_info.log'
            level: info
            max_files: 10
            channels: app
</code>```

I use symfony 4 (or 5)

Body:
I am using Symfony2 and monolog to write in specific logs in a defined logfile (mylogfile.log):

#config_dev.yml
monolog:
    handlers:
        main:
           type:  stream
           path:  %kernel.logs_dir%/%kernel.environment%.log
           level: debug
       file:
           type:   stream
           path:   %kernel.logs_dir%/mylogfile.log
           level:  info

I am accessing the logfile in my controller via:

    $logger = $this->get('logger'); // Log
    $logger->info('somelogcontent');

Now my issue is that my log file contains the whole info level, meaning it gives me all  app.INFO logs (which is what I want) and request.INFO (which I don't really need):

[2012-04-04 11:13:17] request.INFO: Matched route ... blablabla
[2012-04-04 11:13:17] app.INFO: somelogcontent
...

Is there any way not to log the Request.INFO?

Mike

Body:
Add in your config\packages\monolog.yaml file the "app" spécific channel

monolog:
    handlers:
        info:
            type:  rotating_file
            path:  '%kernel.logs_dir%/info_%kernel.environment%_info.log'
            level: info
            max_files: 10
            channels: app

I use symfony 4 (or 5)


答:
Using reduce to build object and getting Object.values will simplify.

const update = data => {
  return Object.values(
    data.reduce((acc, curr) => {
      const dt = curr.created_at;
      acc[dt] =
        dt in acc
          ? { dt, arr: [...acc[dt].arr, { ...curr }] }
          : { dt, arr: [{ ...curr }] };
      return acc;
    }, {})
  );
};

let messages = [
  { text: "A", status: "r", created_at: "2020-02-06" },
  { text: "B", status: "s", created_at: "2020-02-06" },
  { text: "C", status: "r", created_at: "2020-02-06" },
  { text: "D", status: "s", created_at: "2020-02-07" },
  { text: "E", status: "s", created_at: "2020-02-07" },
  { text: "F", status: "r", created_at: "2020-02-09" },
  { text: "G", status: "s", created_at: "2020-02-09" },
  { text: "H", status: "s", created_at: "2020-02-10" }
];

console.log(update(messages));```

Title: Trying to group an array of objects under same keys resulting in a new array of objects

Body:
I have an array of messages consisting of objects, where each object represents a single message and the created_at key representing the date of the message. I am receiving this data from the API. Here is the structure that I get:

let messages = [
  {text: "A", status: 'r', created_at: "2020-02-06"},
  {text: "B", status: 's', created_at: "2020-02-06"},
  {text: "C", status: 'r', created_at: "2020-02-06"},
  {text: "D", status: 's', created_at: "2020-02-07"},
  {text: "E", status: 's', created_at: "2020-02-07"},
  {text: "F", status: 'r', created_at: "2020-02-09"},
  {text: "G", status: 's', created_at: "2020-02-09"},
  {text: "H", status: 's', created_at: "2020-02-10"}
]

I am using vuejs to render these messages in a chat application (similar to WhatsApp), where I want to display the date on top and the messages under that date in chronological order, just like WhatsApp. I am receiving the messages from the API in chronological order like the messages array I pasted above.
I would like to have the following output, so that I can use v-for directive in vuejs to loop through the messages and render them according to the date they were created:

  output:
    [
      {
        dt: "2020-02-06",
        arr: [
            {text: "A", status: 'r', created_at: "2020-02-06"},
            {text: "B", status: 's', created_at: "2020-02-06"},
            {text: "C", status: 'r', created_at: "2020-02-06"},
        ]
      },
      {
        dt: "2020-02-07",
        arr: [
            {text: "D", status: 's', created_at: "2020-02-06"},
            {text: "E", status: 's', created_at: "2020-02-06"},
        ]
      },
      {
        dt: "2020-02-09",
        arr: [
            {text: "F", status: 'r', created_at: "2020-02-09"},
            {text: "G", status: 's', created_at: "2020-02-09"},
        ]
      },
        {
        dt: "2020-02-10",
        arr: [
           {text: "H", status: 's', created_at: "2020-02-10"}
        ]
      },
    ]

Is there a library in lodash that can achieve this directly?

What I have tried so far:

I was able to group the dates in an array without the dates repeating, like so:

let dates = messages.map((item => {
    return item.created_at
}))
let uniq = [...new Set(dates)];
console.log(uniq)

...which gives the following output:

uniq = ["2020-02-06", "2020-02-07", "2020-02-09", "2020-02-10"]

I am not able to move ahead of this.

Thanks in advance!


问:
How to order child records by parent column using flask-sqlalchemy?
```<code>class Parent(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    role_id = db.Column(db.Integer, db.ForeignKey('role.id')
    name = db.Column(db.String())
    children = db.relationship('Child', backref='parent')

class Child(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    parent_id = db.Column(db.Integer, db.ForeignKey('parent.id')
    name = db.Column(db.String())
</code>```

I am trying to order child records by parent role_id:

```<code>child_recs = Child.query.order_by(?).all()
</code>```

I tried by placing order_by attribute in db.relationship(), but it's not working.

```<code>children = db.relationship('Child', backref='parent', order_by='Parent.role_id')
</code>```

答:
I got the required results with the help of sorted():

```<code>child_recs = Child.query.all()
ordered_child_recs = sorted(child_recs, key=lambda rec: rec.parent.role_id)
</code>```

Body:
class Parent(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    role_id = db.Column(db.Integer, db.ForeignKey('role.id')
    name = db.Column(db.String())
    children = db.relationship('Child', backref='parent')

class Child(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    parent_id = db.Column(db.Integer, db.ForeignKey('parent.id')
    name = db.Column(db.String())

I am trying to order child records by parent role_id:

child_recs = Child.query.order_by(?).all()

I tried by placing order_by attribute in db.relationship(), but it's not working.

children = db.relationship('Child', backref='parent', order_by='Parent.role_id')

Body:
I got the required results with the help of sorted():

child_recs = Child.query.all()
ordered_child_recs = sorted(child_recs, key=lambda rec: rec.parent.role_id)


问:
Blocking tab key in a web page
I have a web app in which the users rapidly respond to neuropsychological stimuli using the Q and P keys (this is not changeable). Problem is, sometimes users mistakenly move their finger and then press the tab key, in which case the focus is shifted from the page body (which I understand is the default, using activeElement) to somewhere else in the browser window (tabs, address bar, ...).

I have seen this question and indeed have tried to use both event.preventDefault() and event.stopPropagation() upon catching the keydown event, but this doesn't help. If, for example, I add an alert - it alerts and then still goes on to change the focus.

Does anyone has an idea on how to prevent this, except customizing the browser to completely block thie tab key?

some code reference:

```<code>var ansFlag = false;

document.addEventListener("keydown", keydown);

function showTarget(){
    draw(stimInfo());
    run = setTimeout(advance,maxResponseTime);
    ansFlag = true;
    startTime = performance.now();
}

function keydown(e) {
    e = e || window.event;
    keyCode = e.keyCode;
    if (ansFlag){
        endTime = performance.now();
        if ((keyCode == Q_KEY) || (keyCode == P_KEY)) {
            response_given = true;
            clearTimeout(run);
            advance();
        }
        else{
            return false;
        }
    }
    else{
        if(e.key == "Tab"){
            e.preventDefault();
            e.stopPropagation();
            alert("tab!!!");
            if(e.defaultPrevented){
                console.log("saved the day!");
                return;
            }
        }
        else{
            return false;
        }
    }
}
</code>```

答:
I've found a trick for this that might help.

When you press the tab key, the browser focuses only on your input.
You can hide this input

Of course I didn't see any code from you, but maybe this example will help you

const playground = document.querySelector('.playground');
const focusInput1 = playground.querySelector('#focus1');

window.addEventListener('keydown' , function (e) {

    if(e.keyCode === 9){
        focusInput1.focus();
    }

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>       .playground{
            background-color: blue;
            height: 500px;
            width: 100%;
        }
        .other{
            background-color: red;
            height: 500px;
            width: 100%;
        }</code>```

        <input id="focus1">
        <input id="focus2">

```

Title: Blocking tab key in a web page

Body:
I have a web app in which the users rapidly respond to neuropsychological stimuli using the Q and P keys (this is not changeable). Problem is, sometimes users mistakenly move their finger and then press the tab key, in which case the focus is shifted from the page body (which I understand is the default, using activeElement) to somewhere else in the browser window (tabs, address bar, ...).

I have seen this question and indeed have tried to use both event.preventDefault() and event.stopPropagation() upon catching the keydown event, but this doesn't help. If, for example, I add an alert - it alerts and then still goes on to change the focus.

Does anyone has an idea on how to prevent this, except customizing the browser to completely block thie tab key?

some code reference:

var ansFlag = false;

document.addEventListener("keydown", keydown);

function showTarget(){
    draw(stimInfo());
    run = setTimeout(advance,maxResponseTime);
    ansFlag = true;
    startTime = performance.now();
}

function keydown(e) {
    e = e || window.event;
    keyCode = e.keyCode;
    if (ansFlag){
        endTime = performance.now();
        if ((keyCode == Q_KEY) || (keyCode == P_KEY)) {
            response_given = true;
            clearTimeout(run);
            advance();
        }
        else{
            return false;
        }
    }
    else{
        if(e.key == "Tab"){
            e.preventDefault();
            e.stopPropagation();
            alert("tab!!!");
            if(e.defaultPrevented){
                console.log("saved the day!");
                return;
            }
        }
        else{
            return false;
        }
    }
}

Body:
I've found a trick for this that might help.

When you press the tab key, the browser focuses only on your input.
You can hide this input

Of course I didn't see any code from you, but maybe this example will help you

const playground = document.querySelector('.playground');
const focusInput1 = playground.querySelector('#focus1');

window.addEventListener('keydown' , function (e) {

    if(e.keyCode === 9){
        focusInput1.focus();
    }

});

       .playground{
            background-color: blue;
            height: 500px;
            width: 100%;
        }
        .other{
            background-color: red;
            height: 500px;
            width: 100%;
        }

    <div class="playground">
        <input id="focus1">
        <input id="focus2">
    </div>

    <div class="other">

    </div>