问:
How to set useMongoClient (Mongoose 4.11.0)?
This is the code I use to connect to my database:

```<code>private connectDatabase(databaseUri: string): Promise<Mongoose.Connection> {
    return Mongoose.connect(databaseUri).then(() => {
        debug('Connected to MongoDB at %O', databaseUri);
        return Mongoose.connection;
    });
}
</code>```

Today I updated Mongoose to version 4.11.0 and I got this warning when running my tests:

```<code>(node:4138) DeprecationWarning: `open()` is deprecated in mongoose >= 4.11.0,
use `openUri()` instead, or set the `useMongoClient` option if using `connect()`
or `createConnection()`
</code>```

I can't find any information on how to "set useMongoClient".

Do you guys know how to?

答:
Without Typescript you can pretty much ignore the issue and use Mongoose.connect(databaseUri, { useMongoClient: true }).

If you really want to avoid having the warning avoid the version 4.11.0.

I updated to version 4.11.1 and since @types/mongoose@4.7.18 are not yet updated and they do not mention the field useMongoClient in the ConnectionOptions, this is how i imported the module:

```<code>const Mongoose = require('mongoose');
</code>```

And then used this function:

```<code>private connectDatabase(databaseUri: string): Promise<any> {
    return Mongoose.connect(databaseUri, { useMongoClient: true })
        .then(() => {
            console.log('Connected to MongoDB at ', databaseUri);
            return Mongoose.connection;
        })
        .catch(err => debug(`Database connection error: ${err.message}`));
}
</code>```

Body:
This is the code I use to connect to my database:

private connectDatabase(databaseUri: string): Promise<Mongoose.Connection> {
    return Mongoose.connect(databaseUri).then(() => {
        debug('Connected to MongoDB at %O', databaseUri);
        return Mongoose.connection;
    });
}

Today I updated Mongoose to version 4.11.0 and I got this warning when running my tests:

(node:4138) DeprecationWarning: `open()` is deprecated in mongoose >= 4.11.0,
use `openUri()` instead, or set the `useMongoClient` option if using `connect()`
or `createConnection()`

I can't find any information on how to "set useMongoClient".

Do you guys know how to?

Body:
Without Typescript you can pretty much ignore the issue and use Mongoose.connect(databaseUri, { useMongoClient: true }).

If you really want to avoid having the warning avoid the version 4.11.0.

I updated to version 4.11.1 and since @types/mongoose@4.7.18 are not yet updated and they do not mention the field useMongoClient in the ConnectionOptions, this is how i imported the module:

const Mongoose = require('mongoose');

And then used this function:

private connectDatabase(databaseUri: string): Promise<any> {
    return Mongoose.connect(databaseUri, { useMongoClient: true })
        .then(() => {
            console.log('Connected to MongoDB at ', databaseUri);
            return Mongoose.connection;
        })
        .catch(err => debug(`Database connection error: ${err.message}`));
}


来源: stackexchange

问:
C++ cannot initialize temporary with initializer list
I have a class defining a data structure (let's call it A) and I want to create a simple iterator for it with some basic operations (next, prev, element, valid...).

Iterator.h

```<code>#include "A.h"

class Iterator {
private:
    A* a;
    int current;
public:
    Iterator(A* _a) : a(_a) { current = 0; }
};
</code>```

In my class A, I created a function iterator() which should return an iterator and I thought about something like this:

A.h

```<code>#pragma once
#include "Iterator.h"

class A {
private:
    int some_data;
public:
    friend class Iterator;
    A(int x) : some_data(x) {}
    ~A();

    Iterator iterator() { return Iterator{ this }; }
};
</code>```

But I get this error: "Cannot initialize temporary of type "Iterator" with initializer list". All I want to do is to create and return an Iterator object from the iterator() function in class A.

Note: I have these classes in separate headers in my project. I use Visual Studio.

答:
You have a cyclic dependency. Your A.h includes Iterator.h and vice versa. The result, due to the #pragma once not doing quite what you expected, is that the compiler attempts to compile

```<code>class Iterator {
private:
    A* a;
    int current;
public:
    Iterator(A* _a) : a(_a) { current = 0; }
};

class A {
private:
    int some_data;
public:
    A(int x) : some_data(x) {}
    ~A();

    Iterator iterator() { return Iterator{ this }; }
};
</code>```

This fails, because it uses A before A has been defined. It fails with very confusing error messages, but you were only looking at the last of them, whereas the first error message at least points to where the problem is.

Instead of having Iterator.h include A.h, provide a forward declaration of A:

```<code>class A;
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a class defining a data structure (let's call it A) and I want to create a simple iterator for it with some basic operations (next, prev, element, valid...).

Iterator.h

#include "A.h"

class Iterator {
private:
    A* a;
    int current;
public:
    Iterator(A* _a) : a(_a) { current = 0; }
};

In my class A, I created a function iterator() which should return an iterator and I thought about something like this:

A.h

#pragma once
#include "Iterator.h"

class A {
private:
    int some_data;
public:
    friend class Iterator;
    A(int x) : some_data(x) {}
    ~A();

    Iterator iterator() { return Iterator{ this }; }
};

But I get this error: "Cannot initialize temporary of type "Iterator" with initializer list". All I want to do is to create and return an Iterator object from the iterator() function in class A.

Note: I have these classes in separate headers in my project. I use Visual Studio.

Body:
You have a cyclic dependency. Your A.h includes Iterator.h and vice versa. The result, due to the #pragma once not doing quite what you expected, is that the compiler attempts to compile

class Iterator {
private:
    A* a;
    int current;
public:
    Iterator(A* _a) : a(_a) { current = 0; }
};

class A {
private:
    int some_data;
public:
    A(int x) : some_data(x) {}
    ~A();

    Iterator iterator() { return Iterator{ this }; }
};

This fails, because it uses A before A has been defined. It fails with very confusing error messages, but you were only looking at the last of them, whereas the first error message at least points to where the problem is.

Instead of having Iterator.h include A.h, provide a forward declaration of A:

class A;


问:
Combining OpenGL ES and View-Based Application
How to combine OpenGL ES application with a View-Based Application for iPhone?</p>

答:
You really just link the two together by switching the view in UIWindow.

```<code>[window addSubview:yourView];
</code>```

It really is that easy. You just can't mix OpenGL ES and UIView drawing within the same view, unless you stop OpenGL ES animating of course.

Body:
You really just link the two together by switching the view in UIWindow.

[window addSubview:yourView];

It really is that easy. You just can't mix OpenGL ES and UIView drawing within the same view, unless you stop OpenGL ES animating of course.

ContentLicense: CC BY-SA 2.5


问:
No requests module error
I'm trying to write a web parser script using requests module. Here is my current code:

```<code>import requests
import subprocess
import json
import sys
import threading
import time
from Queue import Queue

numberOfViewers = int(sys.argv[1])
builderThreads = int(sys.argv[2])
startTime = time.time()
numberOfSockets = 0
concurrent = 25
urls = []
urlsUsed = []

def getURL(): # Get tokens
  output = subprocess.Popen(["livestreamer", "twitch.tv/CHANNEL_NAME", "-j"],
  stdout=subprocess.PIPE).communicate()[0]
  return json.loads(output)['streams']['worst']['url'] # Parse json and return the URL parameter

def build(): # Builds a set of tokens, aka viewers
  global numberOfSockets
  global numberOfViewers
  while True:
    if numberOfSockets < numberOfViewers:
      numberOfSockets += 1
      print ("Building viewers " + str(numberOfSockets) + "/" + str(numberOfViewers))
      urls.append(getURL())

def view(): # Opens connections to send views
  global numberOfSockets
  while True:
    url=q.get()
    requests.head(url)
    if (url in urlsUsed):
      urls.remove(url)
      urlsUsed.remove(url)
      numberOfSockets -= 1
    else:
      urlsUsed.append(url)
      q.task_done()

      if __name__ == '__main__':
        for i in range(0, builderThreads):
          threading.Thread(target = build).start()

          while True:
            while (numberOfViewers != numberOfSockets): # Wait until sockets are built
              time.sleep(1)

              q=Queue(concurrent*2)
              for i in range(concurrent):
                try:
                  t=threading.Thread(target=view)
                  t.daemon=True
                  t.start()
                except:
                  print ('thread error')
                  try:
                    for url in urls:
                      print (url)
                      q.put(url.strip())
                      q.join()
                  except KeyboardInterrupt:
                    sys.exit(1)
</code>```

But when I run the code, it says:

```<code>Traceback (most recent call last):
  File "C:\Users\flamelier\Desktop\Twitch.py", line 1, in <module>
    import requests
ImportError: No module named 'requests'
</code>```

Why am I getting this error? How do I install this module?
Will this error keep repeating for all the scripts henceforth?
How can I prevent such similar errors in the future?

答: Requests is a 3rd party module. You should first install it to Python using PIP or easy_install.</p>

Title: No requests module error

Body:
I'm trying to write a web parser script using requests module. Here is my current code:

import requests
import subprocess
import json
import sys
import threading
import time
from Queue import Queue

numberOfViewers = int(sys.argv[1])
builderThreads = int(sys.argv[2])
startTime = time.time()
numberOfSockets = 0
concurrent = 25
urls = []
urlsUsed = []

def getURL(): # Get tokens
  output = subprocess.Popen(["livestreamer", "twitch.tv/CHANNEL_NAME", "-j"],
  stdout=subprocess.PIPE).communicate()[0]
  return json.loads(output)['streams']['worst']['url'] # Parse json and return the URL parameter

def build(): # Builds a set of tokens, aka viewers
  global numberOfSockets
  global numberOfViewers
  while True:
    if numberOfSockets < numberOfViewers:
      numberOfSockets += 1
      print ("Building viewers " + str(numberOfSockets) + "/" + str(numberOfViewers))
      urls.append(getURL())

def view(): # Opens connections to send views
  global numberOfSockets
  while True:
    url=q.get()
    requests.head(url)
    if (url in urlsUsed):
      urls.remove(url)
      urlsUsed.remove(url)
      numberOfSockets -= 1
    else:
      urlsUsed.append(url)
      q.task_done()

      if __name__ == '__main__':
        for i in range(0, builderThreads):
          threading.Thread(target = build).start()

          while True:
            while (numberOfViewers != numberOfSockets): # Wait until sockets are built
              time.sleep(1)

              q=Queue(concurrent*2)
              for i in range(concurrent):
                try:
                  t=threading.Thread(target=view)
                  t.daemon=True
                  t.start()
                except:
                  print ('thread error')
                  try:
                    for url in urls:
                      print (url)
                      q.put(url.strip())
                      q.join()
                  except KeyboardInterrupt:
                    sys.exit(1)

But when I run the code, it says:

Traceback (most recent call last):
  File "C:\Users\flamelier\Desktop\Twitch.py", line 1, in <module>
    import requests
ImportError: No module named 'requests'

Why am I getting this error? How do I install this module?
Will this error keep repeating for all the scripts henceforth?
How can I prevent such similar errors in the future?


问:
Neo4j Cypher query and composite objects
I have a following Cypher query that returns all Decision that belong to a particular Tag:

```<code>MATCH (d:Decision)-[:BELONGS_TO]->(t:Tag) WHERE t.id = {tagId} RETURN d
</code>```

According to my business logic every Tag can have a set of synonyms:

```<code>(t:Tag)<-[:FOR]-(ts:TagSynonym)-[:HAS]->(s:Tag)
</code>```

and every s:Tag can also have a synonyms associated at the same way.. unlimited depth and where ts.approved = true.

Could you please show how to extend the first query in order to return not only Decisions associated with a start tag (t.id = {tagId}) but also the all Decisions associated with all tag's synonyms(unlimited depth).

Ideally all of these Decisions should be returned under one d variable.

Right now I'm playing with the following query:

```<code>MATCH p=(t:Tag)-[:FOR|HAS*]-(end:Tag)
WHERE t.id = {tagId} AND NOT (end)<-[:FOR]-()
OPTIONAL MATCH (d:Decision)-[:BELONGS_TO]->(tag)
RETURN d
</code>```

but it doesn't work.

UPDATED

I have created a Neo4j sandbox:

```<code>http://54.165.53.29:33761/browser/
neo4j
timer-rocks-hilltop
</code>```

Please use the following query:

```<code>MATCH p=(t:Tag)-[:FOR|HAS*0..]-(end:Tag)
WHERE t.id = 1 AND NOT (end)<-[:FOR]-()
MATCH (d:Decision)-[:BELONGS_TO]->(end)
RETURN d
</code>```

It returns only the last Decision in the path(Decision3) but should also return Decision1 and Decision 2.

This is the sample database username/password: neo4j/neo4j1

I have a 3 Tag and 3 Decision associated with this tag.

Also

Tag 2 is a synonym of Tag 1 and Tag 3 is a synonym of Tag 2.

I need to find all of the Decision by Tag 1 and by its synonyms(Tag 2 and Tag 3). This is decisions: Decision1, Decision2, Decision 3

答:
There is a subtle thing with variable depth traversals which is the zero depth :

```<code>MATCH p=(t:Tag)-[:FOR|HAS*0..]-(end:Tag)
WHERE t.id = {tagId} AND NOT (end)<-[:FOR]-()
MATCH (d:Decision)-[:BELONGS_TO]->(end)
RETURN d
</code>```

The idea is that, it handles both the cases where t nodes have a FOR or HAS relationships and when they not. The trick is that found tags (even the t node hence the 0) are under the end alias.

You can find a more in depth documentation about variable length relationships in this article : https://graphaware.com/graphaware/2015/05/19/neo4j-cypher-variable-length-relationships-by-example.html

EDIT

It seems the logic for finding the Tag nodes is wrong on your side, the query returns only one Tag due to this part in the query AND NOT (end)<-[:FOR]-(). Remove it and you'll see it returns 3 Decisions

Body:
I have a following Cypher query that returns all Decision that belong to a particular Tag:

MATCH (d:Decision)-[:BELONGS_TO]->(t:Tag) WHERE t.id = {tagId} RETURN d

According to my business logic every Tag can have a set of synonyms:

(t:Tag)<-[:FOR]-(ts:TagSynonym)-[:HAS]->(s:Tag)

and every s:Tag can also have a synonyms associated at the same way.. unlimited depth and where ts.approved = true.

Could you please show how to extend the first query in order to return not only Decisions associated with a start tag (t.id = {tagId}) but also the all Decisions associated with all tag's synonyms(unlimited depth).

Ideally all of these Decisions should be returned under one d variable.

Right now I'm playing with the following query:

MATCH p=(t:Tag)-[:FOR|HAS*]-(end:Tag)
WHERE t.id = {tagId} AND NOT (end)<-[:FOR]-()
OPTIONAL MATCH (d:Decision)-[:BELONGS_TO]->(tag)
RETURN d

but it doesn't work.

UPDATED

I have created a Neo4j sandbox:

http://54.165.53.29:33761/browser/
neo4j
timer-rocks-hilltop

Please use the following query:

MATCH p=(t:Tag)-[:FOR|HAS*0..]-(end:Tag)
WHERE t.id = 1 AND NOT (end)<-[:FOR]-()
MATCH (d:Decision)-[:BELONGS_TO]->(end)
RETURN d

It returns only the last Decision in the path(Decision3) but should also return Decision1 and Decision 2.

This is the sample database username/password: neo4j/neo4j1

I have a 3 Tag and 3 Decision associated with this tag.

Also

Tag 2 is a synonym of Tag 1 and Tag 3 is a synonym of Tag 2.

I need to find all of the Decision by Tag 1 and by its synonyms(Tag 2 and Tag 3). This is decisions: Decision1, Decision2, Decision 3

Body:
There is a subtle thing with variable depth traversals which is the zero depth :

MATCH p=(t:Tag)-[:FOR|HAS*0..]-(end:Tag)
WHERE t.id = {tagId} AND NOT (end)<-[:FOR]-()
MATCH (d:Decision)-[:BELONGS_TO]->(end)
RETURN d

The idea is that, it handles both the cases where t nodes have a FOR or HAS relationships and when they not. The trick is that found tags (even the t node hence the 0) are under the end alias.

You can find a more in depth documentation about variable length relationships in this article : https://graphaware.com/graphaware/2015/05/19/neo4j-cypher-variable-length-relationships-by-example.html

EDIT

It seems the logic for finding the Tag nodes is wrong on your side, the query returns only one Tag due to this part in the query AND NOT (end)<-[:FOR]-(). Remove it and you'll see it returns 3 Decisions


问:
C++ custom exception message not displaying
I am trying to create a custom exception class, throw it, and display the error message, but I am doing something wrong, causing the exception to not get thrown and the message to not get printed.

Here's the exception class:

```<code>class UnbalancedParenthesesException : public std::exception {
  int line_number {0};
public:
  UnbalancedParenthesesException(int line_number) :
    line_number { line_number }
    {}

  virtual const char* what() const throw() {
    std::string exception_message =
      "Papentheses imbalance at line " + std::to_string(line_number) + "\n";

    return exception_message.c_str();
  }
};
</code>```

I am trying totry/throw/catch as follows:

```<code>void handle_closed_paren(int line_number) {
  try {
    if (definitely_unbalanced()) {
      throw UnbalancedParenthesesException(line_number);
    }
  } catch (const UnbalancedParenthesesException& e) {
      std::out << e.what() << "\n";
}
</code>```

There is nothing pertinent to this error in the console.

Thanks in advance.

答:
Your program has undefined behaviour as you are returning the result of c_str() on a std::string that goes out of scope. Anything could happen.

Beyond that, if you're not seeing an exception then one was not thrown, probably because the result of definitely_unbalanced() is falsey.

Step through your program using your debugger.

Body:
I am trying to create a custom exception class, throw it, and display the error message, but I am doing something wrong, causing the exception to not get thrown and the message to not get printed.

Here's the exception class:

class UnbalancedParenthesesException : public std::exception {
  int line_number {0};
public:
  UnbalancedParenthesesException(int line_number) :
    line_number { line_number }
    {}

  virtual const char* what() const throw() {
    std::string exception_message =
      "Papentheses imbalance at line " + std::to_string(line_number) + "\n";

    return exception_message.c_str();
  }
};

I am trying totry/throw/catch as follows:

void handle_closed_paren(int line_number) {
  try {
    if (definitely_unbalanced()) {
      throw UnbalancedParenthesesException(line_number);
    }
  } catch (const UnbalancedParenthesesException& e) {
      std::out << e.what() << "\n";
}

There is nothing pertinent to this error in the console.

Thanks in advance.


问:
Why doesn't my selection sort algorithm do what it's supposed to (java)?
In the last hours I have tried to write the selection sort algorithm in Java without looking at finished code. I just read how the algorithm works (by words).

I won't copy paste the explanation but rather depict it (to check if I understood it):

-We have one unsorted array A and an empty array B (which has the same size as A)

-Now take the unsorted array A and find its smallest element. Smallest element found, now switch this element with the first element of the unsorted array A

-Put the first element (=smallest element of array A) into the array B

-Repeat till we are done with every element of A

I tried to code that in Java:

```<code>public class Selectionsort{

    public static void main(String[] args) {
        int[] myArray = {9,6,1,3,0,4,2};
        int[] B = new int[myArray.length];

        for(int i=0; i<myArray.length; i++) {
            B[i]=findMIN(myArray, i);
        }
    }

    static int findMIN(int[] A, int c) {
        int x = A[c];
        while(c<A.length) {
            if(x>A[c]) {
                x=A[c];
            }
            c++;
        }
        return x;
    }
}
</code>```

But I get a weird output:

```<code>0 0 0 0 0 2 2
</code>```

答:
"Smallest element found, now switch this element with the first element of the unsorted array A". So, you must switch the first element with the smallest element. You can use the code like this:

```<code>static int findMIN(int[] A, int c) {
    int first = c; // The first element's id
    int id = c; // An id of the smallest element
    int x = A[c];
    while(c<A.length) {
        if(x>A[c]) {
            x=A[c];
            id = c;
        }
        c++;
    }

    // Switching the first element with the smallest element
    int tmp = A[first];
    A[first] = A[id];
    A[id] = tmp;

    return x;
}
</code>```

It works perfectly. Also check @VidorVistrom's answer, if you don't understand why does your code work as it works.

Body:
In the last hours I have tried to write the selection sort algorithm in Java without looking at finished code. I just read how the algorithm works (by words).

I won't copy paste the explanation but rather depict it (to check if I understood it):

-We have one unsorted array A and an empty array B (which has the same size as A)

-Now take the unsorted array A and find its smallest element. Smallest element found, now switch this element with the first element of the unsorted array A

-Put the first element (=smallest element of array A) into the array B

-Repeat till we are done with every element of A

I tried to code that in Java:

public class Selectionsort{

    public static void main(String[] args) {
        int[] myArray = {9,6,1,3,0,4,2};
        int[] B = new int[myArray.length];

        for(int i=0; i<myArray.length; i++) {
            B[i]=findMIN(myArray, i);
        }
    }

    static int findMIN(int[] A, int c) {
        int x = A[c];
        while(cA[c]) {
                x=A[c];
            }
            c++;
        }
        return x;
    }
}

But I get a weird output:

0 0 0 0 0 2 2

Body:
"Smallest element found, now switch this element with the first element of the unsorted array A". So, you must switch the first element with the smallest element. You can use the code like this:

static int findMIN(int[] A, int c) {
    int first = c; // The first element's id
    int id = c; // An id of the smallest element
    int x = A[c];
    while(c<A.length) {
        if(x>A[c]) {
            x=A[c];
            id = c;
        }
        c++;
    }

    // Switching the first element with the smallest element
    int tmp = A[first];
    A[first] = A[id];
    A[id] = tmp;

    return x;
}

It works perfectly. Also check @VidorVistrom's answer, if you don't understand why does your code work as it works.


问:
How do I put extra number at the end of username if duplicate
Hard to explain, and let me show an example.

If username foo already exists in MySQL I want php script will allow it but to be foo1

Then if foo1 exists too, script will generate the username will be foo2

If foo2 existed then become foo3

How to make like that?

Like Col. Shrapnel said Natural increment which seems more sensible. just like "New Folder(3)" stuff in Windows

答:
First, check if the desired username exists in the database:

```<code>SELECT COUNT(*) AS numRows FROM table
WHERE SUBSTRING(username, 1, CHAR_LENGTH(desiredUserName)) = desiredUserName
</code>```

If numRows is 0, you can leave the username as it is.  If it is 1 you can just add '1' to the end of the username.  It gets a bit more complicated if numRows > 1.  You would need to get the current maxmium number which appends that user name:

```<code>SELECT CAST(SUBSTRING(username,(CHAR_LENGTH(desiredUserName) + 1)) AS SIGNED) AS maxNum
FROM table
WHERE SUBSTRING(username,1,CHAR_LENGTH(desiredUserName)) = desiredUserName
ORDER BY CAST(SUBSTRING(username,(CHAR_LENGTH(desiredUserName) + 1)) AS SIGNED) DESC
LIMIT 1
</code>```

Now you just need to add 1 to the returned maxNum and append that to the desired username

Body:
First, check if the desired username exists in the database:

SELECT COUNT(*) AS numRows FROM table
WHERE SUBSTRING(username, 1, CHAR_LENGTH(desiredUserName)) = desiredUserName

If numRows is 0, you can leave the username as it is.  If it is 1 you can just add '1' to the end of the username.  It gets a bit more complicated if numRows > 1.  You would need to get the current maxmium number which appends that user name:

SELECT CAST(SUBSTRING(username,(CHAR_LENGTH(desiredUserName) + 1)) AS SIGNED) AS maxNum
FROM table
WHERE SUBSTRING(username,1,CHAR_LENGTH(desiredUserName)) = desiredUserName
ORDER BY CAST(SUBSTRING(username,(CHAR_LENGTH(desiredUserName) + 1)) AS SIGNED) DESC
LIMIT 1

Now you just need to add 1 to the returned maxNum and append that to the desired username


问:
Efficient way to convert all data frame columns in Scala
I am trying to do type cast of all data frame columns based on an input as shown below, how can I do this with a single command that converts all data frame columns? The following code works fine, but I need a generic command that works for any data frame. Thanks in advance for your kind suggestions.</p>

```<code>    for (colIndex <- 0 to tmpDF.columns.length - 1) {

      val columns = df.columns
      newdf = df.withColumn(columns(0), df(columns(0)).cast(dataType(0)))
        .withColumn(columns(1), df(columns(1)).cast(dataType(1)))
        .withColumn(columns(2), df(columns(2)).cast(dataType(2)))
        .withColumn(columns(3), df(columns(3)).cast(dataType(3)))
        .withColumn(columns(4), df(columns(4)).cast(dataType(4)))

   //  newdf = df.withColumn(columns(colIndex), df(columns(colIndex)).cast(dataType(colIndex))) --> This didn't work, only last column was updated

}
</code>```

答:
Both answers are doing many withColumn - there are ok, but each withColumn adds Projection to query plan. It's better to do one big select:

```<code>val columns = df.columns
val columnsNew = new Array[Column]
for (colIndex <- tmpDF.columns.indices) {
    columnsNew(colIndex) = columns(colIndex), df(columns(colIndex)).cast(dataType(colIndex)))
}
var newDF = df.select(columnsNew :_*)
</code>```

You should have only one projection, so it can be faster on very large dataset - CodeGen deal better with less amount of projections in query plan, that's why it's better to do single select with multiple columns :)

Body:
I am trying to do type cast of all data frame columns based on an input as shown below, how can I do this with a single command that converts all data frame columns? The following code works fine, but I need a generic command that works for any data frame. Thanks in advance for your kind suggestions.

    for (colIndex <- 0 to tmpDF.columns.length - 1) {

      val columns = df.columns
      newdf = df.withColumn(columns(0), df(columns(0)).cast(dataType(0)))
        .withColumn(columns(1), df(columns(1)).cast(dataType(1)))
        .withColumn(columns(2), df(columns(2)).cast(dataType(2)))
        .withColumn(columns(3), df(columns(3)).cast(dataType(3)))
        .withColumn(columns(4), df(columns(4)).cast(dataType(4)))

   //  newdf = df.withColumn(columns(colIndex), df(columns(colIndex)).cast(dataType(colIndex))) --> This didn't work, only last column was updated

}

Body:
Both answers are doing many withColumn - there are ok, but each withColumn adds Projection to query plan. It's better to do one big select:

val columns = df.columns
val columnsNew = new Array[Column]
for (colIndex <- tmpDF.columns.indices) {
    columnsNew(colIndex) = columns(colIndex), df(columns(colIndex)).cast(dataType(colIndex)))
}
var newDF = df.select(columnsNew :_*)

You should have only one projection, so it can be faster on very large dataset - CodeGen deal better with less amount of projections in query plan, that's why it's better to do single select with multiple columns :)


答:
Why doesn't my selection sort algorithm do what it's supposed to
  (java)?

Lets see whats happening:

```<code>   c         A[c]       Returned X
-----------------------------------
   0          9            0(Since minElement is 0 with index >= 0)
   1          6            0(Since minElement is 0 with index >= 1)
   2          1            0(Since minElement is 0 with index >= 2)
   3          3            0(Since minElement is 0 with index >= 3)
   4          0            0(Since minElement is 0 with index >= 4)
   5          4            2(Since minElement is 2 with index >= 5)
   6          2            2(Since minElement is 2 with index >= 6)
</code>```

Body:
Why doesn't my selection sort algorithm do what it's supposed to
  (java)?

Lets see whats happening:

   c         A[c]       Returned X
-----------------------------------
   0          9            0(Since minElement is 0 with index >= 0)
   1          6            0(Since minElement is 0 with index >= 1)
   2          1            0(Since minElement is 0 with index >= 2)
   3          3            0(Since minElement is 0 with index >= 3)
   4          0            0(Since minElement is 0 with index >= 4)
   5          4            2(Since minElement is 2 with index >= 5)
   6          2            2(Since minElement is 2 with index >= 6)


问:
Using c++ typedef/using type alias
I am reading C++ primer book and completely don't understand one line:

```<code> using int_array = int[4];
 typedef int int_array[4]; // This line
 for (int_array *p = ia; p != ia + 3; ++p) {
      for (int *q = *p; q != *p + 4; ++q)
          cout << *q << ' '; cout << endl;
 }
</code>```

Ok typedef is same as using. Does it mean int[4][4] is now int and how to understand that? And what type is int_array in for loop?

Thanks

答:
TL;DR

Both are doing the exact same thing: Defining int_array as an alias of an array of 4 ints

Making Sense of the Syntax

using has a nice A = B notation that is generally much easier to understand.

```<code>using alias = type;
</code>```

typedef's notation is not quite backward. For a simple typedef

```<code>typedef type alias;
</code>```

but more complicated typedefs tend to sprawl. I suspect the syntax was modeled after how one would define a variable, but I can't find where I packed my copy of the old K&R C programming book and can't look that up at the moment.

```<code>int int_array[4];
</code>```

would define int_array to be an array of 4 ints. Slapping typedef on the front

```<code>typedef int int_array[4];
</code>```

makes int_array a type alias instead of a variable.

Another example,

```<code>int * intp;
</code>```

Defines intp to be a pointer to an int.

```<code>typedef int * intp;
</code>```

Defines intp to be an alias to the type pointer to an int.

This gets ugly with more complicated data types as the name of the typedefed alias may be buried somewhere in the middle of the definition. A typedefed function pointer for example:

```<code>typedef void (*funcp)(param_t param1, param_t param2, ...);
</code>```

vs using

```<code>using funcp = void (*)(param_t param1, param_t param2, ...);
</code>```

Making a 2D Array

If you want a 2D array you could

```<code>using int_array2D = int[4][4];
</code>```

or you could define an array of int_array

```<code>using int_array2D = int_array[4];
</code>```

And of course that means you can

```<code>typedef type alias;
</code>```0

and keep on going until the cows come home or you've packed on so many dimensions that The Doctor's brain melts.

ContentLicense: CC BY-SA 4.0

Title: Using c++ typedef/using type alias

Body:
I am reading C++ primer book and completely don't understand one line:

 using int_array = int[4];
 typedef int int_array[4]; // This line
 for (int_array *p = ia; p != ia + 3; ++p) {
      for (int *q = *p; q != *p + 4; ++q)
          cout << *q << ' '; cout << endl;
 }

Ok typedef is same as using. Does it mean int[4][4] is now int and how to understand that? And what type is int_array in for loop?

Thanks

Body:
TL;DR

Both are doing the exact same thing: Defining int_array as an alias of an array of 4 ints

Making Sense of the Syntax

using has a nice A = B notation that is generally much easier to understand.

using alias = type;

typedef's notation is not quite backward. For a simple typedef

typedef type alias;

but more complicated typedefs tend to sprawl. I suspect the syntax was modeled after how one would define a variable, but I can't find where I packed my copy of the old K&R C programming book and can't look that up at the moment.

int int_array[4];

would define int_array to be an array of 4 ints. Slapping typedef on the front

typedef int int_array[4];

makes int_array a type alias instead of a variable.

Another example,

int * intp;

Defines intp to be a pointer to an int.

typedef int * intp;

Defines intp to be an alias to the type pointer to an int.

This gets ugly with more complicated data types as the name of the typedefed alias may be buried somewhere in the middle of the definition. A typedefed function pointer for example:

typedef void (*funcp)(param_t param1, param_t param2, ...);

vs using

using funcp = void (*)(param_t param1, param_t param2, ...);

Making a 2D Array

If you want a 2D array you could

using int_array2D = int[4][4];

or you could define an array of int_array

using int_array2D = int_array[4];

And of course that means you can

using int_array3D = int_array2D[4];

and keep on going until the cows come home or you've packed on so many dimensions that The Doctor's brain melts.


问:
How to properly output a string in a Windows console with go?
I have a exe in go which prints utf-8 encoded strings, with special characters in it.

Since that exe is made to be used from a console window, its output is mangled because Windows uses ibm850 encoding (aka code page 850).

How would you make sure the go exe print correctly encoded strings for a console windows, ie print for instance:

```<code>éèïöîôùòèìë
</code>```

instead of (without any translation to the right charset)

```<code>├®├¿├»├Â├«├┤├╣├▓├¿├¼├½
</code>```

答:
Since 2016, You can now (2017) consider the golang.org/x/text, which comes with a encoding charmap including the ISO-8859 family as well as the Windows 1252 character set.

See "Go Quickly - Converting Character Encodings In Golang"

```<code>r := charmap.ISO8859_1.NewDecoder().Reader(f)
io.Copy(out, r)
</code>```

That is an extract of an example opening a ISO-8859-1 source text (my_isotext.txt), creating a destination file (my_utf.txt), and copying the first to the second.

But to decode from ISO-8859-1 to UTF-8, we wrap the original file reader (f) with a decoder.

I just tested (pseudo-code for illustration):

package main

import (
    "fmt"

    "golang.org/x/text/encoding"
    "golang.org/x/text/encoding/charmap"
)

func main() {
    t := "string composed of character in cp 850"
    d := charmap.CodePage850.NewDecoder()
    st, err := d.String(t)
    if err != nil {
        panic(err)
    }
    fmt.Println(st)
}
```

The result is a string readable in a Windows CMD.

See more in this Nov. 2018 reddit thread.

Body:
I have a exe in go which prints utf-8 encoded strings, with special characters in it.

Since that exe is made to be used from a console window, its output is mangled because Windows uses ibm850 encoding (aka code page 850).

How would you make sure the go exe print correctly encoded strings for a console windows, ie print for instance:

éèïöîôùòèìë

instead of (without any translation to the right charset)

├®├¿├»├Â├«├┤├╣├▓├¿├¼├½

Body:
Since 2016, You can now (2017) consider the golang.org/x/text, which comes with a encoding charmap including the ISO-8859 family as well as the Windows 1252 character set.

See "Go Quickly - Converting Character Encodings In Golang"

r := charmap.ISO8859_1.NewDecoder().Reader(f)
io.Copy(out, r)

That is an extract of an example opening a ISO-8859-1 source text (my_isotext.txt), creating a destination file (my_utf.txt), and copying the first to the second.

But to decode from ISO-8859-1 to UTF-8, we wrap the original file reader (f) with a decoder.

I just tested (pseudo-code for illustration):

package main

import (
    "fmt"

    "golang.org/x/text/encoding"
    "golang.org/x/text/encoding/charmap"
)

func main() {
    t := "string composed of character in cp 850"
    d := charmap.CodePage850.NewDecoder()
    st, err := d.String(t)
    if err != nil {
        panic(err)
    }
    fmt.Println(st)
}

The result is a string readable in a Windows CMD.

See more in this Nov. 2018 reddit thread.


问:
Testing asyn calls throws Unhandled promise rejection in Node JS
I´m unit testing an Express function like this:

```<code>function(request,response,someDependency){
  ...
  someDependency.doStuff(arg1,arg2)
  .then(function(someResponse){
      response.status(200).send({body: someResponse});
  })
  .catch(function(error){
      response.status(500).send({someResponse: 'error');
  });
}
</code>```

In my unit tests (using Mocha), I have decided to mock my response, using assertions inside it, and also to mock my dependency:

An abstraction of my mockedResponse:

```<code>...
exports.expectedStatus = function(status){
  this.expectedCode = status;
}
exports.status = function(realStatus){
  this.expectdCode = realStatus;
  return this;
}
exports.send = function(body){
  assert.strictEqual(this.realStatus,this.expectedCode);
}
</code>```

and an abstraction of my dependency would be:

```<code>exports.setPromiseError(error){
  this.error = error;
};
exports.doStuff(arg1,arg2){
   return new Promise(function (resolve, reject){
      if (!error)
         resolve({this: 'is', a: 'response'});
      else
         reject(error);
     }});
</code>```

In my unit tests I have a test like this:

```<code>mockedResponse = require('./fake/assertiveResponse.js');
mockedDependency       = require('./fake/dependency.js');

it('should throw error',function(){
   mockedDependency.setPromiseError(new Error('sorry, not today');
   myLibUnderTest.myFunctionUnderTest(someFakeRequest,
                                       mockedResponse.get()
                                        .expectedStatus(200), <--I´m forcing a failing test here!
                                      mockedDependency);
});
</code>```

But...my assert appears to be swalled by the promise and I get a passing test with this console output:

```<code>(node:1512) UnhandledPromiseRejectionWarning: Unhandled promise rejection
(rejection id: 2): AssertionError: 500 === 200
</code>```

Right now I´m not even sure I´m using Promises the right way...any help is appreciated.

答:
That was totally a typo, I solved the issue by moving my assertions to a separate method and ensuring it's call using sinon spy. That and using a settimeout to make sure everything gets executed before my assertions with a minimum acceptable time.

Probably not the best...but at least I have my tests running ;)
Thanks for the help.

Body:
I´m unit testing an Express function like this:

function(request,response,someDependency){
  ...
  someDependency.doStuff(arg1,arg2)
  .then(function(someResponse){
      response.status(200).send({body: someResponse});
  })
  .catch(function(error){
      response.status(500).send({someResponse: 'error');
  });
}

In my unit tests (using Mocha), I have decided to mock my response, using assertions inside it, and also to mock my dependency:

An abstraction of my mockedResponse:

...
exports.expectedStatus = function(status){
  this.expectedCode = status;
}
exports.status = function(realStatus){
  this.expectdCode = realStatus;
  return this;
}
exports.send = function(body){
  assert.strictEqual(this.realStatus,this.expectedCode);
}

and an abstraction of my dependency would be:

exports.setPromiseError(error){
  this.error = error;
};
exports.doStuff(arg1,arg2){
   return new Promise(function (resolve, reject){
      if (!error)
         resolve({this: 'is', a: 'response'});
      else
         reject(error);
     }});

In my unit tests I have a test like this:

mockedResponse = require('./fake/assertiveResponse.js');
mockedDependency       = require('./fake/dependency.js');

it('should throw error',function(){
   mockedDependency.setPromiseError(new Error('sorry, not today');
   myLibUnderTest.myFunctionUnderTest(someFakeRequest,
                                       mockedResponse.get()
                                        .expectedStatus(200), <--I´m forcing a failing test here!
                                      mockedDependency);
});

But...my assert appears to be swalled by the promise and I get a passing test with this console output:

(node:1512) UnhandledPromiseRejectionWarning: Unhandled promise rejection
(rejection id: 2): AssertionError: 500 === 200

Right now I´m not even sure I´m using Promises the right way...any help is appreciated.


问:
cannot find my bean using the InitialContext.lookup() method
I have tried to use struts 1.3 API to make a small application with EJB 3.0. Unfortunatelly i cannot use the @EJB annotation to call my bean object from inside my action class. I have solved this problem using different workarounds ( the first one is to use my global jndi name of my bean and the other is to call another class first and use the @EJB annotation from that class). Still these two workarounds have significant disadvantages. I would like to call my EJB directly from my action class. I have read plenty examples using the "java:comp/env/beanName" JNDI name but still haven't figure out how to do it and get name not found axception.
Let the full name of the local EJB class be the com.ejb.myEjbPackage.MyEJBLocal, how can i call it using the context lookup? (can i do it without modifying any of the web.xml and sun-web.xml descriptors?)
I am using glassfish server and Netbeans IDE.

Thank you in advance

答:
I found the answer :
If you cannot use the EJB annotation in the class you want to call the bean then :
If you don't want to mess with XML descriptors to define your bean , you have to do it in the bean class itself.
Hence i used the following annotation in the GameBean class

```<code>     @Stateless
     @EJB(name="ejb/GameBean",beanInterface=GameBeanLocal.class,beanName="GameBean")
     public class GameBean implements GameBeanLocal {.....
</code>```

The beanName is optional. The annotation must be declared in the line ABOVE the declaration of the class.
Then, in order to call the bean from the other class you can do

```<code>     InitialContext ic = new InitialContext();
     ic.lookup("java:comp/env/ejb/GameBean");
</code>```

Body:
I found the answer :
If you cannot use the EJB annotation in the class you want to call the bean then :
If you don't want to mess with XML descriptors to define your bean , you have to do it in the bean class itself.
Hence i used the following annotation in the GameBean class

     @Stateless
     @EJB(name="ejb/GameBean",beanInterface=GameBeanLocal.class,beanName="GameBean")
     public class GameBean implements GameBeanLocal {.....

The beanName is optional. The annotation must be declared in the line ABOVE the declaration of the class.
Then, in order to call the bean from the other class you can do

     InitialContext ic = new InitialContext();
     ic.lookup("java:comp/env/ejb/GameBean");


问:
ASP.NET BoilerPlate: How do I inject object of DbContext in application service?
How do I inject object of DbContext in application service?

Need to access it to create clone of a entity record.

答:
The question is a little ambiguous, but here are a few things for you to consider:

Dependency Injection: AUTOFAC or NINJECT (for example)
This will allow you to inject your DbContext into any class via ctor or property to that you can use it.

Pass it as a parameter (how's your service generated?)

var appService = new ApplicationService(new MyDbContext())

Either one of those will work. If that wasn't what you meant, some more info will help :)


问:
How to fix open redirect issue in java
Currently my java code uses

```<code>response.sendRedirect(request.getRequestUrl().toString());
</code>```

Which is an open redirect.

I have to fix this but I can not white list it since there are too many URL's are associated with it.

I have tried the following solution with ESAPI but it wont work for me.

```<code>ESAPI.httpUtilities().setCurrentHTTP(req, resp);
ESAPI.httpUtilities().sendRedirect(location);
ESAPI.httpUtilities().clearCurrent();
</code>```

I am new to ESAPI.

答:
[Disclaimer]

I'm project co-lead on ESAPI.

I have to fix this but I can not white list it since there are too
  many URL's are associated with it.

Essentially, "I have to fix the problem, but I am restricting myself from the easiest solution."

Here are the best practices enumerated by @jww:

Simply avoid using redirects and forwards.

If used, do not allow the url as user input for the destination. This can usually be done. In this case, you should have a method to validate URL.

If user input can’t be avoided, ensure that the supplied value is valid, appropriate for the application, and is authorized for the user.

It is recommended that any such destination input be mapped to a value, rather than the actual URL or portion of the URL, and that server side code translate this value to the target URL.

Sanitize input by creating a list of trusted URL's (lists of hosts or a regex).

Force all redirects to first go through a page notifying users that they are going off of your site, and have them click a link to confirm.

These are literally all the solutions available to you.  Some web frameworks make this easy for you, like Spring MVC with Spring Security.

These lines:

```<code> ESAPI.httpUtilities().setCurrentHTTP(req, resp);
 ESAPI.httpUtilities().sendRedirect(location);
 ESAPI.httpUtilities().clearCurrent();
</code>```

Don't work because you have to inspect the user input before performing the redirect.

Title: How to fix open redirect issue in java

Body:
Currently my java code uses

response.sendRedirect(request.getRequestUrl().toString());

Which is an open redirect.

I have to fix this but I can not white list it since there are too many URL's are associated with it.

I have tried the following solution with ESAPI but it wont work for me.

ESAPI.httpUtilities().setCurrentHTTP(req, resp);
ESAPI.httpUtilities().sendRedirect(location);
ESAPI.httpUtilities().clearCurrent();

I am new to ESAPI.

Body:
[Disclaimer]

I'm project co-lead on ESAPI.

I have to fix this but I can not white list it since there are too
  many URL's are associated with it.

Essentially, "I have to fix the problem, but I am restricting myself from the easiest solution."

Here are the best practices enumerated by @jww:

Simply avoid using redirects and forwards.

If used, do not allow the url as user input for the destination. This can usually be done. In this case, you should have a method to validate URL.

If user input can’t be avoided, ensure that the supplied value is valid, appropriate for the application, and is authorized for the user.

It is recommended that any such destination input be mapped to a value, rather than the actual URL or portion of the URL, and that server side code translate this value to the target URL.

Sanitize input by creating a list of trusted URL's (lists of hosts or a regex).

Force all redirects to first go through a page notifying users that they are going off of your site, and have them click a link to confirm.

These are literally all the solutions available to you.  Some web frameworks make this easy for you, like Spring MVC with Spring Security.

These lines:

 ESAPI.httpUtilities().setCurrentHTTP(req, resp);
 ESAPI.httpUtilities().sendRedirect(location);
 ESAPI.httpUtilities().clearCurrent();

Don't work because you have to inspect the user input before performing the redirect.


问:
"macro names must be identifiers"
I get the above error message with the code that's shown below. It's for use with a JSN-SR04T sensor. I'm using an Arduino Uno with IDE version 1.8.2.0.

I changed pin numbers and took out all blank spaces just in case there were any embedded characters. Still get the error. Not sure of what else to do. Any suggestions?

Code:

/*
 * Ultrasonic Sensor HC-SR04 and Arduino Tutorial
 *
 * Created by Dejan Nedelkovski,
 * www.HowToMechatronics.com
 *
*/.
#define ECHOPIN 10
#define TRIGPIN 9

const int TRIGPIN = 9;
const int ECHOPIN = 10;
long duration;
int distance;

void setup() {
  pinMode(TRIGPIN, OUTPUT);
  pinMode(ECHOPIN, INPUT);
  Serial.begin(9600);
}

void loop() {
  digitalWrite(TRIGPIN, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIGPIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIGPIN, LOW);
  duration = pulseIn(ECHOPIN, HIGH);
  distance= duration*0.034/2;
  Serial.print("Distance: ");
  Serial.println(distance);
}
```

答:
If this is the original code you copied, then you can see that there are no macro definitions. In your example there are two macro definitions with the same name as the following const int declarations:

```<code>#define ECHOPIN 10
#define TRIGPIN 9

const int TRIGPIN = 9;
const int ECHOPIN = 10;
</code>```

The preprocessor will substitute every ECHOPIN and TRIGPIN macros with their value. Therefore after the preprocessor finished its job, the code snippet above will look like:

```<code>const int 9 = 9;
const int 10 = 10;
</code>```

Remove either the macros or the const int declarations from your code and it may work.

Title: "macro names must be identifiers"

Body:
If this is the original code you copied, then you can see that there are no macro definitions. In your example there are two macro definitions with the same name as the following const int declarations:

#define ECHOPIN 10
#define TRIGPIN 9

const int TRIGPIN = 9;
const int ECHOPIN = 10;

The preprocessor will substitute every ECHOPIN and TRIGPIN macros with their value. Therefore after the preprocessor finished its job, the code snippet above will look like:

const int 9 = 9;
const int 10 = 10;

Remove either the macros or the const int declarations from your code and it may work.


问:
Which type of path to store in MySQL database?
When I come to build a simple site using PHP and MySQL, what is the best method for storing paths of files and images?

Inserting paths to Mysql as (system path C:/----)

Inserting paths to Mysql as (HTTP path http://----)

答:
Just save the image name and let your application handle directory building.

Including the path whether, absolute, virtual or the web address will add an overhead of the file path data to each entry in the image field column.

If you must store this information in your database why not store it as a foreign key to a paths table.


问:
Laravel Multi Auth - Logical issue querying relationships for items owned by user_id
I have setup multi auth on my Laravel project. It's all working fine but I'm getting some crossed lines with the code I've already written.

I have tasks(todo's) which users own many of, so that I can use the following code.

```<code>public function index(Request $request)
{
    return view('task.index', [
        'tasks' => $this->tasks->forUser($request->user()),
    ]);
}
</code>```

My problem is that my different user types have the same ID's so when user_type_a with the id of 1 logs in they see the tasks of user_type_b with the same id.

I was going to just prefix the different user types with something e.g. user_type_a has the id of a_1 and user_type_b has the id of b_1. This doesn't seem like good practice though.

Any ideas?

答: I made a very simple multi-user system. All users in the same user table. The table has additional fields: is_admin, is_manager . If your have match more user roles - you can add additional table user_types. Then you can add scopes in model users like isAdmin(), isManger(), or etc. I did not have any problems belong developing this project. Everything is transparent and simple.</p>

Body:
I have setup multi auth on my Laravel project. It's all working fine but I'm getting some crossed lines with the code I've already written.

I have tasks(todo's) which users own many of, so that I can use the following code.

public function index(Request $request)
{
    return view('task.index', [
        'tasks' => $this->tasks->forUser($request->user()),
    ]);
}

My problem is that my different user types have the same ID's so when user_type_a with the id of 1 logs in they see the tasks of user_type_b with the same id.

I was going to just prefix the different user types with something e.g. user_type_a has the id of a_1 and user_type_b has the id of b_1. This doesn't seem like good practice though.

Any ideas?


问:
Have a UIContainerView point to a ViewController in another Storyboard?
I understand that UIContainerView can be used to embed a UIViewController inside another UIViewController in a Storyboard. However, I would like the embedded UIViewController to live in a different Storyboard file. Is this possible, and if so, how do I make the connection?

答:
You can do that by following the these steps:

In the Storyboard that contains the view controller you want to segue to, set the Storyboard ID for that view controller.

In the storyboard containing the container view, drag a Storyboard Reference from the Object library.

From the attribute inspector, set the Storyboard that contains the view controller you want to segue to, and set the Referenced ID to the ID you set in step 1.

Connect the embed segue between your container view and the storyboard reference like if it is a view controller in the same storyboard.

That's all!


问:
Is there any way to global hook the mouse actions like i'm hooking the keyboard keys?
This is the class i'm using for hooking the keyboard keys.

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

public class Hook : IDisposable
{
    bool Global = false;

    public delegate void LocalKeyEventHandler(Keys key, bool Shift, bool Ctrl, bool Alt);
    public event LocalKeyEventHandler KeyDown;
    public event LocalKeyEventHandler KeyUp;

    public delegate int CallbackDelegate(int Code, int W, int L);

    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
    public struct KBDLLHookStruct
    {
        public Int32 vkCode;
        public Int32 scanCode;
        public Int32 flags;
        public Int32 time;
        public Int32 dwExtraInfo;
    }

    [DllImport("user32", CallingConvention = CallingConvention.StdCall)]
    private static extern int SetWindowsHookEx(HookType idHook, CallbackDelegate lpfn, int hInstance, int threadId);

    [DllImport("user32", CallingConvention = CallingConvention.StdCall)]
    private static extern bool UnhookWindowsHookEx(int idHook);

    [DllImport("user32", CallingConvention = CallingConvention.StdCall)]
    private static extern int CallNextHookEx(int idHook, int nCode, int wParam, int lParam);

    [DllImport("kernel32.dll", CallingConvention = CallingConvention.StdCall)]
    private static extern int GetCurrentThreadId();

    public enum HookType : int
    {
        WH_JOURNALRECORD = 0,
        WH_JOURNALPLAYBACK = 1,
        WH_KEYBOARD = 2,
        WH_GETMESSAGE = 3,
        WH_CALLWNDPROC = 4,
        WH_CBT = 5,
        WH_SYSMSGFILTER = 6,
        WH_MOUSE = 7,
        WH_HARDWARE = 8,
        WH_DEBUG = 9,
        WH_SHELL = 10,
        WH_FOREGROUNDIDLE = 11,
        WH_CALLWNDPROCRET = 12,
        WH_KEYBOARD_LL = 13,
        WH_MOUSE_LL = 14
    }

    private int HookID = 0;
    CallbackDelegate TheHookCB = null;

    //Start hook
    public Hook(bool Global)
    {
        this.Global = Global;
        TheHookCB = new CallbackDelegate(KeybHookProc);
        if (Global)
        {
            HookID = SetWindowsHookEx(HookType.WH_KEYBOARD_LL, TheHookCB,
                0, //0 for local hook. eller hwnd til user32 for global
                0); //0 for global hook. eller thread for hooken
        }
        else
        {
            HookID = SetWindowsHookEx(HookType.WH_KEYBOARD, TheHookCB,
                0, //0 for local hook. or hwnd to user32 for global
                GetCurrentThreadId()); //0 for global hook. or thread for the hook
        }
    }

    bool IsFinalized = false;
    ~Hook()
    {
        if (!IsFinalized)
        {
            UnhookWindowsHookEx(HookID);
            IsFinalized = true;
        }
    }
    public void Dispose()
    {
        if (!IsFinalized)
        {
            UnhookWindowsHookEx(HookID);
            IsFinalized = true;
        }
    }

    //The listener that will trigger events
    private int KeybHookProc(int Code, int W, int L)
    {
        KBDLLHookStruct LS = new KBDLLHookStruct();
        if (Code < 0)
        {
            return CallNextHookEx(HookID, Code, W, L);
        }
        try
        {
            if (!Global)
            {
                if (Code == 3)
                {
                    IntPtr ptr = IntPtr.Zero;

                    int keydownup = L >> 30;
                    if (keydownup == 0)
                    {
                        if (KeyDown != null) KeyDown((Keys)W, GetShiftPressed(), GetCtrlPressed(), GetAltPressed());
                    }
                    if (keydownup == -1)
                    {
                        if (KeyUp != null) KeyUp((Keys)W, GetShiftPressed(), GetCtrlPressed(), GetAltPressed());
                    }
                    //System.Diagnostics.Debug.WriteLine("Down: " + (Keys)W);
                }
            }
            else
            {
                KeyEvents kEvent = (KeyEvents)W;

                Int32 vkCode = Marshal.ReadInt32((IntPtr)L); //Leser vkCode som er de første 32 bits hvor L peker.

                if (kEvent != KeyEvents.KeyDown && kEvent != KeyEvents.KeyUp && kEvent != KeyEvents.SKeyDown && kEvent != KeyEvents.SKeyUp)
                {
                }
                if (kEvent == KeyEvents.KeyDown || kEvent == KeyEvents.SKeyDown)
                {
                    if (KeyDown != null) KeyDown((Keys)vkCode, GetShiftPressed(), GetCtrlPressed(), GetAltPressed());
                }
                if (kEvent == KeyEvents.KeyUp || kEvent == KeyEvents.SKeyUp)
                {
                    if (KeyUp != null) KeyUp((Keys)vkCode, GetShiftPressed(), GetCtrlPressed(), GetAltPressed());
                }
            }
        }
        catch (Exception)
        {
            //Ignore all errors...
        }

        return CallNextHookEx(HookID, Code, W, L);

    }

    public enum KeyEvents
    {
        KeyDown = 0x0100,
        KeyUp = 0x0101,
        SKeyDown = 0x0104,
        SKeyUp = 0x0105
    }

    [DllImport("user32.dll")]
    static public extern short GetKeyState(System.Windows.Forms.Keys nVirtKey);

    public static bool GetCapslock()
    {
        return Convert.ToBoolean(GetKeyState(System.Windows.Forms.Keys.CapsLock)) & true;
    }
    public static bool GetNumlock()
    {
        return Convert.ToBoolean(GetKeyState(System.Windows.Forms.Keys.NumLock)) & true;
    }
    public static bool GetScrollLock()
    {
        return Convert.ToBoolean(GetKeyState(System.Windows.Forms.Keys.Scroll)) & true;
    }
    public static bool GetShiftPressed()
    {
        int state = GetKeyState(System.Windows.Forms.Keys.ShiftKey);
        if (state > 1 || state < -1) return true;
        return false;
    }
    public static bool GetCtrlPressed()
    {
        int state = GetKeyState(System.Windows.Forms.Keys.ControlKey);
        if (state > 1 || state < -1) return true;
        return false;
    }
    public static bool GetAltPressed()
    {
        int state = GetKeyState(System.Windows.Forms.Keys.Menu);
        if (state > 1 || state < -1) return true;
        return false;
    }
}
</code>```

And in form1 a sample how to work with it:

```<code>using System;
using System.Windows.Forms;

namespace KeyboardHook
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            Hook kh = new Hook(true);
            kh.KeyDown += Kh_KeyDown;
        }

        private void Kh_KeyDown(Keys key, bool Shift, bool Ctrl, bool Alt)
        {
            MessageBox.Show(key.ToString());
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }
    }
}
</code>```

I wonder if there is a way using the class or some other way to hook also the mouse ? For exmaple when i click the mouse middle button. Or if i roll the mouse wheel then give once a message i rolled the wheel but the wheel is not so important is more the buttons left,right,middle.

答:
Yes, i used the following code in a project of mine, it allows direct access to most windows mouse events:

```<code>using System;
using System.Runtime.InteropServices;

/// <summary>
///     The CallWndProc hook procedure is an application-defined or library-defined
///     callback function used with the SetWindowsHookEx function. The HOOKPROC type
///     defines a pointer to this callback function. CallWndProc is a placeholder for
///     the application-defined or library-defined function name.
/// </summary>
/// <param name="nCode">
///     Specifies whether the hook procedure must process the message.
/// </param>
/// <param name="wParam">
///     Specifies whether the message was sent by the current thread.
/// </param>
/// <param name="lParam">
///     Pointer to a CWPSTRUCT structure that contains details about the message.
/// </param>
/// <returns>
///     If nCode is less than zero, the hook procedure must return the value returned
///     by CallNextHookEx. If nCode is greater than or equal to zero, it is highly
///     recommended that you call CallNextHookEx and return the value it returns;
///     otherwise, other applications that have installed WH_CALLWNDPROC hooks will
///     not receive hook notifications and may behave incorrectly as a result. If the
///     hook procedure does not call CallNextHookEx, the return value should be zero.
/// </returns>
internal delegate int HookProc(int nCode, IntPtr wParam, IntPtr lParam);

internal class NativeMethods
{
    /// <summary>
    ///     The SetWindowsHookEx function installs an application-defined hook
    ///     procedure into a hook chain. You would install a hook procedure to monitor
    ///     the system for certain types of events. These events are associated either
    ///     with a specific thread or with all threads in the same desktop as the
    ///     calling thread.
    /// </summary>
    /// <param name="hookType">
    ///     Specifies the type of hook procedure to be installed
    /// </param>
    /// <param name="callback">Pointer to the hook procedure.</param>
    /// <param name="hMod">
    ///     Handle to the DLL containing the hook procedure pointed to by the lpfn
    ///     parameter. The hMod parameter must be set to NULL if the dwThreadId
    ///     parameter specifies a thread created by the current process and if the
    ///     hook procedure is within the code associated with the current process.
    /// </param>
    /// <param name="dwThreadId">
    ///     Specifies the identifier of the thread with which the hook procedure is
    ///     to be associated.
    /// </param>
    /// <returns>
    ///     If the function succeeds, the return value is the handle to the hook
    ///     procedure. If the function fails, the return value is 0.
    /// </returns>
    [DllImport("user32.dll", CharSet = CharSet.Auto)]
    public static extern IntPtr SetWindowsHookEx(HookType hookType,
        HookProc callback, IntPtr hMod, uint dwThreadId);

    /// <summary>
    ///     The UnhookWindowsHookEx function removes a hook procedure installed in
    ///     a hook chain by the SetWindowsHookEx function.
    /// </summary>
    /// <param name="hhk">Handle to the hook to be removed.</param>
    /// <returns>
    ///     If the function succeeds, the return value is true.
    ///     If the function fails, the return value is false.
    /// </returns>
    [DllImport("user32.dll", CharSet = CharSet.Auto)]
    public static extern bool UnhookWindowsHookEx(IntPtr hhk);

    /// <summary>
    ///     The CallNextHookEx function passes the hook information to the next hook
    ///     procedure in the current hook chain. A hook procedure can call this
    ///     function either before or after processing the hook information.
    /// </summary>
    /// <param name="idHook">Handle to the current hook.</param>
    /// <param name="nCode">
    ///     Specifies the hook code passed to the current hook procedure.
    /// </param>
    /// <param name="wParam">
    ///     Specifies the wParam value passed to the current hook procedure.
    /// </param>
    /// <param name="lParam">
    ///     Specifies the lParam value passed to the current hook procedure.
    /// </param>
    /// <returns>
    ///     This value is returned by the next hook procedure in the chain.
    /// </returns>
    [DllImport("user32.dll", CharSet = CharSet.Auto)]
    public static extern int CallNextHookEx(IntPtr hhk, int nCode,
        IntPtr wParam, IntPtr lParam);
}

internal static class HookCodes
{
    public const int HC_ACTION = 0;
    public const int HC_GETNEXT = 1;
    public const int HC_SKIP = 2;
    public const int HC_NOREMOVE = 3;
    public const int HC_NOREM = HC_NOREMOVE;
    public const int HC_SYSMODALON = 4;
    public const int HC_SYSMODALOFF = 5;
}

internal enum HookType
{
    WH_KEYBOARD = 2,
    WH_MOUSE = 7,
    WH_KEYBOARD_LL = 13,
    WH_MOUSE_LL = 14
}

[StructLayout(LayoutKind.Sequential)]
internal class POINT
{
    public int x;
    public int y;
}

/// <summary>
///     The MSLLHOOKSTRUCT structure contains information about a low-level keyboard
///     input event.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
internal struct MOUSEHOOKSTRUCT
{
    public POINT pt; // The x and y coordinates in screen coordinates
    public int hwnd; // Handle to the window that'll receive the mouse message
    public int wHitTestCode;
    public int dwExtraInfo;
}

/// <summary>
///     The MOUSEHOOKSTRUCT structure contains information about a mouse event passed
///     to a WH_MOUSE hook procedure, MouseProc.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
internal struct MSLLHOOKSTRUCT
{
    public POINT pt; // The x and y coordinates in screen coordinates.
    public int mouseData; // The mouse wheel and button info.
    public int flags;
    public int time; // Specifies the time stamp for this message.
    public IntPtr dwExtraInfo;
}

internal enum MouseMessage
{
    WM_MOUSEMOVE = 0x0200,
    WM_LBUTTONDOWN = 0x0201,
    WM_LBUTTONUP = 0x0202,
    WM_LBUTTONDBLCLK = 0x0203,
    WM_RBUTTONDOWN = 0x0204,
    WM_RBUTTONUP = 0x0205,
    WM_RBUTTONDBLCLK = 0x0206,
    WM_MBUTTONDOWN = 0x0207,
    WM_MBUTTONUP = 0x0208,
    WM_MBUTTONDBLCLK = 0x0209,

    WM_MOUSEWHEEL = 0x020A,
    WM_MOUSEHWHEEL = 0x020E,

    WM_NCMOUSEMOVE = 0x00A0,
    WM_NCLBUTTONDOWN = 0x00A1,
    WM_NCLBUTTONUP = 0x00A2,
    WM_NCLBUTTONDBLCLK = 0x00A3,
    WM_NCRBUTTONDOWN = 0x00A4,
    WM_NCRBUTTONUP = 0x00A5,
    WM_NCRBUTTONDBLCLK = 0x00A6,
    WM_NCMBUTTONDOWN = 0x00A7,
    WM_NCMBUTTONUP = 0x00A8,
    WM_NCMBUTTONDBLCLK = 0x00A9
}

/// <summary>
///     The structure contains information about a low-level keyboard input event.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
internal struct KBDLLHOOKSTRUCT
{
    public int vkCode; // Specifies a virtual-key code
    public int scanCode; // Specifies a hardware scan code for the key
    public int flags;
    public int time; // Specifies the time stamp for this message
    public int dwExtraInfo;
}

internal enum KeyboardMessage
{
    WM_KEYDOWN = 0x0100,
    WM_KEYUP = 0x0101,
    WM_SYSKEYDOWN = 0x0104,
    WM_SYSKEYUP = 0x0105
}
</code>```

To use it you have to register the mouse hook. LowLevelMouseProc is the callback. This method is executed every time a new mouse event occures.

```<code>private void SetUpHook()
{
    Logger.Debug("Setting up global mouse hook");

    // Create an instance of HookProc.
    _globalLlMouseHookCallback = LowLevelMouseProc;

    _hGlobalLlMouseHook = NativeMethods.SetWindowsHookEx(
        HookType.WH_MOUSE_LL,
        _globalLlMouseHookCallback,
        Marshal.GetHINSTANCE(Assembly.GetExecutingAssembly().GetModules()[0]),
        0);

    if (_hGlobalLlMouseHook == IntPtr.Zero)
    {
        Logger.Fatal("Unable to set global mouse hook");
        throw new Win32Exception("Unable to set MouseHook");
    }
}
</code>```

To clear mouse hook:

```<code>private void ClearHook()
{
    Logger.Debug("Deleting global mouse hook");

    if (_hGlobalLlMouseHook != IntPtr.Zero)
    {
        // Unhook the low-level mouse hook
        if (!NativeMethods.UnhookWindowsHookEx(_hGlobalLlMouseHook))
            throw new Win32Exception("Unable to clear MouseHoo;");

        _hGlobalLlMouseHook = IntPtr.Zero;
    }
}
</code>```

And last but not least an example of the LowLevelMouseProc, the callback you can use to intercept mouse events:

```<code>public int LowLevelMouseProc(int nCode, IntPtr wParam, IntPtr lParam)
{
    if (nCode >= 0)
    {
        // Get the mouse WM from the wParam parameter
        var wmMouse = (MouseMessage) wParam;
        if (wmMouse == MouseMessage.WM_LBUTTONDOWN && LeftButtonState == ButtonState.Released)
        {
            Logger.Debug("Left Mouse down");
        }
        if (wmMouse == MouseMessage.WM_LBUTTONUP && LeftButtonState == ButtonState.Down)
        {
            Logger.Debug("Left Mouse up");
        }

        if (wmMouse == MouseMessage.WM_RBUTTONDOWN && RightButtonState == ButtonState.Released)
        {
            Logger.Debug("Right Mouse down");
        }
        if (wmMouse == MouseMessage.WM_RBUTTONUP && RightButtonState == ButtonState.Down)
        {
            Logger.Debug("Right Mouse up");
        }
    }

    // Pass the hook information to the next hook procedure in chain
    return NativeMethods.CallNextHookEx(_hGlobalLlMouseHook, nCode, wParam, lParam);
}
</code>```

As with all direct windows calls, the code gets unnecessarily long. But the only thing you have to do, is to call SetUpHook and provide your own version of LowLevelMouseProc.

EDIT: There are shorter versions to do this. But this method allows you to catch global mouse events. Not just events issued to your window. All mouse events, system wide will be piped into LowLevelMouseProc

Body:
This is the class i'm using for hooking the keyboard keys.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

public class Hook : IDisposable
{
    bool Global = false;

    public delegate void LocalKeyEventHandler(Keys key, bool Shift, bool Ctrl, bool Alt);
    public event LocalKeyEventHandler KeyDown;
    public event LocalKeyEventHandler KeyUp;

    public delegate int CallbackDelegate(int Code, int W, int L);

    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
    public struct KBDLLHookStruct
    {
        public Int32 vkCode;
        public Int32 scanCode;
        public Int32 flags;
        public Int32 time;
        public Int32 dwExtraInfo;
    }

    [DllImport("user32", CallingConvention = CallingConvention.StdCall)]
    private static extern int SetWindowsHookEx(HookType idHook, CallbackDelegate lpfn, int hInstance, int threadId);

    [DllImport("user32", CallingConvention = CallingConvention.StdCall)]
    private static extern bool UnhookWindowsHookEx(int idHook);

    [DllImport("user32", CallingConvention = CallingConvention.StdCall)]
    private static extern int CallNextHookEx(int idHook, int nCode, int wParam, int lParam);

    [DllImport("kernel32.dll", CallingConvention = CallingConvention.StdCall)]
    private static extern int GetCurrentThreadId();

    public enum HookType : int
    {
        WH_JOURNALRECORD = 0,
        WH_JOURNALPLAYBACK = 1,
        WH_KEYBOARD = 2,
        WH_GETMESSAGE = 3,
        WH_CALLWNDPROC = 4,
        WH_CBT = 5,
        WH_SYSMSGFILTER = 6,
        WH_MOUSE = 7,
        WH_HARDWARE = 8,
        WH_DEBUG = 9,
        WH_SHELL = 10,
        WH_FOREGROUNDIDLE = 11,
        WH_CALLWNDPROCRET = 12,
        WH_KEYBOARD_LL = 13,
        WH_MOUSE_LL = 14
    }

    private int HookID = 0;
    CallbackDelegate TheHookCB = null;

    //Start hook
    public Hook(bool Global)
    {
        this.Global = Global;
        TheHookCB = new CallbackDelegate(KeybHookProc);
        if (Global)
        {
            HookID = SetWindowsHookEx(HookType.WH_KEYBOARD_LL, TheHookCB,
                0, //0 for local hook. eller hwnd til user32 for global
                0); //0 for global hook. eller thread for hooken
        }
        else
        {
            HookID = SetWindowsHookEx(HookType.WH_KEYBOARD, TheHookCB,
                0, //0 for local hook. or hwnd to user32 for global
                GetCurrentThreadId()); //0 for global hook. or thread for the hook
        }
    }

    bool IsFinalized = false;
    ~Hook()
    {
        if (!IsFinalized)
        {
            UnhookWindowsHookEx(HookID);
            IsFinalized = true;
        }
    }
    public void Dispose()
    {
        if (!IsFinalized)
        {
            UnhookWindowsHookEx(HookID);
            IsFinalized = true;
        }
    }

    //The listener that will trigger events
    private int KeybHookProc(int Code, int W, int L)
    {
        KBDLLHookStruct LS = new KBDLLHookStruct();
        if (Code < 0)
        {
            return CallNextHookEx(HookID, Code, W, L);
        }
        try
        {
            if (!Global)
            {
                if (Code == 3)
                {
                    IntPtr ptr = IntPtr.Zero;

                    int keydownup = L >> 30;
                    if (keydownup == 0)
                    {
                        if (KeyDown != null) KeyDown((Keys)W, GetShiftPressed(), GetCtrlPressed(), GetAltPressed());
                    }
                    if (keydownup == -1)
                    {
                        if (KeyUp != null) KeyUp((Keys)W, GetShiftPressed(), GetCtrlPressed(), GetAltPressed());
                    }
                    //System.Diagnostics.Debug.WriteLine("Down: " + (Keys)W);
                }
            }
            else
            {
                KeyEvents kEvent = (KeyEvents)W;

                Int32 vkCode = Marshal.ReadInt32((IntPtr)L); //Leser vkCode som er de første 32 bits hvor L peker.

                if (kEvent != KeyEvents.KeyDown && kEvent != KeyEvents.KeyUp && kEvent != KeyEvents.SKeyDown && kEvent != KeyEvents.SKeyUp)
                {
                }
                if (kEvent == KeyEvents.KeyDown || kEvent == KeyEvents.SKeyDown)
                {
                    if (KeyDown != null) KeyDown((Keys)vkCode, GetShiftPressed(), GetCtrlPressed(), GetAltPressed());
                }
                if (kEvent == KeyEvents.KeyUp || kEvent == KeyEvents.SKeyUp)
                {
                    if (KeyUp != null) KeyUp((Keys)vkCode, GetShiftPressed(), GetCtrlPressed(), GetAltPressed());
                }
            }
        }
        catch (Exception)
        {
            //Ignore all errors...
        }

        return CallNextHookEx(HookID, Code, W, L);

    }

    public enum KeyEvents
    {
        KeyDown = 0x0100,
        KeyUp = 0x0101,
        SKeyDown = 0x0104,
        SKeyUp = 0x0105
    }

    [DllImport("user32.dll")]
    static public extern short GetKeyState(System.Windows.Forms.Keys nVirtKey);

    public static bool GetCapslock()
    {
        return Convert.ToBoolean(GetKeyState(System.Windows.Forms.Keys.CapsLock)) & true;
    }
    public static bool GetNumlock()
    {
        return Convert.ToBoolean(GetKeyState(System.Windows.Forms.Keys.NumLock)) & true;
    }
    public static bool GetScrollLock()
    {
        return Convert.ToBoolean(GetKeyState(System.Windows.Forms.Keys.Scroll)) & true;
    }
    public static bool GetShiftPressed()
    {
        int state = GetKeyState(System.Windows.Forms.Keys.ShiftKey);
        if (state > 1 || state < -1) return true;
        return false;
    }
    public static bool GetCtrlPressed()
    {
        int state = GetKeyState(System.Windows.Forms.Keys.ControlKey);
        if (state > 1 || state < -1) return true;
        return false;
    }
    public static bool GetAltPressed()
    {
        int state = GetKeyState(System.Windows.Forms.Keys.Menu);
        if (state > 1 || state < -1) return true;
        return false;
    }
}

And in form1 a sample how to work with it:

using System;
using System.Windows.Forms;

namespace KeyboardHook
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            Hook kh = new Hook(true);
            kh.KeyDown += Kh_KeyDown;
        }

        private void Kh_KeyDown(Keys key, bool Shift, bool Ctrl, bool Alt)
        {
            MessageBox.Show(key.ToString());
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }
    }
}

I wonder if there is a way using the class or some other way to hook also the mouse ? For exmaple when i click the mouse middle button. Or if i roll the mouse wheel then give once a message i rolled the wheel but the wheel is not so important is more the buttons left,right,middle.

Body:
Yes, i used the following code in a project of mine, it allows direct access to most windows mouse events:

using System;
using System.Runtime.InteropServices;

/// <summary>
///     The CallWndProc hook procedure is an application-defined or library-defined
///     callback function used with the SetWindowsHookEx function. The HOOKPROC type
///     defines a pointer to this callback function. CallWndProc is a placeholder for
///     the application-defined or library-defined function name.
/// </summary>
/// <param name="nCode">
///     Specifies whether the hook procedure must process the message.
/// </param>
/// <param name="wParam">
///     Specifies whether the message was sent by the current thread.
/// </param>
/// <param name="lParam">
///     Pointer to a CWPSTRUCT structure that contains details about the message.
/// </param>
/// <returns>
///     If nCode is less than zero, the hook procedure must return the value returned
///     by CallNextHookEx. If nCode is greater than or equal to zero, it is highly
///     recommended that you call CallNextHookEx and return the value it returns;
///     otherwise, other applications that have installed WH_CALLWNDPROC hooks will
///     not receive hook notifications and may behave incorrectly as a result. If the
///     hook procedure does not call CallNextHookEx, the return value should be zero.
/// </returns>
internal delegate int HookProc(int nCode, IntPtr wParam, IntPtr lParam);

internal class NativeMethods
{
    /// <summary>
    ///     The SetWindowsHookEx function installs an application-defined hook
    ///     procedure into a hook chain. You would install a hook procedure to monitor
    ///     the system for certain types of events. These events are associated either
    ///     with a specific thread or with all threads in the same desktop as the
    ///     calling thread.
    /// </summary>
    /// <param name="hookType">
    ///     Specifies the type of hook procedure to be installed
    /// </param>
    /// <param name="callback">Pointer to the hook procedure.</param>
    /// <param name="hMod">
    ///     Handle to the DLL containing the hook procedure pointed to by the lpfn
    ///     parameter. The hMod parameter must be set to NULL if the dwThreadId
    ///     parameter specifies a thread created by the current process and if the
    ///     hook procedure is within the code associated with the current process.
    /// </param>
    /// <param name="dwThreadId">
    ///     Specifies the identifier of the thread with which the hook procedure is
    ///     to be associated.
    /// </param>
    /// <returns>
    ///     If the function succeeds, the return value is the handle to the hook
    ///     procedure. If the function fails, the return value is 0.
    /// </returns>
    [DllImport("user32.dll", CharSet = CharSet.Auto)]
    public static extern IntPtr SetWindowsHookEx(HookType hookType,
        HookProc callback, IntPtr hMod, uint dwThreadId);

    /// <summary>
    ///     The UnhookWindowsHookEx function removes a hook procedure installed in
    ///     a hook chain by the SetWindowsHookEx function.
    /// </summary>
    /// <param name="hhk">Handle to the hook to be removed.</param>
    /// <returns>
    ///     If the function succeeds, the return value is true.
    ///     If the function fails, the return value is false.
    /// </returns>
    [DllImport("user32.dll", CharSet = CharSet.Auto)]
    public static extern bool UnhookWindowsHookEx(IntPtr hhk);

    /// <summary>
    ///     The CallNextHookEx function passes the hook information to the next hook
    ///     procedure in the current hook chain. A hook procedure can call this
    ///     function either before or after processing the hook information.
    /// </summary>
    /// <param name="idHook">Handle to the current hook.</param>
    /// <param name="nCode">
    ///     Specifies the hook code passed to the current hook procedure.
    /// </param>
    /// <param name="wParam">
    ///     Specifies the wParam value passed to the current hook procedure.
    /// </param>
    /// <param name="lParam">
    ///     Specifies the lParam value passed to the current hook procedure.
    /// </param>
    /// <returns>
    ///     This value is returned by the next hook procedure in the chain.
    /// </returns>
    [DllImport("user32.dll", CharSet = CharSet.Auto)]
    public static extern int CallNextHookEx(IntPtr hhk, int nCode,
        IntPtr wParam, IntPtr lParam);
}

internal static class HookCodes
{
    public const int HC_ACTION = 0;
    public const int HC_GETNEXT = 1;
    public const int HC_SKIP = 2;
    public const int HC_NOREMOVE = 3;
    public const int HC_NOREM = HC_NOREMOVE;
    public const int HC_SYSMODALON = 4;
    public const int HC_SYSMODALOFF = 5;
}

internal enum HookType
{
    WH_KEYBOARD = 2,
    WH_MOUSE = 7,
    WH_KEYBOARD_LL = 13,
    WH_MOUSE_LL = 14
}

[StructLayout(LayoutKind.Sequential)]
internal class POINT
{
    public int x;
    public int y;
}

/// <summary>
///     The MSLLHOOKSTRUCT structure contains information about a low-level keyboard
///     input event.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
internal struct MOUSEHOOKSTRUCT
{
    public POINT pt; // The x and y coordinates in screen coordinates
    public int hwnd; // Handle to the window that'll receive the mouse message
    public int wHitTestCode;
    public int dwExtraInfo;
}

/// <summary>
///     The MOUSEHOOKSTRUCT structure contains information about a mouse event passed
///     to a WH_MOUSE hook procedure, MouseProc.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
internal struct MSLLHOOKSTRUCT
{
    public POINT pt; // The x and y coordinates in screen coordinates.
    public int mouseData; // The mouse wheel and button info.
    public int flags;
    public int time; // Specifies the time stamp for this message.
    public IntPtr dwExtraInfo;
}

internal enum MouseMessage
{
    WM_MOUSEMOVE = 0x0200,
    WM_LBUTTONDOWN = 0x0201,
    WM_LBUTTONUP = 0x0202,
    WM_LBUTTONDBLCLK = 0x0203,
    WM_RBUTTONDOWN = 0x0204,
    WM_RBUTTONUP = 0x0205,
    WM_RBUTTONDBLCLK = 0x0206,
    WM_MBUTTONDOWN = 0x0207,
    WM_MBUTTONUP = 0x0208,
    WM_MBUTTONDBLCLK = 0x0209,

    WM_MOUSEWHEEL = 0x020A,
    WM_MOUSEHWHEEL = 0x020E,

    WM_NCMOUSEMOVE = 0x00A0,
    WM_NCLBUTTONDOWN = 0x00A1,
    WM_NCLBUTTONUP = 0x00A2,
    WM_NCLBUTTONDBLCLK = 0x00A3,
    WM_NCRBUTTONDOWN = 0x00A4,
    WM_NCRBUTTONUP = 0x00A5,
    WM_NCRBUTTONDBLCLK = 0x00A6,
    WM_NCMBUTTONDOWN = 0x00A7,
    WM_NCMBUTTONUP = 0x00A8,
    WM_NCMBUTTONDBLCLK = 0x00A9
}

/// <summary>
///     The structure contains information about a low-level keyboard input event.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
internal struct KBDLLHOOKSTRUCT
{
    public int vkCode; // Specifies a virtual-key code
    public int scanCode; // Specifies a hardware scan code for the key
    public int flags;
    public int time; // Specifies the time stamp for this message
    public int dwExtraInfo;
}

internal enum KeyboardMessage
{
    WM_KEYDOWN = 0x0100,
    WM_KEYUP = 0x0101,
    WM_SYSKEYDOWN = 0x0104,
    WM_SYSKEYUP = 0x0105
}

To use it you have to register the mouse hook. LowLevelMouseProc is the callback. This method is executed every time a new mouse event occures.

private void SetUpHook()
{
    Logger.Debug("Setting up global mouse hook");

    // Create an instance of HookProc.
    _globalLlMouseHookCallback = LowLevelMouseProc;

    _hGlobalLlMouseHook = NativeMethods.SetWindowsHookEx(
        HookType.WH_MOUSE_LL,
        _globalLlMouseHookCallback,
        Marshal.GetHINSTANCE(Assembly.GetExecutingAssembly().GetModules()[0]),
        0);

    if (_hGlobalLlMouseHook == IntPtr.Zero)
    {
        Logger.Fatal("Unable to set global mouse hook");
        throw new Win32Exception("Unable to set MouseHook");
    }
}

To clear mouse hook:

private void ClearHook()
{
    Logger.Debug("Deleting global mouse hook");

    if (_hGlobalLlMouseHook != IntPtr.Zero)
    {
        // Unhook the low-level mouse hook
        if (!NativeMethods.UnhookWindowsHookEx(_hGlobalLlMouseHook))
            throw new Win32Exception("Unable to clear MouseHoo;");

        _hGlobalLlMouseHook = IntPtr.Zero;
    }
}

And last but not least an example of the LowLevelMouseProc, the callback you can use to intercept mouse events:

public int LowLevelMouseProc(int nCode, IntPtr wParam, IntPtr lParam)
{
    if (nCode >= 0)
    {
        // Get the mouse WM from the wParam parameter
        var wmMouse = (MouseMessage) wParam;
        if (wmMouse == MouseMessage.WM_LBUTTONDOWN && LeftButtonState == ButtonState.Released)
        {
            Logger.Debug("Left Mouse down");
        }
        if (wmMouse == MouseMessage.WM_LBUTTONUP && LeftButtonState == ButtonState.Down)
        {
            Logger.Debug("Left Mouse up");
        }

        if (wmMouse == MouseMessage.WM_RBUTTONDOWN && RightButtonState == ButtonState.Released)
        {
            Logger.Debug("Right Mouse down");
        }
        if (wmMouse == MouseMessage.WM_RBUTTONUP && RightButtonState == ButtonState.Down)
        {
            Logger.Debug("Right Mouse up");
        }
    }

    // Pass the hook information to the next hook procedure in chain
    return NativeMethods.CallNextHookEx(_hGlobalLlMouseHook, nCode, wParam, lParam);
}

As with all direct windows calls, the code gets unnecessarily long. But the only thing you have to do, is to call SetUpHook and provide your own version of LowLevelMouseProc.

EDIT: There are shorter versions to do this. But this method allows you to catch global mouse events. Not just events issued to your window. All mouse events, system wide will be piped into LowLevelMouseProc


问:
size of array of integer pointers
```<code>#include<stdio.h>
#include<conio.h>

void main()
{
  int a[5]={1,2,3,4,5};
  int (*p)[5];
  int *p1[5];
  clrscr();

  printf("%d\n",(int)sizeof(a)); // 10
  printf("%d\n",(int)sizeof(p));  //2
  printf("%d\n",(int)sizeof(p1)); //10
  getch();
}
</code>```

First output is 10 because each integer is of 2 bytes and hence 5 integers would take 10 bytes.

I am not able to understand the 3rd output which is 10. Here we have array of pointers each pointing to an integer. Size of pointer(or address) in my system is 32 bits (4 Bytes) . So the output should be 5*4=20 right as we have 5 pointers each of 4 bytes ?

答:
The second printout shows the size of a pointer on your machine is 2 bytes.
Array int *p1[5]; has 5 elements, not 10.

5 * 2 = 10.

Title: size of array of integer pointers

Body:
#include<stdio.h>
#include<conio.h>

void main()
{
  int a[5]={1,2,3,4,5};
  int (*p)[5];
  int *p1[5];
  clrscr();

  printf("%d\n",(int)sizeof(a)); // 10
  printf("%d\n",(int)sizeof(p));  //2
  printf("%d\n",(int)sizeof(p1)); //10
  getch();
}

First output is 10 because each integer is of 2 bytes and hence 5 integers would take 10 bytes.

I am not able to understand the 3rd output which is 10. Here we have array of pointers each pointing to an integer. Size of pointer(or address) in my system is 32 bits (4 Bytes) . So the output should be 5*4=20 right as we have 5 pointers each of 4 bytes ?


问:
i want to change UIButton and UIImage view by clicking on a button. But images for UIButton and Image view are different
Hello I am new to Swift (Swift 3, Xcode 8).
i want to change UIButton and UIImage view by clicking on a button. But images for UIButton and Image view are different. Basically I have a Button and an Image view. What i want to is to click on the button and change the image view but at the same time button should change too (the button image is different from the image).

I have tried this

```<code>IBAction func testButton(_ sender: UIButton) {

    self.testCircle = (self.testCircle >= self.circleArray.count-1) ? 0 : self.carbsCircle+1

        self.testImage.image = UIImage(named:circleArray[testCircle])
</code>```

but here they come from the same Array, but if i use a different Array for the image, i am not getting anything.

How can i do it? Thank you very much guys.

答:
I hope I got your question correct. You have a button with an image on it and an imageview. 2 separate things. And you want to change your images.

If you want to change your buttons image by clicking on it you should not only have IBAction but also IBOutlet for that button. Control drag and make an outlet for it. In the button's IBAction function just change your button's image to what you want, as well as your image view's.

Body:
Hello I am new to Swift (Swift 3, Xcode 8).
i want to change UIButton and UIImage view by clicking on a button. But images for UIButton and Image view are different. Basically I have a Button and an Image view. What i want to is to click on the button and change the image view but at the same time button should change too (the button image is different from the image).

I have tried this

IBAction func testButton(_ sender: UIButton) {

    self.testCircle = (self.testCircle >= self.circleArray.count-1) ? 0 : self.carbsCircle+1

        self.testImage.image = UIImage(named:circleArray[testCircle])

but here they come from the same Array, but if i use a different Array for the image, i am not getting anything.

How can i do it? Thank you very much guys.


答:
First, fix your findMIN, you should return the index of the minimum element (and compare the element at the current value to the minimum). Like,

```<code>static int findMIN(int[] A, int c) {
    int x = c;
    for (; c < A.length; c++) {
        if (A[c] < A[x]) {
            x = c;
        }
    }
    return x;
}
</code>```

Then I would use a swap method, like

```<code>static void swap(int[] A, int a, int b) {
    if (a != b) {
        int t = A[a];
        A[a] = A[b];
        A[b] = t;
    }
}
</code>```

Finally, tie it together like

```<code>public static void main(String[] args) {
    int[] myArray = { 9, 6, 1, 3, 0, 4, 2 };

    for (int i = 0; i < myArray.length; i++) {
        swap(myArray, i, findMIN(myArray, i));
    }
    System.out.println(Arrays.toString(myArray));
}
</code>```

And, I get

```<code>[0, 1, 2, 3, 4, 6, 9]
</code>```

Title: Why doesn't my selection sort algorithm do what it's supposed to (java)?

Body:
In the last hours I have tried to write the selection sort algorithm in Java without looking at finished code. I just read how the algorithm works (by words).

I won't copy paste the explanation but rather depict it (to check if I understood it):

-We have one unsorted array A and an empty array B (which has the same size as A)

-Now take the unsorted array A and find its smallest element. Smallest element found, now switch this element with the first element of the unsorted array A

-Put the first element (=smallest element of array A) into the array B

-Repeat till we are done with every element of A

I tried to code that in Java:

public class Selectionsort{

    public static void main(String[] args) {
        int[] myArray = {9,6,1,3,0,4,2};
        int[] B = new int[myArray.length];

        for(int i=0; i<myArray.length; i++) {
            B[i]=findMIN(myArray, i);
        }
    }

    static int findMIN(int[] A, int c) {
        int x = A[c];
        while(cA[c]) {
                x=A[c];
            }
            c++;
        }
        return x;
    }
}

But I get a weird output:

0 0 0 0 0 2 2

Body:
First, fix your findMIN, you should return the index of the minimum element (and compare the element at the current value to the minimum). Like,

static int findMIN(int[] A, int c) {
    int x = c;
    for (; c < A.length; c++) {
        if (A[c] < A[x]) {
            x = c;
        }
    }
    return x;
}

Then I would use a swap method, like

static void swap(int[] A, int a, int b) {
    if (a != b) {
        int t = A[a];
        A[a] = A[b];
        A[b] = t;
    }
}

Finally, tie it together like

public static void main(String[] args) {
    int[] myArray = { 9, 6, 1, 3, 0, 4, 2 };

    for (int i = 0; i < myArray.length; i++) {
        swap(myArray, i, findMIN(myArray, i));
    }
    System.out.println(Arrays.toString(myArray));
}

And, I get

[0, 1, 2, 3, 4, 6, 9]