问:
Intro slider next button cutting off flutter

As you can see in the picture the next button is not there. I have no clue what is wrong since i measure the height and width of the device with MediaQuery.of(context).size. I left the code inside a paste bin any help is appreciated.

https://pastebin.com/LYgytDkr

https://pastebin.com/GuzyzPXQ

EDIT:
This bug only finds place on a samsung a50 as far as we know. We haven't encountered this bug on any other device yet

答:
Try removing widthDoneBtn value from IntroSlider,

I tried to replicate your problem but my code is running fine.

```<code>
import "package:flutter/material.dart";
import "package:intro_slider/intro_slider.dart";
import "package:intro_slider/slide_object.dart";

class Tutorial extends StatefulWidget {
  Tutorial({Key key}) : super(key: key);

  @override
  TutorialState createState() => new TutorialState();
}

class TutorialState extends State<Tutorial> {
  List<Slide> slides = new List();
  Size screenSize;
  double buttonWidth;

  @override
  void initState() {
    super.initState();
  }

  /// When tutorial is done.
  void onDonePress() {
    // TutorialHelper.setTutorialStatus(true);
    // Navigator.push(
    //     context, new MyCustomRoute(builder: (context) => OverviewPage()));
  }

  @override
  Widget build(BuildContext context) {
    // screenSize = MediaQuery.of(context).size;
    // buttonWidth = screenSize.width / 3;
    slides.clear();

    slides.add(
      new Slide(
          title: ('OFFERS'),
          marginTitle: EdgeInsets.all(40),
          description: ('tutorial_offers'),
          marginDescription: EdgeInsets.only(top: 30, left: 20, right: 20),
          pathImage: 'assets/wp_logo.png',
          backgroundColor: Color.fromRGBO(51, 130, 255, 1.0)),
    );
    slides.add(
      new Slide(
          title: ('AVAILABLE OFFERS'),
          maxLineTitle: 2,
          marginTitle: EdgeInsets.all(40),
          description: ('tutorial_available_offers'),
          marginDescription: EdgeInsets.only(top: 30, left: 20, right: 20),
          pathImage: 'assets/wp_logo.png',
          backgroundColor: Color.fromRGBO(51, 130, 255, 1.0)),
    );
    slides.add(
      new Slide(
          title: ('SAVED OFFERS'),
          maxLineTitle: 2,
          marginTitle: EdgeInsets.all(40),
          description: ('tutorial_saved_offers'),
          marginDescription: EdgeInsets.only(top: 30, left: 20, right: 20),
          pathImage: 'assets/wp_logo.png',
          backgroundColor: Color.fromRGBO(51, 130, 255, 1.0)),
    );
    slides.add(
      new Slide(
          title: ('PROFILE'),
          marginTitle: EdgeInsets.all(40),
          description: ('tutorial_profile'),
          marginDescription: EdgeInsets.only(top: 30, left: 20, right: 20),
          pathImage: 'assets/wp_logo.png',
          backgroundColor: Color.fromRGBO(51, 160, 255, 1.0)),
    );
    slides.add(
      new Slide(
          title: ('EDIT PROFILE'),
          marginTitle: EdgeInsets.all(40),
          description: ('tutorial_edit_profile'),
          marginDescription: EdgeInsets.only(top: 30, left: 20, right: 20),
          pathImage: 'assets/wp_logo.png',
          backgroundColor: Color.fromRGBO(51, 160, 255, 1.0)),
    );
    slides.add(
      new Slide(
          title: "CHAT",
          marginTitle: EdgeInsets.all(40),
          description: ('tutorial_chat'),
          marginDescription: EdgeInsets.only(top: 30, left: 20, right: 20),
          pathImage: 'assets/wp_logo.png',
          backgroundColor: Color.fromRGBO(132, 200, 255, 1.0)),
    );

    return MaterialApp(
      home: Scaffold(
        body: IntroSlider(
          isShowSkipBtn: true,
          slides: this.slides,
          onDonePress: this.onDonePress,
          nameNextBtn: ('next'),
          nameDoneBtn: ('done'),
          // widthDoneBtn: buttonWidth,
          isScrollable: true,
        ),
      ),
    );
  }

  @override
  void dispose() {
    super.dispose();
  }
}
</code>```

Output:

Body:
Try removing widthDoneBtn value from IntroSlider,

I tried to replicate your problem but my code is running fine.

import "package:flutter/material.dart";
import "package:intro_slider/intro_slider.dart";
import "package:intro_slider/slide_object.dart";

class Tutorial extends StatefulWidget {
  Tutorial({Key key}) : super(key: key);

  @override
  TutorialState createState() => new TutorialState();
}

class TutorialState extends State<Tutorial> {
  List<Slide> slides = new List();
  Size screenSize;
  double buttonWidth;

  @override
  void initState() {
    super.initState();
  }

  /// When tutorial is done.
  void onDonePress() {
    // TutorialHelper.setTutorialStatus(true);
    // Navigator.push(
    //     context, new MyCustomRoute(builder: (context) => OverviewPage()));
  }

  @override
  Widget build(BuildContext context) {
    // screenSize = MediaQuery.of(context).size;
    // buttonWidth = screenSize.width / 3;
    slides.clear();

    slides.add(
      new Slide(
          title: ('OFFERS'),
          marginTitle: EdgeInsets.all(40),
          description: ('tutorial_offers'),
          marginDescription: EdgeInsets.only(top: 30, left: 20, right: 20),
          pathImage: 'assets/wp_logo.png',
          backgroundColor: Color.fromRGBO(51, 130, 255, 1.0)),
    );
    slides.add(
      new Slide(
          title: ('AVAILABLE OFFERS'),
          maxLineTitle: 2,
          marginTitle: EdgeInsets.all(40),
          description: ('tutorial_available_offers'),
          marginDescription: EdgeInsets.only(top: 30, left: 20, right: 20),
          pathImage: 'assets/wp_logo.png',
          backgroundColor: Color.fromRGBO(51, 130, 255, 1.0)),
    );
    slides.add(
      new Slide(
          title: ('SAVED OFFERS'),
          maxLineTitle: 2,
          marginTitle: EdgeInsets.all(40),
          description: ('tutorial_saved_offers'),
          marginDescription: EdgeInsets.only(top: 30, left: 20, right: 20),
          pathImage: 'assets/wp_logo.png',
          backgroundColor: Color.fromRGBO(51, 130, 255, 1.0)),
    );
    slides.add(
      new Slide(
          title: ('PROFILE'),
          marginTitle: EdgeInsets.all(40),
          description: ('tutorial_profile'),
          marginDescription: EdgeInsets.only(top: 30, left: 20, right: 20),
          pathImage: 'assets/wp_logo.png',
          backgroundColor: Color.fromRGBO(51, 160, 255, 1.0)),
    );
    slides.add(
      new Slide(
          title: ('EDIT PROFILE'),
          marginTitle: EdgeInsets.all(40),
          description: ('tutorial_edit_profile'),
          marginDescription: EdgeInsets.only(top: 30, left: 20, right: 20),
          pathImage: 'assets/wp_logo.png',
          backgroundColor: Color.fromRGBO(51, 160, 255, 1.0)),
    );
    slides.add(
      new Slide(
          title: "CHAT",
          marginTitle: EdgeInsets.all(40),
          description: ('tutorial_chat'),
          marginDescription: EdgeInsets.only(top: 30, left: 20, right: 20),
          pathImage: 'assets/wp_logo.png',
          backgroundColor: Color.fromRGBO(132, 200, 255, 1.0)),
    );

    return MaterialApp(
      home: Scaffold(
        body: IntroSlider(
          isShowSkipBtn: true,
          slides: this.slides,
          onDonePress: this.onDonePress,
          nameNextBtn: ('next'),
          nameDoneBtn: ('done'),
          // widthDoneBtn: buttonWidth,
          isScrollable: true,
        ),
      ),
    );
  }

  @override
  void dispose() {
    super.dispose();
  }
}

Output:


来源: stackexchange

问:
How to check when my widget screen comes to visibility in flutter like onResume in Android
In android if an activity is visible onResume is called. What is the equivalent method of onResume in Flutter?

I need the know when my widget screen is visible so I can auto-play a video based on that. I might go to another widget screen an when I come back it should auto-play.

My approach was to play the video in didUpdateWidget but didUpdateWidget is called every-time even the widget screen is not visible.

Note: I'm not asking about didChangeAppLifecycleState from WidgetsBindingObserver as it gives onResume etc callbacks for the app lifecycle not a particular widget screen.

答:
I struggled to get a video to pause when not viewing the main screen of my app. I applied this VisibilityDetector and grabbed the visiblePercentage to force a pause or resume:

```<code>VisibilityDetector(
    key: Key('visible-video--key-${this.randomkeygenerator}-1'),
    onVisibilityChanged: (visibilityInfo) {
      var visiblePercentage = visibilityInfo.visibleFraction * 100;

      if (visiblePercentage < 1){ //the magic is done here
        if(_video_controller != null) {
          if(disposed_vid == false) {
            _video_controller.pause();
          }
        }

      }else{
        if(_video_controller != null) {
          if(disposed_vid == false) {
            _video_controller.play();
          }
        }
      }
      debugPrint(
          'Widget ${visibilityInfo.key} is ${visiblePercentage}% visible');
    },
    child: VideoPlayer(_video_controller)),

  @override
  void dispose() {
    // If the video is playing, pause it.
    _video_controller .pause();
    _video_controller .dispose();
    disposed_vid = true;
    super.dispose();
  }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I struggled to get a video to pause when not viewing the main screen of my app. I applied this VisibilityDetector and grabbed the visiblePercentage to force a pause or resume:

VisibilityDetector(
    key: Key('visible-video--key-${this.randomkeygenerator}-1'),
    onVisibilityChanged: (visibilityInfo) {
      var visiblePercentage = visibilityInfo.visibleFraction * 100;

      if (visiblePercentage < 1){ //the magic is done here
        if(_video_controller != null) {
          if(disposed_vid == false) {
            _video_controller.pause();
          }
        }

      }else{
        if(_video_controller != null) {
          if(disposed_vid == false) {
            _video_controller.play();
          }
        }
      }
      debugPrint(
          'Widget ${visibilityInfo.key} is ${visiblePercentage}% visible');
    },
    child: VideoPlayer(_video_controller)),

  @override
  void dispose() {
    // If the video is playing, pause it.
    _video_controller .pause();
    _video_controller .dispose();
    disposed_vid = true;
    super.dispose();
  }


问:
How does sqs message deletion flow works in celery-sqs
I was looking for how celery and sqs deletion works?
When does celery delete message from sqs?
Does it delete when message is picked from sqs or after completion of tasks?
What happens if there is some error in task or it raises error?
Will the message (task) will be there if the tasks is taking too long like and 20 mins.</p>

答:
The selected answer is (unfortunately) incorrect for SQS, as this open issue indicates.

There was an attempt at fixing the issue, as evidenced by this merged PR.

However, there are bugs with the above implementation.

Long story short, messages will be deleted from an SQS queue 100% of the time, regardless of any exception that occurs within the task.

edit: this may have been resolved, per this PR

I'll update this answer after I've confirmed via personal testing that this functions correctly


问:
SQL: convert 24-hour time to 12-hour time
I'm creating a SQL report that tracks agent login and logout times. The request is to add a threshold to login time to track agents coming in late. I've separated the DATETIME field to be able to add the threshold, but now I only get 24-hour time instead of 12-hour time. Here's my query:

```<code>    SELECT Interval = CONVERT(char,AL.LogoutDateTime,101),
   Year = DATEPART(yy, AL.LogoutDateTime),
   Month = DATEPART(mm, AL.LogoutDateTime),
   Day = DATEPART(dd, AL.LogoutDateTime),
   Week = DATEPART(ww, AL.LogoutDateTime),
   DOY = DATEPART(dy, AL.LogoutDateTime),
   DOW = DATEPART(dw, AL.LogoutDateTime),
   A.EnterpriseName as AgentName,
    AL.LogoutDateTime,
    AL.LoginDuration,
    AL.Extension,
    AL.ReasonCode,
    CONVERT(VARCHAR(8), DATEADD(s, -(AL.LoginDuration), AL.LogoutDateTime),101) AS LoginDate,
    CONVERT(VARCHAR(8), DATEADD(s, -(AL.LoginDuration), AL.LogoutDateTime),8) AS LoginTime,
    A.SkillTargetID

    FROM
    Agent_Logout AL
    JOIN Agent A ON AL.SkillTargetID = A.SkillTargetID
    where LogoutDateTime between :start_date and :end_date
    and A.SkillTargetID IN (select SkillTargetID from Agent_Team_Member where AgentTeamID in
    (:Agent))
    group by LogoutDateTime,
    EnterpriseName,
    LoginDuration,
    Extension,
    ReasonCode,
    A.SkillTargetID,
    DATEPART(yy, AL.LogoutDateTime),
    DATEPART(mm, AL.LogoutDateTime),
    DATEPART(dd, AL.LogoutDateTime),
    DATEPART(ww, AL.LogoutDateTime),
    DATEPART(dy, AL.LogoutDateTime),
    DATEPART(dw, AL.LogoutDateTime),
    CONVERT(char,AL.LogoutDateTime,101)

    order by EnterpriseName
</code>```

Here are my results:

```<code>    Interval    Year    Month   Day Week    DOY DOW AgentName   LogoutDateTime          LoginDuration   Extension   LoginDate   LoginTime
    05/27/2020  2020    5       27  22      148 4   Jane Doe    2020-05-27 12:43:53.227 7429     1234   05/27/20    14:40:04
</code>```

I know the issue is the the LoginTime field that I create, but I can't figure out how to convert it back to standard time. If I leave the field DATETIME, I can't set login thresholds because the date keeps the threshold from working correctly...so how can I split the datetime field while maintaining the 12-hour time? Instead of 14:40:04 it would be 2:40:04 pm.

答:
Instead of

```<code>CONVERT(VARCHAR(8), DATEADD(s, -(AL.LoginDuration), AL.LogoutDateTime),8)
</code>```

use

```<code>CONVERT(VARCHAR(8), CAST(DATEADD(s, -(AL.LoginDuration), AL.LogoutDateTime) AS TIME),0)
</code>```

It converts datetime to time (no date part), and then time to stardard format

Body:
I'm creating a SQL report that tracks agent login and logout times. The request is to add a threshold to login time to track agents coming in late. I've separated the DATETIME field to be able to add the threshold, but now I only get 24-hour time instead of 12-hour time. Here's my query:

    SELECT Interval = CONVERT(char,AL.LogoutDateTime,101),
   Year = DATEPART(yy, AL.LogoutDateTime),
   Month = DATEPART(mm, AL.LogoutDateTime),
   Day = DATEPART(dd, AL.LogoutDateTime),
   Week = DATEPART(ww, AL.LogoutDateTime),
   DOY = DATEPART(dy, AL.LogoutDateTime),
   DOW = DATEPART(dw, AL.LogoutDateTime),
   A.EnterpriseName as AgentName,
    AL.LogoutDateTime,
    AL.LoginDuration,
    AL.Extension,
    AL.ReasonCode,
    CONVERT(VARCHAR(8), DATEADD(s, -(AL.LoginDuration), AL.LogoutDateTime),101) AS LoginDate,
    CONVERT(VARCHAR(8), DATEADD(s, -(AL.LoginDuration), AL.LogoutDateTime),8) AS LoginTime,
    A.SkillTargetID

    FROM
    Agent_Logout AL
    JOIN Agent A ON AL.SkillTargetID = A.SkillTargetID
    where LogoutDateTime between :start_date and :end_date
    and A.SkillTargetID IN (select SkillTargetID from Agent_Team_Member where AgentTeamID in
    (:Agent))
    group by LogoutDateTime,
    EnterpriseName,
    LoginDuration,
    Extension,
    ReasonCode,
    A.SkillTargetID,
    DATEPART(yy, AL.LogoutDateTime),
    DATEPART(mm, AL.LogoutDateTime),
    DATEPART(dd, AL.LogoutDateTime),
    DATEPART(ww, AL.LogoutDateTime),
    DATEPART(dy, AL.LogoutDateTime),
    DATEPART(dw, AL.LogoutDateTime),
    CONVERT(char,AL.LogoutDateTime,101)

    order by EnterpriseName

Here are my results:

    Interval    Year    Month   Day Week    DOY DOW AgentName   LogoutDateTime          LoginDuration   Extension   LoginDate   LoginTime
    05/27/2020  2020    5       27  22      148 4   Jane Doe    2020-05-27 12:43:53.227 7429     1234   05/27/20    14:40:04

I know the issue is the the LoginTime field that I create, but I can't figure out how to convert it back to standard time. If I leave the field DATETIME, I can't set login thresholds because the date keeps the threshold from working correctly...so how can I split the datetime field while maintaining the 12-hour time? Instead of 14:40:04 it would be 2:40:04 pm.

Body:
Instead of

CONVERT(VARCHAR(8), DATEADD(s, -(AL.LoginDuration), AL.LogoutDateTime),8)

use

CONVERT(VARCHAR(8), CAST(DATEADD(s, -(AL.LoginDuration), AL.LogoutDateTime) AS TIME),0)

It converts datetime to time (no date part), and then time to stardard format


问:
Apache and Node.js on the Same Server
I want to use Node because it's swift, uses the same language I am using on the client side, and it's non-blocking by definition.  But the guy who I hired to write the program for file handling (saving, editing, renaming, downloading, uploading files, etc.), he wants to use apache.  So, I must:

Convince him to use Node (he's giving up little ground on that)

Figure out how to upload, download, rename, save, etc. files in node or

I must install apache and node on the same server.

Which is the most favorable situation, and how do I implement that?

答:
I combined the answer above with certbot SSL cert and CORS access-control-allow-headers and got it working so I thought I would share the results.

Apache httpd.conf added to the bottom of the file:

```<code>LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_http_module modules/mod_proxy_http.so
</code>```

Apache VirtualHost settings (doc root for PHP is under Apache and SSL with Certbot, while node.js/socket.io site runs on port 3000 - and uses SSL cert from Apache)
Also notice the node.js site uses the proxy for the folder /nodejs, socket.io, and ws (websockets):

```<code><IfModule mod_ssl.c>
<VirtualHost *:443>
    ServerName www.example.com
    ServerAlias www.example.com
    DocumentRoot /var/html/www.example.com
    ErrorLog /var/html/log/error.log
    CustomLog /var/html/log/requests.log combined
    SSLCertificateFile /etc/letsencrypt/live/www.example.com/fullchain.pem
    SSLCertificateKeyFile /etc/letsencrypt/live/www.example.com/privkey.pem
    Include /etc/letsencrypt/options-ssl-apache.conf

    RewriteEngine On
    RewriteCond %{REQUEST_URI}  ^socket.io          [NC]
    RewriteCond %{QUERY_STRING} transport=websocket [NC]
    RewriteRule /{.*}       ws://localhost:3000/$1  [P,L]

    RewriteCond %{HTTP:Connection} Upgrade [NC]
    RewriteRule /(.*) ws://localhost:3000/$1 [P,L]

    ProxyPass /nodejs http://localhost:3000/
    ProxyPassReverse /nodejs http://localhost:3000/

    ProxyPass /socket.io http://localhost:3000/socket.io
    ProxyPassReverse /socket.io http://localhost:3000/socket.io

    ProxyPass /socket.io ws://localhost:3000/socket.io
    ProxyPassReverse /socket.io ws://localhost:3000/socket.io

</VirtualHost>
</IfModule>
</code>```

Then my node.js app (app.js):

```<code>var express = require('express');
var app = express();
    app.use(function(req, res, next) {
        res.header("Access-Control-Allow-Origin", "*");
        res.header("Access-Control-Allow-Headers", "X-Requested-With");
        res.header("Access-Control-Allow-Headers", "Content-Type");
        res.header("Access-Control-Allow-Methods", "PUT, GET, POST, DELETE, OPTIONS");
        next();
    });
var http = require('http').Server(app);
var io = require('socket.io')(http);

http.listen({host:'0.0.0.0',port:3000});
</code>```

I force a ip4 listener, but that is optional - you can substitute:

```<code>http.listen(3000);
</code>```

node.js app (app.js) code continues with:

```<code>io.of('/nodejs').on('connection', function(socket) {
    //optional settings:
    io.set('heartbeat timeout', 3000);
    io.set('heartbeat interval', 1000);

    //listener for when a user is added
    socket.on('add user', function(data) {
         socket.join('AnyRoomName');
         socket.broadcast.emit('user joined', data);
    });

    //listener for when a user leaves
    socket.on('remove user', function(data) {
         socket.leave('AnyRoomName');
         socket.broadcast.emit('user left', data);
    });

    //sample listener for any other function
    socket.on('named-event', function(data) {
         //code....
         socket.broadcast.emit('named-event-broadcast', data);
    });

    // add more listeners as needed... use different named-events...
});
</code>```

finally, on the client side (created as nodejs.js):

```<code>//notice the /nodejs path
var socket = io.connect('https://www.example.com/nodejs');

//listener for user joined
socket.on('user joined', function(data) {
    // code... data shows who joined...
});

//listener for user left
socket.on('user left', function(data) {
    // code... data shows who left...
});

// sample listener for any function:
socket.on('named-event-broadcast', function(data) {
    // this receives the broadcast data (I use json then parse and execute code)
    console.log('data1=' + data.data1);
    console.log('data2=' + data.data2);
});

// sample send broadcast json data for user joined:
socket.emit('user joined', {
    'userid': 'userid-value',
    'username':'username-value'
});

// sample send broadcast json data for user left
//(I added the following with an event listener for 'beforeunload'):
// socket.emit('user joined', {
//     'userid': 'userid-value',
//     'username':'username-value'
// });

// sample send broadcast json data for any named-event:
socket.emit('named-event', {
    'data1': 'value1',
    'data2':'value2'
});
</code>```

In this example when the JS loads, it will emit to the socket a "named-event" sending the data in JSON to the node.js/socket.io server.

Using the io and socket on the server under path /nodejs (connected by client), receives the data an then resends it as a broadcast. Any other users in the socket would receive the data with their listener "named-event-broadcast". Note that the sender does not receive their own broadcast.

ContentLicense: CC BY-SA 3.0

Title: Apache and Node.js on the Same Server

Body:
I combined the answer above with certbot SSL cert and CORS access-control-allow-headers and got it working so I thought I would share the results.

Apache httpd.conf added to the bottom of the file:

LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_http_module modules/mod_proxy_http.so

Apache VirtualHost settings (doc root for PHP is under Apache and SSL with Certbot, while node.js/socket.io site runs on port 3000 - and uses SSL cert from Apache)
Also notice the node.js site uses the proxy for the folder /nodejs, socket.io, and ws (websockets):

<IfModule mod_ssl.c>
<VirtualHost *:443>
    ServerName www.example.com
    ServerAlias www.example.com
    DocumentRoot /var/html/www.example.com
    ErrorLog /var/html/log/error.log
    CustomLog /var/html/log/requests.log combined
    SSLCertificateFile /etc/letsencrypt/live/www.example.com/fullchain.pem
    SSLCertificateKeyFile /etc/letsencrypt/live/www.example.com/privkey.pem
    Include /etc/letsencrypt/options-ssl-apache.conf

    RewriteEngine On
    RewriteCond %{REQUEST_URI}  ^socket.io          [NC]
    RewriteCond %{QUERY_STRING} transport=websocket [NC]
    RewriteRule /{.*}       ws://localhost:3000/$1  [P,L]

    RewriteCond %{HTTP:Connection} Upgrade [NC]
    RewriteRule /(.*) ws://localhost:3000/$1 [P,L]

    ProxyPass /nodejs http://localhost:3000/
    ProxyPassReverse /nodejs http://localhost:3000/

    ProxyPass /socket.io http://localhost:3000/socket.io
    ProxyPassReverse /socket.io http://localhost:3000/socket.io

    ProxyPass /socket.io ws://localhost:3000/socket.io
    ProxyPassReverse /socket.io ws://localhost:3000/socket.io

</VirtualHost>
</IfModule>

Then my node.js app (app.js):

var express = require('express');
var app = express();
    app.use(function(req, res, next) {
        res.header("Access-Control-Allow-Origin", "*");
        res.header("Access-Control-Allow-Headers", "X-Requested-With");
        res.header("Access-Control-Allow-Headers", "Content-Type");
        res.header("Access-Control-Allow-Methods", "PUT, GET, POST, DELETE, OPTIONS");
        next();
    });
var http = require('http').Server(app);
var io = require('socket.io')(http);

http.listen({host:'0.0.0.0',port:3000});

I force a ip4 listener, but that is optional - you can substitute:

http.listen(3000);

node.js app (app.js) code continues with:

io.of('/nodejs').on('connection', function(socket) {
    //optional settings:
    io.set('heartbeat timeout', 3000);
    io.set('heartbeat interval', 1000);

    //listener for when a user is added
    socket.on('add user', function(data) {
         socket.join('AnyRoomName');
         socket.broadcast.emit('user joined', data);
    });

    //listener for when a user leaves
    socket.on('remove user', function(data) {
         socket.leave('AnyRoomName');
         socket.broadcast.emit('user left', data);
    });

    //sample listener for any other function
    socket.on('named-event', function(data) {
         //code....
         socket.broadcast.emit('named-event-broadcast', data);
    });

    // add more listeners as needed... use different named-events...
});

finally, on the client side (created as nodejs.js):

//notice the /nodejs path
var socket = io.connect('https://www.example.com/nodejs');

//listener for user joined
socket.on('user joined', function(data) {
    // code... data shows who joined...
});

//listener for user left
socket.on('user left', function(data) {
    // code... data shows who left...
});

// sample listener for any function:
socket.on('named-event-broadcast', function(data) {
    // this receives the broadcast data (I use json then parse and execute code)
    console.log('data1=' + data.data1);
    console.log('data2=' + data.data2);
});

// sample send broadcast json data for user joined:
socket.emit('user joined', {
    'userid': 'userid-value',
    'username':'username-value'
});

// sample send broadcast json data for user left
//(I added the following with an event listener for 'beforeunload'):
// socket.emit('user joined', {
//     'userid': 'userid-value',
//     'username':'username-value'
// });

// sample send broadcast json data for any named-event:
socket.emit('named-event', {
    'data1': 'value1',
    'data2':'value2'
});

In this example when the JS loads, it will emit to the socket a "named-event" sending the data in JSON to the node.js/socket.io server.

Using the io and socket on the server under path /nodejs (connected by client), receives the data an then resends it as a broadcast. Any other users in the socket would receive the data with their listener "named-event-broadcast". Note that the sender does not receive their own broadcast.


问:
How can I compare two matrixes for similarity using Python?
Python 3:
How can I compare two matrices of similar shape to one another?

For example, lets say we have matrix x:

```<code>1 0 1
0 0 1
1 1 0
</code>```

I would like to compare this to matrix y:

```<code>1 0 1
0 0 1
1 1 1
</code>```

Which would give me a score, for example, 8/9 as 8/9 of the items were the same, with the exception of that last digit that went from 0 to 1. The matrices I am dealing with are much larger, but their dimensions are consistent for comparison.

There must be a library of some sort that can do this. Any thoughts?

答:
If you are using numpy, you can simply use np.mean() on the boolean array after comparison as follows.

import numpy as np

m1 = np.array([
    [1, 0, 1],
    [0, 0, 1],
    [1, 1, 0],
])

m2 = np.array([
    [1, 0, 1],
    [0, 0, 1],
    [1, 1, 1],
])

score = np.mean(m1 == m2)
print(score) # prints 0.888..
```

Body:
Python 3:
How can I compare two matrices of similar shape to one another?

For example, lets say we have matrix x:

1 0 1
0 0 1
1 1 0

I would like to compare this to matrix y:

1 0 1
0 0 1
1 1 1

Which would give me a score, for example, 8/9 as 8/9 of the items were the same, with the exception of that last digit that went from 0 to 1. The matrices I am dealing with are much larger, but their dimensions are consistent for comparison.

There must be a library of some sort that can do this. Any thoughts?


问:
How to create user a service which takes JWT token and returns user object
I have 3 services

angular (frontend)

java (fapi)

java (backend, jpa)

Every user's request consists of header <Authentification> with a JWT Token(interceptor in angular) key.

How can I get user from this token, for example to create users page? Or will admin understand this is user or not?

I'm trying to save  Map(key,value) pairs (token,user) in my front, but this map deleted every time.

Do I need to create this Map in fapi? Or save token in database?

答:
When the user logs in, the token can either be stored in the local storage or in the cookies.

The token will only contain encrypted data that you put in. If you need the user’s username from a token, you need to include the username when creating the token.


问:
What's default password in docker container mysql-server when you don't set one?
I am try to run a mysql container and connect with mysql client then:

I've used following commands:

```<code>docker run --name=mysql -d mysql/mysql-server:latest
docker exec -it mysql mysql -uroot -p
</code>```

According to tutorial, the last command allow me configure database password but When I introduce the first password it fails...

The first password was root and I get an unusual error, then I try with admin, admin an even my linux user password but They don't work...

I would like to know what's the error?

答:
There is no default password, try login in using:</p>

```<code>sudo docker exec -it mysql mysql -u root
</code>```

Body:
I am try to run a mysql container and connect with mysql client then:

I've used following commands:

docker run --name=mysql -d mysql/mysql-server:latest
docker exec -it mysql mysql -uroot -p

According to tutorial, the last command allow me configure database password but When I introduce the first password it fails...

The first password was root and I get an unusual error, then I try with admin, admin an even my linux user password but They don't work...

I would like to know what's the error?

Body:
There is no default password, try login in using:

sudo docker exec -it mysql mysql -u root


问:
How to unit test an array as a prop using react-testing-library
How would you match mock props to the wrapper component props, im a bit confused. I know how to do it in enzyme jest. But not sure how to do it with react-testing-library.

I'm trying it match props.comments to the wrapper:

```<code>const commentList = render(<CommentList {...props} />);
</code>```

What should i be checking for ? I want to match the prop comments to the comments in the render/wrapper ?

Should i test it like this

```<code> const commentList = render(<CommentList comments={props.comments}/>);
 expect(commentList).toHaveLength(2)
</code>```

What would be the right approach to test mock items in an array.

CommentList.test.tsx

```<code>import "@testing-library/jest-dom";
import React, { Ref } from "react";
import CommentList from "./CommentList";
import { render, getByText, queryByText, getAllByTestId } from "@testing-library/react";

const props = {
    user: {},
    postId: null,
    userId: null,
    currentUser: {},
    ref: {
        current: undefined,
    },
    comments: [
        {
            author: { username: "barnowl", gravatar: "https://api.adorable.io/avatars/400/bf1eed82fbe37add91cb4192e4d14de6.png", bio: null },
            comment_body: "fsfsfsfsfs",
            createdAt: "2020-05-27T14:32:01.682Z",
            gifUrl: "",
            id: 520,
            postId: 28,
            updatedAt: "2020-05-27T14:32:01.682Z",
            userId: 9,
        },
        {
            author: { username: "barnowl", gravatar: "https://api.adorable.io/avatars/400/bf1eed82fbe37add91cb4192e4d14de6.png", bio: null },
            comment_body: "fsfsfsfsfs",
            createdAt: "2020-05-27T14:32:01.682Z",
            gifUrl: "",
            id: 519,
            postId: 27,
            updatedAt: "2020-05-27T14:32:01.682Z",
            userId: 10,
        },
    ],
    deleteComment: jest.fn(),
};
describe("Should render <CommentList/>", () => {
    it("should render <CommentList/>", () => {
        const commentList = render(<CommentList {...props} />);
        expect(commentList).toBeTruthy();
    });

    it("should render first comment", () => {
        const { getByTestId } = render(<CommentList {...props} />);
        const commentList = getByTestId("comment-list-div");
        expect(commentList.firstChild).toBeTruthy();
    });

    it("should render second child", () => {
        const { getByTestId } = render(<CommentList {...props} />);
        const commentList = getByTestId("comment-list-div");
        expect(commentList.lastChild).toBeTruthy();
    });

    it("should check comments", () => {
        const { getByTestId } = render(<CommentList {...props} />);
        const commentList = getByTestId("comment-list-div");
        expect(commentList).toBeInTheDocument();
    });
});
</code>```

CommentList.tsx

```<code>import React, { Fragment, useState, Ref } from "react";
import Grid from "@material-ui/core/Grid";
import OurSecondaryButton from "../../../common/OurSecondaryButton";
import CommentListContainer from "../commentListContainer/commentListContainer";

function CommentList(props: any, ref: Ref<HTMLDivElement>) {
    const [showMore, setShowMore] = useState<Number>(2);
    const [openModal, setOpenModal] = useState(false);
    const [showLessFlag, setShowLessFlag] = useState<Boolean>(false);
    const the_comments = props.comments.length;
    const inc = showMore as any;
    const min = Math.min(2, the_comments - inc);
    const showComments = (e) => {
        e.preventDefault();
        if (inc + 2 && inc <= the_comments) {
            setShowMore(inc + 2);
            setShowLessFlag(true);
        } else {
            setShowMore(the_comments);
        }
    };
    const handleClickOpen = () => {
        setOpenModal(true);
    };
    const handleCloseModal = () => {
        setOpenModal(false);
    };

    const showLessComments = (e) => {
        e.preventDefault();
        setShowMore(2);
        setShowLessFlag(false);
    };
    const isBold = (comment) => {
        return comment.userId === props.userId ? 800 : 400;
    };
    // show comments by recent, and have the latest comment at the bottom, with the previous one just before it.
    const filterComments = props.comments
        .slice(0)
        .sort((a, b) => {
            const date1 = new Date(a.createdAt) as any;
            const date2 = new Date(b.createdAt) as any;
            return date2 - date1;
        })
        .slice(0, inc)
        .reverse();

    const showMoreComments = () => {
        return filterComments.map((comment, i) => (
            <div key={i}>
                <CommentListContainer ref={ref} comment={comment} openModal={openModal} handleCloseModal={handleCloseModal} isBold={isBold} handleClickOpen={handleClickOpen} {...props} />
            </div>
        ));
    };
    console.log(ref);
    return (
        <Grid data-testid="comment-list-div">
            <Fragment>
                <div style={{ margin: "30px 0px" }}>
                    {props.comments.length > 2 ? (
                        <Fragment>
                            {min !== -1 && min !== -2 ? (
                                <Fragment>
                                    {min !== 0 ? (
                                        <OurSecondaryButton onClick={(e) => showComments(e)} component="span" color="secondary">
                                            View {min !== -1 && min !== -2 ? min : 0} More Comments
                                        </OurSecondaryButton>
                                    ) : (
                                        <OurSecondaryButton onClick={(e) => showLessComments(e)} component="span" color="secondary">
                                            Show Less Comments
                                        </OurSecondaryButton>
                                    )}
                                </Fragment>
                            ) : (
                                <OurSecondaryButton onClick={(e) => showLessComments(e)} component="span" color="secondary">
                                    Show Less Comments
                                </OurSecondaryButton>
                            )}
                        </Fragment>
                    ) : null}
                </div>
            </Fragment>
            {showLessFlag === true ? (
                // will show most recent comments below
                showMoreComments()
            ) : (
                <Fragment>
                    {/* filter based on first comment  */}
                    {filterComments.map((comment, i) => (
                        <div key={i}>
                            <CommentListContainer ref={ref} comment={comment} openModal={openModal} handleCloseModal={handleCloseModal} isBold={isBold} handleClickOpen={handleClickOpen} {...props} />
                        </div>
                    ))}
                </Fragment>
            )}
        </Grid>
    );
}

export default React.forwardRef(CommentList) as React.RefForwardingComponent<HTMLDivElement, any>;
</code>```

答:
You should test against visual elements rendered in the comments list. If your component renders comment bodies, you could do :

```<code>const rtl = render(<CommentList comments={props.comments}/>);

// test that both comments bodies are present in DOM
expect(rtl.getByText('firstCommentBody').toBeTruthy();
expect(rtl.getByText('secondCommentBody').toBeTruthy();

// or testing number of individual comment, assuming they are in li.comment, wrapped in a div with data-testid=comment-wrapper
expect(rtl.getByTestId('comment-wrapper').querySelectorAll('li.comment').length).toEqual(2);
</code>```

React-testing-library promotes to test like a real user would : check printed strings, number of elements, labels, placeholders, roles...

Just ask yourself : what do I expect to see on the screen ? Write your tests as you answer this question.

Body:
How would you match mock props to the wrapper component props, im a bit confused. I know how to do it in enzyme jest. But not sure how to do it with react-testing-library.

I'm trying it match props.comments to the wrapper:

const commentList = render(<CommentList {...props} />);

What should i be checking for ? I want to match the prop comments to the comments in the render/wrapper ?

Should i test it like this

 const commentList = render(<CommentList comments={props.comments}/>);
 expect(commentList).toHaveLength(2)

What would be the right approach to test mock items in an array.

CommentList.test.tsx

import "@testing-library/jest-dom";
import React, { Ref } from "react";
import CommentList from "./CommentList";
import { render, getByText, queryByText, getAllByTestId } from "@testing-library/react";

const props = {
    user: {},
    postId: null,
    userId: null,
    currentUser: {},
    ref: {
        current: undefined,
    },
    comments: [
        {
            author: { username: "barnowl", gravatar: "https://api.adorable.io/avatars/400/bf1eed82fbe37add91cb4192e4d14de6.png", bio: null },
            comment_body: "fsfsfsfsfs",
            createdAt: "2020-05-27T14:32:01.682Z",
            gifUrl: "",
            id: 520,
            postId: 28,
            updatedAt: "2020-05-27T14:32:01.682Z",
            userId: 9,
        },
        {
            author: { username: "barnowl", gravatar: "https://api.adorable.io/avatars/400/bf1eed82fbe37add91cb4192e4d14de6.png", bio: null },
            comment_body: "fsfsfsfsfs",
            createdAt: "2020-05-27T14:32:01.682Z",
            gifUrl: "",
            id: 519,
            postId: 27,
            updatedAt: "2020-05-27T14:32:01.682Z",
            userId: 10,
        },
    ],
    deleteComment: jest.fn(),
};
describe("Should render <CommentList/>", () => {
    it("should render <CommentList/>", () => {
        const commentList = render(<CommentList {...props} />);
        expect(commentList).toBeTruthy();
    });

    it("should render first comment", () => {
        const { getByTestId } = render(<CommentList {...props} />);
        const commentList = getByTestId("comment-list-div");
        expect(commentList.firstChild).toBeTruthy();
    });

    it("should render second child", () => {
        const { getByTestId } = render(<CommentList {...props} />);
        const commentList = getByTestId("comment-list-div");
        expect(commentList.lastChild).toBeTruthy();
    });

    it("should check comments", () => {
        const { getByTestId } = render(<CommentList {...props} />);
        const commentList = getByTestId("comment-list-div");
        expect(commentList).toBeInTheDocument();
    });
});

CommentList.tsx

import React, { Fragment, useState, Ref } from "react";
import Grid from "@material-ui/core/Grid";
import OurSecondaryButton from "../../../common/OurSecondaryButton";
import CommentListContainer from "../commentListContainer/commentListContainer";

function CommentList(props: any, ref: Ref<HTMLDivElement>) {
    const [showMore, setShowMore] = useState<Number>(2);
    const [openModal, setOpenModal] = useState(false);
    const [showLessFlag, setShowLessFlag] = useState<Boolean>(false);
    const the_comments = props.comments.length;
    const inc = showMore as any;
    const min = Math.min(2, the_comments - inc);
    const showComments = (e) => {
        e.preventDefault();
        if (inc + 2 && inc <= the_comments) {
            setShowMore(inc + 2);
            setShowLessFlag(true);
        } else {
            setShowMore(the_comments);
        }
    };
    const handleClickOpen = () => {
        setOpenModal(true);
    };
    const handleCloseModal = () => {
        setOpenModal(false);
    };

    const showLessComments = (e) => {
        e.preventDefault();
        setShowMore(2);
        setShowLessFlag(false);
    };
    const isBold = (comment) => {
        return comment.userId === props.userId ? 800 : 400;
    };
    // show comments by recent, and have the latest comment at the bottom, with the previous one just before it.
    const filterComments = props.comments
        .slice(0)
        .sort((a, b) => {
            const date1 = new Date(a.createdAt) as any;
            const date2 = new Date(b.createdAt) as any;
            return date2 - date1;
        })
        .slice(0, inc)
        .reverse();

    const showMoreComments = () => {
        return filterComments.map((comment, i) => (

                <CommentListContainer ref={ref} comment={comment} openModal={openModal} handleCloseModal={handleCloseModal} isBold={isBold} handleClickOpen={handleClickOpen} {...props} />

        ));
    };
    console.log(ref);
    return (
        <Grid data-testid="comment-list-div">
            <Fragment>

                    {props.comments.length > 2 ? (
                        <Fragment>
                            {min !== -1 && min !== -2 ? (
                                <Fragment>
                                    {min !== 0 ? (
                                        <OurSecondaryButton onClick={(e) => showComments(e)} component="span" color="secondary">
                                            View {min !== -1 && min !== -2 ? min : 0} More Comments
                                        </OurSecondaryButton>
                                    ) : (
                                        <OurSecondaryButton onClick={(e) => showLessComments(e)} component="span" color="secondary">
                                            Show Less Comments
                                        </OurSecondaryButton>
                                    )}
                                </Fragment>
                            ) : (
                                <OurSecondaryButton onClick={(e) => showLessComments(e)} component="span" color="secondary">
                                    Show Less Comments
                                </OurSecondaryButton>
                            )}
                        </Fragment>
                    ) : null}

            </Fragment>
            {showLessFlag === true ? (
                // will show most recent comments below
                showMoreComments()
            ) : (
                <Fragment>
                    {/* filter based on first comment  */}
                    {filterComments.map((comment, i) => (

                            <CommentListContainer ref={ref} comment={comment} openModal={openModal} handleCloseModal={handleCloseModal} isBold={isBold} handleClickOpen={handleClickOpen} {...props} />

                    ))}
                </Fragment>
            )}
        </Grid>
    );
}

export default React.forwardRef(CommentList) as React.RefForwardingComponent<HTMLDivElement, any>;

Body:
You should test against visual elements rendered in the comments list. If your component renders comment bodies, you could do :

const rtl = render(<CommentList comments={props.comments}/>);

// test that both comments bodies are present in DOM
expect(rtl.getByText('firstCommentBody').toBeTruthy();
expect(rtl.getByText('secondCommentBody').toBeTruthy();

// or testing number of individual comment, assuming they are in li.comment, wrapped in a div with data-testid=comment-wrapper
expect(rtl.getByTestId('comment-wrapper').querySelectorAll('li.comment').length).toEqual(2);

React-testing-library promotes to test like a real user would : check printed strings, number of elements, labels, placeholders, roles...

Just ask yourself : what do I expect to see on the screen ? Write your tests as you answer this question.


问:
R's plm package equivalent for python/pyspark
Is there a Python or PySpark equivalent to R's plm package for models with fixed effects and random effects?

答:
There is a module called linearmodels for Python: https://bashtage.github.io/linearmodels/

It contains some model estimation procedures but does not seem as comprehensive regards test procedures.


问:
CMake Package Support - Includes and Libraries not found
I am currently developing a software package, for which I'd like to provide the cmake package support (so users can find it with find_package(...)). The Problem is, the package is found but FOO_INCLUDE_DIR and FOO_LIBRARIES is empty.

Within my package I have several modules, each with a CMakeLists file which installs the respective library and headers with:

```<code>install(TARGETS ${LIBRARY_NAME} EXPORT FooTargets
    RUNTIME       DESTINATION ${Foo_RUNTIME_INSTALL_DIR}
    LIBRARY       DESTINATION ${Foo_LIBRARY_INSTALL_DIR}
    ARCHIVE       DESTINATION ${Foo_ARCHIVE_INSTALL_DIR}
    FRAMEWORK     DESTINATION ${Foo_FRAMEWORK_INSTALL_DIR})

# Headers
install(
        DIRECTORY include/${LIBRARY_NAME}
        DESTINATION include/${PROJECT_NAME}
        FILES_MATCHING
            PATTERN "*.h"
            PATTERN "*.hpp"
)
</code>```

The headers for the library are included with target_include_directories like this:

```<code>target_include_directories(${LIBRARY_NAME} PUBLIC
        $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include> # for headers when building
        $<INSTALL_INTERFACE:${Foo_INC_INSTALL_DIR}> # for client in install mode
)
</code>```

I checked the folders and all libraries and headers are correctly installed. In my toplevel CMakeLists I export my targets with:

```<code>install(
        EXPORT FooTargets
        DESTINATION ${Foo_CMAKE_CONFIG_INSTALL_DIR}
        FILE FooConfig.cmake
)
</code>```

The config is where I assume it to be (usr/local/lib/cmake/Foo). So everything seems to be correct. When I look into my FooConfig.cmake it says:

```<code># Create imported target realm_densifier_base
add_library(FooLib1 SHARED IMPORTED)

set_target_properties(FooLib1 PROPERTIES
  INTERFACE_INCLUDE_DIRECTORIES "/usr/local/include/Foo"
  INTERFACE_LINK_LIBRARIES "...several libraries..."
)
</code>```

...which is absolutely correct and exactly what I expected. What part of the puzzle is missing? Is INTERFACE_INCLUDE_DIRECTORIES and INTERFACE_LINK_LIBRARIES not the correct flag to be set?

Thanks for the help and best regards,

Alex

Edit:

@Guillaume Racicot already cleared most things up, I only knew the "non target" way of adding headers to my project, that was with include_directories(Foo_INCLUDE_DIRS). However, in the target-world linking against my library Foo was enough. Another thing was that I messed up some directories in the target_include_directories(...) command, so directories were wrong and therefore could not be found in my other project. Thanks for the help!

答:
Why would FOO_INCLUDE_DIR or FOO_LIBRARIES be set? This may be how old find modules worked, but not how config files work. Even newer find modules expose targets instead of directory variables.

When generating an XYZConfig.cmake file, informations about targets will be exported, not informations on the directory.

With such exportation:

```<code>install(
    EXPORT FooTargets
    NAMESPACE Foo::
    DESTINATION ${Foo_CMAKE_CONFIG_INSTALL_DIR}
    FILE FooConfig.cmake
)
</code>```

You would expect users of the package to use it like so:

```<code>find_package(Foo REQUIRED)

#         or PUBLIC ------v
target_link_libraries(bar PRIVATE Foo::FooLib1)
</code>```

If your package has multiple targets in the export set, then you can link to both or only one

```<code>target_link_libraries(bar PRIVATE Foo::FooLib1 Foo::FooLib2)
target_link_libraries(baz PUBLIC  Foo::FooLib2) # link to lib2 only
</code>```

When you link to an exported target like Foo::FooLib1, its public interface will be transitively transmitted to its user. In the example above, bar will inherit properties from the linked target.

So the INTERFACE_INCLUDE_DIRECTORIES of Foo::FooLib1 and Foo::FooLib2 will be appended to bar's INCLUDE_DIRECTORIES. Same for LINK_LIBRARIES.

For baz, not only its INCLUDE_DIRECTORIES will contain Foo::FooLib2 entries, but also its own INTERFACE_INCLUDE_DIRECTORIES will transitively transmit the usage requirements of Foo::FooLib2

Body:
I am currently developing a software package, for which I'd like to provide the cmake package support (so users can find it with find_package(...)). The Problem is, the package is found but FOO_INCLUDE_DIR and FOO_LIBRARIES is empty.

Within my package I have several modules, each with a CMakeLists file which installs the respective library and headers with:

install(TARGETS ${LIBRARY_NAME} EXPORT FooTargets
    RUNTIME       DESTINATION ${Foo_RUNTIME_INSTALL_DIR}
    LIBRARY       DESTINATION ${Foo_LIBRARY_INSTALL_DIR}
    ARCHIVE       DESTINATION ${Foo_ARCHIVE_INSTALL_DIR}
    FRAMEWORK     DESTINATION ${Foo_FRAMEWORK_INSTALL_DIR})

# Headers
install(
        DIRECTORY include/${LIBRARY_NAME}
        DESTINATION include/${PROJECT_NAME}
        FILES_MATCHING
            PATTERN "*.h"
            PATTERN "*.hpp"
)

The headers for the library are included with target_include_directories like this:

target_include_directories(${LIBRARY_NAME} PUBLIC
        $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include> # for headers when building
        $<INSTALL_INTERFACE:${Foo_INC_INSTALL_DIR}> # for client in install mode
)

I checked the folders and all libraries and headers are correctly installed. In my toplevel CMakeLists I export my targets with:

install(
        EXPORT FooTargets
        DESTINATION ${Foo_CMAKE_CONFIG_INSTALL_DIR}
        FILE FooConfig.cmake
)

The config is where I assume it to be (usr/local/lib/cmake/Foo). So everything seems to be correct. When I look into my FooConfig.cmake it says:

# Create imported target realm_densifier_base
add_library(FooLib1 SHARED IMPORTED)

set_target_properties(FooLib1 PROPERTIES
  INTERFACE_INCLUDE_DIRECTORIES "/usr/local/include/Foo"
  INTERFACE_LINK_LIBRARIES "...several libraries..."
)

...which is absolutely correct and exactly what I expected. What part of the puzzle is missing? Is INTERFACE_INCLUDE_DIRECTORIES and INTERFACE_LINK_LIBRARIES not the correct flag to be set?

Thanks for the help and best regards,

Alex

Edit:

@Guillaume Racicot already cleared most things up, I only knew the "non target" way of adding headers to my project, that was with include_directories(Foo_INCLUDE_DIRS). However, in the target-world linking against my library Foo was enough. Another thing was that I messed up some directories in the target_include_directories(...) command, so directories were wrong and therefore could not be found in my other project. Thanks for the help!

Body:
Why would FOO_INCLUDE_DIR or FOO_LIBRARIES be set? This may be how old find modules worked, but not how config files work. Even newer find modules expose targets instead of directory variables.

When generating an XYZConfig.cmake file, informations about targets will be exported, not informations on the directory.

With such exportation:

install(
    EXPORT FooTargets
    NAMESPACE Foo::
    DESTINATION ${Foo_CMAKE_CONFIG_INSTALL_DIR}
    FILE FooConfig.cmake
)

You would expect users of the package to use it like so:

find_package(Foo REQUIRED)

#         or PUBLIC ------v
target_link_libraries(bar PRIVATE Foo::FooLib1)

If your package has multiple targets in the export set, then you can link to both or only one

target_link_libraries(bar PRIVATE Foo::FooLib1 Foo::FooLib2)
target_link_libraries(baz PUBLIC  Foo::FooLib2) # link to lib2 only

When you link to an exported target like Foo::FooLib1, its public interface will be transitively transmitted to its user. In the example above, bar will inherit properties from the linked target.

So the INTERFACE_INCLUDE_DIRECTORIES of Foo::FooLib1 and Foo::FooLib2 will be appended to bar's INCLUDE_DIRECTORIES. Same for LINK_LIBRARIES.

For baz, not only its INCLUDE_DIRECTORIES will contain Foo::FooLib2 entries, but also its own INTERFACE_INCLUDE_DIRECTORIES will transitively transmit the usage requirements of Foo::FooLib2


问:
Is it possible to disable some specific ciphers from CloudFront?
I'm using a tool to do security checks and this tool marked the following ciphers as weak:

```<code>TLS_RSA_WITH_AES_128_CBC_SHA256 (0x003C)
TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 (0xC027)
TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 (0xC028)
</code>```

I'm using the latest CloudFront Security Policy which is TLSv1.2_2018 and the Minimum Origin SSL Protocol set to TLSv1.2.

But even with these settings the weak ciphers is still allowed.

Is it possible to disable some specific ciphers on CloudFront?

答:
AWS doesn't allow customers to choose individual ciphers for Amazon CloudFront. Instead it allows customers to choose between different security policies. The available security policies are listed in their documentation. As of now TLSv1.2_2018 is the latest security policy they offer and also the one they recommend customers to use. This policy includes the three ciphers you'd like to disable, so there is currently no way to use TLS with AWS CloudFront without these ciphers.

Aside from the security policies offered to customers right now, AWS has already defined newer security policies for use with Amazon CloudFront in s2n, the TLS-implementation they use for most of their public facing products.

Looking into the source code of s2n reveals the following additional security policies and the ciphers they support:

TLSv1.2_2019:

```<code>TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384
TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384
TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256
</code>```

TLSv1.2_2020:

```<code>TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384
TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256
</code>```

The latest security policy (TLSv1.2_2020) doesn't include the three ciphers you want to disable anymore, so whenever AWS decides to make this security policy available to its customers, you'll be able to disable the ciphers in question.

Body:
I'm using a tool to do security checks and this tool marked the following ciphers as weak:

TLS_RSA_WITH_AES_128_CBC_SHA256 (0x003C)
TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 (0xC027)
TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 (0xC028)

I'm using the latest CloudFront Security Policy which is TLSv1.2_2018 and the Minimum Origin SSL Protocol set to TLSv1.2.

But even with these settings the weak ciphers is still allowed.

Is it possible to disable some specific ciphers on CloudFront?

Body:
AWS doesn't allow customers to choose individual ciphers for Amazon CloudFront. Instead it allows customers to choose between different security policies. The available security policies are listed in their documentation. As of now TLSv1.2_2018 is the latest security policy they offer and also the one they recommend customers to use. This policy includes the three ciphers you'd like to disable, so there is currently no way to use TLS with AWS CloudFront without these ciphers.

Aside from the security policies offered to customers right now, AWS has already defined newer security policies for use with Amazon CloudFront in s2n, the TLS-implementation they use for most of their public facing products.

Looking into the source code of s2n reveals the following additional security policies and the ciphers they support:

TLSv1.2_2019:

TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384
TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384
TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256

TLSv1.2_2020:

TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384
TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256

The latest security policy (TLSv1.2_2020) doesn't include the three ciphers you want to disable anymore, so whenever AWS decides to make this security policy available to its customers, you'll be able to disable the ciphers in question.


问:
How to display html5 video to cover the entire screen and play only the video visible
I want am building a mobile application with ionic, I want to display every video to cover the entire screen and also play only the video that is displaying on the screen and pause all others, the video is displaying as full screen but not playing one video at a time, Here is the code

```<code><style>
        main{
        overflow-y: auto;
        width: 100%;
        height: 100%;
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        display:block;
    }
    video{
        background-color: transparent;
        width:100%;
        height:100%;
        z-index:5;
        object-fit:fill;
    }
            </style>
            <main></main>
            <script>
                let url='http://localhost/test/'
                $(document).ready(()=>{
                    $.get(url,data=>{
                        data.map(video=>$('main').append(`<video src="${url}${video.src}"></video>`))
                    })
                })
            </script>
</code>```

Now the problem is how can i play only one video at a time, how can i play the video that is at the viewpoint, like tiktok

答:
checkout this awesome plugin:
https://ionicframework.com/docs/native/video-player

it should fix your problem. Good Luck!

Body:
I want am building a mobile application with ionic, I want to display every video to cover the entire screen and also play only the video that is displaying on the screen and pause all others, the video is displaying as full screen but not playing one video at a time, Here is the code

Now the problem is how can i play only one video at a time, how can i play the video that is at the viewpoint, like tiktok


问:
Swift: Avoid scrolling top 2 tableview cells
Is there a way to stop scrolling certain cells in tableview? I want the top 2 cells in UITableView to be static and have scroll enabled on other cells. Scroll enabled property is on tableview, so it scrolls all the cells.

The top 2 cells are of height 44.0 each. I tried the below code, but it still scrolls the top 2 cells.

```<code>func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
    isScrolling = true
}

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    let startScrollingOffset = 88.0
    if (scrollView.contentOffset.y < CGFloat(startScrollingOffset)) {
        // moved to top
        isScrollDown = false
    } else if (scrollView.contentOffset.y > CGFloat(startScrollingOffset)) {
        // moved to bottom
        isScrollDown = true
    } else {
        // didn't move
    }
}

func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
    if isScrollDown == false {
        return
    }
}
</code>```

答:
The solution could be take out first two row data from your data source( may be an array) and and create a custom view with that two row data. then set the custom view in the tableviewHeader using viewForHeaderInSection

As you have already removed first two row your table will show the data from third entry and the first two will be in top of them as header.

Body:
Is there a way to stop scrolling certain cells in tableview? I want the top 2 cells in UITableView to be static and have scroll enabled on other cells. Scroll enabled property is on tableview, so it scrolls all the cells.

The top 2 cells are of height 44.0 each. I tried the below code, but it still scrolls the top 2 cells.

func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
    isScrolling = true
}

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    let startScrollingOffset = 88.0
    if (scrollView.contentOffset.y < CGFloat(startScrollingOffset)) {
        // moved to top
        isScrollDown = false
    } else if (scrollView.contentOffset.y > CGFloat(startScrollingOffset)) {
        // moved to bottom
        isScrollDown = true
    } else {
        // didn't move
    }
}

func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
    if isScrollDown == false {
        return
    }
}


问:
Why can not Hostname of NiFi Certificate Authority be updated using NIFI-TOOLKIT?
Toolkit to generate keystore and truststore with "-c 'hhh'",but the CN is 'localhost'?Can u get me suggestion?Thanks in  advance!

-c,--certificateAuthorityHostname    Hostname of NiFi Certificate Authority (default: localhost)

答:
I experienced the same problem here, my solution was to remove de target file, as suggested in previous post, and run the script with an additional param, in your case it should be something like this

tls-toolkit.sh standalone .... --certificateAuthorityHostname hhh

It worked for me


问:
CSS class not applying style
In regard to the first CSS rule, it works when i use the 'p' tag by itself. When I apply the 'article' class with or without the 'p' tag, it doesn't work. Why is that? Also the 'hr' tag with the class of 'one' works (which means CSS file is working). This seems so basic. I don't understand why it isn't working. Any ideas?

HTML

```<code><p class=article>{{ post.body|truncatewords:30|linebreaks }}</p>
</code>```

-- Also tried this

```<code><p class="article">{{ post.body|truncatewords:30|linebreaks }}</p>
</code>```

external CSS file

```<code>p.article {
    color:red;
}

hr.one {
    border:none;
    height: 2px;
    background: #cec4c4;
}
</code>```

HTML Output

```<code><div>

        <h1 class=display-4><a href="/blog/2020/5/28/gdddsasddsg/">gdddsasddsg</a></h1>

        <h6><span class="font-italic font-weight-normal">By: </span>gdorman619  <span
                class="font-italic font-weight-normal">Published Date: </span> May 28, 2020, 12:24 p.m.</h6>

        <p class="article"><p>sdadfsdsfdsfa</p></p>

        <hr class="one">

    </div>
</code>```

答: Are you printing content from a WYSIWYG-editor or something else that is not a pure string? In that case, that content will likely enforce its own markup as inline HTML and external css is not going to work as inline CSS inside HTML has a higher specificity then CSS placed in an external stylesheet, unless you apply <code>!important</code> to the color, which makes me cringe on my behalf. </p>

Title: CSS class not applying style

Body:
In regard to the first CSS rule, it works when i use the 'p' tag by itself. When I apply the 'article' class with or without the 'p' tag, it doesn't work. Why is that? Also the 'hr' tag with the class of 'one' works (which means CSS file is working). This seems so basic. I don't understand why it isn't working. Any ideas?

HTML

{{ post.body|truncatewords:30|linebreaks }}

-- Also tried this

{{ post.body|truncatewords:30|linebreaks }}

external CSS file

p.article {
    color:red;
}

hr.one {
    border:none;
    height: 2px;
    background: #cec4c4;
}

HTML Output

gdddsasddsg

By: gdorman619  Published Date:  May 28, 2020, 12:24 p.m.

sdadfsdsfdsfa

Body: Are you printing content from a WYSIWYG-editor or something else that is not a pure string? In that case, that content will likely enforce its own markup as inline HTML and external css is not going to work as inline CSS inside HTML has a higher specificity then CSS placed in an external stylesheet, unless you apply !important to the color, which makes me cringe on my behalf.


问:
C++ library related queries
What does the inside of a library look like?

Are the different function codes just stored in there in different blocks one after another like in a C++ program as follows?

```<code>function1_name (argument_1, argument_2)
{
//function_1 code
}

function2_name (argument_1)
{
//function_2 code
}
.
.
.
.
</code>```

答:
An executable is something that can be run directly and it can contain many functions in it, but one of them is the "entry point". We can see the entry point as the function that it is first run (there are a few things that can run before - read this for more info). In C/C++ the entry point is the main function.

On the other hand, a library is not run directly and instead, it provides functions (or classes, etc) that can be called from other libraries or from the executable. In C/C++ a library will not have a main function, since otherwise when the executable is linked with the library you would get multiple definitions for the main function.

Besides this, there is not much difference between an executable and a library and how they "look inside" will depend on the format. A python library is just another text file with a bunch of functions and classes, while in C/C++ a compiled library is the corresponding binary code of a bunch of functions and classes. In Linux, this binary code is probably in the ELF format and thus you can read about how the ELF format works to understand how a library "looks inside" in binary format (at least in Linux).

As a final note, the "entry point" does not necessarily need to be the main function. This is just the convention if you don't specify otherwise. In this link there is an example of compiling with gcc and specifying a different entry point for the executable. When you compile your code what you get is either a library of an executable depending on how you compiled.

Title: C++ library related queries

Body:
What does the inside of a library look like?

Are the different function codes just stored in there in different blocks one after another like in a C++ program as follows?

function1_name (argument_1, argument_2)
{
//function_1 code
}

function2_name (argument_1)
{
//function_2 code
}
.
.
.
.


问:
Kotlinx Serialization - Custom serializer to ignore null value
Let's say I'm having a class like:

```<code>@Serializable
data class MyClass(
    @SerialName("a") val a: String?,
    @SerialName("b") val b: String
)
</code>```

Assume the a is null and b's value is "b value", then Json.stringify(MyClass.serializer(), this) produces:

```<code>{ "a": null, "b": "b value" }
</code>```

Basically if a is null, I wanted to get this:

```<code>{ "b": "b value" }
</code>```

From some research I found this is currently not doable out of the box with Kotlinx Serialization so I was trying to build a custom serializer to explicitly ignore null value. I followed the guide from here but couldn't make a correct one.

Can someone please shed my some light? Thanks.

答: Use encodeDefaults = false property in JsonConfiguration and it won't serialize nulls (or other optional values)

Body:
Let's say I'm having a class like:

@Serializable
data class MyClass(
    @SerialName("a") val a: String?,
    @SerialName("b") val b: String
)

Assume the a is null and b's value is "b value", then Json.stringify(MyClass.serializer(), this) produces:

{ "a": null, "b": "b value" }

Basically if a is null, I wanted to get this:

{ "b": "b value" }

From some research I found this is currently not doable out of the box with Kotlinx Serialization so I was trying to build a custom serializer to explicitly ignore null value. I followed the guide from here but couldn't make a correct one.

Can someone please shed my some light? Thanks.


问:
From in the message appearing wrong
How do I make the email of who sent it from appear? Currently, when the person sends the email, it appears that the person who sent the email was the person who received it</p>

```<code>let transporter = nodemailer.createTransport({
    service: "gmail",
    host: "smtp.gmail.com",
    auth: {
      user: "***********@gmail.com",
      pass: "********",
    },
  });
  const message = {
    from: `${request.body.name} <${request.body.email}>`,
    to: "**********@gmail.com",
    cc: request.body.email,
    subject: request.body.subject,
    html: `Message`,
  };
</code>```

答:
You cannot send an email on behalf of the user without having access to his account, setting the from field will not change the fact that you are the sender. To try and see the difference, send the email from the account you used for the trasporter, to another account of yours.

```<code>let transporter = nodemailer.createTransport({
    service: "gmail",
    host: "smtp.gmail.com",
    auth: {
      user: "yourFirstEmail@gmail.com",
      pass: "********",
    },
  });
  const message = {
    from: "yourFirstEmail@gmail.com"`,
    to: "yourSecondEmail@gmail.com",
    cc: request.body.email,
    subject: request.body.subject,
    html: `Message`,
  };
</code>```

This should work.

Title: From in the message appearing wrong

Body:
How do I make the email of who sent it from appear? Currently, when the person sends the email, it appears that the person who sent the email was the person who received it

let transporter = nodemailer.createTransport({
    service: "gmail",
    host: "smtp.gmail.com",
    auth: {
      user: "***********@gmail.com",
      pass: "********",
    },
  });
  const message = {
    from: `${request.body.name} <${request.body.email}>`,
    to: "**********@gmail.com",
    cc: request.body.email,
    subject: request.body.subject,
    html: `Message`,
  };

Body:
You cannot send an email on behalf of the user without having access to his account, setting the from field will not change the fact that you are the sender. To try and see the difference, send the email from the account you used for the trasporter, to another account of yours.

let transporter = nodemailer.createTransport({
    service: "gmail",
    host: "smtp.gmail.com",
    auth: {
      user: "yourFirstEmail@gmail.com",
      pass: "********",
    },
  });
  const message = {
    from: "yourFirstEmail@gmail.com"`,
    to: "yourSecondEmail@gmail.com",
    cc: request.body.email,
    subject: request.body.subject,
    html: `Message`,
  };

This should work.


问:
SQL NESTED JOIN ISSUES
I'm having a heck of a time getting my query to work properly.  I have 3 tables (ORDERS, ORDERSITEMS, ORDERPAYMENTS) that I'm trying to build a report for monthly sales taxes due which will look like this:

```<code>MONTH      YEAR        TOTAL RECEIPTS        EXEMPT RECEIPTS     NON-EXEMPT RECEIPTS        SALES TAX
1           2020        $5,000                $4,500                $500                      $31.25
</code>```

TOTAL RECEIPTS:  To get this number you have to add together all of the C.OrderPayments_Amount for the given time frame, in this case  MONTH(C.OrderPayments_Date) = 1  AND YEAR(C.OrderPayments_Date) = 2020

EXEMPT RECEIPTS: You have to determine if an item is taxable (eg. digital files are not sales taxable, physical prints are).  To get this you have determine if the item is taxable by checking the B.OrdersItems_ItemChargeSalesTax.  If this field is 0 it does not get charged sales tax and if it is 1 then it does.  You then have to filter to only get ORDERSITEMS for the Jan 2020 time frame using  by grouping by the C.OrderPayments_Date column that have the B.OrdersItems_ItemChargeSalesTax = 0 and finally add the B.OrdersItems_Total together.

NON-EXEMPT RECEIPTS:  To get this number you do the same exact thing for EXEMPT RECEIPTS above except you look for B.OrdersItems_ItemChargeSalesTax = 1 and add the B.OrdersItems_Total together.

SALES TAX: To get this number you use the same date filter as before MONTH(C.OrderPayments_Date) = 1  AND YEAR(C.OrderPayments_Date) = 2020 and then add the A.Order_SalesTax column together.

The first query I have listed is working fine to bring me the total taxes paid and the total income for the month (right now I have hard coded the WHERE statement but that is going to be applied via filters on my list page).  What I
need to get from the ORDERSITEMS table is a field called ORDERSITEMS_ItemTotal and sum that field so it is a single line entry on the query.  I have seen another person do a nested join.  Any suggestions would be greatly appreciated.

```<code>**ORDERS TABLE "A"**
  Order_ID,
  Order_SalesTax,
  stateTaxAbbreviation

**ORDERSITEMS TABLE "B"**
  Order_FK,
  OrdersItems_ItemChargeSalesTax,
  OrdersItems_Total
</code>```

NOTE:  In the ORDERSITEMS table a single Order_FK may appear several times as there can be many items on an order

```<code>**ORDERPAYMENTS TABLE "C"**
  Order_FK,
  OrderPayments_PaymentDate,
  OrderPayments_Amount
</code>```

NOTE:  In the ORDERPAYMENTS table a single Order_FK may appear several times as there can be multiple payments on an order

While writing this out it seems to be an easy task but when I attempt to put it all together the numbers are wrong because it is adding entries multiple times because there are multiple items on an order and thus it is adding the total payment every time.

Here is the code that I've been tinkering with and I would really appreciate any guidance.  Thank you in advance and hopefully I've explained my situation clearly enough.

```<code>Select
    a.stateTaxAbbreviation AS StateAbbr,
    MONTH(c.OrderPayments_Date) AS PaymentMonth,
    YEAR(c.OrderPayments_Date) AS PaymentYear,
    SUM(c.OrderPayments_Amount) AS TotalPayments,
    SUM(a.Order_SalesTax) AS sales_tax
FROM dbo.ORDERS a
   INNER JOIN ORDERPAYMENTS as c ON c.Order_FK = a.Order_ID
      LEFT OUTER JOIN ORDERITEMS b on b.Order_FK = a.Order_ID
  WHERE a.stateTaxAbbreviation = 'MA' AND Month(b.OrderPayments_Date) = 1 AND YEAR(b.OrderPayments_Date) = 2020
  GROUP BY stateTaxAbbreviation , MONTH(c.OrderPayments_Date), Year(c.OrderPayments_Date)
</code>```

答:
You should probably write 2 queries, one where you join the ORDERPAYMENTS table, and another where you join the ORDERITEMS table.  Then you can combine them with UNION ALL.

Something like this:

```<code>SELECT StateAbbr,PaymentMonth,PaymentYear,SUM(TotalPayments),SUM(sales_tax),SUM(OrdersItems_Total)
FROM (
    Select
        a.stateTaxAbbreviation AS StateAbbr,
        MONTH(c.OrderPayments_Date) AS PaymentMonth,
        YEAR(c.OrderPayments_Date) AS PaymentYear,
        SUM(c.OrderPayments_Amount) AS TotalPayments,
        SUM(a.Order_SalesTax) AS sales_tax,
        0 as OrdersItems_Total
    FROM dbo.ORDERS a
       INNER JOIN ORDERPAYMENTS as c ON c.Order_FK = a.Order_ID
     WHERE a.stateTaxAbbreviation = 'MA' AND Month(c.OrderPayments_Date) = 1 AND YEAR(c.OrderPayments_Date) = 2020
     GROUP BY stateTaxAbbreviation , MONTH(c.OrderPayments_Date), Year(c.OrderPayments_Date)

     UNION ALL

     Select
        a.stateTaxAbbreviation AS StateAbbr,
        MONTH(c.OrderPayments_Date) AS PaymentMonth,
        YEAR(c.OrderPayments_Date) AS PaymentYear,
        0 AS TotalPayments,
        0 AS sales_tax,
        SUM(B.OrdersItems_Total) as OrdersItems_Total

    FROM dbo.ORDERS a
     INNER JOIN ORDERITEMS b on b.Order_FK = a.Order_ID
     WHERE a.stateTaxAbbreviation = 'MA' AND Month(b.OrderPayments_Date) = 1 AND YEAR(b.OrderPayments_Date) = 2020
     GROUP BY stateTaxAbbreviation , MONTH(c.OrderPayments_Date), Year(c.OrderPayments_Date)
 )t
GROUP BY StateAbbr,PaymentMonth,PaymentYear
</code>```

Title: SQL NESTED JOIN ISSUES

Body:
I'm having a heck of a time getting my query to work properly.  I have 3 tables (ORDERS, ORDERSITEMS, ORDERPAYMENTS) that I'm trying to build a report for monthly sales taxes due which will look like this:

MONTH      YEAR        TOTAL RECEIPTS        EXEMPT RECEIPTS     NON-EXEMPT RECEIPTS        SALES TAX
1           2020        $5,000                $4,500                $500                      $31.25

TOTAL RECEIPTS:  To get this number you have to add together all of the C.OrderPayments_Amount for the given time frame, in this case  MONTH(C.OrderPayments_Date) = 1  AND YEAR(C.OrderPayments_Date) = 2020

EXEMPT RECEIPTS: You have to determine if an item is taxable (eg. digital files are not sales taxable, physical prints are).  To get this you have determine if the item is taxable by checking the B.OrdersItems_ItemChargeSalesTax.  If this field is 0 it does not get charged sales tax and if it is 1 then it does.  You then have to filter to only get ORDERSITEMS for the Jan 2020 time frame using  by grouping by the C.OrderPayments_Date column that have the B.OrdersItems_ItemChargeSalesTax = 0 and finally add the B.OrdersItems_Total together.

NON-EXEMPT RECEIPTS:  To get this number you do the same exact thing for EXEMPT RECEIPTS above except you look for B.OrdersItems_ItemChargeSalesTax = 1 and add the B.OrdersItems_Total together.

SALES TAX: To get this number you use the same date filter as before MONTH(C.OrderPayments_Date) = 1  AND YEAR(C.OrderPayments_Date) = 2020 and then add the A.Order_SalesTax column together.

The first query I have listed is working fine to bring me the total taxes paid and the total income for the month (right now I have hard coded the WHERE statement but that is going to be applied via filters on my list page).  What I
need to get from the ORDERSITEMS table is a field called ORDERSITEMS_ItemTotal and sum that field so it is a single line entry on the query.  I have seen another person do a nested join.  Any suggestions would be greatly appreciated.

**ORDERS TABLE "A"**
  Order_ID,
  Order_SalesTax,
  stateTaxAbbreviation

**ORDERSITEMS TABLE "B"**
  Order_FK,
  OrdersItems_ItemChargeSalesTax,
  OrdersItems_Total

NOTE:  In the ORDERSITEMS table a single Order_FK may appear several times as there can be many items on an order

**ORDERPAYMENTS TABLE "C"**
  Order_FK,
  OrderPayments_PaymentDate,
  OrderPayments_Amount

NOTE:  In the ORDERPAYMENTS table a single Order_FK may appear several times as there can be multiple payments on an order

While writing this out it seems to be an easy task but when I attempt to put it all together the numbers are wrong because it is adding entries multiple times because there are multiple items on an order and thus it is adding the total payment every time.

Here is the code that I've been tinkering with and I would really appreciate any guidance.  Thank you in advance and hopefully I've explained my situation clearly enough.

Select
    a.stateTaxAbbreviation AS StateAbbr,
    MONTH(c.OrderPayments_Date) AS PaymentMonth,
    YEAR(c.OrderPayments_Date) AS PaymentYear,
    SUM(c.OrderPayments_Amount) AS TotalPayments,
    SUM(a.Order_SalesTax) AS sales_tax
FROM dbo.ORDERS a
   INNER JOIN ORDERPAYMENTS as c ON c.Order_FK = a.Order_ID
      LEFT OUTER JOIN ORDERITEMS b on b.Order_FK = a.Order_ID
  WHERE a.stateTaxAbbreviation = 'MA' AND Month(b.OrderPayments_Date) = 1 AND YEAR(b.OrderPayments_Date) = 2020
  GROUP BY stateTaxAbbreviation , MONTH(c.OrderPayments_Date), Year(c.OrderPayments_Date)

Body:
You should probably write 2 queries, one where you join the ORDERPAYMENTS table, and another where you join the ORDERITEMS table.  Then you can combine them with UNION ALL.

Something like this:

SELECT StateAbbr,PaymentMonth,PaymentYear,SUM(TotalPayments),SUM(sales_tax),SUM(OrdersItems_Total)
FROM (
    Select
        a.stateTaxAbbreviation AS StateAbbr,
        MONTH(c.OrderPayments_Date) AS PaymentMonth,
        YEAR(c.OrderPayments_Date) AS PaymentYear,
        SUM(c.OrderPayments_Amount) AS TotalPayments,
        SUM(a.Order_SalesTax) AS sales_tax,
        0 as OrdersItems_Total
    FROM dbo.ORDERS a
       INNER JOIN ORDERPAYMENTS as c ON c.Order_FK = a.Order_ID
     WHERE a.stateTaxAbbreviation = 'MA' AND Month(c.OrderPayments_Date) = 1 AND YEAR(c.OrderPayments_Date) = 2020
     GROUP BY stateTaxAbbreviation , MONTH(c.OrderPayments_Date), Year(c.OrderPayments_Date)

     UNION ALL

     Select
        a.stateTaxAbbreviation AS StateAbbr,
        MONTH(c.OrderPayments_Date) AS PaymentMonth,
        YEAR(c.OrderPayments_Date) AS PaymentYear,
        0 AS TotalPayments,
        0 AS sales_tax,
        SUM(B.OrdersItems_Total) as OrdersItems_Total

    FROM dbo.ORDERS a
     INNER JOIN ORDERITEMS b on b.Order_FK = a.Order_ID
     WHERE a.stateTaxAbbreviation = 'MA' AND Month(b.OrderPayments_Date) = 1 AND YEAR(b.OrderPayments_Date) = 2020
     GROUP BY stateTaxAbbreviation , MONTH(c.OrderPayments_Date), Year(c.OrderPayments_Date)
 )t
GROUP BY StateAbbr,PaymentMonth,PaymentYear


问:
Nesting nuget packages
I have a nuget package containing retry policies and a number of nuget packages for
database , http and cache clients. The idea is that all external depedencies should be accessed in an ordered and safe way. All packages are hosted in a private nuget server.

If I include the retry policy nuget package into the individual clients' nuget package, would be great on one hand because the end application using only one package will get the full functionality.

On the other hand, an update in the base package (retry policy in this examples case) would trigger a massive need for updates in many other nuget packages, used by several applications.

Is there any established best practice?

答:
My personal practice is to keep the nugets as independant as possible. So the less dependecies the better.

If your client nuget code depends on it (as it does not compile without it) you have to add it anyway.

If your client nugets code don't diectly depend on the retry policies than you are better of don't adding it as dependency.

This keeps you flexible enough in the future for using differrent retry policies when the client nugets are used.

As you already expect: If you add it and you have to update your retry policy nuget you will have to update the client nugets too for just using a different version of the dependency (though no actual code has been changed).

For bundling a set of nugets with specified versions (as i think you want) you can still create meta packages/nugets which just hold the selected dependencies and no code.

Title: Nesting nuget packages


问:
update null column from select
I have the below table, approx 3 million rows.

```<code>at_id  a.at_type_cd
  1      red
  2      blue
  3      yellow
</code>```

I want to add a column, so I did the below.

```<code>alter table ship.alt
add (src_ind char(1) null)
</code>```

Now I have the below table:

```<code>at_id    at_type_cd   src_ind
  1      red           (null)
  2      blue          (null)
  3      yellow        (null)
</code>```

All values in the src_ind are null. I want to add values to the src_ind based of a select from another table.

```<code>merge into &tableschema..alt dest
using (select /* parallel(a,16) */
    x.at_id,
    x.src_ind
    from (select
          a.at_id,
          case
          when alt.tracks_t is null
          then 'H'
          when alt.tracks_at = 1
          then 'B'
          else 'x'
          end src_ind
          from &tableschema..alt a
          left join (select
                     alt.at_type,
                     alt.tracks_at
                     from &tableschema..at_tys@db alt
                     where alt.tracks_at <> 0) alt
                     on a.at_type_cd = alt.at_type
                     where 1=1)x ) src
                     on (src.at_id = dest.at_id)
when matched then
 update set
 dest.src_ind = src.src_ind
when not matched then
insert (src_ind)
values (src.src_ind)
</code>```

This takes over two hours on my end. I'm not sure this is correct, using the eyeball test, is there a more efficient way to add column values based on a select?

update vs insert vs merge

Maybe a insert with a where exist?

答:
Your table at_tys seems to be on another database, so I would copy it over, preselecting the rows you'll need:

```<code>CREATE TABLE local_tys NOLOGGING AS
SELECT at_type, at_tracks_at
  FROM &tableschema..at_tys@db alt
  WHER alt.tracks_at <> 0;
</code>```

Next, I'd write a SELECT that joins your old table without the column and the values of the new column. I did't fully understand your join, so this is just a mockup:

```<code>SELECT a.at_id, a.at_type_cd, b.
  FROM &tableschema..alt a
  JOIN local_tys b
    ON a.at_type_cd = b.at_type ....
</code>```

I would then create a table from this query, and once it's built drop the old table and rename the temp table, create index etc.

Title: update null column from select

Body:
I have the below table, approx 3 million rows.

at_id  a.at_type_cd
  1      red
  2      blue
  3      yellow

I want to add a column, so I did the below.

alter table ship.alt
add (src_ind char(1) null)

Now I have the below table:

at_id    at_type_cd   src_ind
  1      red           (null)
  2      blue          (null)
  3      yellow        (null)

All values in the src_ind are null. I want to add values to the src_ind based of a select from another table.

merge into &tableschema..alt dest
using (select /* parallel(a,16) */
    x.at_id,
    x.src_ind
    from (select
          a.at_id,
          case
          when alt.tracks_t is null
          then 'H'
          when alt.tracks_at = 1
          then 'B'
          else 'x'
          end src_ind
          from &tableschema..alt a
          left join (select
                     alt.at_type,
                     alt.tracks_at
                     from &tableschema..at_tys@db alt
                     where alt.tracks_at <> 0) alt
                     on a.at_type_cd = alt.at_type
                     where 1=1)x ) src
                     on (src.at_id = dest.at_id)
when matched then
 update set
 dest.src_ind = src.src_ind
when not matched then
insert (src_ind)
values (src.src_ind)

This takes over two hours on my end. I'm not sure this is correct, using the eyeball test, is there a more efficient way to add column values based on a select?

update vs insert vs merge

Maybe a insert with a where exist?

Body:
Your table at_tys seems to be on another database, so I would copy it over, preselecting the rows you'll need:

CREATE TABLE local_tys NOLOGGING AS
SELECT at_type, at_tracks_at
  FROM &tableschema..at_tys@db alt
  WHER alt.tracks_at <> 0;

Next, I'd write a SELECT that joins your old table without the column and the values of the new column. I did't fully understand your join, so this is just a mockup:

SELECT a.at_id, a.at_type_cd, b.
  FROM &tableschema..alt a
  JOIN local_tys b
    ON a.at_type_cd = b.at_type ....

I would then create a table from this query, and once it's built drop the old table and rename the temp table, create index etc.


问:
brew link new php version error
brew link php70 is giving me the following error:

```<code>Warning: php@7.0 is keg-only and must be linked with --force
Note that doing so can interfere with building software.
If you need to have this software first in your PATH instead consider running:
  echo 'export PATH="/usr/local/opt/php@7.0/bin:$PATH"' >> ~/.bash_profile
  echo 'export PATH="/usr/local/opt/php@7.0/sbin:$PATH"' >> ~/.bash_profile
</code>```

but in ~/.bash_profiles:

```<code>PATH=$PATH:/usr/local/opt/php@7.0/bin
export PATH
</code>```

please tell me how I can solve it.

thanks.

答:
I encountered a similar issue too, running the following command from the terminal fixed it.

Please note that this is for PHP@7.2 and I use ZSH shell:

```<code>  echo 'export PATH="/usr/local/opt/php@7.2/bin:$PATH"' >> ~/.zshrc
  echo 'export PATH="/usr/local/opt/php@7.2/sbin:$PATH"' >> ~/.zshrc
</code>```

So you would run:

```<code>echo 'export PATH="/usr/local/opt/php@7.0/bin:$PATH"' >> ~/.bash_profile
echo 'export PATH="/usr/local/opt/php@7.0/sbin:$PATH"' >> ~/.bash_profile
</code>```

Afterwards, close and reopen your terminal for the changes to take affect.

Title: brew link new php version error

Body:
brew link php70 is giving me the following error:

Warning: php@7.0 is keg-only and must be linked with --force
Note that doing so can interfere with building software.
If you need to have this software first in your PATH instead consider running:
  echo 'export PATH="/usr/local/opt/php@7.0/bin:$PATH"' >> ~/.bash_profile
  echo 'export PATH="/usr/local/opt/php@7.0/sbin:$PATH"' >> ~/.bash_profile

but in ~/.bash_profiles:

PATH=$PATH:/usr/local/opt/php@7.0/bin
export PATH

please tell me how I can solve it.

thanks.

Body:
I encountered a similar issue too, running the following command from the terminal fixed it.

Please note that this is for PHP@7.2 and I use ZSH shell:

  echo 'export PATH="/usr/local/opt/php@7.2/bin:$PATH"' >> ~/.zshrc
  echo 'export PATH="/usr/local/opt/php@7.2/sbin:$PATH"' >> ~/.zshrc

So you would run:

echo 'export PATH="/usr/local/opt/php@7.0/bin:$PATH"' >> ~/.bash_profile
echo 'export PATH="/usr/local/opt/php@7.0/sbin:$PATH"' >> ~/.bash_profile

Afterwards, close and reopen your terminal for the changes to take affect.


问:
How to change a range of array with one value Javascript?
I have an array like below let's say

```<code>var myArray = ["1", "", "", "2","3","","","8"];
</code>```

And I want to fill each " " value with previous not null value

According to that expectation should be like below

```<code>var myArray = ["1", "2", "2", "2","3","8","8","8"];
</code>```

Here what I tried but didn't work

    var myArray = ["1", "", "", "2","3","","","8"];

    function myFunction() {
      let currentEl=myArray [0];
      let prevIndex=0;
      fruits.map((e,a)=>{
      if(e!="" && myArray[a-1]==""){
       currentEl=e;
       let interval=arrayGenerate(a-currentIndex-1,currentEl);
       fruits.splice(currentIndex-1, currentEl+1, interval);
       currentIndex=a;
      }
      })
    }
    function arrayGenerate(iteration,value){
      let arr=[];
      for(var i=0;i<iteration;i++){
      arr.push(value);
      }
      return arr;
    }

console.log(myArray)```

答:
You could map the new values and find the missing following value.

var array = ["1", "", "", "2", "3", "", "", "8"],
    result = array.map((v, i, a) => v || a.find((w, j) => j > i && w));

console.log(result);```
</div>
</div>
</p>

<p>A solution with the same array, by looping from the end and storing the last value.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var array = ["1", "", "", "2", "3", "", "", "8"],
    i = array.length,
    value;

while (i--) {
    if (array[i]) value = array[i];
    else array[i] = value;
}

console.log(array);</code>```

Body:
I have an array like below let's say

var myArray = ["1", "", "", "2","3","","","8"];

And I want to fill each " " value with previous not null value

According to that expectation should be like below

var myArray = ["1", "2", "2", "2","3","8","8","8"];

Here what I tried but didn't work

    var myArray = ["1", "", "", "2","3","","","8"];

    function myFunction() {
      let currentEl=myArray [0];
      let prevIndex=0;
      fruits.map((e,a)=>{
      if(e!="" && myArray[a-1]==""){
       currentEl=e;
       let interval=arrayGenerate(a-currentIndex-1,currentEl);
       fruits.splice(currentIndex-1, currentEl+1, interval);
       currentIndex=a;
      }
      })
    }
    function arrayGenerate(iteration,value){
      let arr=[];
      for(var i=0;i<iteration;i++){
      arr.push(value);
      }
      return arr;
    }

console.log(myArray)

Body:
You could map the new values and find the missing following value.

var array = ["1", "", "", "2", "3", "", "", "8"],
    result = array.map((v, i, a) => v || a.find((w, j) => j > i && w));

console.log(result);

A solution with the same array, by looping from the end and storing the last value.

var array = ["1", "", "", "2", "3", "", "", "8"],
    i = array.length,
    value;

while (i--) {
    if (array[i]) value = array[i];
    else array[i] = value;
}

console.log(array);


答:
Try with this css.

```<code>.article {
    color:red;
}

.one {
    border:none;
    height: 2px;
    background: #cec4c4;
}
</code>```

it may help you

Title: CSS class not applying style

Body:
Try with this css.

.article {
    color:red;
}

.one {
    border:none;
    height: 2px;
    background: #cec4c4;
}

it may help you


问:
How do I measure the size of a TextBlock in WPF before it is rendered?
I have a WPF DataTemplate with two TextBlock controls (stacked) and then some other elements underneath.  Due to some complicated layout code, I need to know the height of the two TextBlock elements so that I can draw some fancy connector lines, and line up other controls, etc.

If I know the text that's going into the TextBlocks, and I know the font, etc., is there some way I can compute or measure the height of these TextBlocks without actually rendering them?

答:
And since Measure is defined in UIElement you can measure the shape of any UIElement derived object including TextBlock:</p>

```<code>public static Size ShapeMeasure(UIElement e) {
// Measured Size is bounded to be less than maxSize
Size maxSize = new Size(
     double.PositiveInfinity,
     double.PositiveInfinity);
e.Measure(maxSize);
return e.DesiredSize;
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
And since Measure is defined in UIElement you can measure the shape of any UIElement derived object including TextBlock:

public static Size ShapeMeasure(UIElement e) {
// Measured Size is bounded to be less than maxSize
Size maxSize = new Size(
     double.PositiveInfinity,
     double.PositiveInfinity);
e.Measure(maxSize);
return e.DesiredSize;
}


问:
Can I safely remove await Task.CompletedTask call at the end of a method?
I was looking over some old code and I found an async method doing some async stuff and at the end calling await Task.CompletedTask; like below:

```<code>    public async Task SomeMethod()
    {
        //some code
        //...

        await _someService.DoStuffAsync();
        await Task.CompletedTask;
    }
</code>```

From what I read it seems safe to remove the last line, as it does not have a functional impact over the method execution, since the Task.CompletedTask will return a task that is already completed so it will not await it, but I have second thoughts about this.

Is it safe to delete the last line? Is it redundant?

答:
Yes, it's perfectly safe to remove that.
This call doesn't do anything there other than checking that the task is already completed.

Years ago, when async was not yet available but Task was, we had to have

```<code>public Task Something()
{
    ....

    return Task.FromResult(0);
}
</code>```

People adopted this when Task.CompletedTask was added and you will often see

```<code>public Task Something()
{
    ....

    return Task.CompletedTask;
}
</code>```

This is something that makes sense if .... doesn't do anything async but you still have to return a Task.

When async is available and the method body awaits, the method doesn't have to return anything:

```<code>public async Task Something()
{
    await SomethingElse();
}
</code>```

But awaiting the Task.CompletedTask - I don't think there's a scenario where this would be useful.

Body:
I was looking over some old code and I found an async method doing some async stuff and at the end calling await Task.CompletedTask; like below:

    public async Task SomeMethod()
    {
        //some code
        //...

        await _someService.DoStuffAsync();
        await Task.CompletedTask;
    }

From what I read it seems safe to remove the last line, as it does not have a functional impact over the method execution, since the Task.CompletedTask will return a task that is already completed so it will not await it, but I have second thoughts about this.

Is it safe to delete the last line? Is it redundant?

Body:
Yes, it's perfectly safe to remove that.
This call doesn't do anything there other than checking that the task is already completed.

Years ago, when async was not yet available but Task was, we had to have

public Task Something()
{
    ....

    return Task.FromResult(0);
}

People adopted this when Task.CompletedTask was added and you will often see

public Task Something()
{
    ....

    return Task.CompletedTask;
}

This is something that makes sense if .... doesn't do anything async but you still have to return a Task.

When async is available and the method body awaits, the method doesn't have to return anything:

public async Task Something()
{
    await SomethingElse();
}

But awaiting the Task.CompletedTask - I don't think there's a scenario where this would be useful.