问:
More rows after Left Join in MySQL
I've two tables, table1 contains 22780 rows. Now I left join table1 with table2 (which doesn't contain any duplicates) and I get 23588 rows.

```<code>SELECT   * FROM Table1
left join Tabelle6 ON CAST(Table1.Customer AS Int) = table2.Customer
</code>```

Why do I get more rows now? I only need every row from table1 once.

Edit: found my issue, table 2 does contain duplicates. But is there any way to join every row only once and ignore any further matches?

答:
As the comment suggests, the easiest way to handle this would probably be to do SELECT DISTINCT to remove duplicates from your result set:

```<code>SELECT DISTINCT
    t1.col1,
    t1.col2,
    t1.Customer,
    ...
FROM Table1 t1
LEFT JOIN Table2 t2
    ON CAST(t1.Customer AS Int) = t2.Customer
</code>```

But there is another option here.  We could also join to a subquery which removes duplicate customers.  This would ensure that no record from the first table gets duplicated from matching to more than one record in the second table.

```<code>SELECT *
FROM Table1 t1
LEFT JOIN
(
    SELECT DISTINCT Customer
    FROM Table2
) t2
    ON CAST(t1.Customer AS Int) = t2.Customer
</code>```

Title: More rows after Left Join in MySQL

Body:
I've two tables, table1 contains 22780 rows. Now I left join table1 with table2 (which doesn't contain any duplicates) and I get 23588 rows.

SELECT   * FROM Table1
left join Tabelle6 ON CAST(Table1.Customer AS Int) = table2.Customer

Why do I get more rows now? I only need every row from table1 once.

Edit: found my issue, table 2 does contain duplicates. But is there any way to join every row only once and ignore any further matches?

Body:
As the comment suggests, the easiest way to handle this would probably be to do SELECT DISTINCT to remove duplicates from your result set:

SELECT DISTINCT
    t1.col1,
    t1.col2,
    t1.Customer,
    ...
FROM Table1 t1
LEFT JOIN Table2 t2
    ON CAST(t1.Customer AS Int) = t2.Customer

But there is another option here.  We could also join to a subquery which removes duplicate customers.  This would ensure that no record from the first table gets duplicated from matching to more than one record in the second table.

SELECT *
FROM Table1 t1
LEFT JOIN
(
    SELECT DISTINCT Customer
    FROM Table2
) t2
    ON CAST(t1.Customer AS Int) = t2.Customer


来源: stackexchange

问:
multiple div's shown with select option
Im still kind of new to scripts, but i know what im trying to do is not impossible. im trying to use a select option to show div's, I have it currently so it shows 1 div at a time currently but I cannot get it to show 2 separate divs at the same time. so for example im trying to select option 1, and to unhide the same selected options that were selected.
I tried what was suggested in "Can an Option in a Select tag carry multiple values?"

but none of it worked

```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="header">
<select name="dropdown" id='target'>
<option value="temp1" value2="form1">option1</option>
<option value="temp2" value2="form2">option2</option>
</select>
</div>

<div class="temps">
<div id="temp1" class="initial"><?php include "temp1.php"; ?></div>
<div id="temp2" class="initial"><?php include "temp2.php"; ?></div>
</div>

<div class="forms">
<div id="form1" class="initial"><?php include "form1.php"; ?></div>
<div id="form2" class="initial"><?php include "form2.php"; ?></div>
</div></code>```

答:
your selector was wrong its document.getElementById() not a document.getElementByValue .And you are using querySelectorAll() its matching all the .vis class element ,so you need to iterate with forEach  .And change the if condition with vis.length>0

document.getElementById('target').addEventListener('change', function() {

  var vis = document.querySelectorAll('.vis'),
    target = document.getElementById(this.value);
  if (vis.length > 0) {
    vis.forEach(function(a) {
      a.className = 'initial';
      console.log(a.outerHTML)
    })
  }
  if (target !== null) {
    target.className = 'vis';
  }
  console.log(target.outerHTML)
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="header">
  <select name="dropdown" id='target'>
<option value="temp1" value2="form1">option1</option>
<option value="temp2" value2="form2">option2</option>
</select>
</div>

<div class="temps">
  <div id="temp1" class="initial">
    <?php include "temp1.php"; ?>
  </div>
  <div id="temp2" class="initial">
    <?php include "temp2.php"; ?>
  </div>
</div>

<div class="forms">
  <div id="form1" class="initial">
    <?php include "form1.php"; ?>
  </div>
  <div id="form2" class="initial">
    <?php include "form2.php"; ?>
  </div>
</div></code>```

ContentLicense: CC BY-SA 3.0

Title: multiple div's shown with select option

Body:
Im still kind of new to scripts, but i know what im trying to do is not impossible. im trying to use a select option to show div's, I have it currently so it shows 1 div at a time currently but I cannot get it to show 2 separate divs at the same time. so for example im trying to select option 1, and to unhide the same selected options that were selected.
I tried what was suggested in "Can an Option in a Select tag carry multiple values?"

but none of it worked

<select name="dropdown" id='target'>
<option value="temp1" value2="form1">option1</option>
<option value="temp2" value2="form2">option2</option>
</select>

<?php include "temp1.php"; ?>

<?php include "temp2.php"; ?>

<?php include "form1.php"; ?>

<?php include "form2.php"; ?>

Body:
your selector was wrong its document.getElementById() not a document.getElementByValue .And you are using querySelectorAll() its matching all the .vis class element ,so you need to iterate with forEach  .And change the if condition with vis.length>0

document.getElementById('target').addEventListener('change', function() {

  var vis = document.querySelectorAll('.vis'),
    target = document.getElementById(this.value);
  if (vis.length > 0) {
    vis.forEach(function(a) {
      a.className = 'initial';
      console.log(a.outerHTML)
    })
  }
  if (target !== null) {
    target.className = 'vis';
  }
  console.log(target.outerHTML)
});

<div class="header">
  <select name="dropdown" id='target'>
<option value="temp1" value2="form1">option1</option>
<option value="temp2" value2="form2">option2</option>
</select>
</div>

<div class="temps">
  <div id="temp1" class="initial">
    <?php include "temp1.php"; ?>
  </div>
  <div id="temp2" class="initial">
    <?php include "temp2.php"; ?>
  </div>
</div>

<div class="forms">
  <div id="form1" class="initial">
    <?php include "form1.php"; ?>
  </div>
  <div id="form2" class="initial">
    <?php include "form2.php"; ?>
  </div>
</div>


问:
dimesion percentage over over time by line chart in Tableau
In a dimension item, I have 3 categories (say: A,B,C) and would like to plot the measure of A as percentage of total (A,B,C combined) over time. And I tried something very simple SUM(IF [category] = "A" THEN [Some Amt] ELSE 0 END) / TOTAL(SUM([Some Amt])), but it always return 0. (I had put the time dimension in the column field) Appreciate your inputs.

答:
I am using in my data select only one customer name my calculation filed result 1.

SUM(IF [Customer Name] = "Aaron Hawkins" THEN [Sales] ELSE 0 END) / SUM([Sales])

percentage of total sale particular customer.


问:
why static method can not be called inside instance method?
The error says that global name "get_words" is not defined. But I did define a static method named get_words. What should I do if I want to call get_words function inside train()</p>

```<code>class classfier(object):
    def __init__(self):
        self.fc = {}
        self.cc = {}

    @staticmethod
    def get_words(item):
        words = re.split(r"\W+",item.strip())
        words =  [element.lower() for element in words if len(element)>2 and len(element)<20]
        return set(words)

    def train(self,item,cat):
        features = get_words(item)
        for f in features:
            self.incf(f,cat)
        self.incc(cat)
</code>```

答:
in C++

```<code>class Something
{
private:
    static int s_value;
public:
    static int getValue() { return s_value; } // static member function
};

int Something::s_value = 1; // initializer

int main()
{
    std::cout << Something::getValue() << '\n';
}
</code>```

In Java -

```<code>class Student9{
 int rollno;
 String name;
 static String college = "ITS";

 static void change(){
 college = "BBDIT";
 }

 Student9(int r, String n){
 rollno = r;
 name = n;
 }

 void display (){System.out.println(rollno+" "+name+" "+college);}

public static void main(String args[]){
Student9.change();

Student9 s1 = new Student9 (111,"Indian");
Student9 s2 = new Student9 (222,"American");
Student9 s3 = new Student9 (333,"China");

s1.display();
s2.display();
s3.display();
}
}
</code>```

And finally in Python -

```<code>class MyClass(object):
    @staticmethod
    def the_static_method(x):
        print x

MyClass.the_static_method(2) # outputs 2
</code>```

See everywhere we use the class name to call the static method! and here is something for you from the documentation

Return a static method for function.

A static method does not receive an implicit first argument. To
  declare a static method, use this idiom:

class C(object):
      @staticmethod
      def f(arg1, arg2, ...):
          ... The @staticmethod form is a function decorator – see the description of function definitions in Function definitions for
  details.

It can be called either on the class (such as C.f()) or on an instance
  (such as C().f()). The instance is ignored except for its class.

Static methods in Python are similar to those found in Java or C++.
  Also see classmethod() for a variant that is useful for creating
  alternate class constructors.

For more information on static methods, consult the documentation on
  the standard type hierarchy in The standard type hierarchy.

New in version 2.2.

Changed in version 2.4: Function decorator syntax added.

As mentioned in the comment, this is what you should be doing when you are calling a static method from outside a class instance method. However, if you want to call a static method from inside a class's instance method then using self is probably the best idea and let the interpreter resolve the reference for you. Sorry for the little confusion. I tried to provide the comparison among three languages and tried to explain things but kind of missed the main point a bit.

Body:
The error says that global name "get_words" is not defined. But I did define a static method named get_words. What should I do if I want to call get_words function inside train()

class classfier(object):
    def __init__(self):
        self.fc = {}
        self.cc = {}

    @staticmethod
    def get_words(item):
        words = re.split(r"\W+",item.strip())
        words =  [element.lower() for element in words if len(element)>2 and len(element)<20]
        return set(words)

    def train(self,item,cat):
        features = get_words(item)
        for f in features:
            self.incf(f,cat)
        self.incc(cat)

Body:
in C++

class Something
{
private:
    static int s_value;
public:
    static int getValue() { return s_value; } // static member function
};

int Something::s_value = 1; // initializer

int main()
{
    std::cout << Something::getValue() << '\n';
}

In Java -

class Student9{
 int rollno;
 String name;
 static String college = "ITS";

 static void change(){
 college = "BBDIT";
 }

 Student9(int r, String n){
 rollno = r;
 name = n;
 }

 void display (){System.out.println(rollno+" "+name+" "+college);}

public static void main(String args[]){
Student9.change();

Student9 s1 = new Student9 (111,"Indian");
Student9 s2 = new Student9 (222,"American");
Student9 s3 = new Student9 (333,"China");

s1.display();
s2.display();
s3.display();
}
}

And finally in Python -

class MyClass(object):
    @staticmethod
    def the_static_method(x):
        print x

MyClass.the_static_method(2) # outputs 2

See everywhere we use the class name to call the static method! and here is something for you from the documentation

Return a static method for function.

A static method does not receive an implicit first argument. To
  declare a static method, use this idiom:

class C(object):
      @staticmethod
      def f(arg1, arg2, ...):
          ... The @staticmethod form is a function decorator – see the description of function definitions in Function definitions for
  details.

It can be called either on the class (such as C.f()) or on an instance
  (such as C().f()). The instance is ignored except for its class.

Static methods in Python are similar to those found in Java or C++.
  Also see classmethod() for a variant that is useful for creating
  alternate class constructors.

For more information on static methods, consult the documentation on
  the standard type hierarchy in The standard type hierarchy.

New in version 2.2.

Changed in version 2.4: Function decorator syntax added.

As mentioned in the comment, this is what you should be doing when you are calling a static method from outside a class instance method. However, if you want to call a static method from inside a class's instance method then using self is probably the best idea and let the interpreter resolve the reference for you. Sorry for the little confusion. I tried to provide the comparison among three languages and tried to explain things but kind of missed the main point a bit.


问:
Mysql container can not mount data to a nfs folder
By swarm mode, containers may deploy in any joined  nodes. I created a shared nfs folder as mysql data folder on  host1.

```<code>mkdir -p /nfs/data-volume
</code>```

In another host2, it mounts to this shared folder. And added necessary permission. I tried this nfs share folder by reading and writing some text file in it. It worked very well. (There was no permission error)
After these nfs configuration , I defined my container volume like this;

```<code>mysqldb-read:
    image: demo/db-slave
    ports:
     - "3308:3306"
    volumes:
     - /nfs/data-volume:/var/lib/mysql
</code>```

The result is:
If mysql container run on host1, works very good.
If mysql container run on host2, it doesn't startup. But the container doesn't exit, the thread stay there and looks like wait something.
By running check log command:

```<code>docker logs -f mymysql
</code>```

It shows logs like this:

```<code>   2017-06-07T02:40:13.627195Z 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp server option (see documentation for more details).
2017-06-07T02:40:13.632313Z 0 [Note] mysqld (mysqld 5.7.18-log) starting as process 52 ...
2017-06-07T02:40:13.648010Z 0 [Note] InnoDB: PUNCH HOLE support available
2017-06-07T02:40:13.648054Z 0 [Note] InnoDB: Mutexes and rw_locks use GCC atomic builtins
2017-06-07T02:40:13.648059Z 0 [Note] InnoDB: Uses event mutexes
2017-06-07T02:40:13.648062Z 0 [Note] InnoDB: GCC builtin __atomic_thread_fence() is used for memory barrier
2017-06-07T02:40:13.648066Z 0 [Note] InnoDB: Compressed tables use zlib 1.2.3
2017-06-07T02:40:13.648069Z 0 [Note] InnoDB: Using Linux native AIO
2017-06-07T02:40:13.648326Z 0 [Note] InnoDB: Number of pools: 1
2017-06-07T02:40:13.648770Z 0 [Note] InnoDB: Using CPU crc32 instructions
2017-06-07T02:40:13.651011Z 0 [Note] InnoDB: Initializing buffer pool, total size = 128M, instances = 1, chunk size = 128M
2017-06-07T02:40:13.760444Z 0 [Note] InnoDB: Completed initialization of buffer pool
2017-06-07T02:40:13.829981Z 0 [Note] InnoDB: If the mysqld execution user is authorized, page cleaner thread priority can be changed. See the man page of setpriority().
</code>```

Nothing more on this log, it stops on this line.
I tried to login into container, and input command

```<code>mysqld -uroot -proot
</code>```

The showing log is totally same.

I feel this is caused by nfs. But I googled and found almost all materials suggested to use nfs to share data. Is there anyone who successfully make this work? Or any suggestion to me?

Thanks

答:
Q1: Is there anyone who successfully make this work ?

My experience is... No. I tried NFS, MySQL and Docker Swarm (v1.12) some months ago and I also did fail with that.

They are pretty clear with that indeed, from MySQL documentation:

Using NFS with MySQL

Caution is advised when considering using NFS with MySQL. Potential issues, which vary by operating system and NFS version, include:

MySQL data and log files placed on NFS volumes becoming locked and unavailable for use...

Data inconsistencies...

Maximum file size limitations

I also experienced file locks, slow queries and slow writes...

Q2: Or any suggestion to me?

One of docker-swarm tricky part is indeed with the data, especially with databases. You don't know on witch host the mysql container will be run. I've used two alternatives so overcome this:

1. Swarm mode service creation --constraint option

This option will instruct docker to deploy your MySQL container always on the same host, for instance:

```<code>mysqldb-read:
  image: demo/db-slave
  ports:
    - "3308:3306"
  volumes:
    - /nfs/data-volume:/var/lib/mysql
  deploy:
    placement:
      constraints: [node.hostname == host1]
</code>```

If docker swarm service mysqldb-read restarts, this will always be on host1 node.

2. Docker volumes

Another option is to dynamically attach a shared docker volume to the MySQL service before startup. The documentation states:

If you want your data to persist, use a named volume and a volume driver that is multi-host aware, so that the data is accessible from any node...

There are some docker volume plugins that allow you to do that. I personally tried rancher's convoy in an AWS environment, but I also have other issues with volume deletion, sync, etc...

You can also have a look at this popular SO thread about swarm and docker volumes.

PS: About NFS

I'm not saying that you should give up NFS for other docker services, I still use it for read-only configuration files (Apache Tomcat and Nginx configuration, etc...), but for MySQL it's a no go.

Hope my experience will help!

Body:
By swarm mode, containers may deploy in any joined  nodes. I created a shared nfs folder as mysql data folder on  host1.

mkdir -p /nfs/data-volume

In another host2, it mounts to this shared folder. And added necessary permission. I tried this nfs share folder by reading and writing some text file in it. It worked very well. (There was no permission error)
After these nfs configuration , I defined my container volume like this;

mysqldb-read:
    image: demo/db-slave
    ports:
     - "3308:3306"
    volumes:
     - /nfs/data-volume:/var/lib/mysql

The result is:
If mysql container run on host1, works very good.
If mysql container run on host2, it doesn't startup. But the container doesn't exit, the thread stay there and looks like wait something.
By running check log command:

docker logs -f mymysql

It shows logs like this:

   2017-06-07T02:40:13.627195Z 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp server option (see documentation for more details).
2017-06-07T02:40:13.632313Z 0 [Note] mysqld (mysqld 5.7.18-log) starting as process 52 ...
2017-06-07T02:40:13.648010Z 0 [Note] InnoDB: PUNCH HOLE support available
2017-06-07T02:40:13.648054Z 0 [Note] InnoDB: Mutexes and rw_locks use GCC atomic builtins
2017-06-07T02:40:13.648059Z 0 [Note] InnoDB: Uses event mutexes
2017-06-07T02:40:13.648062Z 0 [Note] InnoDB: GCC builtin __atomic_thread_fence() is used for memory barrier
2017-06-07T02:40:13.648066Z 0 [Note] InnoDB: Compressed tables use zlib 1.2.3
2017-06-07T02:40:13.648069Z 0 [Note] InnoDB: Using Linux native AIO
2017-06-07T02:40:13.648326Z 0 [Note] InnoDB: Number of pools: 1
2017-06-07T02:40:13.648770Z 0 [Note] InnoDB: Using CPU crc32 instructions
2017-06-07T02:40:13.651011Z 0 [Note] InnoDB: Initializing buffer pool, total size = 128M, instances = 1, chunk size = 128M
2017-06-07T02:40:13.760444Z 0 [Note] InnoDB: Completed initialization of buffer pool
2017-06-07T02:40:13.829981Z 0 [Note] InnoDB: If the mysqld execution user is authorized, page cleaner thread priority can be changed. See the man page of setpriority().

Nothing more on this log, it stops on this line.
I tried to login into container, and input command

mysqld -uroot -proot

The showing log is totally same.

I feel this is caused by nfs. But I googled and found almost all materials suggested to use nfs to share data. Is there anyone who successfully make this work? Or any suggestion to me?

Thanks

Body:
Q1: Is there anyone who successfully make this work ?

My experience is... No. I tried NFS, MySQL and Docker Swarm (v1.12) some months ago and I also did fail with that.

They are pretty clear with that indeed, from MySQL documentation:

Using NFS with MySQL

Caution is advised when considering using NFS with MySQL. Potential issues, which vary by operating system and NFS version, include:

MySQL data and log files placed on NFS volumes becoming locked and unavailable for use...

Data inconsistencies...

Maximum file size limitations

I also experienced file locks, slow queries and slow writes...

Q2: Or any suggestion to me?

One of docker-swarm tricky part is indeed with the data, especially with databases. You don't know on witch host the mysql container will be run. I've used two alternatives so overcome this:

1. Swarm mode service creation --constraint option

This option will instruct docker to deploy your MySQL container always on the same host, for instance:

mysqldb-read:
  image: demo/db-slave
  ports:
    - "3308:3306"
  volumes:
    - /nfs/data-volume:/var/lib/mysql
  deploy:
    placement:
      constraints: [node.hostname == host1]

If docker swarm service mysqldb-read restarts, this will always be on host1 node.

2. Docker volumes

Another option is to dynamically attach a shared docker volume to the MySQL service before startup. The documentation states:

If you want your data to persist, use a named volume and a volume driver that is multi-host aware, so that the data is accessible from any node...

There are some docker volume plugins that allow you to do that. I personally tried rancher's convoy in an AWS environment, but I also have other issues with volume deletion, sync, etc...

You can also have a look at this popular SO thread about swarm and docker volumes.

PS: About NFS

I'm not saying that you should give up NFS for other docker services, I still use it for read-only configuration files (Apache Tomcat and Nginx configuration, etc...), but for MySQL it's a no go.

Hope my experience will help!


问:
C++: Failing to make a hash function for a Vertex object
So I'm trying to make a Graph class as part of another project. The vertices are stored in an adjacency list, which is defined by an unordered_map. I am trying to create a hash function to allow my Vertex class to be stored in this map, but I don't know what I am doing wrong. I get this error:

```<code>no matching function for call to ‘std::hash<Vertex<int> >::hash(int)’
</code>```

Here is my graph.h file

```<code>#ifndef GRAPH_GRAPH_H_
#define GRAPH_GRAPH_H_

#include <vector>
#include <unordered_map>

template <typename T>
class Vertex {
    private:
        T value;
    public:
        Vertex(T value);
        T getValue() const;
        void setValue(T value);

        //Equality check. This also requires an equality check to exist for T. If it does not (e.g. custom class), make sure you impemented one
        bool operator==(const Vertex<T>& v) const{
            return (this->value == v.value);
        }
};

template <typename T>
Vertex<T>::Vertex(T value) {
    this->value = value;
}

template <typename T>
T Vertex<T>::getValue() const{
    return this->value;
}

template <typename T>
void Vertex<T>::setValue(T value) {
    this->value = value;
}

//If you want to hash a vertex, T needs a way of being hashed
namespace std {
    template<typename T> struct hash<Vertex<T>> {
        size_t operator()(Vertex<T> const& v) const {
            return hash(v.getValue());
        }
    };
}

template <typename T>
class Graph {
private:
    //Now I know what you're thinking. Graph theory taught me that a graph needs a set of nodes, and an adjacency list.
    //All you've given us is an adjacency list.
    //Well, since we need to use our nodes as keys, the set of keys is equivalent to the set of nodes. So there.

    unordered_map<Vertex<T>, std::vector<Vertex<T>>> adjacencyList;

public:
    Graph(); //Needs a hash function. For example, if your vertices are storing std::pairs, we need a hash to convert the pair into a key
             //Since I don't know what you will be storing, you should provide a hash function
    ~Graph();
    //Since we are initialising a new object, v must be whatever we are using to initialise our vertices
    void addVertex(T value, std::vector<T> adjacent);
    void removeVertex(T value);
    void printGraph();
};

template <typename T>
Graph<T>::Graph() {
}

template <typename T>
Graph<T>::~Graph() {
}

template <typename T>
void Graph<T>::addVertex(T value, std::vector<T> adjacent) {
    //Check that the value does not already exist
    if (this->adjacencyList.find(Vertex<T>(value)) == this->adjacencyList.end()) {
        Vertex<T> v = Vertex<T>(value);
        std::vector<Vertex<T>> adj;
        for (unsigned int i = 0; i < adjacent.size(); i++) {
            Vertex<T> vAdj = Vertex<T>(adjacent[i]);
            adj.push_back(vAdj);
        }
        this->adjacencyList.insert(make_pair(v, adj));
    }
        //If the values does not exist, place it and the adjacency in there
        //Otherwise, do nothing

}

template <typename T>
void Graph<T>::removeVertex(T value) {
    //Check that the value does not already exist
    //if (this->adjacencyList.find(Vertex<T>(value)) != this->adjacencyList.end()) {
        this->adjacencyList.erase(Vertex<T>(value));
    //}
}

template <typename T>
void Graph<T>::printGraph() {

}
#endif /* GRAPH_GRAPH_H_ */
</code>```

答:
You have an error in

```<code>return hash(v.getValue());
</code>```

std::hash is not a function, it's a struct, so you need to create an object first. For example

```<code>return hash<T>{}(v.getValue());
</code>```

Body:
So I'm trying to make a Graph class as part of another project. The vertices are stored in an adjacency list, which is defined by an unordered_map. I am trying to create a hash function to allow my Vertex class to be stored in this map, but I don't know what I am doing wrong. I get this error:

no matching function for call to ‘std::hash<Vertex<int> >::hash(int)’

Here is my graph.h file

#ifndef GRAPH_GRAPH_H_
#define GRAPH_GRAPH_H_

#include <vector>
#include <unordered_map>

template <typename T>
class Vertex {
    private:
        T value;
    public:
        Vertex(T value);
        T getValue() const;
        void setValue(T value);

        //Equality check. This also requires an equality check to exist for T. If it does not (e.g. custom class), make sure you impemented one
        bool operator==(const Vertex<T>& v) const{
            return (this->value == v.value);
        }
};

template <typename T>
Vertex<T>::Vertex(T value) {
    this->value = value;
}

template <typename T>
T Vertex<T>::getValue() const{
    return this->value;
}

template <typename T>
void Vertex<T>::setValue(T value) {
    this->value = value;
}

//If you want to hash a vertex, T needs a way of being hashed
namespace std {
    template<typename T> struct hash<Vertex<T>> {
        size_t operator()(Vertex<T> const& v) const {
            return hash(v.getValue());
        }
    };
}

template <typename T>
class Graph {
private:
    //Now I know what you're thinking. Graph theory taught me that a graph needs a set of nodes, and an adjacency list.
    //All you've given us is an adjacency list.
    //Well, since we need to use our nodes as keys, the set of keys is equivalent to the set of nodes. So there.

    unordered_map<Vertex<T>, std::vector<Vertex<T>>> adjacencyList;

public:
    Graph(); //Needs a hash function. For example, if your vertices are storing std::pairs, we need a hash to convert the pair into a key
             //Since I don't know what you will be storing, you should provide a hash function
    ~Graph();
    //Since we are initialising a new object, v must be whatever we are using to initialise our vertices
    void addVertex(T value, std::vector<T> adjacent);
    void removeVertex(T value);
    void printGraph();
};

template <typename T>
Graph<T>::Graph() {
}

template <typename T>
Graph<T>::~Graph() {
}

template <typename T>
void Graph<T>::addVertex(T value, std::vector<T> adjacent) {
    //Check that the value does not already exist
    if (this->adjacencyList.find(Vertex<T>(value)) == this->adjacencyList.end()) {
        Vertex<T> v = Vertex<T>(value);
        std::vector<Vertex<T>> adj;
        for (unsigned int i = 0; i < adjacent.size(); i++) {
            Vertex<T> vAdj = Vertex<T>(adjacent[i]);
            adj.push_back(vAdj);
        }
        this->adjacencyList.insert(make_pair(v, adj));
    }
        //If the values does not exist, place it and the adjacency in there
        //Otherwise, do nothing

}

template <typename T>
void Graph<T>::removeVertex(T value) {
    //Check that the value does not already exist
    //if (this->adjacencyList.find(Vertex<T>(value)) != this->adjacencyList.end()) {
        this->adjacencyList.erase(Vertex<T>(value));
    //}
}

template <typename T>
void Graph<T>::printGraph() {

}
#endif /* GRAPH_GRAPH_H_ */

Body:
You have an error in

return hash(v.getValue());

std::hash is not a function, it's a struct, so you need to create an object first. For example

return hash<T>{}(v.getValue());


问:
Delete until whitespace in Emacs
Is there an Emacs function to delete (forward or backwards) until the first whitespace?  For example, I have the following line, and the cursor is marked by the caret:

```<code>someword ?(&)!* morewords
               ^
</code>```

I want to delete the backwards the sequence of non-alphanumeric characters, but not the word someword.  Using backward-delete-word will wipe out the word as well.  The same is with the cursor before the weird characters and kill-word.

答: emacs has the function zap-to-char which will delete everything up to a specific character. So, this won't work for all whitespace but if your specific problem is everything up to a space you can use this function. Give the function a negative argument to zap backwards.

ContentLicense: CC BY-SA 2.5

Title: Delete until whitespace in Emacs

Body:
Is there an Emacs function to delete (forward or backwards) until the first whitespace?  For example, I have the following line, and the cursor is marked by the caret:

someword ?(&)!* morewords
               ^

I want to delete the backwards the sequence of non-alphanumeric characters, but not the word someword.  Using backward-delete-word will wipe out the word as well.  The same is with the cursor before the weird characters and kill-word.


问:
how to scroll a web page using watir
I am trying to scroll a web page to find and click on a content that is lazily loaded when the page is scrolled. I am using following command

```<code>require 'watir-webdriver'

@browser = Watir::new :firefox
@browser.send_keys :space
</code>```

I am using web-driver with firefox and I am on ubuntu but it is not working. In the following ruby code I am trying to scroll the page down until I don't find the element with :id. The element is loading lazily.
I am getting timeout after few seconds, any idea what is wrong with the following code.

```<code>When /^deal (\d+) is loaded$/ do |id|
  (0..5).each do |click|
    @browser.send_keys :space
  end
end
</code>```

What is the best way to scroll a page using watir-driver ?

答:
It works</p>

```<code>evaluate_script("document.getElementsByTagName('body')[0].scrollTop=0;")
</code>```

Title: how to scroll a web page using watir

Body:
I am trying to scroll a web page to find and click on a content that is lazily loaded when the page is scrolled. I am using following command

require 'watir-webdriver'

@browser = Watir::new :firefox
@browser.send_keys :space

I am using web-driver with firefox and I am on ubuntu but it is not working. In the following ruby code I am trying to scroll the page down until I don't find the element with :id. The element is loading lazily.
I am getting timeout after few seconds, any idea what is wrong with the following code.

When /^deal (\d+) is loaded$/ do |id|
  (0..5).each do |click|
    @browser.send_keys :space
  end
end

What is the best way to scroll a page using watir-driver ?

Body:
It works

evaluate_script("document.getElementsByTagName('body')[0].scrollTop=0;")


问:
Direct db connection per http request vs connection pooling- what is the difference
Let's say I am storing data of Person(id, country_id, name). And let's say user just sent the id and country_id and we send back the name.

Now I have one db and 2 webserver and each webserver keeps a connection pool (e.g. c3p0) of 20 connection.

That means db is maintaining 40 connections and each webserver is maintaining 20 connections.

Analyzing the above system we can see that we used connection pool because people say "creating db connection is expensive"

This all make sense

Now let's say I shard table data on country_id, so now there may be 200 db, also assuming our app is popular now and we need to have 50 webserver.

Now the above strategy of connection pooling fails as if each webserver is keeping 20 connections in the pool for each db.

that means each webserver will have 20*200 db = 4000 connection

and each db will have 50 web server *20 = 1000 connection.

This doesn't sound good, so I got the question that why use connection pooling what is the overhead of creating 1 connection per web request?

So I run a test where I saw that DriverManager.getConnection() takes a average of 20 ms on localhost.

20 ms extra per request is not a game killer

Question1: Is there any other downside of using 1 connection per web request ?

Question2: People all over internet say "db connection is expensive". What are the different expenses?

PS: I also see pinterest doing same https://medium.com/@Pinterest_Engineering/sharding-pinterest-how-we-scaled-our-mysql-fleet-3f341e96ca6f

答:
If you have a busy web site and every request to the database opens and closes a connection, you are dead in the water.

The 20ms you measured are for a localhost connection. I don't think that all your 50 web servers will be on localhost...

Apart from the time it takes to establish and close a database connection, it also uses resources on the database server. This is mostly the CPU, but there could also be contention on kernel data structures.

Also, if you allow several thousand connections, there is nothing that keeps them from all gettings busy at the same time, in which case your database server will be overloaded and unresponsive unless it has several thousand cores (and even then you'd be limited by lock contention).

Your solution is an external connection pool like pgBouncer.


问:
How to remove empty rows from an md-virtual-repeat-container?
The below code is working for me to get data on API calls but I have one question here. Every time it creates elements in DOM and populate the data which we get from API. But if I get lesser records it is showing blank/empty records. How can I remove or stop generating those blank records?

```<code>this.infiniteItems = {
    numLoaded_: 0,
    toLoad_: 0,
    items: [],
    getItemAtIndex: function (index) {
    if (index > this.numLoaded_) {
        this.fetchMoreItems_(index);
            return null;
        }
        return this.items[index];
     },
     getLength: function() {
        return this.numLoaded_ + 25;
     },
     fetchMoreItems_: function (index) {
         if (this.toLoad_ < index) {
             this.toLoad_ += 5;
             var offset = 0;

             $http({
                 method: 'GET',
                 datatype: 'json',
                 url: '{my-api-call}',
                 contentType: "application/json; charset=utf-8",
                 cache: false,
                 params: {
                     param: query,
                     page: offset
                 }
              }).then(angular.bind(this, function (obj) {
                 this.items = this.items.concat(obj.data.SearchResults);
                 this.numLoaded_ = this.toLoad_;
                 this.offset++;
                 $scope.searchResults = obj.data.SearchResults;
              }));
         }
     }
};
</code>```

Thanks in advance.

答:
You should check if your API call has reached the lastPage.

```<code>fetchMoreItems_: function (index) {
                if ((this.toLoad_ < index) && !this.lastPage) {
                    this.toLoad_ += this.size;
                    newsActions.getNews(this.page++, this.size).then(angular.bind(this, function (newsData) {
                        this.items = this.items.concat(newsData.content);
                        this.numLoaded_ = this.toLoad_ >= newsData.totalElements ? newsData.totalElements : this.toLoad_  ;
                        this.lastPage = newsData.last;
                    }));
                }
            }
</code>```

Then use it in getLength function:

```<code>getLength: function () {
              if(this.lastPage){
                return this.numLoaded_
              }
              return this.numLoaded_ + 2;
            },
</code>```

Body:
The below code is working for me to get data on API calls but I have one question here. Every time it creates elements in DOM and populate the data which we get from API. But if I get lesser records it is showing blank/empty records. How can I remove or stop generating those blank records?

this.infiniteItems = {
    numLoaded_: 0,
    toLoad_: 0,
    items: [],
    getItemAtIndex: function (index) {
    if (index > this.numLoaded_) {
        this.fetchMoreItems_(index);
            return null;
        }
        return this.items[index];
     },
     getLength: function() {
        return this.numLoaded_ + 25;
     },
     fetchMoreItems_: function (index) {
         if (this.toLoad_ < index) {
             this.toLoad_ += 5;
             var offset = 0;

             $http({
                 method: 'GET',
                 datatype: 'json',
                 url: '{my-api-call}',
                 contentType: "application/json; charset=utf-8",
                 cache: false,
                 params: {
                     param: query,
                     page: offset
                 }
              }).then(angular.bind(this, function (obj) {
                 this.items = this.items.concat(obj.data.SearchResults);
                 this.numLoaded_ = this.toLoad_;
                 this.offset++;
                 $scope.searchResults = obj.data.SearchResults;
              }));
         }
     }
};

Thanks in advance.

Body:
You should check if your API call has reached the lastPage.

fetchMoreItems_: function (index) {
                if ((this.toLoad_ < index) && !this.lastPage) {
                    this.toLoad_ += this.size;
                    newsActions.getNews(this.page++, this.size).then(angular.bind(this, function (newsData) {
                        this.items = this.items.concat(newsData.content);
                        this.numLoaded_ = this.toLoad_ >= newsData.totalElements ? newsData.totalElements : this.toLoad_  ;
                        this.lastPage = newsData.last;
                    }));
                }
            }

Then use it in getLength function:

getLength: function () {
              if(this.lastPage){
                return this.numLoaded_
              }
              return this.numLoaded_ + 2;
            },


问:
working ffmpeg command fails when using in nginx with rtmp module
I have a tested code I did in a "bash" file. It works perfect on shell. I change only params to get it to work  with nginx rtmp module, but ffmpeg says always and understandable error. This is the code:

```<code>exec_push ffmpeg -re -y -i rtmp://localhost:1935/live/$name  \
                            -c:v libx264 -c:a aac  \
                            -g 24 -keyint_min 24   -preset veryfast -tune zerolatency -movflags +faststart -vsync passthrough  \
                            -filter_complex '[0:v]format=pix_fmts=yuv420p,split=3[in1][in2][in3];[in1]scale=320:-2[320x];[in2]scale=640:-2[HQ640x];[in3]scale=1280:-2[HD1280x];[0:a]aresample=44100[audio]'  \
                            -map '[320x]'       -profile:v baseline -level 3.0 -crf 31 -maxrate 170k -bufsize 170k      -f mp4 rtmp://localhost:1935/rtmp_hls/$name_320x  \
                            -map '[HQ640x]'     -profile:v baseline -level 3.1 -crf 25 -maxrate 1000k -bufsize 1000k    -f mp4 rtmp://localhost:1935/rtmp_hls/$name_HQ640x  \
                            -map '[HD1280x]'    -profile:v main -level 3.1 -crf 19 -maxrate 4000k -bufsize 4000k        -f mp4 rtmp://localhost:1935/rtmp_hls/$name_HD1280x  \
                            -map '[audio]'      -b 128k                                                                 -f mp4 rtmp://localhost:1935/rtmp_hls/$name_audio 2>>/var/www/html/ffmpeg-live-output-$name.log;
</code>```

And this is the error launched by mmpeg

```<code>ffmpeg version 3.2.4-1~bpo8+1 Copyright (c) 2000-2017 the FFmpeg developers
  built with gcc 4.9.2 (Debian 4.9.2-10)
  configuration: --prefix=/usr --extra-version='1~bpo8+1' --toolchain=hardened --libdir=/usr/lib/x86_64-linux-gnu --incdir=/usr/include/x86_64-linux-gnu --enable-gpl --disable-stripping --enable-avresample --enable-avisynth --enable-gnutls --enable-ladspa --enable-libass --enable-libbluray --enable-libbs2b --enable-libcaca --enable-libcdio --disable-libebur128 --enable-libflite --enable-libfontconfig --enable-libfreetype --enable-libfribidi --enable-libgme --enable-libgsm --enable-libmodplug --enable-libmp3lame --enable-libopenjpeg --enable-libopus --enable-libpulse --enable-librubberband --enable-libshine --enable-libsnappy --enable-libsoxr --enable-libspeex --enable-libssh --enable-libtheora --enable-libtwolame --enable-libvorbis --enable-libvpx --enable-libwavpack --enable-libwebp --enable-libx265 --enable-libxvid --enable-libzmq --enable-libzvbi --enable-omx --enable-openal --enable-opengl --enable-sdl2 --enable-libdc1394 --enable-libiec61883 --enable-chromaprint --enable-frei0r --enable-libopencv --enable-libx264 --enable-shared
  libavutil      55. 34.101 / 55. 34.101
  libavcodec     57. 64.101 / 57. 64.101
  libavformat    57. 56.101 / 57. 56.101
  libavdevice    57.  1.100 / 57.  1.100
  libavfilter     6. 65.100 /  6. 65.100
  libavresample   3.  1.  0 /  3.  1.  0
  libswscale      4.  2.100 /  4.  2.100
  libswresample   2.  3.100 /  2.  3.100
  libpostproc    54.  1.100 / 54.  1.100
[flv @ 0x55e430547740] video stream discovered after head already parsed
[flv @ 0x55e430547740] audio stream discovered after head already parsed
Input #0, flv, from 'rtmp://localhost:1935/live/directo':
  Metadata:
    Server          : NGINX RTMP (github.com/sergey-dryabzhinsky/nginx-rtmp-module)
    displayWidth    : 1280
    displayHeight   : 720
    fps             : 24
    profile         :
    level           :
  Duration: 00:00:00.00, start: 26.023000, bitrate: N/A
    Stream #0:0: Video: h264 (Constrained Baseline), yuv420p(progressive), 1280x720 [SAR 1:1 DAR 16:9], 24.42 fps, 24 tbr, 1k tbn, 48 tbc
    Stream #0:1: Audio: aac (LC), 44100 Hz, mono, fltp
[NULL @ 0x55e4305e0b40] Unable to find a suitable output format for '
'

: Invalid argument
</code>```

Does anyone could help me?

Thank you

答:
There's no need for line breaks \. Nginx usess regular expressions to parse the configuration:

```<code>exec_push ffmpeg line 1
                 line 2
                  ...
                 line n;
</code>```

Body:
I have a tested code I did in a "bash" file. It works perfect on shell. I change only params to get it to work  with nginx rtmp module, but ffmpeg says always and understandable error. This is the code:

exec_push ffmpeg -re -y -i rtmp://localhost:1935/live/$name  \
                            -c:v libx264 -c:a aac  \
                            -g 24 -keyint_min 24   -preset veryfast -tune zerolatency -movflags +faststart -vsync passthrough  \
                            -filter_complex '[0:v]format=pix_fmts=yuv420p,split=3[in1][in2][in3];[in1]scale=320:-2[320x];[in2]scale=640:-2[HQ640x];[in3]scale=1280:-2[HD1280x];[0:a]aresample=44100[audio]'  \
                            -map '[320x]'       -profile:v baseline -level 3.0 -crf 31 -maxrate 170k -bufsize 170k      -f mp4 rtmp://localhost:1935/rtmp_hls/$name_320x  \
                            -map '[HQ640x]'     -profile:v baseline -level 3.1 -crf 25 -maxrate 1000k -bufsize 1000k    -f mp4 rtmp://localhost:1935/rtmp_hls/$name_HQ640x  \
                            -map '[HD1280x]'    -profile:v main -level 3.1 -crf 19 -maxrate 4000k -bufsize 4000k        -f mp4 rtmp://localhost:1935/rtmp_hls/$name_HD1280x  \
                            -map '[audio]'      -b 128k                                                                 -f mp4 rtmp://localhost:1935/rtmp_hls/$name_audio 2>>/var/www/html/ffmpeg-live-output-$name.log;

And this is the error launched by mmpeg

ffmpeg version 3.2.4-1~bpo8+1 Copyright (c) 2000-2017 the FFmpeg developers
  built with gcc 4.9.2 (Debian 4.9.2-10)
  configuration: --prefix=/usr --extra-version='1~bpo8+1' --toolchain=hardened --libdir=/usr/lib/x86_64-linux-gnu --incdir=/usr/include/x86_64-linux-gnu --enable-gpl --disable-stripping --enable-avresample --enable-avisynth --enable-gnutls --enable-ladspa --enable-libass --enable-libbluray --enable-libbs2b --enable-libcaca --enable-libcdio --disable-libebur128 --enable-libflite --enable-libfontconfig --enable-libfreetype --enable-libfribidi --enable-libgme --enable-libgsm --enable-libmodplug --enable-libmp3lame --enable-libopenjpeg --enable-libopus --enable-libpulse --enable-librubberband --enable-libshine --enable-libsnappy --enable-libsoxr --enable-libspeex --enable-libssh --enable-libtheora --enable-libtwolame --enable-libvorbis --enable-libvpx --enable-libwavpack --enable-libwebp --enable-libx265 --enable-libxvid --enable-libzmq --enable-libzvbi --enable-omx --enable-openal --enable-opengl --enable-sdl2 --enable-libdc1394 --enable-libiec61883 --enable-chromaprint --enable-frei0r --enable-libopencv --enable-libx264 --enable-shared
  libavutil      55. 34.101 / 55. 34.101
  libavcodec     57. 64.101 / 57. 64.101
  libavformat    57. 56.101 / 57. 56.101
  libavdevice    57.  1.100 / 57.  1.100
  libavfilter     6. 65.100 /  6. 65.100
  libavresample   3.  1.  0 /  3.  1.  0
  libswscale      4.  2.100 /  4.  2.100
  libswresample   2.  3.100 /  2.  3.100
  libpostproc    54.  1.100 / 54.  1.100
[flv @ 0x55e430547740] video stream discovered after head already parsed
[flv @ 0x55e430547740] audio stream discovered after head already parsed
Input #0, flv, from 'rtmp://localhost:1935/live/directo':
  Metadata:
    Server          : NGINX RTMP (github.com/sergey-dryabzhinsky/nginx-rtmp-module)
    displayWidth    : 1280
    displayHeight   : 720
    fps             : 24
    profile         :
    level           :
  Duration: 00:00:00.00, start: 26.023000, bitrate: N/A
    Stream #0:0: Video: h264 (Constrained Baseline), yuv420p(progressive), 1280x720 [SAR 1:1 DAR 16:9], 24.42 fps, 24 tbr, 1k tbn, 48 tbc
    Stream #0:1: Audio: aac (LC), 44100 Hz, mono, fltp
[NULL @ 0x55e4305e0b40] Unable to find a suitable output format for '
'

: Invalid argument

Does anyone could help me?

Thank you

Body:
There's no need for line breaks \. Nginx usess regular expressions to parse the configuration:

exec_push ffmpeg line 1
                 line 2
                  ...
                 line n;


问:
Position of All Matching Elements in List
I'm trying to write a function in Common Lisp similar to the built in position function, that returns a list of the positions of all elements in the haystack that match the needle, as opposed to just the first. I've come up with a few possible solutions (for example recursively searching for the next element using a cdr-from function on the position and adding the result to the previous position) but none of the approaches I've come up with so far seem particularly elegant.

Can anyone suggest what would be the best way of approaching this, as I'm currently struggling.

答:
If you want a recursive function, rather than a (loop ...) based one, you could use something like:

```<code>(defun all-positions (needle haystack)
    (labels ((f (n h c r)
                 (if (null h)
                     r
                     (if (eql (car h) n)
                         (f n (cdr h) (1+ c) (cons c r))
                         (f n (cdr h) (1+ c) r))))))
    (reverse (f needle haystack 0 nil)))
</code>```

Body:
If you want a recursive function, rather than a (loop ...) based one, you could use something like:

(defun all-positions (needle haystack)
    (labels ((f (n h c r)
                 (if (null h)
                     r
                     (if (eql (car h) n)
                         (f n (cdr h) (1+ c) (cons c r))
                         (f n (cdr h) (1+ c) r))))))
    (reverse (f needle haystack 0 nil)))


问:
Selenium PhantomJS Scrolling Down
I tried to scrolling down with selenium, But i use webdriver PhantomJS. I tried selenium for test javascript instagram. As you know, on instagram there have button "Load More", after click button "Load More", we don't have to click again becouse it will auto refresh and it will show more image.

I tried like this :

```<code>driver.find_element_by_xpath("//a[@class='_8ioip _glw1t']").click()
time.sleep(5)

driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
time.sleep(3.6)
</code>```

Actually this code it's work, but not really work, i mean something weird happening at the "time.sleep". If i give 2, the result  are few and if i give 3 the result are just pretty much, But if i give 5, the result same like i give 2.

The question is, How to make teh Scroll get all data

答:
class of "Load more" button seems to have changed.
your code is correct, try with this xpath:

```<code>//a[@class='_8imhp _glz1g']
</code>```

or try to locate the button by it's text content:

```<code>//*/div/a[text()[contains(.,'Load more')]]
</code>```

and before click the button scroll down.. so your code should looks like:

```<code>driver.get('https://www.instagram.com/explore/tags/whatever/')
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
driver.find_element_by_xpath("//*[text()[contains(.,'Load more')]]").click()
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
</code>```

Title: Selenium PhantomJS Scrolling Down

Body:
I tried to scrolling down with selenium, But i use webdriver PhantomJS. I tried selenium for test javascript instagram. As you know, on instagram there have button "Load More", after click button "Load More", we don't have to click again becouse it will auto refresh and it will show more image.

I tried like this :

driver.find_element_by_xpath("//a[@class='_8ioip _glw1t']").click()
time.sleep(5)

driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
time.sleep(3.6)

Actually this code it's work, but not really work, i mean something weird happening at the "time.sleep". If i give 2, the result  are few and if i give 3 the result are just pretty much, But if i give 5, the result same like i give 2.

The question is, How to make teh Scroll get all data

Body:
class of "Load more" button seems to have changed.
your code is correct, try with this xpath:

//a[@class='_8imhp _glz1g']

or try to locate the button by it's text content:

//*/div/a[text()[contains(.,'Load more')]]

and before click the button scroll down.. so your code should looks like:

driver.get('https://www.instagram.com/explore/tags/whatever/')
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
driver.find_element_by_xpath("//*[text()[contains(.,'Load more')]]").click()
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")


问:
Inconsistent/Delayed HTML5 Desktop Push Notifications on Chrome
I'm writing a chat webapp that needs to be able to trigger desktop push notifications through the notifications API: https://developer.mozilla.org/en-US/docs/Web/API/Notifications_API

Unfortunately, it seems that the notifications don't show up until I flush it all out by making another notification with this fiddle: https://jsfiddle.net/yoshi6jp/Umc9A/

This is the code that I am using:

```<code>function triggerDesktopNotification() {
  function makeNotification() {
    var notification = new Notification('AppName', {
      body: 'You have a new message!',
      icon: '/favicon.ico',
    });
    notification.onclick = () => {
      notification.close();
    };
  }

  if (Notification.permission === 'granted') {
    makeNotification();
  }
  else if (Notification.permission !== 'denied') {
    Notification.requestPermission(function (permission) {
      if (permission === 'granted') {
        makeNotification();
      }
    });
  }
}
</code>```

I can confirm that the code is executing properly by placing console.log() immediately after the new Notification call. Interestingly, if I put an alert() there instead, the notification shows up when I see the alert box (after navigating back into my tab).

答:
If I understood you right ;

Alert interrupts program stack where it placed i think.Why dont you try to fire it async with setTimeout function like that ?

```<code> setTimeout(  function(){
       alert("asd");
     })
</code>```

edited js fiddle here

Body:
I'm writing a chat webapp that needs to be able to trigger desktop push notifications through the notifications API: https://developer.mozilla.org/en-US/docs/Web/API/Notifications_API

Unfortunately, it seems that the notifications don't show up until I flush it all out by making another notification with this fiddle: https://jsfiddle.net/yoshi6jp/Umc9A/

This is the code that I am using:

function triggerDesktopNotification() {
  function makeNotification() {
    var notification = new Notification('AppName', {
      body: 'You have a new message!',
      icon: '/favicon.ico',
    });
    notification.onclick = () => {
      notification.close();
    };
  }

  if (Notification.permission === 'granted') {
    makeNotification();
  }
  else if (Notification.permission !== 'denied') {
    Notification.requestPermission(function (permission) {
      if (permission === 'granted') {
        makeNotification();
      }
    });
  }
}

I can confirm that the code is executing properly by placing console.log() immediately after the new Notification call. Interestingly, if I put an alert() there instead, the notification shows up when I see the alert box (after navigating back into my tab).

Body:
If I understood you right ;

Alert interrupts program stack where it placed i think.Why dont you try to fire it async with setTimeout function like that ?

 setTimeout(  function(){
       alert("asd");
     })

edited js fiddle here


问:
Customizing ASP.NET Identity
I'm using Identity Server 4 and I've customised my ASP.NET Identity user as follows:

```<code>public class ApplicationUser : IdentityUser
{
    [MaxLength(100)]
    public virtual string FirstName { get; set; }

    [MaxLength(100)]
    public virtual string LastName { get; set; }
}
</code>```

I can't see where I would configure Identity Server 4 to include these 2 properties in the claims collection.  I've had a look through some of the Identity Server 4 samples but can't see any examples.

I'd ideally like to map these 2 user properties to the given_name and family_name claims.

I'm currently hooking up to the notifications and querying the userinfo endpoint (hybrid flow?).  So I'm not sure if this is configuration of Identity Server or customization of the userinfo endpoint?

答:
I was wondering why there is no documentation on this.  It lead me to realise that I'm probably doing it wrong.

I'd not seen the table AspNetUserClaims created as part of ASP.NET Identity.  I added my claim data into here and the claim data pulls through as part of the profile.

In the POST method for AccountController.Register I added:

```<code>var givenNameClaim = new IdentityUserClaim<string>()
{
    ClaimType = "given_name",
    ClaimValue = model.FirstName
};

var familyNameClaim = new IdentityUserClaim<string>()
{
    ClaimType = "family_name",
    ClaimValue = model.LastName
};

var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
user.Claims.Add(givenNameClaim);
user.Claims.Add(familyNameClaim);
</code>```

Title: Customizing ASP.NET Identity

Body:
I'm using Identity Server 4 and I've customised my ASP.NET Identity user as follows:

public class ApplicationUser : IdentityUser
{
    [MaxLength(100)]
    public virtual string FirstName { get; set; }

    [MaxLength(100)]
    public virtual string LastName { get; set; }
}

I can't see where I would configure Identity Server 4 to include these 2 properties in the claims collection.  I've had a look through some of the Identity Server 4 samples but can't see any examples.

I'd ideally like to map these 2 user properties to the given_name and family_name claims.

I'm currently hooking up to the notifications and querying the userinfo endpoint (hybrid flow?).  So I'm not sure if this is configuration of Identity Server or customization of the userinfo endpoint?

Body:
I was wondering why there is no documentation on this.  It lead me to realise that I'm probably doing it wrong.

I'd not seen the table AspNetUserClaims created as part of ASP.NET Identity.  I added my claim data into here and the claim data pulls through as part of the profile.

In the POST method for AccountController.Register I added:

var givenNameClaim = new IdentityUserClaim<string>()
{
    ClaimType = "given_name",
    ClaimValue = model.FirstName
};

var familyNameClaim = new IdentityUserClaim<string>()
{
    ClaimType = "family_name",
    ClaimValue = model.LastName
};

var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
user.Claims.Add(givenNameClaim);
user.Claims.Add(familyNameClaim);


问:
Lipo Error!! can't open input file
My application was working perfectly fine, then I started integrating SDK for push notification and stop the integration in between. I even deleted the SDK from my project and trying to archive or run the app, it gives me the error:

lipo Error!! can't open input file.

Any help would be appreciated a lot, I have given enough time to solve this but failed.

/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/lipo: can't open input file:
  /Users/XYZ/Library/Developer/Xcode/DerivedData/MyAPP-hjbmqpnmsoruqxbwlayqkjsojccv/Build/Intermediates/MyAPP.build/Debug-iphoneos/MyAPP.build/Objects-normal/armv7s/MyAPP (No such file or directory)

答: i tried to re-select provisioning profile signing for both debug and release. this did fix the issue.</p>

Title: Lipo Error!! can't open input file


问:
Get the 5 most similar images
I would like to compare which are the 5 most similar images to an input image.
To do this I thought to use the SIFT (VLFeat library) and compare the respective descriptors.
So I use the vl_ubcmatch (doc here) method to calculate the similarity measurement between the images.

This is the code:

```<code>path_dir = './img/';
imgs = dir(path_dir);
imgs = imgs(3 : end);
numImgs = size(imgs);
numImgs = numImgs(1);
path1 = './img/car01.jpg';
Ia = imread(path1);
Ia = single(rgb2gray(Ia));
[fa, da] = vl_sift(Ia);

results = struct;
m = 0;
j = 1; % indice dell'img (del for)

for img = imgs'

    path = strcat(path_dir, img.name);
    if(strcmp(path1, path) == 0)
        Ib = imread(path);
        Ib = single(rgb2gray(Ib));
        [fb, db] = vl_sift(Ib);

        [matches, scores] = vl_ubcmatch(da, db);

        s = sum(scores);
        [r, c] = size(scores);
        m = s ./ c;

        results(j).measure = m;
        results(j).img = path;
        j = j + 1;
    end
end
</code>```

As you can see from the code, I thought I would use the mean as a measure of similarity but the results I get are not satisfactory (for example, it tells me that the input image of a cup is more similar to a tree than another cup).

According to you, is it better to have more equal descriptors but with low similar or less similar descriptors but with greater similarity?
I have 50 images of 5 different categories (cups, trees, people, tables and cars) and, given an image as input, the program will return the 5 most similar images to it and preferably belonging to the same category.

What measurement can I use instead of the mean to get a more precise classification?
Thanks!

答:
According to your code you measure the similarity between image (Ia) and all other images (Ib). Therefore you compare the SIFT descriptors of Ia with those of all Ib's - which gives you a list of feature matches for each image pair (matches) and the Euclidean distance of each feature pair (scores).

Now using the mean of all scores of an image pair as a measure of similarity is not a very robust approach because an image pair with only one feature match could (by chance) lead to a better "similarity" than an image pair with many features - which I guess is an unrealistic solution for your task.

Concerning your question it is always better to have meaningful/robust descriptors, even if there are only a few (of course the more the better!), than having a lot of meaningless descriptors.

Proposal: why don't you just count the number of inliers (= number of feature matches for each image pair, numel(matches))?

With this it should give more inliers between images of the same object than different objects, so taking those pairs which have the 5 most inliers should be the most similar ones.

If you just want to distinguish a cup from a tree it should work. If your classification task is getting more difficult and you need to distinguish different types of trees, SIFT is not the best algorithm to use. A learning approach will give better results... but depends on your task.

Title: Get the 5 most similar images

Body:
I would like to compare which are the 5 most similar images to an input image.
To do this I thought to use the SIFT (VLFeat library) and compare the respective descriptors.
So I use the vl_ubcmatch (doc here) method to calculate the similarity measurement between the images.

This is the code:

path_dir = './img/';
imgs = dir(path_dir);
imgs = imgs(3 : end);
numImgs = size(imgs);
numImgs = numImgs(1);
path1 = './img/car01.jpg';
Ia = imread(path1);
Ia = single(rgb2gray(Ia));
[fa, da] = vl_sift(Ia);

results = struct;
m = 0;
j = 1; % indice dell'img (del for)

for img = imgs'

    path = strcat(path_dir, img.name);
    if(strcmp(path1, path) == 0)
        Ib = imread(path);
        Ib = single(rgb2gray(Ib));
        [fb, db] = vl_sift(Ib);

        [matches, scores] = vl_ubcmatch(da, db);

        s = sum(scores);
        [r, c] = size(scores);
        m = s ./ c;

        results(j).measure = m;
        results(j).img = path;
        j = j + 1;
    end
end

As you can see from the code, I thought I would use the mean as a measure of similarity but the results I get are not satisfactory (for example, it tells me that the input image of a cup is more similar to a tree than another cup).

According to you, is it better to have more equal descriptors but with low similar or less similar descriptors but with greater similarity?
I have 50 images of 5 different categories (cups, trees, people, tables and cars) and, given an image as input, the program will return the 5 most similar images to it and preferably belonging to the same category.

What measurement can I use instead of the mean to get a more precise classification?
Thanks!


问:
Why there are the same variables of mine with a ':' in Visual Studio auto complete list?
What's the difference between myVar and myVar: in VS auto-complete list while working with functions. Why the second one is added to this list ?

答:
This is probably when you're setting a value for a parameter when calling a method, yeah? In C# .NET 4, you can set named parameters when calling a method. This removes the need for having to enter your parameters in a set order.</p>

```<code>private void MyMethod(int width, int height){
   // do stuff
}

//These are all the same:
MyMethod(10,12);
MyMethod(width: 10, height: 12);
MyMethod(heigh: 12, width: 12);
</code>```

Body:
This is probably when you're setting a value for a parameter when calling a method, yeah? In C# .NET 4, you can set named parameters when calling a method. This removes the need for having to enter your parameters in a set order.

private void MyMethod(int width, int height){
   // do stuff
}

//These are all the same:
MyMethod(10,12);
MyMethod(width: 10, height: 12);
MyMethod(heigh: 12, width: 12);


问:
Angular - Assign new value to FirebaseListObservable
Not sure how this is suppose to be done.

filter is a Firebase list observable.

```<code>filter: FirebaseListObservable<UserModel[]>;
</code>```

This is the query. It gets all users with a specific occupation.

```<code>this.filter = this.db.list('occupationsUsers/' + occupation + '/users');
</code>```

Then I use an <md-list> which works. It displays all users with occupation.

```<code><md-list>

            <md-list-item *ngFor="let user of filter | async" [value]="user.email">{{user.email}}
              <button md-button [mdMenuTriggerFor]="menu">Menu</button>
              <md-menu #menu="mdMenu">
                <button md-menu-item (click)="removeUserFromFilterList(user.email)">Delete</button>
              </md-menu>
            </md-list-item>
          </md-list>
</code>```

removeUserFromFilterList

```<code>  removeUserFromFilterList(userEmail: string) {
    var index = this.eventForm['guests'].indexOf(userEmail);
    this.filter = this.eventForm['guests'].splice(index, 1);
  }
</code>```

The error:

```<code>ERROR Error: InvalidPipeArgument: '[object Object]' for pipe 'AsyncPipe'
    at invalidPipeArgumentError
</code>```

How do I populate this.filter with the new updated user list and keep it working with the firebase query?

答:
this.filter as you mention , is a FirebaseListObservable. and as i understand , this.eventForm is just an array(and not like this.filter).
i would recommend you to use one of the following methods:

this.filter.update('key-of-some-data', { object to remove });

or

this.filter.remove('key-of-some-data');

you can read more about that on

click here

Body:
Not sure how this is suppose to be done.

filter is a Firebase list observable.

filter: FirebaseListObservable<UserModel[]>;

This is the query. It gets all users with a specific occupation.

this.filter = this.db.list('occupationsUsers/' + occupation + '/users');

Then I use an <md-list> which works. It displays all users with occupation.

<md-list>

            <md-list-item *ngFor="let user of filter | async" [value]="user.email">{{user.email}}
              <button md-button [mdMenuTriggerFor]="menu">Menu</button>
              <md-menu #menu="mdMenu">
                <button md-menu-item (click)="removeUserFromFilterList(user.email)">Delete</button>
              </md-menu>
            </md-list-item>
          </md-list>

removeUserFromFilterList

  removeUserFromFilterList(userEmail: string) {
    var index = this.eventForm['guests'].indexOf(userEmail);
    this.filter = this.eventForm['guests'].splice(index, 1);
  }

The error:

ERROR Error: InvalidPipeArgument: '[object Object]' for pipe 'AsyncPipe'
    at invalidPipeArgumentError

How do I populate this.filter with the new updated user list and keep it working with the firebase query?


问:
OpenCL finding index of minimum in array
I'm using OpenCL (via JOCL) to find minima in a bunch of distance calculations for ray marching. The pseudocode would look something like this:

```<code>Start with a point in 3d space.
There are a number of functions to calculate distances
    to that point from various other points.
    These may be rather complex (transforms, csg etc).
Calculate all of the distances, perhaps into an array
Get the index of the minimum distance in the array..
Use that index to do up other stuff (pigmentation etc).
</code>```

My implementation is kinda crap though. I don't currently parallelize the distance calculations but I would like to. Here's why I don't:

It's easy enough to get the minimum distance, but to retrieve this index is not obvious. I ended up iterating over the distances and keeping track of the current minimum and its index, but this is obviously garbage in a parallel environment.

Could basically use a tip to steer me in the right direction here, or tell me if Im barking up the wrong tree entirely? (e.g. is this a CPU job?)

Thanks!

答:
Tested with a RX550 which is a low end graphics card.

1-million element min() function:

```<code>__kernel void test(__global float * data,__global int * index)
{
    int id=get_global_id(0);
    float d1=data[id];
    float d2=data[id+get_global_size(0)];
    float f=fmin(d1,d2);
    index[id]=select( index[id+get_global_size(0)], index[id], fabs(f-d1)<=fabs(f-d2) );
    data[id]=f;
}");
</code>```

initialized data elements with random values and index elements with indices of their own.

Uploading data and index to GPU through pci-e 2.0 8x took: 3.0 ms

computing with global range=512k,256k,128k,...,1 (logN steps) took: 0.3 ms

downloading data[0] and index[0] took: 0.002 ms

This is a straightforward version which may not be the fastest implementation. To get faster, workgroup level sub-reduction can be added with:

work_group_scan_inclusive_min(x) for OpenCL 2.0+

__local float reductionArray[256] for OpenCL 1.2-

to reduce number of kernel enqueue commands to finish job in less than hundred ? microseconds.

Body:
I'm using OpenCL (via JOCL) to find minima in a bunch of distance calculations for ray marching. The pseudocode would look something like this:

Start with a point in 3d space.
There are a number of functions to calculate distances
    to that point from various other points.
    These may be rather complex (transforms, csg etc).
Calculate all of the distances, perhaps into an array
Get the index of the minimum distance in the array..
Use that index to do up other stuff (pigmentation etc).

My implementation is kinda crap though. I don't currently parallelize the distance calculations but I would like to. Here's why I don't:

It's easy enough to get the minimum distance, but to retrieve this index is not obvious. I ended up iterating over the distances and keeping track of the current minimum and its index, but this is obviously garbage in a parallel environment.

Could basically use a tip to steer me in the right direction here, or tell me if Im barking up the wrong tree entirely? (e.g. is this a CPU job?)

Thanks!

Body:
Tested with a RX550 which is a low end graphics card.

1-million element min() function:

__kernel void test(__global float * data,__global int * index)
{
    int id=get_global_id(0);
    float d1=data[id];
    float d2=data[id+get_global_size(0)];
    float f=fmin(d1,d2);
    index[id]=select( index[id+get_global_size(0)], index[id], fabs(f-d1)<=fabs(f-d2) );
    data[id]=f;
}");

initialized data elements with random values and index elements with indices of their own.

Uploading data and index to GPU through pci-e 2.0 8x took: 3.0 ms

computing with global range=512k,256k,128k,...,1 (logN steps) took: 0.3 ms

downloading data[0] and index[0] took: 0.002 ms

This is a straightforward version which may not be the fastest implementation. To get faster, workgroup level sub-reduction can be added with:

work_group_scan_inclusive_min(x) for OpenCL 2.0+

__local float reductionArray[256] for OpenCL 1.2-

to reduce number of kernel enqueue commands to finish job in less than hundred ? microseconds.


问:
Mock an object created in the middle of a method
I know that creating an instance of a Class in the middle of a method it's a bad practice since it makes code hard to test.
But I can't refactor the code, so I need to find a way to mock an Object created with new in the middle of a method under test.

Used Frameworks: PHPUnit, Mockery, WP_Mock

Example: Here I need to mock the get_second_string() method from the instance of the class ExternalClass

```<code>Class MyClass {

    function methodUnderTest($string) {
        $objToMock = new ExternalClass();
        $second_string = $objToMock->get_second_string();
        $final_string = $string . $second_string;
        return $final_string;
    }
}
Class TestMyClass extends PHPUnit_Framework_TestCase {
    public function setUp() {
    }
    public function tearDown() {
    }

    public function test_methodUnderTest() {
        $externalObject = $this->getMockBuilder('ExternalClass')
                               ->setMethods(['get_second_string'])
                               ->getMock;
        $externalObject->expects($this->once())
                       ->method('get_second_string')
                       ->willReturn(' two');
        $testObj = new MyClass();
        $this->assertEquals('one two', $testObj->methodUnderTest('one');
    }
}
</code>```

答:
If you really have no opportunity to refactor the code or do some appropriate integration testing, you might want to take a look at https://github.com/php-test-helpers/php-test-helpers#intercepting-object-creation and https://github.com/krakjoe/uopz/tree/PHP5

Still I think the code you make would profit a lot more from refactoring than monkey patching.

Besides, the refactoring does not need to be very heavy. You might do at least this:

```<code>class MyClass
{
    private $externalsFactory;

    public function __construct($externalsFactory){
        $this->externalsFactory = $externalsFactory;
    }

    public function methodUnderTest($str){
        $external = $this->externalsFactory->make();
        $second_string = $external->get_second_string();
        $finalString = $str.$second_string;
        return $finalString;
    }
}

class ExternalsFactory
{
    public function make(){
        return new ExternalClass();
    }
}

class ExternalClass
{
    public function get_second_string(){
        return 'some real stuff may be even from database or whatever else it could be';
    }
}

class MyClassTest extends PHPUnit_Framework_TestCase
{
    private $factoryMock;
    private $myClass;

    public function setUp(){
        $this->factoryMock = $this->getMockBuilder('ExternalsFactory')
                                  ->getMock();
        $this->myClass = new MyClass($this->factoryMock);
    }

    public function testMethodUnderTest(){
        $extenalMock = $this->createMock('ExternalClass');
        $extenalMock->method('get_second_string')
                    ->willReturn('second');
        $this->factoryMock->method('make')
                          ->willReturn($extenalMock);
        $this->assertSame('first-and-second', $this->myClass->methodUnderTest('first-and-'));
    }
}
</code>```

Body:
I know that creating an instance of a Class in the middle of a method it's a bad practice since it makes code hard to test.
But I can't refactor the code, so I need to find a way to mock an Object created with new in the middle of a method under test.

Used Frameworks: PHPUnit, Mockery, WP_Mock

Example: Here I need to mock the get_second_string() method from the instance of the class ExternalClass

Class MyClass {

    function methodUnderTest($string) {
        $objToMock = new ExternalClass();
        $second_string = $objToMock->get_second_string();
        $final_string = $string . $second_string;
        return $final_string;
    }
}
Class TestMyClass extends PHPUnit_Framework_TestCase {
    public function setUp() {
    }
    public function tearDown() {
    }

    public function test_methodUnderTest() {
        $externalObject = $this->getMockBuilder('ExternalClass')
                               ->setMethods(['get_second_string'])
                               ->getMock;
        $externalObject->expects($this->once())
                       ->method('get_second_string')
                       ->willReturn(' two');
        $testObj = new MyClass();
        $this->assertEquals('one two', $testObj->methodUnderTest('one');
    }
}

Body:
If you really have no opportunity to refactor the code or do some appropriate integration testing, you might want to take a look at https://github.com/php-test-helpers/php-test-helpers#intercepting-object-creation and https://github.com/krakjoe/uopz/tree/PHP5

Still I think the code you make would profit a lot more from refactoring than monkey patching.

Besides, the refactoring does not need to be very heavy. You might do at least this:

class MyClass
{
    private $externalsFactory;

    public function __construct($externalsFactory){
        $this->externalsFactory = $externalsFactory;
    }

    public function methodUnderTest($str){
        $external = $this->externalsFactory->make();
        $second_string = $external->get_second_string();
        $finalString = $str.$second_string;
        return $finalString;
    }
}

class ExternalsFactory
{
    public function make(){
        return new ExternalClass();
    }
}

class ExternalClass
{
    public function get_second_string(){
        return 'some real stuff may be even from database or whatever else it could be';
    }
}

class MyClassTest extends PHPUnit_Framework_TestCase
{
    private $factoryMock;
    private $myClass;

    public function setUp(){
        $this->factoryMock = $this->getMockBuilder('ExternalsFactory')
                                  ->getMock();
        $this->myClass = new MyClass($this->factoryMock);
    }

    public function testMethodUnderTest(){
        $extenalMock = $this->createMock('ExternalClass');
        $extenalMock->method('get_second_string')
                    ->willReturn('second');
        $this->factoryMock->method('make')
                          ->willReturn($extenalMock);
        $this->assertSame('first-and-second', $this->myClass->methodUnderTest('first-and-'));
    }
}


问:
Angular 4 shows time part wrong in datetime
I have an input on my Angular component html like this:

```<code><input id="orderdate" class="form-control" value="{{order.OrderDate | date: 'd.M.yyyy H:mm:ss'}}" disabled />
</code>```

order.OrderDate has value 2017-06-01T10:52:03.666723, and I expect to see value in format

1.6.2017 10:52:03.

However, what I actually get is

1.6.2017 10:00:6/1/2017 10:52:03 AM:6/1/2017 10:52:03 AM

If I use only date (d.M.yyyy), it works correctly (1.6.2017). Why is the time part showing wrong?

答:
I think its supposed to be in this format 'd.M.y H:mm:ss'.
Angular Date Pipe</p>

Body:
I have an input on my Angular component html like this:

<input id="orderdate" class="form-control" value="{{order.OrderDate | date: 'd.M.yyyy H:mm:ss'}}" disabled />

order.OrderDate has value 2017-06-01T10:52:03.666723, and I expect to see value in format

1.6.2017 10:52:03.

However, what I actually get is

1.6.2017 10:00:6/1/2017 10:52:03 AM:6/1/2017 10:52:03 AM

If I use only date (d.M.yyyy), it works correctly (1.6.2017). Why is the time part showing wrong?


问:
Create a QuickSight dataset from a PostgreSQL materialized view
The AWS QuickSight Documentation mentions that:

You can retrieve data from tables and materialized views in PostgreSQL instances, and from tables in all other database instances.

When creating a dataset from my PostgreSQL 9.5 database, none of my materialized views display in the list to select from.

Is the documentation incorrect? Is there somewhere else I should be selecting from?

答:
I haven't used views as my source. However I can usually see tables only from one schema. Maybe your views are in different schema?

If that is not the case, just use Query instead of Table as source for your dataset and just select * from myview.


问:
Is there an equivalent to the perl debugger 'x' in pdl2 (or Devel::REPL)?
I am using pdl2 (the PDL shell) also as a my default Perl interactive shell (it loads all the nice plugins for Devel::REPL). But I am missing the x dumper-printing alias. p is nice for piddles but it does not work for a normal array ref or hash ref. I have loaded Data::Dumper but it lacks an easy way of controlling depth and I like the way you can quickly set depth limits with x, e.g. x 2 $deep_datastruct for complex data structures. But with Data::Dumper the process is more cumbersome:

```<code>pdl> say $c
HASH(0x53b0b60)

pdl> p $c
HASH(0x12b14018)

pdl> use Data::Dumper

pdl> p Dumper $c
$VAR1 = {
          'c' => {
                   'c' => 3,
                   'a' => 1,
                   'b' => {
                            'c' => '3',
                            'a' => '1',
                            'b' => '2'
                          }
                 },
          'a' => 1,
          'b' => 4
        };
pdl>  $Data::Dumper::Maxdepth = 1;
pdl> p Dumper $c
$VAR1 = {
          'c' => 'HASH(0x97fba70)',
          'a' => 1,
          'b' => 4
        };
</code>```

In the Perl debugger you can achieve the same thing with x 1 $c directly. Does pdl2 have something similar and so concise?

[update]
And related with this question: does pdl2 or Devel::REPL have convenience functions like the Perl debugger commands m or y? Or should one create a module with PadWalker and export them? I would like to use a real REPL instead of the Perl debugger as an interactive shell, but still the Perl debugger has some important things that I don't know how to do with Devel::REPL or pdl2.

For example to see all variables (pdl2 only show piddles):

```<code>pdl> help vars
PDL variables in package main::

Name         Type   Dimension       Flow  State          Mem
----------------------------------------------------------------
no PDL objects in package main::
</code>```

By the way, does someone know a Devel::REPL plugin for listing all the variables in use (like y in the debugger, but only the names, not the values) and then have a x-like to dump the wanted one?

答:
The Devel::REPL shell re.pl already dumps the value of the last expression by default:

```<code>[foo@host]$ re.pl
$ { a => 23, b => 34}
$HASH1 = {
           a => 23,
           b => 34
         };

$
</code>```

Body:
I am using pdl2 (the PDL shell) also as a my default Perl interactive shell (it loads all the nice plugins for Devel::REPL). But I am missing the x dumper-printing alias. p is nice for piddles but it does not work for a normal array ref or hash ref. I have loaded Data::Dumper but it lacks an easy way of controlling depth and I like the way you can quickly set depth limits with x, e.g. x 2 $deep_datastruct for complex data structures. But with Data::Dumper the process is more cumbersome:

pdl> say $c
HASH(0x53b0b60)

pdl> p $c
HASH(0x12b14018)

pdl> use Data::Dumper

pdl> p Dumper $c
$VAR1 = {
          'c' => {
                   'c' => 3,
                   'a' => 1,
                   'b' => {
                            'c' => '3',
                            'a' => '1',
                            'b' => '2'
                          }
                 },
          'a' => 1,
          'b' => 4
        };
pdl>  $Data::Dumper::Maxdepth = 1;
pdl> p Dumper $c
$VAR1 = {
          'c' => 'HASH(0x97fba70)',
          'a' => 1,
          'b' => 4
        };

In the Perl debugger you can achieve the same thing with x 1 $c directly. Does pdl2 have something similar and so concise?

[update]
And related with this question: does pdl2 or Devel::REPL have convenience functions like the Perl debugger commands m or y? Or should one create a module with PadWalker and export them? I would like to use a real REPL instead of the Perl debugger as an interactive shell, but still the Perl debugger has some important things that I don't know how to do with Devel::REPL or pdl2.

For example to see all variables (pdl2 only show piddles):

pdl> help vars
PDL variables in package main::

Name         Type   Dimension       Flow  State          Mem
----------------------------------------------------------------
no PDL objects in package main::

By the way, does someone know a Devel::REPL plugin for listing all the variables in use (like y in the debugger, but only the names, not the values) and then have a x-like to dump the wanted one?

Body:
The Devel::REPL shell re.pl already dumps the value of the last expression by default:

[foo@host]$ re.pl
$ { a => 23, b => 34}
$HASH1 = {
           a => 23,
           b => 34
         };

$


问:
find command with daystart and mmin
How is find daystart used with mmin?  daystart with mtime makes perfect sense, But with mmin its confusing.

Let me explain what I do not get:

find path -daysart -mtime 0 gives files modified today.

find path -daystart -mtime 1 gives files modified yesterday.

How to get files modified today with daystart and mmin?

Also how to find files modified between 23:59 and 12:00 using daystart option and mmin?

答:
On how to use mmin:

If you try to find what files were modified (m in mmin) between 2 and 6 minutes ago:

```<code>find path -mmin +2 -mmin -6
</code>```

to use it with -daystart

daystart option set the plot at the beginning of today. So if you want files modified between the beginning of today and 12:00, you need to know how long ago 12:00 was. Let's say it is 14:00, so it was 120 minutes ago:

```<code>find path -daystart -mmin -120
</code>```

Maybe this site will be of help for you.

Title: find command with daystart and mmin

Body:
On how to use mmin:

If you try to find what files were modified (m in mmin) between 2 and 6 minutes ago:

find path -mmin +2 -mmin -6

to use it with -daystart

daystart option set the plot at the beginning of today. So if you want files modified between the beginning of today and 12:00, you need to know how long ago 12:00 was. Let's say it is 14:00, so it was 120 minutes ago:

find path -daystart -mmin -120

Maybe this site will be of help for you.


问:
iOS:Objective-C:Output issue due to ipad time display 12Hour / 24Hour
In my application i am using one function to change date format to replace / with - and date format also.

When Device is set to 12 Hour, everything works fine. But when i set it to 24Hour it returns wrong value.

```<code>NSDate *newdate = [self convertDateSlashToDash:[obj valueForKey:@"TaskStartDateTime"]]);

//input date is  : 6/6/2017 6:38:00 PM
-(NSDate *)convertDateSlashToDash:(NSString *)dateStr{

if ([dateStr isKindOfClass:[NSDate class]]) {
    return (NSDate*)dateStr;
}

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
//Set the AM and PM symbols
[dateFormatter setAMSymbol:@"AM"];
[dateFormatter setPMSymbol:@"PM"];
//Specify only 1 M for month, 1 d for day and 1 h for hour
[dateFormatter setDateFormat:@"M/d/yyyy h:mm:ss a"];

// in ms 1469077819000 without ms 1469077819 for 7/21/2016 5:10:19 AM
NSTimeInterval ti = [[dateFormatter dateFromString:dateStr] timeIntervalSince1970];
NSDate *date = [NSDate dateWithTimeIntervalSince1970:ti];
NSDateFormatter *formatter= [[NSDateFormatter alloc] init];

// [formatter setLocale:[NSLocale currentLocale]];

[formatter setDateFormat:@"yyyy-MM-dd hh:mm:ss aa"];
NSString *dateString = [formatter stringFromDate:date];
NSDate *parsedDate = [formatter dateFromString:dateString];

return dateString;
}
 //output of this is (24hrs): 1970-01-01 05:30:00AM

 //output of this is (12hrs): 2017-06-06 06:38:00 PM
</code>```

Why it is not working?
Please suggest.

Thank you.

答:
Please add this line to your code to resolve that problem

```<code>[dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];
</code>```

Reade more: https://developer.apple.com/library/content/qa/qa1480/_index.html

Body:
In my application i am using one function to change date format to replace / with - and date format also.

When Device is set to 12 Hour, everything works fine. But when i set it to 24Hour it returns wrong value.

NSDate *newdate = [self convertDateSlashToDash:[obj valueForKey:@"TaskStartDateTime"]]);

//input date is  : 6/6/2017 6:38:00 PM
-(NSDate *)convertDateSlashToDash:(NSString *)dateStr{

if ([dateStr isKindOfClass:[NSDate class]]) {
    return (NSDate*)dateStr;
}

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
//Set the AM and PM symbols
[dateFormatter setAMSymbol:@"AM"];
[dateFormatter setPMSymbol:@"PM"];
//Specify only 1 M for month, 1 d for day and 1 h for hour
[dateFormatter setDateFormat:@"M/d/yyyy h:mm:ss a"];

// in ms 1469077819000 without ms 1469077819 for 7/21/2016 5:10:19 AM
NSTimeInterval ti = [[dateFormatter dateFromString:dateStr] timeIntervalSince1970];
NSDate *date = [NSDate dateWithTimeIntervalSince1970:ti];
NSDateFormatter *formatter= [[NSDateFormatter alloc] init];

// [formatter setLocale:[NSLocale currentLocale]];

[formatter setDateFormat:@"yyyy-MM-dd hh:mm:ss aa"];
NSString *dateString = [formatter stringFromDate:date];
NSDate *parsedDate = [formatter dateFromString:dateString];

return dateString;
}
 //output of this is (24hrs): 1970-01-01 05:30:00AM

 //output of this is (12hrs): 2017-06-06 06:38:00 PM

Why it is not working?
Please suggest.

Thank you.

Body:
Please add this line to your code to resolve that problem

[dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];

Reade more: https://developer.apple.com/library/content/qa/qa1480/_index.html


问:
Rolling correlation between lists in R
I have two lists, listA and listB which I would like to calculate the correlation between them using a rolling window of size 4.

```<code>listA
    A   B   C   D
1)  1   3   4   6
2)  6   9   11  1
3)  1   3   4   5
4)  8   4   5   6
5)  9   9   4   6
6)  1   5   6   6
7)  9   3   6   4
8)  6   7   8   9

listB
    A   B   C   D
1)  1   3   4   3
2)  6   9   5   7
3)  1   1   4   5
4)  7   1   5   6
5)  9   9   3   6
6)  1   5   6   6
7)  9   9   6   4
8)  5   6   4   9
</code>```

Specifically I wish to calculate the cor(listA[1:4,1],listB[1:4,1]) using a rolling window of size 4 which means I'll have 5 values for the correlation between listA and listB for column A. Once this is done for column A I then would like to do the same for column B, C and D.

I have previously achieved this using 'rollapplyr' but the object I was working on was an XTS object and not two individual objects which for my simple little brain made it easier to comprehend.

```<code>'result <- rollapplyr(XTSobject, 4, cor, by.column = FALSE)'
</code>```

Can anyone suggest a way to do this between two lists?

Title: Rolling correlation between lists in R

Body:
I have two lists, listA and listB which I would like to calculate the correlation between them using a rolling window of size 4.

listA
    A   B   C   D
1)  1   3   4   6
2)  6   9   11  1
3)  1   3   4   5
4)  8   4   5   6
5)  9   9   4   6
6)  1   5   6   6
7)  9   3   6   4
8)  6   7   8   9

listB
    A   B   C   D
1)  1   3   4   3
2)  6   9   5   7
3)  1   1   4   5
4)  7   1   5   6
5)  9   9   3   6
6)  1   5   6   6
7)  9   9   6   4
8)  5   6   4   9

Specifically I wish to calculate the cor(listA[1:4,1],listB[1:4,1]) using a rolling window of size 4 which means I'll have 5 values for the correlation between listA and listB for column A. Once this is done for column A I then would like to do the same for column B, C and D.

I have previously achieved this using 'rollapplyr' but the object I was working on was an XTS object and not two individual objects which for my simple little brain made it easier to comprehend.

'result <- rollapplyr(XTSobject, 4, cor, by.column = FALSE)'

Can anyone suggest a way to do this between two lists?

Body:
Using the data from the answer of Lukasz Derylo you can also try:

set.seed(1234)
listA<-data.frame(matrix(rnorm(32), c(8,4)))
listB<-data.frame(matrix(rnorm(32), c(8,4)))
do.call(cbind, Map(function(x, y) sapply(1:5, function(z) cor(x[z:(z+3)], y[z:(z+3)])), listA, listB))
             X1         X2         X3         X4
[1,] -0.2193800  0.3119567 0.31504929  0.7475560
[2,] -0.2669925 -0.4210403 0.43135275  0.9510322
[3,] -0.5657515 -0.6421284 0.82403697  0.2723139
[4,] -0.3829411 -0.6975032 0.09799502 -0.1750354
[5,] -0.8950722 -0.2397563 0.49121024 -0.5240474