问:
Create IoT Policy with AWS Lambda
I am trying to create an IoT Policy within AWS Lambda. My current Lambda Function looks like that:

"use strict";
const AWS = require("aws-sdk");
AWS.config.update({ region: "eu-central-1" });
var iot = new AWS.Iot();

exports.handler = async (event, context) => {

  var params = {
    policyDocument: `{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "iot:Connect"
      ],
      "Resource": [
        "arn:aws:iot:xxxxx:client/sander"
      ]
    },
    {
      "Effect": "Allow",
      "Action": [
        "iot:Subscribe"
      ],
      "Resource": [
        "arn:aws:iot:xxxx:topicfilter/$aws/things/ManuelBohrmaschine/shadow/*",
        "arn:aws:iot:xxxx:topicfilter/$aws/things/HeikoBohrmaschine/shadow/*"
      ]
    },
    {
      "Effect": "Allow",
      "Action": [
        "iot:Publish",
        "iot:Receive"
      ],
      "Resource": [
        "arn:aws:iot:xxxx:topic/$aws/things/ManuelBohrmaschine/shadow/*",
        "arn:aws:iot:xxxx:topic/$aws/things/HeikoBohrmaschine/shadow/*"
      ]
    }
  ]
}`,
    policyName: 'sander1231564654654654',
  };

  try{

    iot.createPolicy(params, function (err, data) {
      if (err) console.log(err, err); // an error occurred
      else {
        console.log("test")
        console.log(data);
        return {
          headers: {
            "Access-Control-Allow-Origin": "*", // Required for CORS support to work
            "Access-Control-Allow-Credentials": true // Required for cookies, authorization headers with HTTPS
          },
          statusCode: 200,
          body: JSON.stringify(data)
        };

      }
    });
  }
  catch(e){
    console.log(e);
  }
};```

The lambda function just returns null and does not even get into the callback function of iot.createPolicy(). I also tried it without try and catch. Same problem. There is no proper error. I am using this documentation: https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/Iot.html#createPolicy-property

答:
I think the reason is that your function returns before it gets a chance to run your iot section. This is beacuse for async handlers:

If your code performs an asynchronous task, return a promise to make sure that it finishes running. When you resolve or reject the promise, Lambda sends the response or error to the invoker.

To overcome this, you can use const promise = new Promise(...) as shown in the docs.

I modified the code to use the Promise pattern (see below). I can't grantee that it fully works but your function should be able to execute iot.createPolicy section now.

```<code>"use strict";
const AWS = require("aws-sdk");
AWS.config.update({ region: "eu-central-1" });
var iot = new AWS.Iot();

exports.handler = async (event, context) => {

  var params = {
    policyDocument: `{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "iot:Connect"
      ],
      "Resource": [
        "arn:aws:iot:xxxxx:client/sander"
      ]
    },
    {
      "Effect": "Allow",
      "Action": [
        "iot:Subscribe"
      ],
      "Resource": [
        "arn:aws:iot:xxxx:topicfilter/$aws/things/ManuelBohrmaschine/shadow/*",
        "arn:aws:iot:xxxx:topicfilter/$aws/things/HeikoBohrmaschine/shadow/*"
      ]
    },
    {
      "Effect": "Allow",
      "Action": [
        "iot:Publish",
        "iot:Receive"
      ],
      "Resource": [
        "arn:aws:iot:xxxx:topic/$aws/things/ManuelBohrmaschine/shadow/*",
        "arn:aws:iot:xxxx:topic/$aws/things/HeikoBohrmaschine/shadow/*"
      ]
    }
  ]
}`,
    policyName: 'sander1231564654654654',
  };

  const promise = new Promise(function(resolve, reject) {

  try{

    console.log(params);

    iot.createPolicy(params, function (err, data) {
      if (err) {
          console.log(err, err); // an error occurred
          reject(Error(err));
      }
      else {
        console.log("test")
        console.log(data);
        resolve({
          headers: {
            "Access-Control-Allow-Origin": "*", // Required for CORS support to work
            "Access-Control-Allow-Credentials": true // Required for cookies, authorization headers with HTTPS
          },
          statusCode: 200,
          body: JSON.stringify(data)
        });

      }
    });
  }
  catch(e){
    console.log(e);
  }
})
 return promise
};
</code>```

Title: Create IoT Policy with AWS Lambda

Body:
I am trying to create an IoT Policy within AWS Lambda. My current Lambda Function looks like that:

"use strict";
const AWS = require("aws-sdk");
AWS.config.update({ region: "eu-central-1" });
var iot = new AWS.Iot();

exports.handler = async (event, context) => {

  var params = {
    policyDocument: `{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "iot:Connect"
      ],
      "Resource": [
        "arn:aws:iot:xxxxx:client/sander"
      ]
    },
    {
      "Effect": "Allow",
      "Action": [
        "iot:Subscribe"
      ],
      "Resource": [
        "arn:aws:iot:xxxx:topicfilter/$aws/things/ManuelBohrmaschine/shadow/*",
        "arn:aws:iot:xxxx:topicfilter/$aws/things/HeikoBohrmaschine/shadow/*"
      ]
    },
    {
      "Effect": "Allow",
      "Action": [
        "iot:Publish",
        "iot:Receive"
      ],
      "Resource": [
        "arn:aws:iot:xxxx:topic/$aws/things/ManuelBohrmaschine/shadow/*",
        "arn:aws:iot:xxxx:topic/$aws/things/HeikoBohrmaschine/shadow/*"
      ]
    }
  ]
}`,
    policyName: 'sander1231564654654654',
  };

  try{

    iot.createPolicy(params, function (err, data) {
      if (err) console.log(err, err); // an error occurred
      else {
        console.log("test")
        console.log(data);
        return {
          headers: {
            "Access-Control-Allow-Origin": "*", // Required for CORS support to work
            "Access-Control-Allow-Credentials": true // Required for cookies, authorization headers with HTTPS
          },
          statusCode: 200,
          body: JSON.stringify(data)
        };

      }
    });
  }
  catch(e){
    console.log(e);
  }
};

The lambda function just returns null and does not even get into the callback function of iot.createPolicy(). I also tried it without try and catch. Same problem. There is no proper error. I am using this documentation: https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/Iot.html#createPolicy-property

Body:
I think the reason is that your function returns before it gets a chance to run your iot section. This is beacuse for async handlers:

If your code performs an asynchronous task, return a promise to make sure that it finishes running. When you resolve or reject the promise, Lambda sends the response or error to the invoker.

To overcome this, you can use const promise = new Promise(...) as shown in the docs.

I modified the code to use the Promise pattern (see below). I can't grantee that it fully works but your function should be able to execute iot.createPolicy section now.

"use strict";
const AWS = require("aws-sdk");
AWS.config.update({ region: "eu-central-1" });
var iot = new AWS.Iot();

exports.handler = async (event, context) => {

  var params = {
    policyDocument: `{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "iot:Connect"
      ],
      "Resource": [
        "arn:aws:iot:xxxxx:client/sander"
      ]
    },
    {
      "Effect": "Allow",
      "Action": [
        "iot:Subscribe"
      ],
      "Resource": [
        "arn:aws:iot:xxxx:topicfilter/$aws/things/ManuelBohrmaschine/shadow/*",
        "arn:aws:iot:xxxx:topicfilter/$aws/things/HeikoBohrmaschine/shadow/*"
      ]
    },
    {
      "Effect": "Allow",
      "Action": [
        "iot:Publish",
        "iot:Receive"
      ],
      "Resource": [
        "arn:aws:iot:xxxx:topic/$aws/things/ManuelBohrmaschine/shadow/*",
        "arn:aws:iot:xxxx:topic/$aws/things/HeikoBohrmaschine/shadow/*"
      ]
    }
  ]
}`,
    policyName: 'sander1231564654654654',
  };

  const promise = new Promise(function(resolve, reject) {

  try{

    console.log(params);

    iot.createPolicy(params, function (err, data) {
      if (err) {
          console.log(err, err); // an error occurred
          reject(Error(err));
      }
      else {
        console.log("test")
        console.log(data);
        resolve({
          headers: {
            "Access-Control-Allow-Origin": "*", // Required for CORS support to work
            "Access-Control-Allow-Credentials": true // Required for cookies, authorization headers with HTTPS
          },
          statusCode: 200,
          body: JSON.stringify(data)
        });

      }
    });
  }
  catch(e){
    console.log(e);
  }
})
 return promise
};


来源: stackexchange

问:
How to post a message once the current instance of the message has finished in MFC?
I don't have enough understanding of messages in Windows applications.

I have this button handler:

```<code>void CChristianLifeMinistryEditorDlg::OnFilePublicTalk()
{
    CWeekendMeetingDlg dlgPublicTalk(this);

    if (m_pEntry != nullptr)
    {
        dlgPublicTalk.SetPublicTalkInfo(m_pEntry->GetPublicTalkInfo());
        dlgPublicTalk.SetCircuitVisitMode(m_iIncludeMode == kIncludeServiceTalk); // AJT v17.0.7
        // AJT v20.0.1
        dlgPublicTalk.SetSongInfo(
            CChristianLifeMinistryUtils::UseSingOutJoyfullyToJehovah(m_datFirstMonday), m_eForeignLang);
        auto iResult = dlgPublicTalk.DoModal();
        if (iResult == IDOK || iResult == to_underlying(CWeekendMeetingDlg::EndResult::PreviousDate) ||
                               iResult == to_underlying(CWeekendMeetingDlg::EndResult::NextDate))
        {
            m_pEntry->SetPublicTalkInfo(dlgPublicTalk.GetPublicTalkInfo());

            SetModified(true);
            UpdatePreview(m_iDateIndex);
            m_pHtmlPreview->Refresh2(REFRESH_COMPLETELY); // Ensure it has refreshed

            // Padlock
            // Reminder
            // Disable controls

            if (iResult == to_underlying(CWeekendMeetingDlg::EndResult::PreviousDate))
            {
                AfxMessageBox(_T("Move to previous week."));
                PostMessage(WM_COMMAND, ID_FILE_PUBLIC_TALK, 0);

                // It can't process this message until the current instance one has finished

            }
            else if (iResult == to_underlying(CWeekendMeetingDlg::EndResult::NextDate))
            {
                AfxMessageBox(_T("Move to next week."));
                PostMessage(WM_COMMAND, ID_FILE_PUBLIC_TALK, 0);

                // It can't process this message until the current instance one has finished
            }
        }
    }
}
</code>```

I have removed code (replaced with the two AfxMessageBox calls) but in principle I want to re-start the same event handler as if the user had clicked it on the File menu. Is it OK to use PostMessage when the current instance of the message has not yet terminated?

I have not yet tried the answer provided, but I have encountered an issue when I introduce two PostMessage calls:

```<code>void CChristianLifeMinistryEditorDlg::OnFilePublicTalk()
{
    CWeekendMeetingDlg dlgPublicTalk(this);

    if (m_pEntry != nullptr)
    {
        dlgPublicTalk.SetPublicTalkInfo(m_pEntry->GetPublicTalkInfo());
        dlgPublicTalk.SetCircuitVisitMode(m_iIncludeMode == kIncludeServiceTalk); // AJT v17.0.7
        // AJT v20.0.1
        dlgPublicTalk.SetSongInfo(
            CChristianLifeMinistryUtils::UseSingOutJoyfullyToJehovah(m_datFirstMonday), m_eForeignLang);

        // AJT v20.1.8
        dlgPublicTalk.SetPreviousNextDateButtonStates(m_btnMovePrevious.IsWindowEnabled(),
                                                      m_btnMoveNext.IsWindowEnabled());
        auto iResult = dlgPublicTalk.DoModal();
        if (iResult == IDOK || iResult == to_underlying(CWeekendMeetingDlg::EndResult::PreviousDate) ||
                               iResult == to_underlying(CWeekendMeetingDlg::EndResult::NextDate))
        {
            m_pEntry->SetPublicTalkInfo(dlgPublicTalk.GetPublicTalkInfo());

            SetModified(true);
            UpdatePreview(m_iDateIndex);
            m_pHtmlPreview->Refresh2(REFRESH_COMPLETELY); // Ensure it has refreshed

            if (iResult == to_underlying(CWeekendMeetingDlg::EndResult::PreviousDate))
            {
                PostMessage(WM_COMMAND, MAKEWPARAM(IDC_MFCBUTTON_PREVIOUS_DATE, BN_CLICKED),
                    (LPARAM)m_btnMovePrevious.GetSafeHwnd());
                PostMessage(WM_COMMAND, ID_FILE_PUBLIC_TALK, 0);
            }
            else if (iResult == to_underlying(CWeekendMeetingDlg::EndResult::NextDate))
            {
                PostMessage(WM_COMMAND, MAKEWPARAM(IDC_MFCBUTTON_NEXT_DATE, BN_CLICKED),
                    (LPARAM)m_btnMoveNext.GetSafeHwnd());
                PostMessage(WM_COMMAND, ID_FILE_PUBLIC_TALK, 0);
            }
        }
    }
}
</code>```

After the actions have been performed and it re-displays the window, and I then click Cancel I get:

If I change it and directly call the button handlers, like this:

```<code>void CChristianLifeMinistryEditorDlg::OnFilePublicTalk()
{
    CWeekendMeetingDlg dlgPublicTalk(this);

    if (m_pEntry != nullptr)
    {
        dlgPublicTalk.SetPublicTalkInfo(m_pEntry->GetPublicTalkInfo());
        dlgPublicTalk.SetCircuitVisitMode(m_iIncludeMode == kIncludeServiceTalk); // AJT v17.0.7
        // AJT v20.0.1
        dlgPublicTalk.SetSongInfo(
            CChristianLifeMinistryUtils::UseSingOutJoyfullyToJehovah(m_datFirstMonday), m_eForeignLang);

        // AJT v20.1.8
        dlgPublicTalk.SetPreviousNextDateButtonStates(m_btnMovePrevious.IsWindowEnabled(),
                                                      m_btnMoveNext.IsWindowEnabled());
        auto iResult = dlgPublicTalk.DoModal();
        if (iResult == IDOK || iResult == to_underlying(CWeekendMeetingDlg::EndResult::PreviousDate) ||
                               iResult == to_underlying(CWeekendMeetingDlg::EndResult::NextDate))
        {
            m_pEntry->SetPublicTalkInfo(dlgPublicTalk.GetPublicTalkInfo());

            SetModified(true);
            UpdatePreview(m_iDateIndex);
            m_pHtmlPreview->Refresh2(REFRESH_COMPLETELY); // Ensure it has refreshed

            if (iResult == to_underlying(CWeekendMeetingDlg::EndResult::PreviousDate))
            {
                //PostMessage(WM_COMMAND, MAKEWPARAM(IDC_MFCBUTTON_PREVIOUS_DATE, BN_CLICKED),
                //  (LPARAM)m_btnMovePrevious.GetSafeHwnd());
                OnBnClickedMfcbuttonPreviousDate();
                PostMessage(WM_COMMAND, ID_FILE_PUBLIC_TALK, 0);
            }
            else if (iResult == to_underlying(CWeekendMeetingDlg::EndResult::NextDate))
            {
                //PostMessage(WM_COMMAND, MAKEWPARAM(IDC_MFCBUTTON_NEXT_DATE, BN_CLICKED),
                //  (LPARAM)m_btnMoveNext.GetSafeHwnd());
                OnBnClickedMfcbuttonNextDate();
                PostMessage(WM_COMMAND, ID_FILE_PUBLIC_TALK, 0);
            }
        }
    }
}
</code>```

This latter approach works. I should point out that these two button handlers update a HTML file and redraw it in the web browser control (which is actually on the parent dialog).

Is it acceptable to directly call those button handlers like this?

Using the answer provided (thank you) this is working well:

```<code>void CChristianLifeMinistryEditorDlg::OnFilePublicTalk()
{
    delay_post_msg dpm{ this };
    CWeekendMeetingDlg dlgPublicTalk(this);

    if (m_pEntry != nullptr)
    {
        dlgPublicTalk.SetPublicTalkInfo(m_pEntry->GetPublicTalkInfo());
        dlgPublicTalk.SetCircuitVisitMode(m_iIncludeMode == kIncludeServiceTalk); // AJT v17.0.7
        // AJT v20.0.1
        dlgPublicTalk.SetSongInfo(
            CChristianLifeMinistryUtils::UseSingOutJoyfullyToJehovah(m_datFirstMonday), m_eForeignLang);

        // AJT v20.1.8
        dlgPublicTalk.SetPreviousNextDateButtonStates(m_btnMovePrevious.IsWindowEnabled(),
                                                      m_btnMoveNext.IsWindowEnabled());
        auto iResult = dlgPublicTalk.DoModal();
        if (iResult == IDOK || iResult == to_underlying(CWeekendMeetingDlg::EndResult::PreviousDate) ||
                               iResult == to_underlying(CWeekendMeetingDlg::EndResult::NextDate))
        {
            m_pEntry->SetPublicTalkInfo(dlgPublicTalk.GetPublicTalkInfo());

            SetModified(true);
            UpdatePreview(m_iDateIndex);
            m_pHtmlPreview->Refresh2(REFRESH_COMPLETELY); // Ensure it has refreshed

            if (iResult == to_underlying(CWeekendMeetingDlg::EndResult::PreviousDate))
            {
                //PostMessage(WM_COMMAND, MAKEWPARAM(IDC_MFCBUTTON_PREVIOUS_DATE, BN_CLICKED),
                //  (LPARAM)m_btnMovePrevious.GetSafeHwnd());
                OnBnClickedMfcbuttonPreviousDate();
                //PostMessage(WM_COMMAND, ID_FILE_PUBLIC_TALK, 0);
                dpm.set_active();
            }
            else if (iResult == to_underlying(CWeekendMeetingDlg::EndResult::NextDate))
            {
                //PostMessage(WM_COMMAND, MAKEWPARAM(IDC_MFCBUTTON_NEXT_DATE, BN_CLICKED),
                //  (LPARAM)m_btnMoveNext.GetSafeHwnd());
                OnBnClickedMfcbuttonNextDate();
                //PostMessage(WM_COMMAND, ID_FILE_PUBLIC_TALK, 0);
                dpm.set_active();
            }
        }
    }
}
</code>```

I had to use the two OnBnClickedMfcbuttonPreviousDate / OnBnClickedMfcbuttonNextDate button handlers directly without using PostMessage to simulate button clicks. I assume that is acceptable?

答:
As written, this is safe. PostMessage generates a queued message that doesn't get observed until the current thread gets around to calling a message-retrieval function (like GetMessage) again. The message loop, however, is blocked, waiting for the current message handler to return control back to it.

Unfortunately, the (main) message loop provided by MFC isn't the only code that potentially dispatches messages. Dialogs (like MessageBoxes) fire up their own message loop, for example. As do menus, or the window resizing implementation. Lots of opportunities to revert back to the reentrancy you were trying to guard against.

A more robust solution could postpone the PostMessage call to just before the function returns. C++ provides all the tools required to implement this: Destructors!

struct delay_post_msg {
    delay_post_msg(CWnd* w) : w_{ w }, active_{ false } {}
    void set_active() { active_ = true; }
    ~delay_post_msg()
    {
        if (active_) w_->PostMessage(WM_COMMAND, ID_FILE_PUBLIC_TALK, 0);
    }
private:
    CWnd* w_;
    bool active_;
};
```

<p>You'd use it something like this:</p>

<pre class="lang-cpp prettyprint-override"><code>void CChristianLifeMinistryEditorDlg::OnFilePublicTalk()
{
    // Objects are destroyed in the opposite order they are created.
    // If this object's d'tor needs to run last, it has to be created first.
    delay_post_msg dpm{ this };

    CWeekendMeetingDlg dlgPublicTalk(this);

    // ...

    if (some_condition)
    {
        dpm.set_active();
    }

    // ...

    // If active, the d'tor of dpm posts the message just before leaving this function.
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I don't have enough understanding of messages in Windows applications.

I have this button handler:

void CChristianLifeMinistryEditorDlg::OnFilePublicTalk()
{
    CWeekendMeetingDlg dlgPublicTalk(this);

    if (m_pEntry != nullptr)
    {
        dlgPublicTalk.SetPublicTalkInfo(m_pEntry->GetPublicTalkInfo());
        dlgPublicTalk.SetCircuitVisitMode(m_iIncludeMode == kIncludeServiceTalk); // AJT v17.0.7
        // AJT v20.0.1
        dlgPublicTalk.SetSongInfo(
            CChristianLifeMinistryUtils::UseSingOutJoyfullyToJehovah(m_datFirstMonday), m_eForeignLang);
        auto iResult = dlgPublicTalk.DoModal();
        if (iResult == IDOK || iResult == to_underlying(CWeekendMeetingDlg::EndResult::PreviousDate) ||
                               iResult == to_underlying(CWeekendMeetingDlg::EndResult::NextDate))
        {
            m_pEntry->SetPublicTalkInfo(dlgPublicTalk.GetPublicTalkInfo());

            SetModified(true);
            UpdatePreview(m_iDateIndex);
            m_pHtmlPreview->Refresh2(REFRESH_COMPLETELY); // Ensure it has refreshed

            // Padlock
            // Reminder
            // Disable controls

            if (iResult == to_underlying(CWeekendMeetingDlg::EndResult::PreviousDate))
            {
                AfxMessageBox(_T("Move to previous week."));
                PostMessage(WM_COMMAND, ID_FILE_PUBLIC_TALK, 0);

                // It can't process this message until the current instance one has finished

            }
            else if (iResult == to_underlying(CWeekendMeetingDlg::EndResult::NextDate))
            {
                AfxMessageBox(_T("Move to next week."));
                PostMessage(WM_COMMAND, ID_FILE_PUBLIC_TALK, 0);

                // It can't process this message until the current instance one has finished
            }
        }
    }
}

I have removed code (replaced with the two AfxMessageBox calls) but in principle I want to re-start the same event handler as if the user had clicked it on the File menu. Is it OK to use PostMessage when the current instance of the message has not yet terminated?

I have not yet tried the answer provided, but I have encountered an issue when I introduce two PostMessage calls:

void CChristianLifeMinistryEditorDlg::OnFilePublicTalk()
{
    CWeekendMeetingDlg dlgPublicTalk(this);

    if (m_pEntry != nullptr)
    {
        dlgPublicTalk.SetPublicTalkInfo(m_pEntry->GetPublicTalkInfo());
        dlgPublicTalk.SetCircuitVisitMode(m_iIncludeMode == kIncludeServiceTalk); // AJT v17.0.7
        // AJT v20.0.1
        dlgPublicTalk.SetSongInfo(
            CChristianLifeMinistryUtils::UseSingOutJoyfullyToJehovah(m_datFirstMonday), m_eForeignLang);

        // AJT v20.1.8
        dlgPublicTalk.SetPreviousNextDateButtonStates(m_btnMovePrevious.IsWindowEnabled(),
                                                      m_btnMoveNext.IsWindowEnabled());
        auto iResult = dlgPublicTalk.DoModal();
        if (iResult == IDOK || iResult == to_underlying(CWeekendMeetingDlg::EndResult::PreviousDate) ||
                               iResult == to_underlying(CWeekendMeetingDlg::EndResult::NextDate))
        {
            m_pEntry->SetPublicTalkInfo(dlgPublicTalk.GetPublicTalkInfo());

            SetModified(true);
            UpdatePreview(m_iDateIndex);
            m_pHtmlPreview->Refresh2(REFRESH_COMPLETELY); // Ensure it has refreshed

            if (iResult == to_underlying(CWeekendMeetingDlg::EndResult::PreviousDate))
            {
                PostMessage(WM_COMMAND, MAKEWPARAM(IDC_MFCBUTTON_PREVIOUS_DATE, BN_CLICKED),
                    (LPARAM)m_btnMovePrevious.GetSafeHwnd());
                PostMessage(WM_COMMAND, ID_FILE_PUBLIC_TALK, 0);
            }
            else if (iResult == to_underlying(CWeekendMeetingDlg::EndResult::NextDate))
            {
                PostMessage(WM_COMMAND, MAKEWPARAM(IDC_MFCBUTTON_NEXT_DATE, BN_CLICKED),
                    (LPARAM)m_btnMoveNext.GetSafeHwnd());
                PostMessage(WM_COMMAND, ID_FILE_PUBLIC_TALK, 0);
            }
        }
    }
}

After the actions have been performed and it re-displays the window, and I then click Cancel I get:

If I change it and directly call the button handlers, like this:

void CChristianLifeMinistryEditorDlg::OnFilePublicTalk()
{
    CWeekendMeetingDlg dlgPublicTalk(this);

    if (m_pEntry != nullptr)
    {
        dlgPublicTalk.SetPublicTalkInfo(m_pEntry->GetPublicTalkInfo());
        dlgPublicTalk.SetCircuitVisitMode(m_iIncludeMode == kIncludeServiceTalk); // AJT v17.0.7
        // AJT v20.0.1
        dlgPublicTalk.SetSongInfo(
            CChristianLifeMinistryUtils::UseSingOutJoyfullyToJehovah(m_datFirstMonday), m_eForeignLang);

        // AJT v20.1.8
        dlgPublicTalk.SetPreviousNextDateButtonStates(m_btnMovePrevious.IsWindowEnabled(),
                                                      m_btnMoveNext.IsWindowEnabled());
        auto iResult = dlgPublicTalk.DoModal();
        if (iResult == IDOK || iResult == to_underlying(CWeekendMeetingDlg::EndResult::PreviousDate) ||
                               iResult == to_underlying(CWeekendMeetingDlg::EndResult::NextDate))
        {
            m_pEntry->SetPublicTalkInfo(dlgPublicTalk.GetPublicTalkInfo());

            SetModified(true);
            UpdatePreview(m_iDateIndex);
            m_pHtmlPreview->Refresh2(REFRESH_COMPLETELY); // Ensure it has refreshed

            if (iResult == to_underlying(CWeekendMeetingDlg::EndResult::PreviousDate))
            {
                //PostMessage(WM_COMMAND, MAKEWPARAM(IDC_MFCBUTTON_PREVIOUS_DATE, BN_CLICKED),
                //  (LPARAM)m_btnMovePrevious.GetSafeHwnd());
                OnBnClickedMfcbuttonPreviousDate();
                PostMessage(WM_COMMAND, ID_FILE_PUBLIC_TALK, 0);
            }
            else if (iResult == to_underlying(CWeekendMeetingDlg::EndResult::NextDate))
            {
                //PostMessage(WM_COMMAND, MAKEWPARAM(IDC_MFCBUTTON_NEXT_DATE, BN_CLICKED),
                //  (LPARAM)m_btnMoveNext.GetSafeHwnd());
                OnBnClickedMfcbuttonNextDate();
                PostMessage(WM_COMMAND, ID_FILE_PUBLIC_TALK, 0);
            }
        }
    }
}

This latter approach works. I should point out that these two button handlers update a HTML file and redraw it in the web browser control (which is actually on the parent dialog).

Is it acceptable to directly call those button handlers like this?

Using the answer provided (thank you) this is working well:

void CChristianLifeMinistryEditorDlg::OnFilePublicTalk()
{
    delay_post_msg dpm{ this };
    CWeekendMeetingDlg dlgPublicTalk(this);

    if (m_pEntry != nullptr)
    {
        dlgPublicTalk.SetPublicTalkInfo(m_pEntry->GetPublicTalkInfo());
        dlgPublicTalk.SetCircuitVisitMode(m_iIncludeMode == kIncludeServiceTalk); // AJT v17.0.7
        // AJT v20.0.1
        dlgPublicTalk.SetSongInfo(
            CChristianLifeMinistryUtils::UseSingOutJoyfullyToJehovah(m_datFirstMonday), m_eForeignLang);

        // AJT v20.1.8
        dlgPublicTalk.SetPreviousNextDateButtonStates(m_btnMovePrevious.IsWindowEnabled(),
                                                      m_btnMoveNext.IsWindowEnabled());
        auto iResult = dlgPublicTalk.DoModal();
        if (iResult == IDOK || iResult == to_underlying(CWeekendMeetingDlg::EndResult::PreviousDate) ||
                               iResult == to_underlying(CWeekendMeetingDlg::EndResult::NextDate))
        {
            m_pEntry->SetPublicTalkInfo(dlgPublicTalk.GetPublicTalkInfo());

            SetModified(true);
            UpdatePreview(m_iDateIndex);
            m_pHtmlPreview->Refresh2(REFRESH_COMPLETELY); // Ensure it has refreshed

            if (iResult == to_underlying(CWeekendMeetingDlg::EndResult::PreviousDate))
            {
                //PostMessage(WM_COMMAND, MAKEWPARAM(IDC_MFCBUTTON_PREVIOUS_DATE, BN_CLICKED),
                //  (LPARAM)m_btnMovePrevious.GetSafeHwnd());
                OnBnClickedMfcbuttonPreviousDate();
                //PostMessage(WM_COMMAND, ID_FILE_PUBLIC_TALK, 0);
                dpm.set_active();
            }
            else if (iResult == to_underlying(CWeekendMeetingDlg::EndResult::NextDate))
            {
                //PostMessage(WM_COMMAND, MAKEWPARAM(IDC_MFCBUTTON_NEXT_DATE, BN_CLICKED),
                //  (LPARAM)m_btnMoveNext.GetSafeHwnd());
                OnBnClickedMfcbuttonNextDate();
                //PostMessage(WM_COMMAND, ID_FILE_PUBLIC_TALK, 0);
                dpm.set_active();
            }
        }
    }
}

I had to use the two OnBnClickedMfcbuttonPreviousDate / OnBnClickedMfcbuttonNextDate button handlers directly without using PostMessage to simulate button clicks. I assume that is acceptable?

Body:
As written, this is safe. PostMessage generates a queued message that doesn't get observed until the current thread gets around to calling a message-retrieval function (like GetMessage) again. The message loop, however, is blocked, waiting for the current message handler to return control back to it.

Unfortunately, the (main) message loop provided by MFC isn't the only code that potentially dispatches messages. Dialogs (like MessageBoxes) fire up their own message loop, for example. As do menus, or the window resizing implementation. Lots of opportunities to revert back to the reentrancy you were trying to guard against.

A more robust solution could postpone the PostMessage call to just before the function returns. C++ provides all the tools required to implement this: Destructors!

struct delay_post_msg {
    delay_post_msg(CWnd* w) : w_{ w }, active_{ false } {}
    void set_active() { active_ = true; }
    ~delay_post_msg()
    {
        if (active_) w_->PostMessage(WM_COMMAND, ID_FILE_PUBLIC_TALK, 0);
    }
private:
    CWnd* w_;
    bool active_;
};

You'd use it something like this:

void CChristianLifeMinistryEditorDlg::OnFilePublicTalk()
{
    // Objects are destroyed in the opposite order they are created.
    // If this object's d'tor needs to run last, it has to be created first.
    delay_post_msg dpm{ this };

    CWeekendMeetingDlg dlgPublicTalk(this);

    // ...

    if (some_condition)
    {
        dpm.set_active();
    }

    // ...

    // If active, the d'tor of dpm posts the message just before leaving this function.
}


问:
Notepad ++ Search and replace the text 2 specific lines only
I have to replace 2 lines in every project.wsCFG file if line 17 contains a specific Pattern.
Files with this name existing in a lot of subdirectories of a project folder.

Example:
if line 17 contains the pattern "ArticleConnectionStringSQL" val="Provider=SQLOLEDB.1"

replace: line 14 with:

and replace line 17 with:

I can search within notepadd++ for these files, that's no problem. And I think the best way to replace these two lines is with regular expression.

Can anybody help me with the regular expression code for this?

Thanks.

Andreas

答:
You could capture the first 13 lines in group 1 using a repeating non capturing group and a quantifier.

Then match line 14 and capture in the second capturing group matching line 15 and 16 using the same mechanism as for the first group.

Then match your pattern in line 17.

```<code>\A((?:.*\R){13}).*((?:\R.*){2})\R.*ArticleConnectionStringSQL" val="Provider=SQLOLEDB\.1.*
</code>```

In parts

\A Start of string

( Capture group 1

(?:.*\R){13} Match first 13 lines where \R matches a unicode newline sequence

) Close group

.* Match line 14

( Capture group 2

(?:\R.*){2} Match line 15 and 16

) Close group

\R.*ArticleConnectionStringSQL" val="Provider=SQLOLEDB\.1.* Match line 17 with your string

Regex demo

In the replacement, use the 2 capturing groups with your replacement values.

```<code>$1<P id="ArticleConnectionType" val="SQL" />$2\n<P id="ArticleConnectionStringSQL" val="Data Source=sv-it-db-6;Initial Catalog=20200526_WSCAD_IPP;Integrated Security=True" />
</code>```

Body:
You could capture the first 13 lines in group 1 using a repeating non capturing group and a quantifier.

Then match line 14 and capture in the second capturing group matching line 15 and 16 using the same mechanism as for the first group.

Then match your pattern in line 17.

\A((?:.*\R){13}).*((?:\R.*){2})\R.*ArticleConnectionStringSQL" val="Provider=SQLOLEDB\.1.*

In parts

\A Start of string

( Capture group 1

(?:.*\R){13} Match first 13 lines where \R matches a unicode newline sequence

) Close group

.* Match line 14

( Capture group 2

(?:\R.*){2} Match line 15 and 16

) Close group

\R.*ArticleConnectionStringSQL" val="Provider=SQLOLEDB\.1.* Match line 17 with your string

Regex demo

In the replacement, use the 2 capturing groups with your replacement values.

$1<P id="ArticleConnectionType" val="SQL" />$2\n<P id="ArticleConnectionStringSQL" val="Data Source=sv-it-db-6;Initial Catalog=20200526_WSCAD_IPP;Integrated Security=True" />


问:
Flutter app crashes on launch on Android
I've been testing my first Flutter app on iOS and its going well.  Now I run it for the first time in an Android simulator and I get this error.

```
07-18 11:42:10.757 4264-4264/? E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.akamojo.liga, PID: 4264
    java.lang.RuntimeException: Unable to instantiate application com.akamojo.liga.liga: java.lang.ClassNotFoundException: Didn't find class "com.akamojo.liga.liga" on path: DexPathList[[zip file "/data/app/com.akamojo.liga-1/base.apk"],nativeLibraryDirectories=[/data/app/com.akamojo.liga-1/lib/x86, /data/app/com.akamojo.liga-1/base.apk!/lib/x86, /vendor/lib, /system/lib]]
        at android.app.LoadedApk.makeApplication(LoadedApk.java:578)
        at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4680)
        at android.app.ActivityThread.-wrap1(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1405)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:148)
        at android.app.ActivityThread.main(ActivityThread.java:5417)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
```

It looks suspicious to me that is says it is looking for the class "com.akamojo.liga.liga".  Is it correct?  My applicationId is "com.akamojo.liga".  Is the Flutter framework creating a starting class called "liga"?

Here is build.gradle.

```<code>def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
    localPropertiesFile.withReader('UTF-8') { reader ->
        localProperties.load(reader)
    }
}

def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
    throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"

def keystorePropertiesFile = rootProject.file("key.properties")
def keystoreProperties = new Properties()
keystoreProperties.load(new FileInputStream(keystorePropertiesFile))

android {
    compileSdkVersion 27

    sourceSets {
        main.java.srcDirs += 'src/main/kotlin'
    }

    lintOptions {
        disable 'InvalidPackage'
    }

    defaultConfig {
        applicationId "com.akamojo.liga"
        minSdkVersion 16
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }

    signingConfigs {
        release {
            keyAlias keystoreProperties['keyAlias']
            keyPassword keystoreProperties['keyPassword']
            storeFile file(keystoreProperties['storeFile'])
            storePassword keystoreProperties['storePassword']
        }
    }
    buildTypes {
        release {
            signingConfig signingConfigs.release
        }
    }
}

flutter {
    source '../..'
}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
}
</code>```

Here is the AndroidManifest.xml file.

```<code><manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.akamojo.liga">

    <!-- The INTERNET permission is required for development. Specifically,
         flutter needs it to communicate with the running application
         to allow setting breakpoints, to provide hot reload, etc.
    -->
    <uses-permission android:name="android.permission.INTERNET"/>

    <!-- io.flutter.app.FlutterApplication is an android.app.Application that
         calls FlutterMain.startInitialization(this); in its onCreate method.
         In most cases you can leave this as-is, but you if you want to provide
         additional functionality it is fine to subclass or reimplement
         FlutterApplication and put your custom class here. -->
    <application
        android:name="liga"
        android:label="liga"
        android:icon="@mipmap/ic_launcher">
        <activity
            android:name=".MainActivity"
            android:launchMode="singleTop"
            android:theme="@style/LaunchTheme"
            android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|density"
            android:hardwareAccelerated="true"
            android:windowSoftInputMode="adjustResize">
            <!-- This keeps the window background of the activity showing
                 until Flutter renders its first frame. It can be removed if
                 there is no splash screen (such as the default splash screen
                 defined in @style/LaunchTheme). -->
            <meta-data
                android:name="io.flutter.app.android.SplashScreenUntilFirstFrame"
                android:value="true" />
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
    </application>
</manifest>
</code>```

答:
My app was working but after Dart plugin update I started to get this error.

```<code>java.lang.RuntimeException: Unable to instantiate activity ComponentInfo com.package.name.MainActivity
</code>```

In my case it was because of incompatibility of Dart and Flutter plugin.
I ran flutter upgrade command and app starting working normal again.

So make sure to keep both Dart and Flutter plugins updated.

Body:
I've been testing my first Flutter app on iOS and its going well.  Now I run it for the first time in an Android simulator and I get this error.

07-18 11:42:10.757 4264-4264/? E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.akamojo.liga, PID: 4264
    java.lang.RuntimeException: Unable to instantiate application com.akamojo.liga.liga: java.lang.ClassNotFoundException: Didn't find class "com.akamojo.liga.liga" on path: DexPathList[[zip file "/data/app/com.akamojo.liga-1/base.apk"],nativeLibraryDirectories=[/data/app/com.akamojo.liga-1/lib/x86, /data/app/com.akamojo.liga-1/base.apk!/lib/x86, /vendor/lib, /system/lib]]
        at android.app.LoadedApk.makeApplication(LoadedApk.java:578)
        at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4680)
        at android.app.ActivityThread.-wrap1(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1405)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:148)
        at android.app.ActivityThread.main(ActivityThread.java:5417)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

It looks suspicious to me that is says it is looking for the class "com.akamojo.liga.liga".  Is it correct?  My applicationId is "com.akamojo.liga".  Is the Flutter framework creating a starting class called "liga"?

Here is build.gradle.

def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
    localPropertiesFile.withReader('UTF-8') { reader ->
        localProperties.load(reader)
    }
}

def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
    throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"

def keystorePropertiesFile = rootProject.file("key.properties")
def keystoreProperties = new Properties()
keystoreProperties.load(new FileInputStream(keystorePropertiesFile))

android {
    compileSdkVersion 27

    sourceSets {
        main.java.srcDirs += 'src/main/kotlin'
    }

    lintOptions {
        disable 'InvalidPackage'
    }

    defaultConfig {
        applicationId "com.akamojo.liga"
        minSdkVersion 16
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }

    signingConfigs {
        release {
            keyAlias keystoreProperties['keyAlias']
            keyPassword keystoreProperties['keyPassword']
            storeFile file(keystoreProperties['storeFile'])
            storePassword keystoreProperties['storePassword']
        }
    }
    buildTypes {
        release {
            signingConfig signingConfigs.release
        }
    }
}

flutter {
    source '../..'
}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
}

Here is the AndroidManifest.xml file.

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.akamojo.liga">

    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:name="liga"
        android:label="liga"
        android:icon="@mipmap/ic_launcher">
        <activity
            android:name=".MainActivity"
            android:launchMode="singleTop"
            android:theme="@style/LaunchTheme"
            android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|density"
            android:hardwareAccelerated="true"
            android:windowSoftInputMode="adjustResize">

            <meta-data
                android:name="io.flutter.app.android.SplashScreenUntilFirstFrame"
                android:value="true" />
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
    </application>
</manifest>

Body:
My app was working but after Dart plugin update I started to get this error.

java.lang.RuntimeException: Unable to instantiate activity ComponentInfo com.package.name.MainActivity

In my case it was because of incompatibility of Dart and Flutter plugin.
I ran flutter upgrade command and app starting working normal again.

So make sure to keep both Dart and Flutter plugins updated.


问:
Alternative to Beanstalk
Since Beanstalk began to support GIT their SVN deployments have slowed down drastically.
Google is throwing up no results and having never setup anything similar to Beanstalk does anybody have any advice.

At the moment Beanstalk handles the following:
 - SVN Hosting
 - Deployments (configurable for per commit or manual with varying servers)

答:
Well, I would personally recommend switching to Mercurial (using BitBucket) or Git (using Beanstalk or GitHub). I think you'd find distributed version control is the way things will be in the future.

If you are stuck with SVN, you can always simply set up your own system on a shared or dedicated host (there are plenty of open source options for deployment from SVN). If you're looking for someone else to blame for backups and such, potential alternatives are CodeBase or codesion.

ContentLicense: CC BY-SA 3.0

Title: Alternative to Beanstalk


问:
How to render Latex in Flutter, offline
There is a package called flutter_tex. But, it required internet access. I want to render Latex without using internet. How to render Latex in flutter, without using internet.</p>

答:
You could use katex_flutter.

katex_flutter is an alternative to flutter_tex which offers actually exactly the same functionality as flutter_tex does. There are some minor differences under the hood: For example katex_flutter does not require an internet connection and uses KaTeX instead of MathJax for rendering equations.

Please read the full instructions in pub.dev about how to set up katex_flutter for your project.

A simple example how to use it:

import 'package:katex_flutter/katex_flutter.dart';

...

return KaTeX(laTeXCode: Text("\\alpha", style: Theme.of(context)
                      .textTheme
                      .bodyText1
                      .copyWith(color: Colors.red)))
```

Title: How to render Latex in Flutter, offline


问:
Keyboard hides TextField in a PageView
I have a quite complex screen with a page view and a FutureBuilder. In the Pagebuilder I also have a TextFormField, when I now click into the text field the keyboard opens like expected. But it then hides the textfield and a button below the text field.
I already searched for solutions, things i tried:

setting resizeToAvoidBottomInset to true

putting the outer column or the pageview into a SingleChildScrollView

adding some padding (in the size of the keyboard) to the bottom

Any other ideas?

I only have ONE Scaffold.

答:
Make your page scrollable and add padding to the button like so:

```<code>SingleChildScrollView(
   child: Column(
      children:
         textInput,
         Padding(padding: ..., child: button)
             ...
</code>```

This would allow user to scroll to the button after edit.

Another solution is to make button float - it would always be above keyboard

```<code>    return Stack(
      children: <Widget>[
        Positioned(
          child: SingleChildScrollView(
              child: Column(
                  children: [textInput]
                    ..add(Container(
                      height: 1111, // button heigh, so could scroll underlapping area
                    )))),
        ),
        Positioned(
          child: Align(
            alignment: Alignment.bottomCenter,
            child: button,
          ),
        )
      ],
    );
</code>```

Title: Keyboard hides TextField in a PageView

Body:
Make your page scrollable and add padding to the button like so:

SingleChildScrollView(
   child: Column(
      children:
         textInput,
         Padding(padding: ..., child: button)
             ...

This would allow user to scroll to the button after edit.

Another solution is to make button float - it would always be above keyboard

    return Stack(
      children: <Widget>[
        Positioned(
          child: SingleChildScrollView(
              child: Column(
                  children: [textInput]
                    ..add(Container(
                      height: 1111, // button heigh, so could scroll underlapping area
                    )))),
        ),
        Positioned(
          child: Align(
            alignment: Alignment.bottomCenter,
            child: button,
          ),
        )
      ],
    );


问:
Is it possible to keep an object hovering in front of the camera using vuforia in android?
I'm developing an app that needs a certain 3d object hovering in front of the user when he looks through the camera. Using vuforia I need to use an Image marker to place an object. Is it possible to do the placing without an image marker?

I also don't want to use Unity 3D as I'm developing a native Android app that has other functionalities too.

答: Instead of the image target, use mid-air target in Vuforia. See Placing Floating Content in your Environment in this article for the detailed explanation.


问:
Why does my Gatsby.js build generate duplicate data for each post?
My gatsby.js site is based off the repo used by egghead.io: gatsby-starter-egghead-blog

When I run a gatsby build command I get the following file structure generated (I've omitted the 404 and index folders)

For each blog post in my "content" folder I get 2 folders generated each with the same name as the blog post.  The one under "public" contains an html file and the one under "page-data" contains a json file containing the exact same content as that rendered in the html file minus any CSS styling.

Why do these json files exist when I already have static html files?  Essentially I'm getting duplicate data.

答:
I think I just found the answer to this.

Gatsby.js follows the PRPL Pattern.

The first page you visit for any Gatsby site loads a static HTML page.  Any subsequent page visits behave more like an SPA.  You can see this if you watch the network tab in Chrome while browsing a Gatsby site.  First the HTML page is loaded and after that, as you navigate the site, the pages are loaded from the page-data.json files.

The implementation of this pattern by Gatsby is described in more detail here.

This explains why the data for each page exists twice in a Gatsby site - as rendered static HTML for first load and as raw JSON data to be loaded dynamically.


问:
Hibernate criteria: why no Subqueries.isNull(DetachedCriteria)?
I want to translate a script like this into criteria:

```<code>SELECT ...
FROM A
WHERE
  A.some_date > (select bdate from B where ...)
  OR (select bdate from B where ...) IS NULL
</code>```

So, an A should be returned if either A.Some_date > B.bdate or if B.bdate is NULL.

I was expecting there to be a Subqueries.notNull(DetachedCriteria) (like there is a SubQueries.notExists(DetachedCriteria)) but this method does not exist nor did I find something else to pull this off.

I could of course work around this by returning a count and check if this is > 0 or such but then I need to write 2 identical (except for the Projection) DetachedCriteria's.

Does anyone know if/how to have the is NULL check for the above case or why this isn't provided in the Hibernate criteria API? Perhaps there's a good reason...

答:
I think

```<code>Subqueries.eq(null, yourDetachedCriteria)
</code>```

should work.

Body:
I want to translate a script like this into criteria:

SELECT ...
FROM A
WHERE
  A.some_date > (select bdate from B where ...)
  OR (select bdate from B where ...) IS NULL

So, an A should be returned if either A.Some_date > B.bdate or if B.bdate is NULL.

I was expecting there to be a Subqueries.notNull(DetachedCriteria) (like there is a SubQueries.notExists(DetachedCriteria)) but this method does not exist nor did I find something else to pull this off.

I could of course work around this by returning a count and check if this is > 0 or such but then I need to write 2 identical (except for the Projection) DetachedCriteria's.

Does anyone know if/how to have the is NULL check for the above case or why this isn't provided in the Hibernate criteria API? Perhaps there's a good reason...

Body:
I think

Subqueries.eq(null, yourDetachedCriteria)

should work.


问:
Algorithm for finding the busiest period?
I have some data like this:

```<code>1: 2 - 10
2: 3 - 15
3: 4 - 9
4: 8 - 14
5: 7 - 13
6: 5 - 10
7: 11 - 15
</code>```

I will attempt a representation to make it clearer:

```<code>        1     2     3     4     5     6     7     8     9     10     11     12     13     14     15
1             |--------------------------------------X---------|
2                   |--------------------------------X--------------------------------------------|
3                         |--------------------------X---|
4                                                  |-X-------------------------------------|
5                                           |--------X------------------------------|
6                               |--------------------X----------|
7                                                                     |---------------------------|
</code>```

So in the example case, 8-9 is the critical period if the second scheme is used because all the points are active. What is a fast and good way to solving this problem in python? I am thinking of using dynamic programming but are there other approaches that are suggested?

My approach until now:

I was thinking more from a real-time perspective. So, whenever I get a new point, I do this: Assume I already got 2-10 and I get 3-15 then I pick the max of start and min of end so this case it is 3-10 and increment this interval's count to 2. Then the third point comes in 4-9, pick the max which is 4 and the min is 9 and update the value 3-10 to 4-9 and update count to 3. Now when 8-14 comes in, I pick the start of this interval is greater than 4-9 and the end of this interval is less than 4-9. In this case, it is not true so I will create a new bucket 8-14 and I put the count to 1. This is not the entire algorithm but should give a high-level idea of what I am doing here. I will see if I can sketch the pseudo-code.

答:
I've put together a small C++ program if you want to have a linear performance here.
I know it is not Python, but the idea is very simple here.

We first create an array with all points and increment the item in the array if the interval starts at that index and decrement it if it ends on that index.

Once the array is constructed, we just iterate over and calculate where we had the maximum number of open intervals.

Time complexity is O(M + N)

Space complexity is O(N)

Where M is the number of intervals and N is the max value from the interval pairs.

#include <iostream>
#include <vector>

int maxLoad(const std::vector<std::pair<int, int>>& intervals) {
    std::vector<int> points;
    for(const auto& interval : intervals) {
        if(interval.second >= points.size()) points.resize(interval.second + 1);
        ++points[interval.first];
        --points[interval.second];
    }

    int ans = 0;
    int sum = 0;
    for(const auto point : points) {
        sum += point;
        ans = std::max(ans, sum);
    }
    return ans;
}

int main() {
    std::vector<std::pair<int, int>> intervals {
        {2, 10}, {3, 15}, {4, 9}, {8, 14}, {7, 13}, {5, 10}, {11, 15}
    };
    std::cout << maxLoad(intervals) << std::endl;
}

```

Body:
I have some data like this:

1: 2 - 10
2: 3 - 15
3: 4 - 9
4: 8 - 14
5: 7 - 13
6: 5 - 10
7: 11 - 15

I will attempt a representation to make it clearer:

        1     2     3     4     5     6     7     8     9     10     11     12     13     14     15
1             |--------------------------------------X---------|
2                   |--------------------------------X--------------------------------------------|
3                         |--------------------------X---|
4                                                  |-X-------------------------------------|
5                                           |--------X------------------------------|
6                               |--------------------X----------|
7                                                                     |---------------------------|

So in the example case, 8-9 is the critical period if the second scheme is used because all the points are active. What is a fast and good way to solving this problem in python? I am thinking of using dynamic programming but are there other approaches that are suggested?

My approach until now:

I was thinking more from a real-time perspective. So, whenever I get a new point, I do this: Assume I already got 2-10 and I get 3-15 then I pick the max of start and min of end so this case it is 3-10 and increment this interval's count to 2. Then the third point comes in 4-9, pick the max which is 4 and the min is 9 and update the value 3-10 to 4-9 and update count to 3. Now when 8-14 comes in, I pick the start of this interval is greater than 4-9 and the end of this interval is less than 4-9. In this case, it is not true so I will create a new bucket 8-14 and I put the count to 1. This is not the entire algorithm but should give a high-level idea of what I am doing here. I will see if I can sketch the pseudo-code.


问:
Can SQL with CASE condition use index in PostgreSQL?
When I write a SQL like
SELECT * FROM table WHERE table.col && object, I could use the index I built (as it support && operator), but with

```<code>SELECT * FROM table WHERE
    CASE
    WHEN table.col && object = true THEN true
    ELSE false
    END
</code>```

It seems I can't use the index?

What is the reason of this? Is there any way to solve it?
Actually I want to implement a logic like CASE WHEN a&&b = true THEN ab END with the support of index, is that possible?

答:
I am guessing that there is not situation where a case expression would use an index in Postgres.  This is because the case expression enforces an order of evaluation -- which is quite hard to ensure once indexes are involved.

There might be some exceptions where the compiler recognizes that the case expression is redundant and it gets removed before the optimization phase.

That said, your case expression is useless.  Just use:

```<code>SELECT *
FROM table
WHERE table.col AND object ;
</code>```

Notes:

The SQL Standard for boolean and is AND.  Use it.

= true is redundant.  You can include it, but it is not necessary.

You have two boolean columns.  In many cases, an index will not be used even if available because the columns are (probably) not very selective.

Body:
When I write a SQL like
SELECT * FROM table WHERE table.col && object, I could use the index I built (as it support && operator), but with

SELECT * FROM table WHERE
    CASE
    WHEN table.col && object = true THEN true
    ELSE false
    END

It seems I can't use the index?

What is the reason of this? Is there any way to solve it?
Actually I want to implement a logic like CASE WHEN a&&b = true THEN ab END with the support of index, is that possible?

Body:
I am guessing that there is not situation where a case expression would use an index in Postgres.  This is because the case expression enforces an order of evaluation -- which is quite hard to ensure once indexes are involved.

There might be some exceptions where the compiler recognizes that the case expression is redundant and it gets removed before the optimization phase.

That said, your case expression is useless.  Just use:

SELECT *
FROM table
WHERE table.col AND object ;

Notes:

The SQL Standard for boolean and is AND.  Use it.

= true is redundant.  You can include it, but it is not necessary.

You have two boolean columns.  In many cases, an index will not be used even if available because the columns are (probably) not very selective.


问:
C program Temperature conversion
Can anyone please explain what am i doing wrong here? It seems whatever is under if is not being executed. but i don't understand why.

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

main()
{   float Fah, Cel, Temp;
    char  scale,F,C;
    printf("Press F to convert to fahrenheit\n");
    printf("Press C to convert in celcius\n");
    scanf("%c",&scale);

    if(scale==C)
    {
      printf("Enter the temp\n");

      scanf("%f",&Fah);
      Temp=(Fah-32)/1.8;
    }
    else
    {
     if(scale==F)
     {
       printf("Enter the temp\n");

       scanf("%f",&Cel);
       Temp=(Cel*1.8)+32;
     }
    }
    printf("The temperature  is %f\n",Temp);
    getch();
}

</code>```

Output:

```<code>Press F to convert to fahrenheit
Press C to convert in celcius
C
The temperature  is 0.000000
Press any key to continue . . .
</code>```

答:
Your code has several issues:

1.

Your approach is incorrect.

You need to use if (scale == 'C') instead of if (scale == C) and if (scale == 'f') instead of if (scale == F) and omit the definition of C and F as char variables.

'C' is a character constant.

C is, in your case, a uninitialized char variable. It does not contain any specified value. Thus, the behavior of the program is undefined.

Same goes for F.

2.

You should have an else statement after if (scale == 'C') and else if (scale == 'F') which covers the case when the input provided is different than 'C' or 'F' (you will never know what the user may input).

3.

Furthermore, since scanf() leaves a trailing newline character back in stdin - Made by the press to Enter - you need to catch this newline character by f.e. getchar() following each scanf() statement to not skip the following input operation.

4.

main() is not correct. Use at least int main(), or even better int main (void) to be standard-compliant.

5.

getch() isn´t part of stdio.h and even the C standard library in general. It is either a function from conio.h (Windows/MS-DOS) or the ncurses-library (Linux). Thus, you need to include the specific header.

Probably it was a typo and you meant getchar() instead, but worth to hint.

Side note:

You should always check the return value of scanf() if the input was successfullly consumed.

Result:

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

int main (void)
{
    float Fah, Cel, Temp;
    char scale;
    printf("Press F to convert to fahrenheit\n");
    printf("Press C to convert in celcius\n");
    scanf("%c", &scale);
    getchar();

    if (scale == 'C')
    {
        printf("Enter the temp\n");

        if (scanf("%f", &Fah) != 1)
        {
             fputs("Wrong Input!", stderr);
             return 1;
        }
        getchar();                  // For catching newline character.

        Temp = (Fah-32) / 1.8;
    }

    else if (scale == 'F')
    {
        printf("Enter the temp\n");

        if (scanf("%f", &Cel) != 1)
        {
            fputs("Wrong Input!", stderr);
             return 1;
        }
        getchar();                   // For catching newline character.

        Temp = (Cel * 1.8) + 32;
    }

        else
        {
               // Case for different input than 'F' and 'C'.
               // Probably Error routine.
               printf("Wrong input!\n");
        }

    printf("The temperature  is %f\n", Temp);
    getchar();

    return 0;
}
</code>```

Title: C program Temperature conversion

Body:
Can anyone please explain what am i doing wrong here? It seems whatever is under if is not being executed. but i don't understand why.

#include<stdio.h>

main()
{   float Fah, Cel, Temp;
    char  scale,F,C;
    printf("Press F to convert to fahrenheit\n");
    printf("Press C to convert in celcius\n");
    scanf("%c",&scale);

    if(scale==C)
    {
      printf("Enter the temp\n");

      scanf("%f",&Fah);
      Temp=(Fah-32)/1.8;
    }
    else
    {
     if(scale==F)
     {
       printf("Enter the temp\n");

       scanf("%f",&Cel);
       Temp=(Cel*1.8)+32;
     }
    }
    printf("The temperature  is %f\n",Temp);
    getch();
}

Output:

Press F to convert to fahrenheit
Press C to convert in celcius
C
The temperature  is 0.000000
Press any key to continue . . .

Body:
Your code has several issues:

1.

Your approach is incorrect.

You need to use if (scale == 'C') instead of if (scale == C) and if (scale == 'f') instead of if (scale == F) and omit the definition of C and F as char variables.

'C' is a character constant.

C is, in your case, a uninitialized char variable. It does not contain any specified value. Thus, the behavior of the program is undefined.

Same goes for F.

2.

You should have an else statement after if (scale == 'C') and else if (scale == 'F') which covers the case when the input provided is different than 'C' or 'F' (you will never know what the user may input).

3.

Furthermore, since scanf() leaves a trailing newline character back in stdin - Made by the press to Enter - you need to catch this newline character by f.e. getchar() following each scanf() statement to not skip the following input operation.

4.

main() is not correct. Use at least int main(), or even better int main (void) to be standard-compliant.

5.

getch() isn´t part of stdio.h and even the C standard library in general. It is either a function from conio.h (Windows/MS-DOS) or the ncurses-library (Linux). Thus, you need to include the specific header.

Probably it was a typo and you meant getchar() instead, but worth to hint.

Side note:

You should always check the return value of scanf() if the input was successfullly consumed.

Result:

#include <stdio.h>

int main (void)
{
    float Fah, Cel, Temp;
    char scale;
    printf("Press F to convert to fahrenheit\n");
    printf("Press C to convert in celcius\n");
    scanf("%c", &scale);
    getchar();

    if (scale == 'C')
    {
        printf("Enter the temp\n");

        if (scanf("%f", &Fah) != 1)
        {
             fputs("Wrong Input!", stderr);
             return 1;
        }
        getchar();                  // For catching newline character.

        Temp = (Fah-32) / 1.8;
    }

    else if (scale == 'F')
    {
        printf("Enter the temp\n");

        if (scanf("%f", &Cel) != 1)
        {
            fputs("Wrong Input!", stderr);
             return 1;
        }
        getchar();                   // For catching newline character.

        Temp = (Cel * 1.8) + 32;
    }

        else
        {
               // Case for different input than 'F' and 'C'.
               // Probably Error routine.
               printf("Wrong input!\n");
        }

    printf("The temperature  is %f\n", Temp);
    getchar();

    return 0;
}


问:
"TypeError: jQuery.easing[this.easing] is not a function" in jQuery 1.9.1
For the first time in too many months (blush), I upgraded my jQuery stuff.  I'm now on:

jquery-1.9.1.js

jquery-ui-1.10.2.custom.js (used ThemeRoller, and included all components, including the Effects Core, which mentions easing in its description)

I also upgraded to the most recent versions of jquery.multiselect and jquery.multiselect.filter plugins.  When I try to close one of the multiselect menus, I get this error:

```<code>TypeError: jQuery.easing[this.easing] is not a function
jquery-1.9.1.js (line 9033)
</code>```

Note that although I'm using the multiselect plugin when the error occurs, the actual error is in the main jQuery file.  The code is:

```<code>/*9031*/ if ( this.options.duration ) {
/*9032*/   this.pos = eased = jQuery.easing[ this.easing ](
/*9033*/     percent, this.options.duration * percent, 0, 1, this.options.duration
/*9034*/   );
/*9035*/ }
</code>```

Did I forget to update some file?  Googling about it, others with the same complaint seem to all be trying to use some sort of additional easing plugin, but I'm not.

答:
The error can be provoked by argument inversion when using an effect method wrongly like .show(duration, easing) as it leads to a call of an invalid easing.

The correct notation is .show(easing, duration) https://api.jquery.com/show/

var duration = 'slow', easing = 'linear';
$("#correct").click(function() {
  $("p").show(duration, easing);
});
$("#error").click(function() {
  $("p").show(easing, duration); // fails -> see error in console
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>p { background: yellow; }</code>```

$("p").show(
<button id="correct">duration, easing</button>
<button id="error">easing, duration -> ERROR</button>
)

Hello
```

Body:
For the first time in too many months (blush), I upgraded my jQuery stuff.  I'm now on:

jquery-1.9.1.js

jquery-ui-1.10.2.custom.js (used ThemeRoller, and included all components, including the Effects Core, which mentions easing in its description)

I also upgraded to the most recent versions of jquery.multiselect and jquery.multiselect.filter plugins.  When I try to close one of the multiselect menus, I get this error:

TypeError: jQuery.easing[this.easing] is not a function
jquery-1.9.1.js (line 9033)

Note that although I'm using the multiselect plugin when the error occurs, the actual error is in the main jQuery file.  The code is:

/*9031*/ if ( this.options.duration ) {
/*9032*/   this.pos = eased = jQuery.easing[ this.easing ](
/*9033*/     percent, this.options.duration * percent, 0, 1, this.options.duration
/*9034*/   );
/*9035*/ }

Did I forget to update some file?  Googling about it, others with the same complaint seem to all be trying to use some sort of additional easing plugin, but I'm not.

Body:
The error can be provoked by argument inversion when using an effect method wrongly like .show(duration, easing) as it leads to a call of an invalid easing.

The correct notation is .show(easing, duration) https://api.jquery.com/show/

var duration = 'slow', easing = 'linear';
$("#correct").click(function() {
  $("p").show(duration, easing);
});
$("#error").click(function() {
  $("p").show(easing, duration); // fails -> see error in console
});

p { background: yellow; }

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
$("p").show(
<button id="correct">duration, easing</button>
<button id="error">easing, duration -> ERROR</button>
)
<p style="display: none">Hello</p>


问:
Fibonacci Sum of Large Numbers(Only Last Digit to be Printed)
I have been trying to come out with a solution regarding the problem of finding the last digit of the sum of large n Fibonacci series.
I have been able to pass several test cases with large n. But I'm stuck at the following case where n = 832564823476. I know it can be solved using Pisano's period but I'm unable to come out with a efficient algo. Any help would be great. Thanks.
My code that I have implemented is as follows-</p>

```<code>#include <iostream>
using namespace std;

int calc_fib(int n) {

    int fib[n+1];
    fib[0]=0;
    fib[1]=1;
    int res = 1;
    for(int i = 2; i<=n;i++){
        fib[i] = (fib[i-1]%10 + fib[i-2]%10)%10;
        res = res + fib[i];
    }
    return (res%10);
}

int main() {
    int n = 0;
    std::cin >> n;

    std::cout << calc_fib(n) << '\n';
    return 0;
}
</code>```

答:
Last digit of Fibonacci sum repeats after 60 elements.

Here the period is 60 [0-59].
  So to get the last digit of n'th sum of number is the last digit of n%60'th sum of
  number

```<code>#include <iostream>
#include <vector>
#include <algorithm>
int get_last_digit(int n){
  std::vector<int> last_digits(60);
  long long a = 0, b = 1;
  last_digits[0] = 0;
  last_digits[1] = 1;
  long long temp, sum = 1;
  // Fill last_digits vector with the first 60 sums last digits
  for (int i = 2; i < 60; i++) {
    temp = a+b;
    a = b;
    b = temp;
    sum += temp;
    last_digits[i] = sum%10;
  }
  // Now return n%60'th element
  return last_digits[n%60];
}
int main(int argc, char const *argv[]) {
  int n;
  std::cin>>n;
  std::cout << get_last_digit(n);
  return 0;
}
</code>```

Body:
I have been trying to come out with a solution regarding the problem of finding the last digit of the sum of large n Fibonacci series.
I have been able to pass several test cases with large n. But I'm stuck at the following case where n = 832564823476. I know it can be solved using Pisano's period but I'm unable to come out with a efficient algo. Any help would be great. Thanks.
My code that I have implemented is as follows-

#include <iostream>
using namespace std;

int calc_fib(int n) {

    int fib[n+1];
    fib[0]=0;
    fib[1]=1;
    int res = 1;
    for(int i = 2; i<=n;i++){
        fib[i] = (fib[i-1]%10 + fib[i-2]%10)%10;
        res = res + fib[i];
    }
    return (res%10);
}

int main() {
    int n = 0;
    std::cin >> n;

    std::cout << calc_fib(n) << '\n';
    return 0;
}

Body:
Last digit of Fibonacci sum repeats after 60 elements.

Here the period is 60 [0-59].
  So to get the last digit of n'th sum of number is the last digit of n%60'th sum of
  number

#include <iostream>
#include <vector>
#include <algorithm>
int get_last_digit(int n){
  std::vector<int> last_digits(60);
  long long a = 0, b = 1;
  last_digits[0] = 0;
  last_digits[1] = 1;
  long long temp, sum = 1;
  // Fill last_digits vector with the first 60 sums last digits
  for (int i = 2; i < 60; i++) {
    temp = a+b;
    a = b;
    b = temp;
    sum += temp;
    last_digits[i] = sum%10;
  }
  // Now return n%60'th element
  return last_digits[n%60];
}
int main(int argc, char const *argv[]) {
  int n;
  std::cin>>n;
  std::cout << get_last_digit(n);
  return 0;
}


问:
how do make this show/hide more concise?
There are many show/hide questions and examples but I can't find the answer.

I have a simple code like this which  is used in a few areas within a page.

```<code>jQuery(document).ready(function () {
    jQuery('#mini-cart').hide();
    jQuery('#mini-cart-a').click(function ()  {
        jQuery('#mini-cart').toggle(400);
        return false;
    });
});
</code>```

Each show/hide uses its own ID, so I simply group ids like so:

```<code>jQuery('#show-hide1, #show-hide2').hide();
</code>```

Problem with this method is, when I click on of the show/hid element, all of the elements show.

So I tried something like this but only the first ones works, the second ones isn't working, when I click on it, it does nothing.

```<code>jQuery(document).ready(function () {
    jQuery('show-hide1, #show-hide2').hide();
    jQuery('show-hide1 a, #show-hide2 a').click(function () {
        jQuery(this).next().toogle(400);
    }
    return false;
    });
});
</code>```

There are 4 different areas that I need the show/hide within a page and  really don't want to repeat the same codes 4 times. Thanks!

Update:
(Sorry I can't use the Add Comment nor answer my question)

Thank you all, for your helpful reply.

Lee's version is more like a tabs - I don't want the hidden div associate an ID to anchor tag. It's CMS enviornment so I try to make it simpler if possible.

Andy's version has similar ID issue, so I opted in for roXon's

RoXon:
http://jsbin.com/ihoqi3/2/
Click on View Bag (2), you can see it's working, however if you go to Questions' tab, click on "Ask a question", it opens up the hidden container from View Bag.

Jeremy B's version:
http://jsbin.com/ibayu4
It hides the toggleLink's text.

From the example page, the "Choose your tea" and "Write a Review" in the Reviews Tab require similar treatment, but if I can get the above mentioned two working, the rest will take care by itself :)

Right now I use 4 separate codes to make it work.

p/s, I need to use the herf anchor because this is important for keyboard user, with the JS show/hide the hidden div can't be toggled.

答:
Specify a class such as ".tab" and the id of the div containing the content that you want to display for the particular ".tab"
i.e.</p>

```<code>$(".tab").click(function(){
   var clickedID = $(this).attr("class").split(" ")[1];
   $("#" + clickedID).toggle();
});

<div class="tab container1"></div>
<div id="container1">This container will be displayed if you click on the div .tab container 1</div>

<div class="tab container2"></div>
<div id="container2">This container will be displayed if you click on the div .tab container 2</div>
</code>```

Body:
There are many show/hide questions and examples but I can't find the answer.

I have a simple code like this which  is used in a few areas within a page.

jQuery(document).ready(function () {
    jQuery('#mini-cart').hide();
    jQuery('#mini-cart-a').click(function ()  {
        jQuery('#mini-cart').toggle(400);
        return false;
    });
});

Each show/hide uses its own ID, so I simply group ids like so:

jQuery('#show-hide1, #show-hide2').hide();

Problem with this method is, when I click on of the show/hid element, all of the elements show.

So I tried something like this but only the first ones works, the second ones isn't working, when I click on it, it does nothing.

jQuery(document).ready(function () {
    jQuery('show-hide1, #show-hide2').hide();
    jQuery('show-hide1 a, #show-hide2 a').click(function () {
        jQuery(this).next().toogle(400);
    }
    return false;
    });
});

There are 4 different areas that I need the show/hide within a page and  really don't want to repeat the same codes 4 times. Thanks!

Update:
(Sorry I can't use the Add Comment nor answer my question)

Thank you all, for your helpful reply.

Lee's version is more like a tabs - I don't want the hidden div associate an ID to anchor tag. It's CMS enviornment so I try to make it simpler if possible.

Andy's version has similar ID issue, so I opted in for roXon's

RoXon:
http://jsbin.com/ihoqi3/2/
Click on View Bag (2), you can see it's working, however if you go to Questions' tab, click on "Ask a question", it opens up the hidden container from View Bag.

Jeremy B's version:
http://jsbin.com/ibayu4
It hides the toggleLink's text.

From the example page, the "Choose your tea" and "Write a Review" in the Reviews Tab require similar treatment, but if I can get the above mentioned two working, the rest will take care by itself :)

Right now I use 4 separate codes to make it work.

p/s, I need to use the herf anchor because this is important for keyboard user, with the JS show/hide the hidden div can't be toggled.

Body:
Specify a class such as ".tab" and the id of the div containing the content that you want to display for the particular ".tab"
i.e.

$(".tab").click(function(){
   var clickedID = $(this).attr("class").split(" ")[1];
   $("#" + clickedID).toggle();
});

<div class="tab container1"></div>
<div id="container1">This container will be displayed if you click on the div .tab container 1</div>

<div class="tab container2"></div>
<div id="container2">This container will be displayed if you click on the div .tab container 2</div>


问:
sequelize findOne doesn't find a userId when that usedIf is in the db
I am using node.js/express/sequelize lo log in a user. I'm testing making the requests in postman to see if it gets anything. I am testing a user and pw that I know are in the db but my findOne query in sequelize returns null even though the tested name is in the db. Here's the query in question:

```<code>    let {  userId, pw } = req.body
  try{
    const foundUser = await User.findOne({ where: { userId: userId } });
    if (foundUser === null) {
        return res.status(401).send({ auth: false, token: null,error: 'name not found' });
    } else {
        const passwordIsValid = bcrypt.compareSync(pw, foundUser.pw);
        if (!passwordIsValid) return res.status(401).send({ auth: false, token: null,error: 'name not found' });
        const token = jwt.sign({ id: foundUser.id}, config.secret, {
            expiresIn: 86400 // expires in 24 hours
          });
        res.status(200).json({auth:true,token:token});
    }

  } catch (err) {
    res.status(500).json(err);
  }

}
</code>```

my json

I have body-parser implemented for jsonenter image description here on index js and the routing works as the userId and pwd values make it to the findOne query. However it still says that there are no results after the query. Terminal runs the following (userId is 'slim')

Executing (default): SELECT id, username, userId, pw, createdAt, updatedAt FROM users AS users WHERE users.userId = 'slim';

'slim' is both in the Json and in the 'userId' section of the db

答: it turns out the issue was because there was more than one 'slim' in the userId section of my db, it was acting funny. When I entered a truly unique value for userId, it returned the token as expected. Maybe it seems obvious but it's important that that value called for authentication in unique.</p>

Body:
I am using node.js/express/sequelize lo log in a user. I'm testing making the requests in postman to see if it gets anything. I am testing a user and pw that I know are in the db but my findOne query in sequelize returns null even though the tested name is in the db. Here's the query in question:

    let {  userId, pw } = req.body
  try{
    const foundUser = await User.findOne({ where: { userId: userId } });
    if (foundUser === null) {
        return res.status(401).send({ auth: false, token: null,error: 'name not found' });
    } else {
        const passwordIsValid = bcrypt.compareSync(pw, foundUser.pw);
        if (!passwordIsValid) return res.status(401).send({ auth: false, token: null,error: 'name not found' });
        const token = jwt.sign({ id: foundUser.id}, config.secret, {
            expiresIn: 86400 // expires in 24 hours
          });
        res.status(200).json({auth:true,token:token});
    }

  } catch (err) {
    res.status(500).json(err);
  }

}

my json

I have body-parser implemented for jsonenter image description here on index js and the routing works as the userId and pwd values make it to the findOne query. However it still says that there are no results after the query. Terminal runs the following (userId is 'slim')

Executing (default): SELECT id, username, userId, pw, createdAt, updatedAt FROM users AS users WHERE users.userId = 'slim';

'slim' is both in the Json and in the 'userId' section of the db


问:
flutter build apk --release command not work
```<code>TYSONs-MacBook-Air:chats jeshurun$ flutter build apk --release
You are building a fat APK that includes binaries for android-arm, android-arm64, android-x64.
 If you are deploying the app to the Play Store, it's recommended to use app bundles or split the APK to reduce the APK size.
To generate an app bundle, run:
    flutter build appbundle --target-platform android-arm,android-arm64,android-x64
    Learn more on: https://developer.android.com/guide/app-bundle
To split the APKs per ABI, run:
    flutter build apk --target-platform android-arm,android-arm64,android-x64 --split-per-abi
    Learn more on:  https://developer.android.com/studio/build/configure-apk-splits#configure-abi-split
 Plugin project :firebase_core_web not found. Please update settings.gradle.
 Plugin project :cloud_firestore_web not found. Please update settings.gradle.

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':device_info:verifyReleaseResources'.
> A failure occurred while executing
com.android.build.gradle.internal.tasks.Workers$ActionFacade
> 1 exception was raised by workers:
 com.android.builder.internal.aapt.v2.Aapt2Exception: Android resource linking failed
 /Users/jeshurun/.gradle/caches/transforms-2/files-2.1/8caf43a43008a17794fe6e0dd5ac61b7/core-1.1.0/res/values/values.xml:142:5-173:25: AAPT: error: resource android:attr/fontVariationSettings not found.

 /Users/jeshurun/.gradle/caches/transforms-2/files-2.1/8caf43a43008a17794fe6e0dd5ac61b7/core-1.1.0/res/values/values.xml:142:5-173:25: AAPT: error: resource android:attr/ttcIndex not found.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 14s
Running Gradle task 'assembleRelease'...
Running Gradle task 'assembleRelease'... Done                      15.6s
The built failed likely due to AndroidX incompatibilities in a plugin.
The tool is about to try using Jetfier to solve the incompatibility.
Building plugin agora_rtc_engine...
Running Gradle task 'assembleAarRelease'...
Running Gradle task 'assembleAarRelease'... Done                    1.7s

FAILURE: Build failed with an exception.

* What went wrong:
Could not determine the dependencies of task ':compileReleaseAidl'.
> SDK location not found. Define location with an ANDROID_SDK_ROOT environment variable or by setting the sdk.dir path in your project's local properties file at '/Users/jeshurun/flutter/.pub-cache/hosted/pub.dartlang.org/agora_rtc_engine-1.0.12/android/local.properties'.
</code>```

Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

Get more help at https://help.gradle.org

BUILD FAILED in 1s

The plugin agora_rtc_engine could not be built due to the issue above.

答: In android build.gradle file try to change the compileSdkVersion to: compileSdkVersion 28

Body:
TYSONs-MacBook-Air:chats jeshurun$ flutter build apk --release
You are building a fat APK that includes binaries for android-arm, android-arm64, android-x64.
 If you are deploying the app to the Play Store, it's recommended to use app bundles or split the APK to reduce the APK size.
To generate an app bundle, run:
    flutter build appbundle --target-platform android-arm,android-arm64,android-x64
    Learn more on: https://developer.android.com/guide/app-bundle
To split the APKs per ABI, run:
    flutter build apk --target-platform android-arm,android-arm64,android-x64 --split-per-abi
    Learn more on:  https://developer.android.com/studio/build/configure-apk-splits#configure-abi-split
 Plugin project :firebase_core_web not found. Please update settings.gradle.
 Plugin project :cloud_firestore_web not found. Please update settings.gradle.

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':device_info:verifyReleaseResources'.
> A failure occurred while executing
com.android.build.gradle.internal.tasks.Workers$ActionFacade
> 1 exception was raised by workers:
 com.android.builder.internal.aapt.v2.Aapt2Exception: Android resource linking failed
 /Users/jeshurun/.gradle/caches/transforms-2/files-2.1/8caf43a43008a17794fe6e0dd5ac61b7/core-1.1.0/res/values/values.xml:142:5-173:25: AAPT: error: resource android:attr/fontVariationSettings not found.

 /Users/jeshurun/.gradle/caches/transforms-2/files-2.1/8caf43a43008a17794fe6e0dd5ac61b7/core-1.1.0/res/values/values.xml:142:5-173:25: AAPT: error: resource android:attr/ttcIndex not found.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 14s
Running Gradle task 'assembleRelease'...
Running Gradle task 'assembleRelease'... Done                      15.6s
The built failed likely due to AndroidX incompatibilities in a plugin.
The tool is about to try using Jetfier to solve the incompatibility.
Building plugin agora_rtc_engine...
Running Gradle task 'assembleAarRelease'...
Running Gradle task 'assembleAarRelease'... Done                    1.7s

FAILURE: Build failed with an exception.

* What went wrong:
Could not determine the dependencies of task ':compileReleaseAidl'.
> SDK location not found. Define location with an ANDROID_SDK_ROOT environment variable or by setting the sdk.dir path in your project's local properties file at '/Users/jeshurun/flutter/.pub-cache/hosted/pub.dartlang.org/agora_rtc_engine-1.0.12/android/local.properties'.

Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

Get more help at https://help.gradle.org

BUILD FAILED in 1s

The plugin agora_rtc_engine could not be built due to the issue above.


问:
What is the difference between np.array() and np.asarray()?
What is the difference between NumPy's np.array and np.asarray? When should I use one rather than the other? They seem to generate identical output.

答:
asarray(x) is like array(x, copy=False)

Use asarray(x) when you want to ensure that x will be an array before any other operations are done. If x is already an array then no copy would be done. It would not cause a redundant performance hit.

Here is an example of a function that ensure x is converted into an array first.

def mysum(x):
    return np.asarray(x).sum()
```


问:
Updating sequence for primary key in postgres for a table with a lot of deletions
I have the following problem: I have a table with a lot of deletions and inserts of rows. Also I would like to assign to each of current rows in tables some id number. Currently I'm trying to do it with

```<code>DROP SEQUENCE IF EXISTS market_orders_seq
CREATE SEQUENCE market_orders_seq CACHE 1
CREATE TABLE market_orders (id int NOT NULL DEFAULT nextval('market_orders_seq') PRIMARY KEY, typ varchar(5), tag varchar(30), owner_id int, owner_tag varchar(5), amount int, price int, market_id int)
ALTER SEQUENCE market_orders_seq OWNED BY market_orders.id
</code>```

But if I understand correctly, sequences are monotonous and can't go down when i delete some rows, so i had encountered a problem of ids being inflated quite fast. What is an solution to this problem? I would like to use the first unused id for my inserts, but I don't know how to do it.

答:
While this is technically feasible, I would not actually recommend going this way.

First, an integer value can store values up to 2 about billions, which you probably won’t hit - and you can still switch to bigint, which may reach about 1^19.

Also, identifying the gaps requires scanning the table for each and every insert, which is inefficient (the larger the table, the less efficient).

```<code>insert into market_orders(id, typ, ...)
select
    min(id) + 1,
    'foo',
    ...
from market_orders mo
where not exists(select 1 from market_orders mo1 where mo1.id = mo + 1)
</code>```

Side note: you should be using the [big]serial datatype, so you don’t need to handle the sequence by yourself.

Body:
I have the following problem: I have a table with a lot of deletions and inserts of rows. Also I would like to assign to each of current rows in tables some id number. Currently I'm trying to do it with

DROP SEQUENCE IF EXISTS market_orders_seq
CREATE SEQUENCE market_orders_seq CACHE 1
CREATE TABLE market_orders (id int NOT NULL DEFAULT nextval('market_orders_seq') PRIMARY KEY, typ varchar(5), tag varchar(30), owner_id int, owner_tag varchar(5), amount int, price int, market_id int)
ALTER SEQUENCE market_orders_seq OWNED BY market_orders.id

But if I understand correctly, sequences are monotonous and can't go down when i delete some rows, so i had encountered a problem of ids being inflated quite fast. What is an solution to this problem? I would like to use the first unused id for my inserts, but I don't know how to do it.

Body:
While this is technically feasible, I would not actually recommend going this way.

First, an integer value can store values up to 2 about billions, which you probably won’t hit - and you can still switch to bigint, which may reach about 1^19.

Also, identifying the gaps requires scanning the table for each and every insert, which is inefficient (the larger the table, the less efficient).

insert into market_orders(id, typ, ...)
select
    min(id) + 1,
    'foo',
    ...
from market_orders mo
where not exists(select 1 from market_orders mo1 where mo1.id = mo + 1)

Side note: you should be using the [big]serial datatype, so you don’t need to handle the sequence by yourself.


问:
jq command optimization with variable keys. Two separate jq commands combined in one
I have a lot of different json files with slightly different structures.

For example, I could access LASTNAME's value in the next json file

```<code>{
  "Results": [
    {
      "Persons": [
        {
          "id": 20,
          "Position": "office employee",
          "Profession": "Office workers",
          "Address": {
            "City": "Portland",
            "State": "Washington",
            "Country": "USA"
          },
          "PersonalInfo": {
            "LASTNAME": "Pete",
            "FIRSTNAME": "Columb",
            "MIDNAME": "George"
          }
        },
        {
          "id": 21,
          "Position": "Manager",
          "Profession": "Medicine",
          "Address": {
            "City": "New York",
            "State": "",
            "Country": "USA"
          },
          "PersonalInfo": {
            "LASTNAME": "Bob",
            "FIRSTNAME": "Smith",
            "MIDNAME": ""
          }
        }
      ],
      "ItemsNumber": 2,
      "AdditionalItems": {}
    }
  ]
}
</code>```

with a command:

```<code>$ jq -r '. | .Results | .[] | .Persons | .[] | .PersonalInfo | .LASTNAME' question.json
</code>```

Output:

```<code>Pete
Bob
</code>```

The second json file example ($ jq -r . question2.json):

```<code>{
  "Results": [
    {
      "Persons": [
        {
          "id": 2000,
          "Position": "Director",
          "Profession": "Marketing",
          "Address": {
            "City": "Las Vegas",
            "State": "Nevada",
            "Country": "USA"
          },
          "PersonalInfo": {
            "Name1": "Steven",
            "Name2": "Bond",
            "Name3": ""
          }
        }
      ],
      "ItemsNumber": 1,
      "AdditionalItems": {}
    }
  ]
}
</code>```

Command:

```<code>jq -r '. | .Results | .[] | .Persons | .[] | .PersonalInfo | .Name2' question2.json
</code>```

Output:

```<code>Bond
</code>```

Question:

Is it possible to combine these two commands in one and make it shorter (or unique: without .Results, .Persons, .PersonalInfo sections accessing)?

I tried the next, for example, to combine:

```<code>jq -r '. | .Results | .[] | .Persons | .[] | .PersonalInfo | (.Name2 or .LASTNAME)' question*.json
</code>```

It outputs:

```<code>true
true
true
</code>```

But I want:

```<code>Pete
Bob
Bond
</code>```

Number of variable keys could be bigger than two: LASTNAME, lname, ThirdName, Name2

Update:

I am currently unable to use the second customcommander's command properly to output required values without "; null; " lines using jq only:

```<code>cat question*.json | jq '.. | (.Address?|.City) + "; " + (.id|tostring) + "; " + (.PersonalInfo?| .LASTNAME // .Name2) | select(.)'
</code>```

Output is not nice in this case:

```<code>"; null; "
"; null; "
"Portland; 20; Pete"
"; null; "
"; null; "
"New York; 21; Bob"
"; null; "
"; null; "
"; null; "
"; null; "
"; null; "
"Las Vegas; 2000; Bond"
"; null; "
"; null; "
"; null; "
</code>```

答:
I think you simply need to use the alternative operator //

```<code>. | .Results | .[] | .Persons | .[] | .PersonalInfo | .LASTNAME // .Name2
</code>```

If you need to shorten the syntax you can use:

```<code>.. | (.LASTNAME? // .Name2?) | select(.)
</code>```

But I'm not sure whether that's either performant or advisable.

Body:
I have a lot of different json files with slightly different structures.

For example, I could access LASTNAME's value in the next json file

{
  "Results": [
    {
      "Persons": [
        {
          "id": 20,
          "Position": "office employee",
          "Profession": "Office workers",
          "Address": {
            "City": "Portland",
            "State": "Washington",
            "Country": "USA"
          },
          "PersonalInfo": {
            "LASTNAME": "Pete",
            "FIRSTNAME": "Columb",
            "MIDNAME": "George"
          }
        },
        {
          "id": 21,
          "Position": "Manager",
          "Profession": "Medicine",
          "Address": {
            "City": "New York",
            "State": "",
            "Country": "USA"
          },
          "PersonalInfo": {
            "LASTNAME": "Bob",
            "FIRSTNAME": "Smith",
            "MIDNAME": ""
          }
        }
      ],
      "ItemsNumber": 2,
      "AdditionalItems": {}
    }
  ]
}

with a command:

$ jq -r '. | .Results | .[] | .Persons | .[] | .PersonalInfo | .LASTNAME' question.json

Output:

Pete
Bob

The second json file example ($ jq -r . question2.json):

{
  "Results": [
    {
      "Persons": [
        {
          "id": 2000,
          "Position": "Director",
          "Profession": "Marketing",
          "Address": {
            "City": "Las Vegas",
            "State": "Nevada",
            "Country": "USA"
          },
          "PersonalInfo": {
            "Name1": "Steven",
            "Name2": "Bond",
            "Name3": ""
          }
        }
      ],
      "ItemsNumber": 1,
      "AdditionalItems": {}
    }
  ]
}

Command:

jq -r '. | .Results | .[] | .Persons | .[] | .PersonalInfo | .Name2' question2.json

Output:

Bond

Question:

Is it possible to combine these two commands in one and make it shorter (or unique: without .Results, .Persons, .PersonalInfo sections accessing)?

I tried the next, for example, to combine:

jq -r '. | .Results | .[] | .Persons | .[] | .PersonalInfo | (.Name2 or .LASTNAME)' question*.json

It outputs:

true
true
true

But I want:

Pete
Bob
Bond

Number of variable keys could be bigger than two: LASTNAME, lname, ThirdName, Name2

Update:

I am currently unable to use the second customcommander's command properly to output required values without "; null; " lines using jq only:

cat question*.json | jq '.. | (.Address?|.City) + "; " + (.id|tostring) + "; " + (.PersonalInfo?| .LASTNAME // .Name2) | select(.)'

Output is not nice in this case:

"; null; "
"; null; "
"Portland; 20; Pete"
"; null; "
"; null; "
"New York; 21; Bob"
"; null; "
"; null; "
"; null; "
"; null; "
"; null; "
"Las Vegas; 2000; Bond"
"; null; "
"; null; "
"; null; "

Body:
I think you simply need to use the alternative operator //

. | .Results | .[] | .Persons | .[] | .PersonalInfo | .LASTNAME // .Name2

If you need to shorten the syntax you can use:

.. | (.LASTNAME? // .Name2?) | select(.)

But I'm not sure whether that's either performant or advisable.