问:
Getting list of clients using WebSockets
I'm building a multiuser sketchpad and having some issues getting and keeping an updated list of all the currently connected users. I'm trying to find the best way to notify all existing clients of a new client, and passing the existing clients to the newly connected one. The reason I'm trying to do this is so when one client draws a line, all the other clients find that client in the list, and add the line coords to the respective array.

Server.js

```<code>var sys = require("sys");
var ws = require('websocket-server');

var server = ws.createServer({debug: true});

server.addListener("connection", function(conn) {
// When a message is received, broadcast it too all the clients
// that are currently connected.
conn.send('NEW_SERVER_MESSAGE:Welcome!');
conn.send('USER_CONNECTED:' + conn.id);

conn.addListener("message", function( msg ){
    switch(msg) {
        case 'GET_ALL_ACTIVE_USERS':
            server.manager.forEach(function(con) {
                conn.broadcast('USER_CONNECTED:' + con.id);
            });
            break;
        case 'UPDATE_CURSOR':
            conn.broadcast( msg + '_' + conn.id );
            break;
        default:
            conn.broadcast( msg );
            break;
    }

});
conn.addListener('close', function( msg ) {
    conn.broadcast('USER_DISCONNECTED:' + conn.id);
});
});

server.addListener("error", function(){
console.log(Array.prototype.join.call(arguments, ", "));
});

server.addListener("listening", function(){
console.log("Listening for connections...");
});

server.addListener("disconnected", function(conn){
console.log("<"+conn.id+"> disconnected.");
});

server.listen(8002);</code>
</code>```

My JS network code:

```<code>sketchPadNet = function (b,s) {
var self = this;

this.host = "ws://localhost:8002/server.js";

this.id = null;
this.users = [];
this.heightOffset = 53;
this.scene = s;
this.connected = b;

var User = function(id) {
    this.id = id;
    this.nickname = id;
    this.lines = [];
    this.position = "";
};

this.init = function () {
    try {
        socket = new WebSocket(self.host);
        socket.onopen = function (msg) {
            socket.send('GET_ALL_ACTIVE_USERS');
        };

        socket.onmessage = function (msg) {
            var m = msg.data.split(':');
            switch(m[0]) {

            case 'USER_CONNECTED':
                console.log('USER_CONNECTED');
                var u = new User(m[1]);
                u.lines = [];
                u.nickname = u.id;
                self.users.push(u);
                console.log(self.users.length);
                console.log(self.users);
                break;

            case 'USER_DISCONNECTED':
                console.log('USER_DISCONNECTED');
                for(var i = 0; i < self.users.length; ++i) {
                    console.log(self.users[i]);
                    if(m[1] == self.users[i].id) {
                        self.users.splice(i, 1);
                    }
                }
                break;

            case 'DRAW_LINE':
                var tmpMsg = m[1].split('_');

                var id = tmpMsg[8];
                var userIndex = '';

                for(var i = 0; i < self.users.length; ++i) {
                    if(self.users[i].id == id) userIndex = i;
                }

                var p1 = (self.users[userIndex].lines.length < 1) ? new BLUR.Vertex3(tmpMsg[0], tmpMsg[1], tmpMsg[2]) : self.users[userIndex].lines[self.users[userIndex].lines.length - 1].point2;
                var p2 = new BLUR.Vertex3(tmpMsg[3], tmpMsg[4], tmpMsg[5]);

                var line = new BLUR.Line3D(p1, p2, tmpMsg[7]);
                line.material = tmpMsg[6];

                // add the newly created line to the scene.
                self.scene.addObject(line);
                self.users[userIndex].lines.push(line);
                break;

            case 'UPDATE_CURSOR':
                for(var i = 0; i < self.scene.objects.length; ++i) {
                    if(self.scene.objects[i].type == 'BLUR.Particle')
                        self.scene.removeObject(scene.objects[i]);
                }

                var coords = m[1].split('_');
                var id = coords[2];
                var userIndex = 0;

                for(var i = 0; i < self.users.length; ++i) {
                    if(self.users[i].id == id)
                        userIndex = i;
                }

                self.users[userIndex].position = new BLUR.Vertex3(coords[0], coords[1], 1);
                var p = new BLUR.Particle( self.users[userIndex].position, 4 );
                p.material = new BLUR.RGBColour(176,23,31,0.3);

                self.scene.addObject(p);
                break;

            case 'RECEIVE_ID':
                self.id = m[1];
                self.connected.nicknameObj.text = self.id;
                console.log(self.id);
                break;

                break;
            }
        };

        socket.onclose = function (msg) {
            // feck!
            self.connected.addServerError('Server disconnected, try refreshing.');
        };
    }
    catch (ex) {
        console.log('EXCEPTION: ' + ex);
    }
};
</code>```

At the moment, when a new client connected it sends out a message and is added to an array, the the reverse when a client disconnects. For some reason though this isn't staying update? For example when a client draws a line, some of the others report this error:

```<code>Uncaught TypeError: Cannot read property 'lines' of undefined
</code>```

Sorry if i'm being incredibly stupid here, but any help is appreciated!!

Cheers :)

答:
Ok the real issue seems to be in 'DRAW_LINE' on the client side. Are you sure that you are broadcasting the message to all users and not just sending back the message to the client?

The error points to this line in your client code:

```<code>var p1 = (self.users[userIndex].lines.length < 1) ? new BLUR.Vertex3(tmpMsg[0], tmpMsg[1], tmpMsg[2]) : self.users[userIndex].lines[self.users[userIndex].lines.length - 1].point2;
</code>```

Please provide the server code for 'DRAW_LINE'. The issue is definitely cropping up in there and not in any of the others.

Also, self.users[userIndex] is undefined. Maybe that user does not exist?

Why do u need that for loop? Why not just:

```<code>if(self.users[id] != undefined) {
  var p1 = (self.users[id].lines.length < 1) ? new BLUR.Vertex3(tmpMsg[0], tmpMsg[1], tmpMsg[2]) : self.users[id].lines[self.users[id].lines.length - 1].point2;
}
</code>```

Body:
I'm building a multiuser sketchpad and having some issues getting and keeping an updated list of all the currently connected users. I'm trying to find the best way to notify all existing clients of a new client, and passing the existing clients to the newly connected one. The reason I'm trying to do this is so when one client draws a line, all the other clients find that client in the list, and add the line coords to the respective array.

Server.js

var sys = require("sys");
var ws = require('websocket-server');

var server = ws.createServer({debug: true});

server.addListener("connection", function(conn) {
// When a message is received, broadcast it too all the clients
// that are currently connected.
conn.send('NEW_SERVER_MESSAGE:Welcome!');
conn.send('USER_CONNECTED:' + conn.id);

conn.addListener("message", function( msg ){
    switch(msg) {
        case 'GET_ALL_ACTIVE_USERS':
            server.manager.forEach(function(con) {
                conn.broadcast('USER_CONNECTED:' + con.id);
            });
            break;
        case 'UPDATE_CURSOR':
            conn.broadcast( msg + '_' + conn.id );
            break;
        default:
            conn.broadcast( msg );
            break;
    }

});
conn.addListener('close', function( msg ) {
    conn.broadcast('USER_DISCONNECTED:' + conn.id);
});
});

server.addListener("error", function(){
console.log(Array.prototype.join.call(arguments, ", "));
});

server.addListener("listening", function(){
console.log("Listening for connections...");
});

server.addListener("disconnected", function(conn){
console.log("<"+conn.id+"> disconnected.");
});

server.listen(8002);

My JS network code:

sketchPadNet = function (b,s) {
var self = this;

this.host = "ws://localhost:8002/server.js";

this.id = null;
this.users = [];
this.heightOffset = 53;
this.scene = s;
this.connected = b;

var User = function(id) {
    this.id = id;
    this.nickname = id;
    this.lines = [];
    this.position = "";
};

this.init = function () {
    try {
        socket = new WebSocket(self.host);
        socket.onopen = function (msg) {
            socket.send('GET_ALL_ACTIVE_USERS');
        };

        socket.onmessage = function (msg) {
            var m = msg.data.split(':');
            switch(m[0]) {

            case 'USER_CONNECTED':
                console.log('USER_CONNECTED');
                var u = new User(m[1]);
                u.lines = [];
                u.nickname = u.id;
                self.users.push(u);
                console.log(self.users.length);
                console.log(self.users);
                break;

            case 'USER_DISCONNECTED':
                console.log('USER_DISCONNECTED');
                for(var i = 0; i < self.users.length; ++i) {
                    console.log(self.users[i]);
                    if(m[1] == self.users[i].id) {
                        self.users.splice(i, 1);
                    }
                }
                break;

            case 'DRAW_LINE':
                var tmpMsg = m[1].split('_');

                var id = tmpMsg[8];
                var userIndex = '';

                for(var i = 0; i < self.users.length; ++i) {
                    if(self.users[i].id == id) userIndex = i;
                }

                var p1 = (self.users[userIndex].lines.length < 1) ? new BLUR.Vertex3(tmpMsg[0], tmpMsg[1], tmpMsg[2]) : self.users[userIndex].lines[self.users[userIndex].lines.length - 1].point2;
                var p2 = new BLUR.Vertex3(tmpMsg[3], tmpMsg[4], tmpMsg[5]);

                var line = new BLUR.Line3D(p1, p2, tmpMsg[7]);
                line.material = tmpMsg[6];

                // add the newly created line to the scene.
                self.scene.addObject(line);
                self.users[userIndex].lines.push(line);
                break;

            case 'UPDATE_CURSOR':
                for(var i = 0; i < self.scene.objects.length; ++i) {
                    if(self.scene.objects[i].type == 'BLUR.Particle')
                        self.scene.removeObject(scene.objects[i]);
                }

                var coords = m[1].split('_');
                var id = coords[2];
                var userIndex = 0;

                for(var i = 0; i < self.users.length; ++i) {
                    if(self.users[i].id == id)
                        userIndex = i;
                }

                self.users[userIndex].position = new BLUR.Vertex3(coords[0], coords[1], 1);
                var p = new BLUR.Particle( self.users[userIndex].position, 4 );
                p.material = new BLUR.RGBColour(176,23,31,0.3);

                self.scene.addObject(p);
                break;

            case 'RECEIVE_ID':
                self.id = m[1];
                self.connected.nicknameObj.text = self.id;
                console.log(self.id);
                break;

                break;
            }
        };

        socket.onclose = function (msg) {
            // feck!
            self.connected.addServerError('Server disconnected, try refreshing.');
        };
    }
    catch (ex) {
        console.log('EXCEPTION: ' + ex);
    }
};

At the moment, when a new client connected it sends out a message and is added to an array, the the reverse when a client disconnects. For some reason though this isn't staying update? For example when a client draws a line, some of the others report this error:

Uncaught TypeError: Cannot read property 'lines' of undefined

Sorry if i'm being incredibly stupid here, but any help is appreciated!!

Cheers :)

Body:
Ok the real issue seems to be in 'DRAW_LINE' on the client side. Are you sure that you are broadcasting the message to all users and not just sending back the message to the client?

The error points to this line in your client code:

var p1 = (self.users[userIndex].lines.length < 1) ? new BLUR.Vertex3(tmpMsg[0], tmpMsg[1], tmpMsg[2]) : self.users[userIndex].lines[self.users[userIndex].lines.length - 1].point2;

Please provide the server code for 'DRAW_LINE'. The issue is definitely cropping up in there and not in any of the others.

Also, self.users[userIndex] is undefined. Maybe that user does not exist?

Why do u need that for loop? Why not just:

if(self.users[id] != undefined) {
  var p1 = (self.users[id].lines.length < 1) ? new BLUR.Vertex3(tmpMsg[0], tmpMsg[1], tmpMsg[2]) : self.users[id].lines[self.users[id].lines.length - 1].point2;
}


来源: stackexchange

问:
What's wrong with my Scanner java code?
```<code>import java.util.Scanner;

public class Exercise5 {

 public static void main(String[] args) {
  Scanner in = new Scanner(System.in);

  System.out.print("Input first number: ");
  int num1 = in.nextInt(5);

  System.out.print("Input second number: ");
  int num2 = in.nextInt(25);

  System.out.println(num1 + " x " + num2 + " = " + num1 * num2);
 }

}
</code>```

**Here is my java code, the expect output should be like this:

Input first number: 25

Input second number: 5

25 x 5 = 125

After I plug in my code and run it, the output is too different with the answer

Here is the output:

```<code>Input first number: Exception in thread "main"   java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at Exercise5.main(Exercise5.java:27)
</code>```

How can I fix my code?

答:
EDIT:  Didn't even notice you were supplying an argument to nextInt().  As the other mentioned, this is not what you want to do.

Also, the new line character is still in the buffer after you call nextInt().  You'll need to fix this as well before your program will operate as you intend.

Understanding Scanner's nextLine(), next(), and nextInt() methods

ContentLicense: CC BY-SA 3.0

Title: What's wrong with my Scanner java code?

Body:
import java.util.Scanner;

public class Exercise5 {

 public static void main(String[] args) {
  Scanner in = new Scanner(System.in);

  System.out.print("Input first number: ");
  int num1 = in.nextInt(5);

  System.out.print("Input second number: ");
  int num2 = in.nextInt(25);

  System.out.println(num1 + " x " + num2 + " = " + num1 * num2);
 }

}

**Here is my java code, the expect output should be like this:

Input first number: 25

Input second number: 5

25 x 5 = 125

After I plug in my code and run it, the output is too different with the answer

Here is the output:

Input first number: Exception in thread "main"   java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at Exercise5.main(Exercise5.java:27)

How can I fix my code?


答:
You shouldn't put 5 and 25 inside brackets of in.nextInt, you will write value inside console line and scanner will read it.

So instead

```<code> int num1 = in.nextInt(5);
</code>```

it should look like

```<code> int num1 = in.nextInt();
</code>```

Title: What's wrong with my Scanner java code?

Body:
You shouldn't put 5 and 25 inside brackets of in.nextInt, you will write value inside console line and scanner will read it.

So instead

 int num1 = in.nextInt(5);

it should look like

 int num1 = in.nextInt();


问:
Defer Parsing Javascript
im wondering how can i fix this?

i've already defer the other .js files, and this are the remaining js files ..

答:
Recaptcha documentation provides you with the correct example, which in this case I've added above. You should add that script tag before your closing  tag.

Or, you could enqueue it in the footer by using the $in_footer parameter of wp_enqueue_script like so:

```<code>wp_enqueue_script('stack-recaptcha','https://www.google.com/recaptcha/api.js','','',true); // $handle, $src, $dep, $ver, $in_footer
</code>```

The first method is the preferred method, to take advantage of the async defer attributes of the script tag.

Title: Defer Parsing Javascript

Body:
<script src="https://www.google.com/recaptcha/api.js" async defer></script>

Recaptcha documentation provides you with the correct example, which in this case I've added above. You should add that script tag before your closing </body> tag.

Or, you could enqueue it in the footer by using the $in_footer parameter of wp_enqueue_script like so:

wp_enqueue_script('stack-recaptcha','https://www.google.com/recaptcha/api.js','','',true); // $handle, $src, $dep, $ver, $in_footer

The first method is the preferred method, to take advantage of the async defer attributes of the script tag.


问:
Run a function on each item in parallel every 5 seconds with Python
I am processing a video and want to check multiple regions of interest in parallel, every 5 seconds. I would like to know if the function I currently have is accomplishing this in the correct manner.

```<code>def checkFrames():
    timer = threading.Timer(5.0, checkFrames)
    timer.daemon = True
    timer.start()
    if(started):
        index = 0
        for region in regions:
            threading.Thread(target=processRegion, args=(frame, region, index)).start()
            index += 1
</code>```

Right now I can't really tell if all of the regions are being processed in parallel (although I know that they are all being processed). The program runs pretty slow here compared to when I'm purposely checking the regions right after the other. The processing for all the regions don't have to start at the same time.

答:
You are currently creating 6 new threads for each iteration (1 checkFrames and 5 processRegion). Creating a threads is time and resources consuming. What I suggest is to create 5 threads that will process each every 5 seconds

```<code>def checkFrame(frame, region, index):
    while True:
        start_time = time.time()
        processRegion(frame, region ,index)
        sleep(5 - time.time() - start_time)
for region in len(regions):
    threading.Thread(target=checkFrame, args=(frame, region, index)).start()
</code>```

This code assumes that a processRegion call takes under 5 seconds.

Body:
I am processing a video and want to check multiple regions of interest in parallel, every 5 seconds. I would like to know if the function I currently have is accomplishing this in the correct manner.

def checkFrames():
    timer = threading.Timer(5.0, checkFrames)
    timer.daemon = True
    timer.start()
    if(started):
        index = 0
        for region in regions:
            threading.Thread(target=processRegion, args=(frame, region, index)).start()
            index += 1

Right now I can't really tell if all of the regions are being processed in parallel (although I know that they are all being processed). The program runs pretty slow here compared to when I'm purposely checking the regions right after the other. The processing for all the regions don't have to start at the same time.

Body:
You are currently creating 6 new threads for each iteration (1 checkFrames and 5 processRegion). Creating a threads is time and resources consuming. What I suggest is to create 5 threads that will process each every 5 seconds

def checkFrame(frame, region, index):
    while True:
        start_time = time.time()
        processRegion(frame, region ,index)
        sleep(5 - time.time() - start_time)
for region in len(regions):
    threading.Thread(target=checkFrame, args=(frame, region, index)).start()

This code assumes that a processRegion call takes under 5 seconds.


问:
how to create separated pages in same pdf document using play pdf
I'm using play2-pdf to generate pdf in my application I created firstly the cover page but when I try to add the other pages its added in the same pdf page how can I create multiple pages in the same pdf document also I'm trying to add a footer to the my first page but still have the same problem

```<code><html>
    <head>
        <style>
        p.serif {
        font-family: "Times New Roman", Times, serif;
        }
        p.sansserif {
        font-family: Arial, Helvetica, sans-serif;
        }
        </style>
    </head>
    <body>
        this is a test
        <div style="position:absolute; bottom:0;right:0;margin:24px;">by bSuccess</div>
    </body>
</html>
</code>```

答:
For headers and footers, you can use css paged media module (https://www.w3.org/TR/css3-page/)

Example:

```<code><html>
    <head>
        <style>
            @@page {
                @@bottom-right {
                    content: "by bSuccess";
                    font-size: 14px;
                }
            }
        </style>
    </head>
    <body>
        this is a test
    </body>
</html>
</code>```

For page breaks, you can use css page break properties (https://css-tricks.com/almanac/properties/p/page-break/)

Example:

```<code><html>
    <head>
        <style>
            @@page {
                @@bottom-right {
                    content: "by bSuccess";
                    font-size: 14px;
                }
            }
        </style>
    </head>
    <body>
        <div>this is a test</div>
        <p style="page-break-after:always;"></p>
        <div>testing page break</div>
    </body>
</html>
</code>```

Body:
I'm using play2-pdf to generate pdf in my application I created firstly the cover page but when I try to add the other pages its added in the same pdf page how can I create multiple pages in the same pdf document also I'm trying to add a footer to the my first page but still have the same problem

        this is a test

by bSuccess

Body:
For headers and footers, you can use css paged media module (https://www.w3.org/TR/css3-page/)

Example:

<html>
    <head>
        <style>
            @@page {
                @@bottom-right {
                    content: "by bSuccess";
                    font-size: 14px;
                }
            }
        </style>
    </head>
    <body>
        this is a test
    </body>
</html>

For page breaks, you can use css page break properties (https://css-tricks.com/almanac/properties/p/page-break/)

Example:

<html>
    <head>
        <style>
            @@page {
                @@bottom-right {
                    content: "by bSuccess";
                    font-size: 14px;
                }
            }
        </style>
    </head>
    <body>
        <div>this is a test</div>
        <p style="page-break-after:always;"></p>
        <div>testing page break</div>
    </body>
</html>


答:
There are 2 nextInt() methods:

nextInt() alone allows you to read an int in base 10 number

nextInt(radix) reads the next number in base N where N is 5, or 25 in your case

So, call the first one and you're done

Title: What's wrong with my Scanner java code?


问:
User CPU time vs System CPU time?
Could you explain more about "user CPU time" and "system CPU time"? I have read a lot, but I couldn't understand it well.</p>

答: The difference is whether the time is spent in user space or kernel space.  User CPU time is time spent on the processor running your program's code (or code in libraries); system CPU time is the time spent running code in the operating system kernel on behalf of your program.</p>

Title: User CPU time vs System CPU time?

ContentLicense: CC BY-SA 2.5


问:
RegEx for swiss phone number
I need a RegEx to do the validation (using Laravel, a php framework) for a swiss phone number which has to fit this format:

+41 11 111 11 11

The "+41" part has to be exactly this way while the rest (11 111 11 11) can be any number between 1 and 9.

The function that invokes the RegEx looks like this:

```<code>    $regex = "thisIsWhereINeedYourHelp";

    if (preg_match($regex, $value)) {
               return true;
            }
    return true;
</code>```

Thanks for your help!

答:
I first cleanup the string a bit (that avoids useless matches):

```<code>// input string cleanup
$input = preg_replace('/[^0-9+\(\)-]/', '', $input);
</code>```

I than match a swiss number:

```<code>// swiss telephone validation +41 (0)xx xxx xxxx
if(preg_match('/^(\+41|0041|0){1}(\(0\))?[0-9]{9}$/',$input))
        $result = "match: CH";
else    $result = "no match";
</code>```

this should match all swiss formats and be fairly reliable

Title: RegEx for swiss phone number

Body:
I need a RegEx to do the validation (using Laravel, a php framework) for a swiss phone number which has to fit this format:

+41 11 111 11 11

The "+41" part has to be exactly this way while the rest (11 111 11 11) can be any number between 1 and 9.

The function that invokes the RegEx looks like this:

    $regex = "thisIsWhereINeedYourHelp";

    if (preg_match($regex, $value)) {
               return true;
            }
    return true;

Thanks for your help!

Body:
I first cleanup the string a bit (that avoids useless matches):

// input string cleanup
$input = preg_replace('/[^0-9+\(\)-]/', '', $input);

I than match a swiss number:

// swiss telephone validation +41 (0)xx xxx xxxx
if(preg_match('/^(\+41|0041|0){1}(\(0\))?[0-9]{9}$/',$input))
        $result = "match: CH";
else    $result = "no match";

this should match all swiss formats and be fairly reliable


问:
How can I separate this grouped data by column value in MYSQL?
I have a table with the follow structure:

```<code>SELECT * FROM logs WHERE data = "Map load"
ORDER BY timestamp DESC LIMIT 5

user_id timestamp            data
3       2017-03-29 18:11:25  Map load
2       2017-03-29 18:10:11  Map load
5       2017-03-29 18:02:07  Map load
5       2017-03-29 17:48:03  Map load
3       2017-03-29 17:38:48  Map load
</code>```

I wish to group rows by 15 minute intervals, which I have done.
However, I also need to segment this data by user_id.

Grouped by interval:

```<code>SELECT FROM_UNIXTIME(FLOOR(UNIX_TIMESTAMP(timestamp)/900)*900) AS `Time`,
COUNT(*) AS `Map Load` FROM logs
WHERE data = "Map load"
GROUP BY `Time` ORDER BY `Time` DESC LIMIT 3

Time                Map Load
2017-03-29 18:00:00 3
2017-03-29 17:45:00 1
2017-03-29 17:30:00 1
</code>```

Desired Result Layout:

```<code>Time                user_id=3 user_id=2 user_id=5
2017-03-29 18:00:00 1         1         1
2017-03-29 17:45:00 0         0         1
2017-03-29 17:30:00 1         0         0
</code>```

I have other 60 users, so other than join a copy of this table for each user_id on the 15min interval timestamps, is there another method to do this?

答:
You can use conditional aggregation for this:

```<code>select FROM_UNIXTIME(FLOOR(UNIX_TIMESTAMP(timestamp) / 900) * 900) as time,
    sum(user_id = 3) as User_id_3,
    sum(user_id = 2) as User_id_2,
    sum(user_id = 5) as User_id_5
from logs
where data = "Map load"
group by time
order by time desc LIMIT 3
</code>```

If you have more number of users, it's more advisable to not pivot values in SQL but rather do it you application code:

```<code>select FROM_UNIXTIME(FLOOR(UNIX_TIMESTAMP(timestamp) / 900) * 900) as time,
    user_id,
    count(*) as cnt
from logs l
join (
    select FROM_UNIXTIME(FLOOR(UNIX_TIMESTAMP(timestamp) / 900) * 900) as time
    from logs
    group by time
    order by time desc limit 3
    ) t on FROM_UNIXTIME(FLOOR(UNIX_TIMESTAMP(timestamp) / 900) * 900) = t.time
where data = 'Map load'
group by time,
    user_id
order by time desc;
</code>```

Body:
I have a table with the follow structure:

SELECT * FROM logs WHERE data = "Map load"
ORDER BY timestamp DESC LIMIT 5

user_id timestamp            data
3       2017-03-29 18:11:25  Map load
2       2017-03-29 18:10:11  Map load
5       2017-03-29 18:02:07  Map load
5       2017-03-29 17:48:03  Map load
3       2017-03-29 17:38:48  Map load

I wish to group rows by 15 minute intervals, which I have done.
However, I also need to segment this data by user_id.

Grouped by interval:

SELECT FROM_UNIXTIME(FLOOR(UNIX_TIMESTAMP(timestamp)/900)*900) AS `Time`,
COUNT(*) AS `Map Load` FROM logs
WHERE data = "Map load"
GROUP BY `Time` ORDER BY `Time` DESC LIMIT 3

Time                Map Load
2017-03-29 18:00:00 3
2017-03-29 17:45:00 1
2017-03-29 17:30:00 1

Desired Result Layout:

Time                user_id=3 user_id=2 user_id=5
2017-03-29 18:00:00 1         1         1
2017-03-29 17:45:00 0         0         1
2017-03-29 17:30:00 1         0         0

I have other 60 users, so other than join a copy of this table for each user_id on the 15min interval timestamps, is there another method to do this?

Body:
You can use conditional aggregation for this:

select FROM_UNIXTIME(FLOOR(UNIX_TIMESTAMP(timestamp) / 900) * 900) as time,
    sum(user_id = 3) as User_id_3,
    sum(user_id = 2) as User_id_2,
    sum(user_id = 5) as User_id_5
from logs
where data = "Map load"
group by time
order by time desc LIMIT 3

If you have more number of users, it's more advisable to not pivot values in SQL but rather do it you application code:

select FROM_UNIXTIME(FLOOR(UNIX_TIMESTAMP(timestamp) / 900) * 900) as time,
    user_id,
    count(*) as cnt
from logs l
join (
    select FROM_UNIXTIME(FLOOR(UNIX_TIMESTAMP(timestamp) / 900) * 900) as time
    from logs
    group by time
    order by time desc limit 3
    ) t on FROM_UNIXTIME(FLOOR(UNIX_TIMESTAMP(timestamp) / 900) * 900) = t.time
where data = 'Map load'
group by time,
    user_id
order by time desc;


问:
Copying selection from last row
I have a table, with headers in the range A2:V2 and the data in the range A3:VXX, where XX is the last row number.

I am trying to write a macro which duplicates the values of the last row, but only for columns A:P. So Duplicating the values in AXX:PXX. I have no issues finding and copying the entire last row, however I cannot copy a limited range within it.

Apologies earlier for not including the code I have used.

```<code>With Activesheet
    .cells(.rows.count,1).end(xlup).entirerow.copy
End With
</code>```

答:
you can use:

```<code>With ActiveSheet
    .Cells(.Rows.Count, 1).End(xlUp).EntireRow.Columns("A:P").Copy
End With
</code>```

or, since ActiveSheet is the default sheet, simply:

```<code>Cells(Rows.Count, 1).End(xlUp).EntireRow.Columns("A:P").Copy
</code>```

Title: Copying selection from last row

Body:
I have a table, with headers in the range A2:V2 and the data in the range A3:VXX, where XX is the last row number.

I am trying to write a macro which duplicates the values of the last row, but only for columns A:P. So Duplicating the values in AXX:PXX. I have no issues finding and copying the entire last row, however I cannot copy a limited range within it.

Apologies earlier for not including the code I have used.

With Activesheet
    .cells(.rows.count,1).end(xlup).entirerow.copy
End With

Body:
you can use:

With ActiveSheet
    .Cells(.Rows.Count, 1).End(xlUp).EntireRow.Columns("A:P").Copy
End With

or, since ActiveSheet is the default sheet, simply:

Cells(Rows.Count, 1).End(xlUp).EntireRow.Columns("A:P").Copy


问:
how to switch to a variable sheet based on a cell value in google sheets
I am looking to create a button in google sheets and assign it a script which will take the user to a specific sheet based on a specific string in a cell.

I have played around trying to merge other answers to similar questions but i haven't been successful!

This is where i am at currently:

```<code>function sheetchanger() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var cell = ss.getRange("Lookup!B5");
ss.setActiveSheet(cell)
</code>```

I am really, REALLY new to code, so please excuse the above if it is way off!

Thanks for any and all help :)

答:
It seems in my terrible knowledge of coding, I asked the script to look at the data in B5 but not to take it....

```<code>function sheetchanger() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('Lookup');
var cell = sheet.getRange("B5").getValue();

ss.setActiveSheet(ss.getSheetByName(cell));
}
</code>```

I just needed to add the .getValue on it!

Body:
I am looking to create a button in google sheets and assign it a script which will take the user to a specific sheet based on a specific string in a cell.

I have played around trying to merge other answers to similar questions but i haven't been successful!

This is where i am at currently:

function sheetchanger() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var cell = ss.getRange("Lookup!B5");
ss.setActiveSheet(cell)

I am really, REALLY new to code, so please excuse the above if it is way off!

Thanks for any and all help :)

Body:
It seems in my terrible knowledge of coding, I asked the script to look at the data in B5 but not to take it....

function sheetchanger() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('Lookup');
var cell = sheet.getRange("B5").getValue();

ss.setActiveSheet(ss.getSheetByName(cell));
}

I just needed to add the .getValue on it!


问:
Why does my Visual Studio Win32 project require .NET 3.5 SP1 to install?
Using Visual Studio 2008, I created a C++ Win32 project. To release the program, I made a Visual Studio setup project within the same solution.

The setup.exe prompts my users to install .NET 3.5 SP1, which is often a 15+ minute install and only allowed to administrator level accounts. If they do not there is an error along the lines of "wrong framework". I am confused over what in my project requires .NET 3.5 SP1. I suspect just because that is the framework my PC is on... Is there a way to broaden which frameworks it will run on?

The code is mostly Win32 API calls. Just in case, here are my dependencies and #includes:

```<code>gdiplus.lib
comctl32.lib
Winmm.lib
d3d9.lib
</code>```

(The setup project automatically added comdlg32.dll, then tells me to exclude it.)

```<code>#include <windows.h>
#include <tchar.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <fstream>
#include <string.h>

#include <commctrl.h>
#include <process.h>
#include <sstream>
#include <math.h>
#include <d3d9.h>
#include <time.h>
#include <gdiplus.h>
</code>```

My guess is that somewhere through windows.h there is a WIN_VER or similar version setting that is set to .NET 3.5 SP1, and this is where the dependency comes from. If that is the case, and I need to define a different version, I would love to hear everyone's advice on does / don'ts / and how-to and how far back can I go for maximum inclusion.

答:
In my case, I fixed all the problems the UI would let me, Prerequistes, common properties...  Didn't matter, still wanted that .NET 3.5.

So, I opened up the vdproj file in slickedit and modified it directly.  Changed

```<code>    "ExternalPersistence"
    {
        "LaunchCondition"
        {
            "{A06ECF26-33A3-4562-8140-9B0E340D4F24}:_38ABBBBC51344AFFA38F2922DFFFE5B5"
            {
            "Name" = "8:.NET Framework"
            "Message" = "8:[VSDNETMSG]"
            "Version" = "8:3.5.30729"
            "AllowLaterVersions" = "11:FALSE"
            "InstallUrl" = "8:http://go.microsoft.com/fwlink/?LinkId=76617"
            }
        }
    }
</code>```

to

```<code>    "ExternalPersistence"
    {
    }
</code>```

And it quit asking for .NET 3.5

OwnerDisplayName: Jeff

Body:
Using Visual Studio 2008, I created a C++ Win32 project. To release the program, I made a Visual Studio setup project within the same solution.

The setup.exe prompts my users to install .NET 3.5 SP1, which is often a 15+ minute install and only allowed to administrator level accounts. If they do not there is an error along the lines of "wrong framework". I am confused over what in my project requires .NET 3.5 SP1. I suspect just because that is the framework my PC is on... Is there a way to broaden which frameworks it will run on?

The code is mostly Win32 API calls. Just in case, here are my dependencies and #includes:

gdiplus.lib
comctl32.lib
Winmm.lib
d3d9.lib

(The setup project automatically added comdlg32.dll, then tells me to exclude it.)

#include <windows.h>
#include <tchar.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <fstream>
#include <string.h>

#include <commctrl.h>
#include <process.h>
#include <sstream>
#include <math.h>
#include <d3d9.h>
#include <time.h>
#include <gdiplus.h>

My guess is that somewhere through windows.h there is a WIN_VER or similar version setting that is set to .NET 3.5 SP1, and this is where the dependency comes from. If that is the case, and I need to define a different version, I would love to hear everyone's advice on does / don'ts / and how-to and how far back can I go for maximum inclusion.

Body:
In my case, I fixed all the problems the UI would let me, Prerequistes, common properties...  Didn't matter, still wanted that .NET 3.5.

So, I opened up the vdproj file in slickedit and modified it directly.  Changed

    "ExternalPersistence"
    {
        "LaunchCondition"
        {
            "{A06ECF26-33A3-4562-8140-9B0E340D4F24}:_38ABBBBC51344AFFA38F2922DFFFE5B5"
            {
            "Name" = "8:.NET Framework"
            "Message" = "8:[VSDNETMSG]"
            "Version" = "8:3.5.30729"
            "AllowLaterVersions" = "11:FALSE"
            "InstallUrl" = "8:http://go.microsoft.com/fwlink/?LinkId=76617"
            }
        }
    }

to

    "ExternalPersistence"
    {
    }

And it quit asking for .NET 3.5


问:
Android App Indexing - > FirebaseAppIndexingInvalidArgumentException
Hej!

I'm trying to implement app indexing content and I've started with the app-indexing Google codelabs sample.

Running this code

```<code> Indexable recipeToIndex = new Indexable.Builder()
           .setName(mRecipe.getTitle())
           .setUrl(mRecipe.getRecipeUrl())
           .setImage(mRecipe.getPhoto())
           .setDescription(mRecipe.getDescription())
           .build();

 FirebaseAppIndex.getInstance().update(recipeToIndex);
</code>```

always results in a FirebaseAppIndexingInvalidArgumentException thrown by the update() method.

```<code>com.google.firebase.appindexing.FirebaseAppIndexingInvalidArgumentException: Intent 'Intent { act=android.intent.action.VIEW dat=http://example.com pkg=com.example }' cannot be resolved. The invalid indexable is: Indexable { { id: 'http://example.com/123' } Properties { { key: 'name' value: [ 'test_name' ] } } Metadata { worksOffline: false, score: 0 } }
                          at com.google.firebase.appindexing.internal.zzn.zzb(Unknown Source)
                          at com.google.firebase.appindexing.internal.zzd$zzc$1.onComplete(Unknown Source)
                          at com.google.android.gms.tasks.zzc$1.run(Unknown Source)
                          at android.os.Handler.handleCallback(Handler.java:739)
                          at android.os.Handler.dispatchMessage(Handler.java:95)
                          at android.os.Looper.loop(Looper.java:145)
                          at android.app.ActivityThread.main(ActivityThread.java:5951)
                          at java.lang.reflect.Method.invoke(Native Method)
                          at java.lang.reflect.Method.invoke(Method.java:372)
                          at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1400)
                          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1195)
</code>```

Do you have an suggestions how to add an image to the Indexable?

答:
Delete the image message or edit the code like this.

```<code>if (friendlyMessage.getText() != null) {
   FirebaseAppIndex.getInstance().update(getMessageIndexable(friendlyMessage));
}
FirebaseUserActions.getInstance().end(getMessageViewAction(friendlyMessage));
</code>```

It seems the tutorial does not consider the message without message. All the messages should be text or text with image. To fix it you should check.
https://github.com/firebase/friendlychat/issues/160

Body:
Hej!

I'm trying to implement app indexing content and I've started with the app-indexing Google codelabs sample.

Running this code

 Indexable recipeToIndex = new Indexable.Builder()
           .setName(mRecipe.getTitle())
           .setUrl(mRecipe.getRecipeUrl())
           .setImage(mRecipe.getPhoto())
           .setDescription(mRecipe.getDescription())
           .build();

 FirebaseAppIndex.getInstance().update(recipeToIndex);

always results in a FirebaseAppIndexingInvalidArgumentException thrown by the update() method.

com.google.firebase.appindexing.FirebaseAppIndexingInvalidArgumentException: Intent 'Intent { act=android.intent.action.VIEW dat=http://example.com pkg=com.example }' cannot be resolved. The invalid indexable is: Indexable { { id: 'http://example.com/123' } Properties { { key: 'name' value: [ 'test_name' ] } } Metadata { worksOffline: false, score: 0 } }
                          at com.google.firebase.appindexing.internal.zzn.zzb(Unknown Source)
                          at com.google.firebase.appindexing.internal.zzd$zzc$1.onComplete(Unknown Source)
                          at com.google.android.gms.tasks.zzc$1.run(Unknown Source)
                          at android.os.Handler.handleCallback(Handler.java:739)
                          at android.os.Handler.dispatchMessage(Handler.java:95)
                          at android.os.Looper.loop(Looper.java:145)
                          at android.app.ActivityThread.main(ActivityThread.java:5951)
                          at java.lang.reflect.Method.invoke(Native Method)
                          at java.lang.reflect.Method.invoke(Method.java:372)
                          at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1400)
                          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1195)

Do you have an suggestions how to add an image to the Indexable?

Body:
Delete the image message or edit the code like this.

if (friendlyMessage.getText() != null) {
   FirebaseAppIndex.getInstance().update(getMessageIndexable(friendlyMessage));
}
FirebaseUserActions.getInstance().end(getMessageViewAction(friendlyMessage));

It seems the tutorial does not consider the message without message. All the messages should be text or text with image. To fix it you should check.
https://github.com/firebase/friendlychat/issues/160


问:
How a function can be automatically called upon a variable change?
I have a class consisting of variable members and a function member. The variable member occasionally changes. I want the function to be called automatically upon the variable changes. In other words, how can I tie the variables inside a class?

```<code>class line
{
   double x, y; // The poition of the lind end. The line starts at the origin (0,0)
   double l; // The length of the line
   void length()
   {
      l = Math.sqrt(x*x+y*y);
   }
}
</code>```

In example above, I need the length to be updated when x and y change.

答:
you can you properties</p>

```<code>int x
int X {
   get { return x; }
   set { x = value; YouMethod();}
}
</code>```

Body:
I have a class consisting of variable members and a function member. The variable member occasionally changes. I want the function to be called automatically upon the variable changes. In other words, how can I tie the variables inside a class?

class line
{
   double x, y; // The poition of the lind end. The line starts at the origin (0,0)
   double l; // The length of the line
   void length()
   {
      l = Math.sqrt(x*x+y*y);
   }
}

In example above, I need the length to be updated when x and y change.

Body:
you can you properties

int x
int X {
   get { return x; }
   set { x = value; YouMethod();}
}


问:
node-red displaying msyql results using the dashboard node
Newbie question: I've started playing with node-red and think it could be a great gateway drug for node.js (and javascript for that matter). But I'm already a bit stuck.

I have a flow which is performing a very simply query against a mysql database. I'm getting the results returned to me, but I have so far not been able to parse those results in any meaningful way. It looks the results are returned as an array, but how can I access and manipulate that array, in a function? Below is the data being passed in from the mysql node:

```<code>[
  { "at_time": "2017-03-27T18:33:46.000Z", "event": "gone_to_bed" },
  { "at_time": "2017-03-27T22:14:02.000Z", "event": "woke_up" },
  { "at_time": "2017-03-27T22:14:12.000Z", "event": "food" },
  { "at_time": "2017-03-28T00:13:42.000Z", "event": "woke_up" },
  { "at_time": "2017-03-28T03:50:15.000Z", "event": "woke_up" },
  { "at_time": "2017-03-28T05:12:33.000Z", "event": "woke_up" },
  { "at_time": "2017-03-28T05:12:38.000Z", "event": "food" },
  { "at_time": "2017-03-28T06:56:29.000Z", "event": "up_for_day" },
  { "at_time": "2017-03-28T18:08:49.000Z", "event": "gone_to_bed" },
  { "at_time": "2017-03-28T18:32:48.000Z", "event": "woke_up" }
]
</code>```

Thanks!

答:
JavaScript arrays have many functions available to help you work with their content. It is too broad a subject to provide a succinct answer without more details on specifically what you want to do.

As you identify, Node-RED is built using JavaScript and its Function node is no different.

Assuming your Function is receiving that array as msg.payload, you would use the following syntax to access the various elements:

```<code>var firstElement = msg.payload[0];
var secondElement = msg.payload[1];
</code>```

and so on.

Each element of that array appears to be a JavaScript object - with key/value pairs. To access those values you would use the following syntax:

```<code>var first_at_time = firstElement.at_time;
var first_event = firstElement.event;
</code>```

These are fundamental operations with javascript and there are plenty of guides available that will introduce you to them, such as: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps/Arrays

Body:
Newbie question: I've started playing with node-red and think it could be a great gateway drug for node.js (and javascript for that matter). But I'm already a bit stuck.

I have a flow which is performing a very simply query against a mysql database. I'm getting the results returned to me, but I have so far not been able to parse those results in any meaningful way. It looks the results are returned as an array, but how can I access and manipulate that array, in a function? Below is the data being passed in from the mysql node:

[
  { "at_time": "2017-03-27T18:33:46.000Z", "event": "gone_to_bed" },
  { "at_time": "2017-03-27T22:14:02.000Z", "event": "woke_up" },
  { "at_time": "2017-03-27T22:14:12.000Z", "event": "food" },
  { "at_time": "2017-03-28T00:13:42.000Z", "event": "woke_up" },
  { "at_time": "2017-03-28T03:50:15.000Z", "event": "woke_up" },
  { "at_time": "2017-03-28T05:12:33.000Z", "event": "woke_up" },
  { "at_time": "2017-03-28T05:12:38.000Z", "event": "food" },
  { "at_time": "2017-03-28T06:56:29.000Z", "event": "up_for_day" },
  { "at_time": "2017-03-28T18:08:49.000Z", "event": "gone_to_bed" },
  { "at_time": "2017-03-28T18:32:48.000Z", "event": "woke_up" }
]

Thanks!

Body:
JavaScript arrays have many functions available to help you work with their content. It is too broad a subject to provide a succinct answer without more details on specifically what you want to do.

As you identify, Node-RED is built using JavaScript and its Function node is no different.

Assuming your Function is receiving that array as msg.payload, you would use the following syntax to access the various elements:

var firstElement = msg.payload[0];
var secondElement = msg.payload[1];

and so on.

Each element of that array appears to be a JavaScript object - with key/value pairs. To access those values you would use the following syntax:

var first_at_time = firstElement.at_time;
var first_event = firstElement.event;

These are fundamental operations with javascript and there are plenty of guides available that will introduce you to them, such as: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps/Arrays


问:
Confirmation message before removing a product from cart
I just notice that in WooCommerce if customer removes a product from cart, there is no warning message or confirmation before deleting it.

Is there any ways to make a confirmation before removing a product from cart?

Thanks.

答:
If you look at WC_Cart remove_cart_item() method source code here you will see on line 1015 that you can only use woocommerce_remove_cart_item action hook that is triggered before an item is removed from cart.

As removing an item is ajax driven in cart page, to do what you are expecting is certainly possible, but something really complicated.

Remember that on cart page, you already got a notice when you remove a cart items, that allow you to restore it… So adding a confirmation notice, is not really viable and even disturbing for customer experience.


答:
No need to specify the radix to nextInt.

Just use the no args version of nextInt.

Replace

int num1 = in.nextInt(5);

with

int num1 = in.nextInt();

And

int num2 = in.nextInt(25);

with

int num2 = in.nextInt();

Title: What's wrong with my Scanner java code?

Body:
import java.util.Scanner;

public class Exercise5 {

 public static void main(String[] args) {
  Scanner in = new Scanner(System.in);

  System.out.print("Input first number: ");
  int num1 = in.nextInt(5);

  System.out.print("Input second number: ");
  int num2 = in.nextInt(25);

  System.out.println(num1 + " x " + num2 + " = " + num1 * num2);
 }

}

**Here is my java code, the expect output should be like this:

Input first number: 25

Input second number: 5

25 x 5 = 125

After I plug in my code and run it, the output is too different with the answer

Here is the output:

Input first number: Exception in thread "main"   java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at Exercise5.main(Exercise5.java:27)

How can I fix my code?


问:
Only one IF ELSE statement working SAS
Can someone explain to me why only the first IF ELSE statement in my code works? I am trying to combine multiple variables into one.

```<code>DATA BCMasterSet2;
SET BCMasterSet;
drop PositiveLymphNodes1;
if PositiveLymphNodes1 = "." then PositiveLymphNodes =
put(PositiveLymphNodes2, 2.);
else PositiveLymphNodes = PositiveLymphNodes1;
if PositiveLymphNodes2 = "." then new_posLymph = put(PositiveLymphNodes,
2.);
else new_posLymph = PositiveLymphNodes2;
RUN;
</code>```

Here is a nice screenshot of what the incorrect output looks like:OUTPUT

Thanks!

答:
Hard to say without seeing all of your data, but I have a suspicion:  is positivelymphnodes1 character or numeric?  Is it ever actually equal to "."?

If you are trying to say "if PositiveLymphNodes1 is missing", then you can say that this way:

```<code>if missing(positivelymphnodes1) then ...
</code>```

You can also do the same thing using coalesce or coalescec (the latter is character, the former numeric, in its return value).  It chooses the first nonmissing argument. - so if the first argument is missing, it chooses the second.

```<code>positiveLymphNodes = coalescec(PositiveLymphNodes1, put(positiveLymphNodes2,2.));
new_posLymph = coalescec(positiveLymphNodes2, put(positiveLymphNodes,2.));
</code>```

I would be curious why you're using put only in one place and not the other - use it in both or neither, I would suggest.

Title: Only one IF ELSE statement working SAS

Body:
Can someone explain to me why only the first IF ELSE statement in my code works? I am trying to combine multiple variables into one.

DATA BCMasterSet2;
SET BCMasterSet;
drop PositiveLymphNodes1;
if PositiveLymphNodes1 = "." then PositiveLymphNodes =
put(PositiveLymphNodes2, 2.);
else PositiveLymphNodes = PositiveLymphNodes1;
if PositiveLymphNodes2 = "." then new_posLymph = put(PositiveLymphNodes,
2.);
else new_posLymph = PositiveLymphNodes2;
RUN;

Here is a nice screenshot of what the incorrect output looks like:OUTPUT

Thanks!

Body:
Hard to say without seeing all of your data, but I have a suspicion:  is positivelymphnodes1 character or numeric?  Is it ever actually equal to "."?

If you are trying to say "if PositiveLymphNodes1 is missing", then you can say that this way:

if missing(positivelymphnodes1) then ...

You can also do the same thing using coalesce or coalescec (the latter is character, the former numeric, in its return value).  It chooses the first nonmissing argument. - so if the first argument is missing, it chooses the second.

positiveLymphNodes = coalescec(PositiveLymphNodes1, put(positiveLymphNodes2,2.));
new_posLymph = coalescec(positiveLymphNodes2, put(positiveLymphNodes,2.));

I would be curious why you're using put only in one place and not the other - use it in both or neither, I would suggest.


问:
How to test value is inside array with awk

my-script.awk

```<code>#!/env/bin awk
BEGIN {
    toggleValues="U+4E00,U+9FFF,U+3400,U+4DBF,U+20000,U+2A6DF,U+2A700,U+2B73F,U+2B740,U+2B81F,U+2B820,U+2CEAF,U+F900,U+FAFF"
    split(toggleValues, boundaries, ",")
    if ("U+4E00" in boundaries) {print "inside"}
}
</code>```

Run

```<code>echo ''| awk -f my-script.awk
</code>```

Question

Why I don't see inside printed?

答:
awk stores arrays differently then what you expect. It's a key/value pair with the key (from split() is the integer index starting at 0 and the value is the string that was split() it into that element.

The awk in condition tests keys, not values. So your "U+4E00" in boundaries condition isn't going to pass. Instead you'll need to iterate your array and look for the value.

```<code>for (boundary in boundaries) { if(boundaries[boundary] == "U+4E00") { print "inside" }
</code>```

Either that or you can create a new array based on the existing one, but with the values stored as the key so the in operator will work as is.

```<code>for (i in boundaries) {boundaries2[boundaries[i]] = ""}
if ("U+4E00" in boundaries2){print "inside"}
</code>```

This second method is a little hackey since all your element values are set to "", but it's useful if you are going to iterate through large file and just want to use the in operator to test that a field is in your array (as opposed to iterating the array on each record, which might be more expensive).

Body:
my-script.awk

#!/env/bin awk
BEGIN {
    toggleValues="U+4E00,U+9FFF,U+3400,U+4DBF,U+20000,U+2A6DF,U+2A700,U+2B73F,U+2B740,U+2B81F,U+2B820,U+2CEAF,U+F900,U+FAFF"
    split(toggleValues, boundaries, ",")
    if ("U+4E00" in boundaries) {print "inside"}
}

Run

echo ''| awk -f my-script.awk

Question

Why I don't see inside printed?

Body:
awk stores arrays differently then what you expect. It's a key/value pair with the key (from split() is the integer index starting at 0 and the value is the string that was split() it into that element.

The awk in condition tests keys, not values. So your "U+4E00" in boundaries condition isn't going to pass. Instead you'll need to iterate your array and look for the value.

for (boundary in boundaries) { if(boundaries[boundary] == "U+4E00") { print "inside" }

Either that or you can create a new array based on the existing one, but with the values stored as the key so the in operator will work as is.

for (i in boundaries) {boundaries2[boundaries[i]] = ""}
if ("U+4E00" in boundaries2){print "inside"}

This second method is a little hackey since all your element values are set to "", but it's useful if you are going to iterate through large file and just want to use the in operator to test that a field is in your array (as opposed to iterating the array on each record, which might be more expensive).


问:
android firebase one to one chat application
i try to develop one to one chat application using mvp
when the application run for the first time the chat  works correctly and  messsges are sent to users .
the problem is when i try to register with another account  and try to send messages firebase  creates two different chat rooms and i can't get messages because the second user didn't detect that a chat room has been created and create an other one
cn you help me please ??
This the code where i try to send message:

final String room_type_1 = chat.getSenderUid() + "_" + chat.getReceiverUid();
        final String room_type_2 = chat.getReceiverUid() + "_" + chat.getSenderUid();

```<code>    final DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference();

    databaseReference.child(Constants.ARG_CHAT_ROOMS).getRef().addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if (dataSnapshot.hasChild(room_type_1)) {
                Log.e(TAG, "sendMessageToFirebaseUser: " + room_type_1 + " exists");
                databaseReference.child(Constants.ARG_CHAT_ROOMS).child(room_type_1).child(String.valueOf(chat.getTimestamp())).setValue(chat);
            } else if (dataSnapshot.hasChild(room_type_2)) {
                Log.e(TAG, "sendMessageToFirebaseUser: " + room_type_2 + " exists");
                databaseReference.child(Constants.ARG_CHAT_ROOMS).child(room_type_2).child(String.valueOf(chat.getTimestamp())).setValue(chat);

            } else {
                Log.e(TAG, "sendMessageToFirebaseUser: success");
                Log.e("sender uis",""+chat.getSenderUid());
                Log.e("srevier uis",""+chat.getSenderUid());
                databaseReference.child(Constants.ARG_CHAT_ROOMS).child(room_type_1).child(String.valueOf(chat.getTimestamp())).setValue(chat);
                getMessageFromFirebaseUser(chat.getSenderUid(), chat.getReceiverUid());

            }

            sendPushNotificationToReceiver(chat.sender,
                    chat.message,
                    chat.senderUid,
                    new SharedPrefUtil(context).getString(Constants.ARG_FIREBASE_TOKEN),
                    receiverFirebaseToken);
            mOnSendMessageListener.onSendMessageSuccess();

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            mOnSendMessageListener.onSendMessageFailure("Unable to send message: " + databaseError.getMessage());
        }
    });
}
</code>```

and this is the code where i get message from firebase

public void getMessageFromFirebaseUser(final Context context, String senderUid, String receiverUid, final ChatFragmentListener chatFragmentListener) {

```<code>    final String room_type_1 = senderUid + "_" + receiverUid;
    final String room_type_2 = receiverUid + "_" + senderUid;

    final DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference();

    final DatabaseReference databaseChats = FirebaseDatabase.getInstance().getReference().child(Constants.ARG_CHAT_ROOMS);
    databaseChats.keepSynced(true);

    databaseReference.child(Constants.ARG_CHAT_ROOMS).getRef().addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if (dataSnapshot.hasChild(room_type_1)) {
                Log.e(TAG, "getMessageFromFirebaseUser: " + room_type_1 + " exists");

                FirebaseDatabase.getInstance()
                        .getReference()
                        .child(Constants.ARG_CHAT_ROOMS)
                        .child(room_type_1).addChildEventListener(new ChildEventListener() {
                    @Override
                    public void onChildAdded(DataSnapshot dataSnapshot, String s) {

                        if (dataSnapshot.getKey() != s) {
                            Chat chat = new Chat();
                            chat = dataSnapshot.getValue(Chat.class);
                            chatFragmentListener.onGetMessagesSuccess(chat);

                            Log.e("1", "get");
                        }

                        // do something here

                    }

                    @Override
                    public void onChildChanged(DataSnapshot dataSnapshot, String s) {
                             /* Log.e("childadded","eeeee"+s);
                                Log.e("chilchanged","ee"+dataSnapshot.getKey());
                                Chat chat=dataSnapshot.getValue(Chat.class);
                                String key=dataSnapshot.getKey();
                                if(!key.equals(s)){chats.add(chat);}*/

                    }

                    @Override
                    public void onChildRemoved(DataSnapshot dataSnapshot) {

                    }

                    @Override
                    public void onChildMoved(DataSnapshot dataSnapshot, String s) {
                              /* Log.e("childadded","eeeee"+s);
                                Log.e("childmoved","ee"+dataSnapshot.getKey());
                                Chat chat=dataSnapshot.getValue(Chat.class);
                                String key=dataSnapshot.getKey();
                                if(key.equals(s)){chats.remove(chat);}*/
                    }

                    @Override
                    public void onCancelled(DatabaseError databaseError) {
                        // lll
                        chatFragmentListener.onGetMessagesFailure("Unable to get message: " + databaseError.getMessage());
                    }
                });

            } else if (dataSnapshot.hasChild(room_type_2)) {
                Log.e(TAG, "getMessageFromFirebaseUser: " + room_type_2 + " exists");

                FirebaseDatabase.getInstance()
                        .getReference()
                        .child(Constants.ARG_CHAT_ROOMS)
                        .child(room_type_2).addChildEventListener(new ChildEventListener() {
                    @Override
                    public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                        Chat chat = new Chat();
                        chat = dataSnapshot.getValue(Chat.class);
                        chatFragmentListener.onGetMessagesSuccess(chat);
                        Log.e("2", "get");
                    }

                    @Override
                    public void onChildChanged(DataSnapshot dataSnapshot, String s) {

                    }

                    @Override
                    public void onChildRemoved(DataSnapshot dataSnapshot) {

                    }

                    @Override
                    public void onChildMoved(DataSnapshot dataSnapshot, String s) {

                    }

                    @Override
                    public void onCancelled(DatabaseError databaseError) {
                        chatFragmentListener.onGetMessagesFailure("Unable to get message: " + databaseError.getMessage());
                    }
                });

            } else {
                Log.e(TAG, "getMessageFromFirebaseUser: no such room available");
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            chatFragmentListener.onGetMessagesFailure("Unable to get message: " + databaseError.getMessage());
        }
    });

}
</code>```

.

答:
Simplest solution for this problem is create chat room by arranging both the user uuid in ascending or descending order.

```<code>public String getChatRoom(String fromUserId,String toMessageId){

           String chatRoom;

            if(fromUserId.compareTo(toMessageId) < 0 ){
                // ToMessageId has less alphabetic order then fromUserId
              chatRoom =  toMessageId+" "+fromUserId;
            }else{
              chatRoom  = fromUserId+" "+toMessageId;
            }
            return chatRoom;
}
</code>```

Here is sample implementation of firebase chat app

Body:
i try to develop one to one chat application using mvp
when the application run for the first time the chat  works correctly and  messsges are sent to users .
the problem is when i try to register with another account  and try to send messages firebase  creates two different chat rooms and i can't get messages because the second user didn't detect that a chat room has been created and create an other one
cn you help me please ??
This the code where i try to send message:

final String room_type_1 = chat.getSenderUid() + "_" + chat.getReceiverUid();
        final String room_type_2 = chat.getReceiverUid() + "_" + chat.getSenderUid();

    final DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference();

    databaseReference.child(Constants.ARG_CHAT_ROOMS).getRef().addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if (dataSnapshot.hasChild(room_type_1)) {
                Log.e(TAG, "sendMessageToFirebaseUser: " + room_type_1 + " exists");
                databaseReference.child(Constants.ARG_CHAT_ROOMS).child(room_type_1).child(String.valueOf(chat.getTimestamp())).setValue(chat);
            } else if (dataSnapshot.hasChild(room_type_2)) {
                Log.e(TAG, "sendMessageToFirebaseUser: " + room_type_2 + " exists");
                databaseReference.child(Constants.ARG_CHAT_ROOMS).child(room_type_2).child(String.valueOf(chat.getTimestamp())).setValue(chat);

            } else {
                Log.e(TAG, "sendMessageToFirebaseUser: success");
                Log.e("sender uis",""+chat.getSenderUid());
                Log.e("srevier uis",""+chat.getSenderUid());
                databaseReference.child(Constants.ARG_CHAT_ROOMS).child(room_type_1).child(String.valueOf(chat.getTimestamp())).setValue(chat);
                getMessageFromFirebaseUser(chat.getSenderUid(), chat.getReceiverUid());

            }

            sendPushNotificationToReceiver(chat.sender,
                    chat.message,
                    chat.senderUid,
                    new SharedPrefUtil(context).getString(Constants.ARG_FIREBASE_TOKEN),
                    receiverFirebaseToken);
            mOnSendMessageListener.onSendMessageSuccess();

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            mOnSendMessageListener.onSendMessageFailure("Unable to send message: " + databaseError.getMessage());
        }
    });
}

and this is the code where i get message from firebase

public void getMessageFromFirebaseUser(final Context context, String senderUid, String receiverUid, final ChatFragmentListener chatFragmentListener) {

    final String room_type_1 = senderUid + "_" + receiverUid;
    final String room_type_2 = receiverUid + "_" + senderUid;

    final DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference();

    final DatabaseReference databaseChats = FirebaseDatabase.getInstance().getReference().child(Constants.ARG_CHAT_ROOMS);
    databaseChats.keepSynced(true);

    databaseReference.child(Constants.ARG_CHAT_ROOMS).getRef().addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if (dataSnapshot.hasChild(room_type_1)) {
                Log.e(TAG, "getMessageFromFirebaseUser: " + room_type_1 + " exists");

                FirebaseDatabase.getInstance()
                        .getReference()
                        .child(Constants.ARG_CHAT_ROOMS)
                        .child(room_type_1).addChildEventListener(new ChildEventListener() {
                    @Override
                    public void onChildAdded(DataSnapshot dataSnapshot, String s) {

                        if (dataSnapshot.getKey() != s) {
                            Chat chat = new Chat();
                            chat = dataSnapshot.getValue(Chat.class);
                            chatFragmentListener.onGetMessagesSuccess(chat);

                            Log.e("1", "get");
                        }

                        // do something here

                    }

                    @Override
                    public void onChildChanged(DataSnapshot dataSnapshot, String s) {
                             /* Log.e("childadded","eeeee"+s);
                                Log.e("chilchanged","ee"+dataSnapshot.getKey());
                                Chat chat=dataSnapshot.getValue(Chat.class);
                                String key=dataSnapshot.getKey();
                                if(!key.equals(s)){chats.add(chat);}*/

                    }

                    @Override
                    public void onChildRemoved(DataSnapshot dataSnapshot) {

                    }

                    @Override
                    public void onChildMoved(DataSnapshot dataSnapshot, String s) {
                              /* Log.e("childadded","eeeee"+s);
                                Log.e("childmoved","ee"+dataSnapshot.getKey());
                                Chat chat=dataSnapshot.getValue(Chat.class);
                                String key=dataSnapshot.getKey();
                                if(key.equals(s)){chats.remove(chat);}*/
                    }

                    @Override
                    public void onCancelled(DatabaseError databaseError) {
                        // lll
                        chatFragmentListener.onGetMessagesFailure("Unable to get message: " + databaseError.getMessage());
                    }
                });

            } else if (dataSnapshot.hasChild(room_type_2)) {
                Log.e(TAG, "getMessageFromFirebaseUser: " + room_type_2 + " exists");

                FirebaseDatabase.getInstance()
                        .getReference()
                        .child(Constants.ARG_CHAT_ROOMS)
                        .child(room_type_2).addChildEventListener(new ChildEventListener() {
                    @Override
                    public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                        Chat chat = new Chat();
                        chat = dataSnapshot.getValue(Chat.class);
                        chatFragmentListener.onGetMessagesSuccess(chat);
                        Log.e("2", "get");
                    }

                    @Override
                    public void onChildChanged(DataSnapshot dataSnapshot, String s) {

                    }

                    @Override
                    public void onChildRemoved(DataSnapshot dataSnapshot) {

                    }

                    @Override
                    public void onChildMoved(DataSnapshot dataSnapshot, String s) {

                    }

                    @Override
                    public void onCancelled(DatabaseError databaseError) {
                        chatFragmentListener.onGetMessagesFailure("Unable to get message: " + databaseError.getMessage());
                    }
                });

            } else {
                Log.e(TAG, "getMessageFromFirebaseUser: no such room available");
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            chatFragmentListener.onGetMessagesFailure("Unable to get message: " + databaseError.getMessage());
        }
    });

}

.

Body:
Simplest solution for this problem is create chat room by arranging both the user uuid in ascending or descending order.

public String getChatRoom(String fromUserId,String toMessageId){

           String chatRoom;

            if(fromUserId.compareTo(toMessageId) < 0 ){
                // ToMessageId has less alphabetic order then fromUserId
              chatRoom =  toMessageId+" "+fromUserId;
            }else{
              chatRoom  = fromUserId+" "+toMessageId;
            }
            return chatRoom;
}

Here is sample implementation of firebase chat app


问:
Update multiple columns in table with SET command
I don't necessarily have an error, mainly curious as to what is going on behind the scenes with an UPDATE I am trying to perform on multiple columns of the same table on a single record, using the value of one column and some math to set the value in the other column. Basically a two for one is what I am trying to accomplish.
I have this row in a table named pipe_tally3:

```<code> id |  jt_id   | man_jt_num |  heat  | lt |   manu   | wall_thick | diam | grade | coat_type | coat_thick | loc  | cuts | new_lt | pup | notes |    date
----+----------+------------+--------+----+----------+------------+------+-------+-----------+------------+------+------+--------+-----+-------+------------
  2 | Asset-33 | 1919A      | 39393b | 74 | american |      0.393 |   10 | x44   | stiff     | 12 mils    | yard |    0 |      0 | na  | na    | 2017-03-27
</code>```

I try to UPDATE it like this:

```<code>UPDATE pipe_tally3
SET cuts = 2.0, new_lt = lt - cuts
WHERE jt_id = 'Asset-33';
UPDATE 1
</code>```

Then when I check that row again:

```<code> id |  jt_id   | man_jt_num |  heat  | lt |   manu   | wall_thick | diam | grade | coat_type | coat_thick | loc  | cuts | new_lt | pup | notes |    date
----+----------+------------+--------+----+----------+------------+------+-------+-----------+------------+------+------+--------+-----+-------+------------
  2 | Asset-33 | 1919A      | 39393b | 74 | american |      0.393 |   10 | x44   | stiff     | 12 mils    | yard |    2 |     74 | na  | na    | 2017-03-27
</code>```

The cuts column did get updated and is now showing the value 2 but the new_lt columns shows the value 74. But it should be (or I want it set to) the value of 72, which would be the value of the lt column 74 subtracted from the cuts column of 2. Why does this not work like this is my main question?
But if I update the cuts column by itself with

```<code>UPDATE pipe_tally3
SET cuts = 3.0 WHERE jt_id = 'Asset-33';
UPDATE 1
</code>```

And it does get updated.

```<code>id |  jt_id   | man_jt_num |  heat  | lt |   manu   | wall_thick | diam | grade | coat_type | coat_thick | loc  | cuts | new_lt | pup | notes |    date
----+----------+------------+--------+----+----------+------------+------+-------+-----------+------------+------+------+--------+-----+-------+------------
  2 | Asset-33 | 1919A      | 39393b | 74 | american |      0.393 |   10 | x44   | stiff     | 12 mils    | yard |    3 |     72 | na  | na    | 2017-03-27
</code>```

I can then use

```<code>UPDATE pipe_tally3
SET new_lt = lt - cuts WHERE jt_id = 'Asset-33';
UPDATE 1
</code>```

And it works as desired by using the values from the lt and cuts columns when it sets the new_lt:

```<code>id |  jt_id   | man_jt_num |  heat  | lt |   manu   | wall_thick | diam | grade | coat_type | coat_thick | loc  | cuts | new_lt | pup | notes |    date
----+----------+------------+--------+----+----------+------------+------+-------+-----------+------------+------+------+--------+-----+-------+------------
  2 | Asset-33 | 1919A      | 39393b | 74 | american |      0.393 |   10 | x44   | stiff     | 12 mils    | yard |    3 |     71 | na  | na    | 2017-03-27
</code>```

Is there a way I can accomplish this in PostgreSQL? Thanks in advance.

Edit
I realize I can always do this by hard coding the value in as well:

```<code>UPDATE pipe_tally3
SET cuts = 3.5, new_lt = lt - 3.5
WHERE jt_id = 'Asset-33';
UPDATE 1
</code>```

And that works

```<code>id |  jt_id   | man_jt_num |  heat  | lt |   manu   | wall_thick | diam | grade | coat_type | coat_thick | loc  | cuts | new_lt | pup | notes |    date
----+----------+------------+--------+----+----------+------------+------+-------+-----------+------------+------+------+--------+-----+-------+------------
  2 | Asset-33 | 1919A      | 39393b | 74 | american |      0.393 |   10 | x44   | stiff     | 12 mils    | yard |  3.5 |   70.5 | na  | na    | 2017-03-27
</code>```

Just wanted to know why it does not work (or I am not doing something correctly) the other way as specified above.

答:
As you observe = lt - cuts uses the value of cuts before its been updated which is 74 - 0 so the value remains 74.

This is the behaviour in most databases, describing the expression value for set the documentation confirms this:

An expression to assign to the column. The expression can use the old values of this and other columns in the table.

Body:
I don't necessarily have an error, mainly curious as to what is going on behind the scenes with an UPDATE I am trying to perform on multiple columns of the same table on a single record, using the value of one column and some math to set the value in the other column. Basically a two for one is what I am trying to accomplish.
I have this row in a table named pipe_tally3:

 id |  jt_id   | man_jt_num |  heat  | lt |   manu   | wall_thick | diam | grade | coat_type | coat_thick | loc  | cuts | new_lt | pup | notes |    date
----+----------+------------+--------+----+----------+------------+------+-------+-----------+------------+------+------+--------+-----+-------+------------
  2 | Asset-33 | 1919A      | 39393b | 74 | american |      0.393 |   10 | x44   | stiff     | 12 mils    | yard |    0 |      0 | na  | na    | 2017-03-27

I try to UPDATE it like this:

UPDATE pipe_tally3
SET cuts = 2.0, new_lt = lt - cuts
WHERE jt_id = 'Asset-33';
UPDATE 1

Then when I check that row again:

 id |  jt_id   | man_jt_num |  heat  | lt |   manu   | wall_thick | diam | grade | coat_type | coat_thick | loc  | cuts | new_lt | pup | notes |    date
----+----------+------------+--------+----+----------+------------+------+-------+-----------+------------+------+------+--------+-----+-------+------------
  2 | Asset-33 | 1919A      | 39393b | 74 | american |      0.393 |   10 | x44   | stiff     | 12 mils    | yard |    2 |     74 | na  | na    | 2017-03-27

The cuts column did get updated and is now showing the value 2 but the new_lt columns shows the value 74. But it should be (or I want it set to) the value of 72, which would be the value of the lt column 74 subtracted from the cuts column of 2. Why does this not work like this is my main question?
But if I update the cuts column by itself with

UPDATE pipe_tally3
SET cuts = 3.0 WHERE jt_id = 'Asset-33';
UPDATE 1

And it does get updated.

id |  jt_id   | man_jt_num |  heat  | lt |   manu   | wall_thick | diam | grade | coat_type | coat_thick | loc  | cuts | new_lt | pup | notes |    date
----+----------+------------+--------+----+----------+------------+------+-------+-----------+------------+------+------+--------+-----+-------+------------
  2 | Asset-33 | 1919A      | 39393b | 74 | american |      0.393 |   10 | x44   | stiff     | 12 mils    | yard |    3 |     72 | na  | na    | 2017-03-27

I can then use

UPDATE pipe_tally3
SET new_lt = lt - cuts WHERE jt_id = 'Asset-33';
UPDATE 1

And it works as desired by using the values from the lt and cuts columns when it sets the new_lt:

id |  jt_id   | man_jt_num |  heat  | lt |   manu   | wall_thick | diam | grade | coat_type | coat_thick | loc  | cuts | new_lt | pup | notes |    date
----+----------+------------+--------+----+----------+------------+------+-------+-----------+------------+------+------+--------+-----+-------+------------
  2 | Asset-33 | 1919A      | 39393b | 74 | american |      0.393 |   10 | x44   | stiff     | 12 mils    | yard |    3 |     71 | na  | na    | 2017-03-27

Is there a way I can accomplish this in PostgreSQL? Thanks in advance.

Edit
I realize I can always do this by hard coding the value in as well:

UPDATE pipe_tally3
SET cuts = 3.5, new_lt = lt - 3.5
WHERE jt_id = 'Asset-33';
UPDATE 1

And that works

id |  jt_id   | man_jt_num |  heat  | lt |   manu   | wall_thick | diam | grade | coat_type | coat_thick | loc  | cuts | new_lt | pup | notes |    date
----+----------+------------+--------+----+----------+------------+------+-------+-----------+------------+------+------+--------+-----+-------+------------
  2 | Asset-33 | 1919A      | 39393b | 74 | american |      0.393 |   10 | x44   | stiff     | 12 mils    | yard |  3.5 |   70.5 | na  | na    | 2017-03-27

Just wanted to know why it does not work (or I am not doing something correctly) the other way as specified above.


问:
Recursively search groups under specific ou for a user in LDAP
We currently have an LDAP deployment with millions of users and hundreds of thousands of groups (if not millions), so doing a full recursive lookup for a user takes >3m per query.

I'm needing to find all groups for a user, but only for groups under a specific OU, as others are not relevant and are a waste of search time.

Is there a search for LDAP that can reduce the amount of searching required for the group lookup?

答:
Does your directory stamp the membership on the Users?  eDirectory does (groupMembership). Active Directory does a synthetic attribute that does the lookup when you query the attribute memberOf.

Consider stamping that on the users, then as you look at a user, the data you want is stored on the User. Not in the thousands of groups out there, where youo have to go look to see which the user is a member.


答:
If you define properties, on your class, you can make X and Y autoprops, then make a read-only property L that is calculated from these values:

```<code>public class Line //class names should be Capitalized
{
   public double X{ get; set; } //prop names should be Capitalized
   public double Y{ get; set; }
   public double L{
    get{
      return Math.Sqrt(X * X + Y * Y);
    }
   }
}
</code>```

Title: How a function can be automatically called upon a variable change?

Body:
If you define properties, on your class, you can make X and Y autoprops, then make a read-only property L that is calculated from these values:

public class Line //class names should be Capitalized
{
   public double X{ get; set; } //prop names should be Capitalized
   public double Y{ get; set; }
   public double L{
    get{
      return Math.Sqrt(X * X + Y * Y);
    }
   }
}


问:
Kestrel webserver for Asp.Net Core - does it recycle / reload after some time
Simple noob question :-)

I'm about to go into production with a small .NET core app host that's hosted in a droplet at digitalocean. I've always hosted websites using IIS, but I would like to move to linux distributions and use nginx as reverse proxy.

My question is as the title says :-) Does kestrel every need to recycle a "application pool" like the IIS does? If not, does that mean the application is loaded from Kestrel is online until it's shut down?

Best regards
Jens

答:
Based on bits of information here and there from watching all the http://live.asp.net Community Standup meetings I'd so no, Kestrel does not recycle itself the way IIS does.

The reason for this is that Kestrel currently has no way to restart itself if it stops.  That's one of the many reasons why it's important to put it behind some sort of reverse proxy like IIS or nginx.  This kind of process lifetime management functionality must currently come from a software layer outside of Kestrel.  If Kestrel dies due to a software bug or other reason and there is no reverse proxy or other process to restart it, it will not restart by itself and the website will be stay down.

For additional information, this article talks about Publishing to a Linux Production Environment and includes an example nginx system service file that has  Restart=always  https://learn.microsoft.com/en-us/aspnet/core/publishing/linuxproduction


问:
C++ static member modifiers for subclasses
Consider the following code:

```<code>#include <stdio.h>
#include <iostream>

/// Header-file
class Base {
public:
  virtual void do_something() const =0;

  int GetAttrib () const {return constattribute_;};

  static const int constattribute_;
};

typedef Base* Derived_Ptr; //<< adress derived classes by their base-class ptr; so no templates for Base

class DerivedA : public Base {
//   static const int constattribute_; //<< change this static attribute for all DerivedA class instances and their derivatives

  void do_something() const {};
};

class DerivedB : public Base {
//   static const int constattribute_; //<< change this static attribute for all DerivedB class instances and their derivatives

  void do_something() const {};
};

/// CC-file
using namespace std;

const int Base::constattribute_(0);
const int DerivedA::constattribute_(1); //<<error: no such variable 'constattribute' in class DerivedA
const int DerivedB::constattribute_(2); //<<error: no such variable 'constattribute' in class DerivedB

int main(void) {
  Derived_Ptr derivedA = new DerivedA();
  Derived_Ptr derivedB = new DerivedB();

  cout << derivedA->GetAttrib() << derivedB->GetAttrib() <<endl;
  return 0;
};
</code>```

The intend being that i have some abstract interface (Base) which defines also a variable, which should be present for all derived classes, and is retrievable. All flavours of subclasses should be forced to/able to redefine their specific value for this variable, at best during class declaration (the values are known at the time the class is declared after all).

I want to achieve code, not altering the main()-program so that the output is '12' and not as of now (uncommenting current lines in the code) '00' (Doing so shadows the fields from base class).

I tried to look into the matter, and there are different paths for solutions, many of which however go contrary to my intuition:
1. Some follow the CRTP pattern, which is however impossible if I want to address my subclasses by their base-ptr in main.
2. Other solutions require to virtualize the 'GetAttrib()' function for every derived instance., which is cumbersome, and action of modifying the attribute is masked within a function definition.
3. A third possibility is to remove the static pattern and have the 'constattribute_' field as a regular member, which however forces me to drag it through all constructors as a parameter.

I am quite sure that there must be some smarter way to do this. Any hints are appreciated.

答:
static variable in base class is single instance hence it will be reflected same in derived class.

You can make same static member variable in derived class with specific different value you want. Now make getter member function of static variable in Base class as virtual and overload it in derived class which returns is static instance value.

I have update your code to work it, please check ..

```<code>#include <iostream>

using namespace std;

class Base {
public:
  static const int constattribute_;
  virtual void do_something() const =0;
  virtual int GetAttrib () const {return constattribute_;};
};

typedef Base* Derived_Ptr; //<< adress derived classes by their base-class ptr; so no templates for Base

class DerivedA : public Base {
  static const int constattribute_; //<< change this static attribute for all DerivedA class instances and their derivatives

  void do_something() const {};
  int GetAttrib () const {return constattribute_;};
};

class DerivedB : public Base {
  static const int constattribute_; //<< change this static attribute for all DerivedB class instances and their derivatives

  void do_something() const {};
  int GetAttrib () const {return constattribute_;};
};

const int Base::constattribute_(0);
const int DerivedA::constattribute_(1); //<<error: no such variable 'constattribute' in class DerivedA
const int DerivedB::constattribute_(2); //<<error: no such variable 'constattribute' in class DerivedB

int main(void) {
  Derived_Ptr derivedA = new DerivedA();
  Derived_Ptr derivedB = new DerivedB();

  cout << derivedA->GetAttrib() << derivedB->GetAttrib() <<endl;

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

You should get desired output.

Note : Remember all member variables and func in derived class are private.

Body:
Consider the following code:

#include <stdio.h>
#include <iostream>

/// Header-file
class Base {
public:
  virtual void do_something() const =0;

  int GetAttrib () const {return constattribute_;};

  static const int constattribute_;
};

typedef Base* Derived_Ptr; //<< adress derived classes by their base-class ptr; so no templates for Base

class DerivedA : public Base {
//   static const int constattribute_; //<< change this static attribute for all DerivedA class instances and their derivatives

  void do_something() const {};
};

class DerivedB : public Base {
//   static const int constattribute_; //<< change this static attribute for all DerivedB class instances and their derivatives

  void do_something() const {};
};

/// CC-file
using namespace std;

const int Base::constattribute_(0);
const int DerivedA::constattribute_(1); //<<error: no such variable 'constattribute' in class DerivedA
const int DerivedB::constattribute_(2); //<<error: no such variable 'constattribute' in class DerivedB

int main(void) {
  Derived_Ptr derivedA = new DerivedA();
  Derived_Ptr derivedB = new DerivedB();

  cout << derivedA->GetAttrib() << derivedB->GetAttrib() <<endl;
  return 0;
};

The intend being that i have some abstract interface (Base) which defines also a variable, which should be present for all derived classes, and is retrievable. All flavours of subclasses should be forced to/able to redefine their specific value for this variable, at best during class declaration (the values are known at the time the class is declared after all).

I want to achieve code, not altering the main()-program so that the output is '12' and not as of now (uncommenting current lines in the code) '00' (Doing so shadows the fields from base class).

I tried to look into the matter, and there are different paths for solutions, many of which however go contrary to my intuition:
1. Some follow the CRTP pattern, which is however impossible if I want to address my subclasses by their base-ptr in main.
2. Other solutions require to virtualize the 'GetAttrib()' function for every derived instance., which is cumbersome, and action of modifying the attribute is masked within a function definition.
3. A third possibility is to remove the static pattern and have the 'constattribute_' field as a regular member, which however forces me to drag it through all constructors as a parameter.

I am quite sure that there must be some smarter way to do this. Any hints are appreciated.

Body:
static variable in base class is single instance hence it will be reflected same in derived class.

You can make same static member variable in derived class with specific different value you want. Now make getter member function of static variable in Base class as virtual and overload it in derived class which returns is static instance value.

I have update your code to work it, please check ..

#include <iostream>

using namespace std;

class Base {
public:
  static const int constattribute_;
  virtual void do_something() const =0;
  virtual int GetAttrib () const {return constattribute_;};
};

typedef Base* Derived_Ptr; //<< adress derived classes by their base-class ptr; so no templates for Base

class DerivedA : public Base {
  static const int constattribute_; //<< change this static attribute for all DerivedA class instances and their derivatives

  void do_something() const {};
  int GetAttrib () const {return constattribute_;};
};

class DerivedB : public Base {
  static const int constattribute_; //<< change this static attribute for all DerivedB class instances and their derivatives

  void do_something() const {};
  int GetAttrib () const {return constattribute_;};
};

const int Base::constattribute_(0);
const int DerivedA::constattribute_(1); //<<error: no such variable 'constattribute' in class DerivedA
const int DerivedB::constattribute_(2); //<<error: no such variable 'constattribute' in class DerivedB

int main(void) {
  Derived_Ptr derivedA = new DerivedA();
  Derived_Ptr derivedB = new DerivedB();

  cout << derivedA->GetAttrib() << derivedB->GetAttrib() <<endl;

  return 0;
};

You should get desired output.

Note : Remember all member variables and func in derived class are private.


问:
Qr code scanner not running in android 6.0.1 (showing white screen)
Qr code scanner not running in android 6.0.1 ie redmi note 4 (showing white screen and camera is not opening). Also, The app is running perfectly fine on my kit-kat(4.4) and lolipop device (5.1). please explain what was causing the issue.

```<code>package com.example.android.qrking;

import android.app.Activity;
import android.support.v7.app.AlertDialog;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import com.google.zxing.Result;
import me.dm7.barcodescanner.zxing.ZXingScannerView;

public class MainActivity extends Activity implements ZXingScannerView.ResultHandler{
    private  ZXingScannerView mScannerView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mScannerView = new ZXingScannerView(this);
    }

    public void onClick(View v){

        setContentView(mScannerView);
        mScannerView.setResultHandler(this);
        mScannerView.startCamera();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mScannerView.stopCamera();
    }

    @Override
    public void handleResult(Result result){
        Log.v("handler result", result.getText());
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("scan results");
        builder.setMessage(result.getText());
        AlertDialog alertDialog = builder.create();
        alertDialog.show();
        //uncomment to scan again
        mScannerView.resumeCameraPreview(this);
    }
}
</code>```

my layout file

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.android.qrking.MainActivity">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Scan qr code"
        android:layout_centerInParent="true"
        android:onClick="onClick"/>
</RelativeLayout>
</code>```

答: The correct way to use zxing is by sending an Intent that it will handle. See http://github.com/zxing/zxing/wiki/Scanning-Via-Intent for details about how to do this.</p>

Body:
Qr code scanner not running in android 6.0.1 ie redmi note 4 (showing white screen and camera is not opening). Also, The app is running perfectly fine on my kit-kat(4.4) and lolipop device (5.1). please explain what was causing the issue.

package com.example.android.qrking;

import android.app.Activity;
import android.support.v7.app.AlertDialog;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import com.google.zxing.Result;
import me.dm7.barcodescanner.zxing.ZXingScannerView;

public class MainActivity extends Activity implements ZXingScannerView.ResultHandler{
    private  ZXingScannerView mScannerView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mScannerView = new ZXingScannerView(this);
    }

    public void onClick(View v){

        setContentView(mScannerView);
        mScannerView.setResultHandler(this);
        mScannerView.startCamera();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mScannerView.stopCamera();
    }

    @Override
    public void handleResult(Result result){
        Log.v("handler result", result.getText());
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("scan results");
        builder.setMessage(result.getText());
        AlertDialog alertDialog = builder.create();
        alertDialog.show();
        //uncomment to scan again
        mScannerView.resumeCameraPreview(this);
    }
}

my layout file

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.android.qrking.MainActivity">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Scan qr code"
        android:layout_centerInParent="true"
        android:onClick="onClick"/>
</RelativeLayout>


问:
How could I make the input box looks like this way based on bootrap
I'm creating my site based on bootstrap But wanna do some customization.

Any idea to overwrite the bootstrap default style with this one

I know to replace the box style to underline only can use this

```<code>        border: 0;
        outline: 0;
</code>```

But not knowing how to bend the line

答:
I looked up the relevant Bootstrap 3.3.7 (most recent non-alpha) code for you, which would be the .form-control class.

If you override that class with the following CSS you will likely achieve the effect you are looking for.

```<code>.form-control {
  border: 0; /* to hide border initially */
  border-bottom: 1px solid #ccc; /* to set the bottom border (the only one we need) */
  border-radius: 8px; /* to round borders or 'bend the line' */
}
</code>```

Thus, border-radius is the CSS property you are looking for.

Body:
I'm creating my site based on bootstrap But wanna do some customization.

Any idea to overwrite the bootstrap default style with this one

I know to replace the box style to underline only can use this

        border: 0;
        outline: 0;

But not knowing how to bend the line

Body:
I looked up the relevant Bootstrap 3.3.7 (most recent non-alpha) code for you, which would be the .form-control class.

If you override that class with the following CSS you will likely achieve the effect you are looking for.

.form-control {
  border: 0; /* to hide border initially */
  border-bottom: 1px solid #ccc; /* to set the bottom border (the only one we need) */
  border-radius: 8px; /* to round borders or 'bend the line' */
}

Thus, border-radius is the CSS property you are looking for.