问:
NodeJS & Gmail API - Access last 3 emails based on "To:" recipient
I am currently utilising NodeJS and the Gmail API to access my gmail account and return the last email I've received which is obviously only going to be 1 email using this code: (which is a slightly modified version of the example seen here: https://www.codediesel.com/nodejs/how-to-access-gmail-using-nodejs-and-the-gmail-api/

```<code>var fs = require('fs');
var readline = require('readline');
var {google} = require('googleapis');

// If modifying these scopes, delete your previously saved credentials
// at TOKEN_DIR/gmail-nodejs.json
var SCOPES = ['https://www.googleapis.com/auth/gmail.readonly'];

// Change token directory to your system preference
var TOKEN_DIR = ('./');
var TOKEN_PATH = TOKEN_DIR + 'gmail-nodejs.json';

var gmail = google.gmail('v1');
//exports.confirmationEmailFinal;

// Load client secrets from a local file.
fs.readFile('client_secret.json', function processClientSecrets(err, content) {
  if (err) {
    console.log('Error loading client secret file: ' + err);
    return;
  }
  // Authorize a client with the loaded credentials, then call the
  // Gmail API.
  authorize(JSON.parse(content), getRecentEmail);

});

/**
 * Create an OAuth2 client with the given credentials, and then execute the
 * given callback function.
 *
 * @param {Object} credentials The authorization client credentials.
 * @param {function} callback The callback to call with the authorized client.
 */
function authorize(credentials, callback) {
    var clientSecret = credentials.installed.client_secret;
    var clientId = credentials.installed.client_id;
    var redirectUrl = credentials.installed.redirect_uris[0];

    var OAuth2 = google.auth.OAuth2;

    var oauth2Client = new OAuth2(clientId, clientSecret,  redirectUrl);

    // Check if we have previously stored a token.
    fs.readFile(TOKEN_PATH, function(err, token) {
      if (err) {
        getNewToken(oauth2Client, callback);
      } else {
        oauth2Client.credentials = JSON.parse(token);
        callback(oauth2Client);
      }
    });
}

/**
* Get and store new token after prompting for user authorization, and then
* execute the given callback with the authorized OAuth2 client.
*
* @param {google.auth.OAuth2} oauth2Client The OAuth2 client to get token for.
* @param {getEventsCallback} callback The callback to call with the authorized
*     client.
*/
function getNewToken(oauth2Client, callback) {
  var authUrl = oauth2Client.generateAuthUrl({access_type: 'offline', scope: SCOPES});
  console.log('Authorize this app by visiting this url: ', authUrl);
  var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
  });

  rl.question('Enter the code from that page here: ', function(code) {
    rl.close();
    oauth2Client.getToken(code, function(err, token) {
      if (err) {
        console.log('Error while trying to retrieve access token', err);
        return;
      }
      oauth2Client.credentials = token;
      storeToken(token);
      callback(oauth2Client);
    });
  });
}

/**
* Store token to disk be used in later program executions.
*
* @param {Object} token The token to store to disk.
*/
function storeToken(token) {
  try {
    fs.mkdirSync(TOKEN_DIR);
  } catch (err) {
    if (err.code != 'EEXIST') {
      throw err;
    }
  }
  fs.writeFileSync(TOKEN_PATH, JSON.stringify(token));
  console.log('Token stored to ' + TOKEN_PATH);
}

/**
* Lists the labels in the user's account.
*
* @param {google.auth.OAuth2} auth An authorized OAuth2 client.
*/

function listLabels(auth) {
  gmail.users.labels.list({auth: auth, userId: 'me',}, function(err, response) {
    if (err) {
      console.log('The API returned an error: ' + err);
      return;
    }

    var labels = response.data.labels;

    if (labels.length == 0) {
      console.log('No labels found.');
    } else {
      console.log('Labels:');
      for (var i = 0; i < labels.length; i++) {
        var label = labels[i];
        console.log('%s', label.name);
      }
    }
  });

}

/**
* Get the recent email from your Gmail account
*
* @param {google.auth.OAuth2} auth An authorized OAuth2 client.
*/
function getRecentEmail(auth) {
    // Only get the recent email - 'maxResults' parameter
    gmail.users.messages.list({auth: auth, userId: 'me', maxResults: 1,}, function(err, response) {
        if (err) {
            console.log('The API returned an error: ' + err);
            return;
        }

      // Get the message id which we will need to retreive tha actual message next.
      var message_id = response['data']['messages'][0]['id'];

      // Retreive the actual message using the message id
      gmail.users.messages.get({auth: auth, userId: 'me', 'id': message_id}, function(err, response) {
          if (err) {
              console.log('The API returned an error: ' + err);
              return;
          }

          // Access the email body content, like this...
          try {
            const message_raw = response.data.payload.body.data;

            data = message_raw;
            buff = new Buffer.from(data, 'base64');
            text = buff.toString();
            console.log(text);
          }
          catch (err){
            const message_raw = response.data.payload.parts[0].body.data;
            console.log('error');

            data = message_raw;
            buff = new Buffer.from(data, 'base64');
            text = buff.toString();
            console.log(text);
          }

      });
    });
}
</code>```

Although this works perfectly fine, I am looking to find the 3 latest emails (not just 1) based on the email's "TO:" recipient which I currently have stored as the email variable.

Any help would be appreciated!

答:
Use filters via q property:

```<code>const email = 'myEmail@example.com';
gmail.users.messages.list({
 auth: auth,
 userId: 'me',
 maxResults: 1,
 q: `to:${email}`
}
</code>```

Beside to:address you can use all other search/filter params, like is:unread etc.

Body:
I am currently utilising NodeJS and the Gmail API to access my gmail account and return the last email I've received which is obviously only going to be 1 email using this code: (which is a slightly modified version of the example seen here: https://www.codediesel.com/nodejs/how-to-access-gmail-using-nodejs-and-the-gmail-api/

var fs = require('fs');
var readline = require('readline');
var {google} = require('googleapis');

// If modifying these scopes, delete your previously saved credentials
// at TOKEN_DIR/gmail-nodejs.json
var SCOPES = ['https://www.googleapis.com/auth/gmail.readonly'];

// Change token directory to your system preference
var TOKEN_DIR = ('./');
var TOKEN_PATH = TOKEN_DIR + 'gmail-nodejs.json';

var gmail = google.gmail('v1');
//exports.confirmationEmailFinal;

// Load client secrets from a local file.
fs.readFile('client_secret.json', function processClientSecrets(err, content) {
  if (err) {
    console.log('Error loading client secret file: ' + err);
    return;
  }
  // Authorize a client with the loaded credentials, then call the
  // Gmail API.
  authorize(JSON.parse(content), getRecentEmail);

});

/**
 * Create an OAuth2 client with the given credentials, and then execute the
 * given callback function.
 *
 * @param {Object} credentials The authorization client credentials.
 * @param {function} callback The callback to call with the authorized client.
 */
function authorize(credentials, callback) {
    var clientSecret = credentials.installed.client_secret;
    var clientId = credentials.installed.client_id;
    var redirectUrl = credentials.installed.redirect_uris[0];

    var OAuth2 = google.auth.OAuth2;

    var oauth2Client = new OAuth2(clientId, clientSecret,  redirectUrl);

    // Check if we have previously stored a token.
    fs.readFile(TOKEN_PATH, function(err, token) {
      if (err) {
        getNewToken(oauth2Client, callback);
      } else {
        oauth2Client.credentials = JSON.parse(token);
        callback(oauth2Client);
      }
    });
}

/**
* Get and store new token after prompting for user authorization, and then
* execute the given callback with the authorized OAuth2 client.
*
* @param {google.auth.OAuth2} oauth2Client The OAuth2 client to get token for.
* @param {getEventsCallback} callback The callback to call with the authorized
*     client.
*/
function getNewToken(oauth2Client, callback) {
  var authUrl = oauth2Client.generateAuthUrl({access_type: 'offline', scope: SCOPES});
  console.log('Authorize this app by visiting this url: ', authUrl);
  var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
  });

  rl.question('Enter the code from that page here: ', function(code) {
    rl.close();
    oauth2Client.getToken(code, function(err, token) {
      if (err) {
        console.log('Error while trying to retrieve access token', err);
        return;
      }
      oauth2Client.credentials = token;
      storeToken(token);
      callback(oauth2Client);
    });
  });
}

/**
* Store token to disk be used in later program executions.
*
* @param {Object} token The token to store to disk.
*/
function storeToken(token) {
  try {
    fs.mkdirSync(TOKEN_DIR);
  } catch (err) {
    if (err.code != 'EEXIST') {
      throw err;
    }
  }
  fs.writeFileSync(TOKEN_PATH, JSON.stringify(token));
  console.log('Token stored to ' + TOKEN_PATH);
}

/**
* Lists the labels in the user's account.
*
* @param {google.auth.OAuth2} auth An authorized OAuth2 client.
*/

function listLabels(auth) {
  gmail.users.labels.list({auth: auth, userId: 'me',}, function(err, response) {
    if (err) {
      console.log('The API returned an error: ' + err);
      return;
    }

    var labels = response.data.labels;

    if (labels.length == 0) {
      console.log('No labels found.');
    } else {
      console.log('Labels:');
      for (var i = 0; i < labels.length; i++) {
        var label = labels[i];
        console.log('%s', label.name);
      }
    }
  });

}

/**
* Get the recent email from your Gmail account
*
* @param {google.auth.OAuth2} auth An authorized OAuth2 client.
*/
function getRecentEmail(auth) {
    // Only get the recent email - 'maxResults' parameter
    gmail.users.messages.list({auth: auth, userId: 'me', maxResults: 1,}, function(err, response) {
        if (err) {
            console.log('The API returned an error: ' + err);
            return;
        }

      // Get the message id which we will need to retreive tha actual message next.
      var message_id = response['data']['messages'][0]['id'];

      // Retreive the actual message using the message id
      gmail.users.messages.get({auth: auth, userId: 'me', 'id': message_id}, function(err, response) {
          if (err) {
              console.log('The API returned an error: ' + err);
              return;
          }

          // Access the email body content, like this...
          try {
            const message_raw = response.data.payload.body.data;

            data = message_raw;
            buff = new Buffer.from(data, 'base64');
            text = buff.toString();
            console.log(text);
          }
          catch (err){
            const message_raw = response.data.payload.parts[0].body.data;
            console.log('error');

            data = message_raw;
            buff = new Buffer.from(data, 'base64');
            text = buff.toString();
            console.log(text);
          }

      });
    });
}

Although this works perfectly fine, I am looking to find the 3 latest emails (not just 1) based on the email's "TO:" recipient which I currently have stored as the email variable.

Any help would be appreciated!

Body:
Use filters via q property:

const email = 'myEmail@example.com';
gmail.users.messages.list({
 auth: auth,
 userId: 'me',
 maxResults: 1,
 q: `to:${email}`
}

Beside to:address you can use all other search/filter params, like is:unread etc.


来源: stackexchange

问:
Flex 4 - How to loop over children of a container when they are state-dependant
Flex's new States re-parents visual items that are marked with includeIn/excludeFrom. If I have a Group (MainGroup) with 5 children/elements that are state controlled, is there still a way to get a reference to MainGroup's children? mainGroup.numChildren and mainGroup.numElements don't work since the children are re-parented. At best, they show 1.</p>

```<code><s:states>
   <s:State name="view1State" />
   <s:State name="view2State" />
   <s:State name="view3State" />
   <s:State name="view4State" />
</s:states>

<s:Group id="mainGroup">
    <shipping:OrderShipping id="view1"
            includeIn="view1State" />
    <payment:OrderPayment id="view2"
            includeIn="view2State" />
    <verification:OrderVerification id="view3"
            includeIn="view3State" />
    <confirmation:OrderConfirmation id="view4"
            includeIn="view4State" />
</s:Group>
</code>```

答:
I got the best answer! Well, I will let you decide. Just operate on the states array...</p>

```<code> for each (var viewState:State in mainDocument.states)
{
    var overrides:Array = viewState.overrides;

    for (var i:int = 0; i < overrides.length; i++)
    {
        var addItems:AddItems = overrides[i];
        if (addItems.destination === mainDocument.mainGroup)
            trace((addItems.items as UIComponent).name);
    }

}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Flex's new States re-parents visual items that are marked with includeIn/excludeFrom. If I have a Group (MainGroup) with 5 children/elements that are state controlled, is there still a way to get a reference to MainGroup's children? mainGroup.numChildren and mainGroup.numElements don't work since the children are re-parented. At best, they show 1.

<s:states>
   <s:State name="view1State" />
   <s:State name="view2State" />
   <s:State name="view3State" />
   <s:State name="view4State" />
</s:states>

<s:Group id="mainGroup">
    <shipping:OrderShipping id="view1"
            includeIn="view1State" />
    <payment:OrderPayment id="view2"
            includeIn="view2State" />
    <verification:OrderVerification id="view3"
            includeIn="view3State" />
    <confirmation:OrderConfirmation id="view4"
            includeIn="view4State" />
</s:Group>

Body:
I got the best answer! Well, I will let you decide. Just operate on the states array...

 for each (var viewState:State in mainDocument.states)
{
    var overrides:Array = viewState.overrides;

    for (var i:int = 0; i < overrides.length; i++)
    {
        var addItems:AddItems = overrides[i];
        if (addItems.destination === mainDocument.mainGroup)
            trace((addItems.items as UIComponent).name);
    }

}


问:
How do filter with multiple contains in pyspark
I'm going to do a query with pyspark to filter row who contains at least one word in array. For example, the dataframe is:

```<code>     "content"                "other"
My father is big.              ...
My mother is beautiful.        ...
I'm going to travel.           ...
</code>```

I have an array:

```<code>array=["mother","father"]
</code>```

And the output must be this:

```<code>     "content"                "other"
My father is big.              ...
My mother is beautiful.        ...
</code>```

A simple filter for word in array.

答:
Had the same thoughts as  @ARCrow but using instr.

```<code>lst=["mother","father"]
</code>```

DataFrame

```<code>data= [
  (1,"My father is big."),
  (2, "My mother is beautiful"),
  (3,"I'm going to travel.")
]

df=spark.createDataFrame(data, ("id",'content'))
</code>```

Solution

```<code>df=(df
 .withColumn('phrases', f.array([f.lit(element) for element in lst]))
.where(f.expr('exists(phrases, element -> instr (content, element)>=1)'))
.drop('phrases')

)

df.show()
</code>```

Outcome

```<code>+---+--------------------+
| id|             content|
+---+--------------------+
|  1|   My father is big.|
|  2|My mother is beau...|
+---+--------------------+
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm going to do a query with pyspark to filter row who contains at least one word in array. For example, the dataframe is:

     "content"                "other"
My father is big.              ...
My mother is beautiful.        ...
I'm going to travel.           ...

I have an array:

array=["mother","father"]

And the output must be this:

     "content"                "other"
My father is big.              ...
My mother is beautiful.        ...

A simple filter for word in array.

Body:
Had the same thoughts as  @ARCrow but using instr.

lst=["mother","father"]

DataFrame

data= [
  (1,"My father is big."),
  (2, "My mother is beautiful"),
  (3,"I'm going to travel.")
]

df=spark.createDataFrame(data, ("id",'content'))

Solution

df=(df
 .withColumn('phrases', f.array([f.lit(element) for element in lst]))
.where(f.expr('exists(phrases, element -> instr (content, element)>=1)'))
.drop('phrases')

)

df.show()

Outcome

+---+--------------------+
| id|             content|
+---+--------------------+
|  1|   My father is big.|
|  2|My mother is beau...|
+---+--------------------+


问:
SQL - Aggregate and Group by
I am trying to break out email types into separate columns in a SQL query. I want a column for Home, another for work, and another for alternate. I have all kinds of combinations. I put comments in my work logic, home is much the same. I am having two problems.

If I don't include . A07.EmailAddress ,A07.Active,A07.EmailType, A07.UseAsPrimary in my code it throws the error 'is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.' but if I include it, it does not count the emails correctly

I need to identify the alternate as the leftover ones in home. The logic would be that there was a valid home one in the home case and this is a second one. By definition it would have to be on accounts with multiple home emails and one already identified in the first case.

Thanks in advance

```<code>SELECT

    A01.RecordId
    ,a01.AccountNumber
    ,A01.FamilyId
    ,case
        when A01.OrganizationName IS NULL OR Len(A01.OrganizationName) = 0
        then A01.FirstName + ' ' + A01.LastName
        else A01.OrganizationName
            end as 'Name'
    , case
        when (A07.Active = 1 and A07.EmailType = 'WORK'
            AND ((sum(case when A07.EmailType = 'WORK' then 1 else null end) = 1) --- there is only one work email
            OR (sum(case when A07.EmailType = 'WORK' then 1 else null end) > 1 and A07.UseAsPrimary = 1) --- multiple work emails but one is marked primary
                )
              )
        then A07.EmailAddress
        when A07.EmailType = 'WORK' then A07.EmailAddress --- one work email but not marked primary
        end as 'Work Email'
    ,case
       when (A07.Active = 1 and A07.EmailType = 'HOME'
            AND ((sum(case when A07.EmailType = 'HOME' then 1 else null end) = 1)
            OR (sum(case when A07.EmailType = 'HOME' then 1 else null end) > 1 and A07.UseAsPrimary = 1)
                )
              )
        then A07.EmailAddress
        when A07.EmailType = 'HOME' then A07.EmailAddress
        end as 'Home Email'
        ----------------
    , case
       when (A07.Active = 1 and A07.EmailType = 'HOME'
            AND ((sum(case when A07.EmailType = 'HOME' then 1 else null end) > 1
                and  A07.UseAsPrimary <> 1)
                )
              )
        then A07.EmailAddress
        --when A07.EmailType = 'HOME' then A07.EmailAddress
        end as 'Alternate Email'

  FROM A01_ACCOUNTMASTER A01
  left JOIN [dbo].[A07_AccountEmails] A07 on A01.AccountNumber = A07.AccountNumber

  where
    A01.[Status] = 'A'
  group by A01.AccountNumber, a01.RecordId, A01.FamilyId, A01.OrganizationName, A01.FirstName, A01.LastName
  --, A07.EmailAddress ,A07.Active,A07.EmailType, A07.UseAsPrimary
</code>```

答:
Maybe using window function sum() over partition

Not tested:

```<code>SELECT distinct -- replaced group by with distinct
  A01.RecordId,a01.AccountNumber,A01.FamilyId
 ,case
    when A01.OrganizationName IS NULL OR Len(A01.OrganizationName) = 0
      then A01.FirstName + ' ' + A01.LastName
    else A01.OrganizationName
  end as 'Name'
 ,case
    when (
      A07.Active = 1 and A07.EmailType = 'WORK'
      AND (
        (sum(case when A07.EmailType = 'WORK' then 1 else null end) over partition by (A01.AccountNumber)= 1) --- there is only one work email
        OR
        (sum(case when A07.EmailType = 'WORK' then 1 else null end) over partition by (A01.AccountNumber)> 1 and A07.UseAsPrimary = 1) --- multiple work emails but one is marked primary
      )
    )
      then A07.EmailAddress
    when A07.EmailType = 'WORK' then A07.EmailAddress --- one work email but not marked primary
  end as 'Work Email'
 ,case
    when (
      A07.Active = 1 and A07.EmailType = 'HOME'
      AND (
        (sum(case when A07.EmailType = 'HOME' then 1 else null end) over partition by (A01.AccountNumber) = 1)
        OR
        (sum(case when A07.EmailType = 'HOME' then 1 else null end) over partition by (A01.AccountNumber) > 1 and A07.UseAsPrimary = 1)
      )
    )
      then A07.EmailAddress
    when A07.EmailType = 'HOME' then A07.EmailAddress
  end as 'Home Email'
  ----------------
 ,case
    when (
      A07.Active = 1 and A07.EmailType = 'HOME'
      AND sum(case when A07.EmailType = 'HOME' then 1 else null end) over partition by (A01.AccountNumber) > 1
      and  A07.UseAsPrimary <> 1
    )
      then A07.EmailAddress
    --when A07.EmailType = 'HOME' then A07.EmailAddress
  end as 'Alternate Email'
FROM A01_ACCOUNTMASTER A01
  left JOIN [dbo].[A07_AccountEmails] A07 on A01.AccountNumber = A07.AccountNumber
  where A01.[Status] = 'A'
  -- group by A01.AccountNumber, a01.RecordId, A01.FamilyId, A01.OrganizationName, A01.FirstName, A01.LastName
  --, A07.EmailAddress ,A07.Active,A07.EmailType, A07.UseAsPrimary
</code>```

Title: SQL - Aggregate and Group by

Body:
I am trying to break out email types into separate columns in a SQL query. I want a column for Home, another for work, and another for alternate. I have all kinds of combinations. I put comments in my work logic, home is much the same. I am having two problems.

If I don't include . A07.EmailAddress ,A07.Active,A07.EmailType, A07.UseAsPrimary in my code it throws the error 'is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.' but if I include it, it does not count the emails correctly

I need to identify the alternate as the leftover ones in home. The logic would be that there was a valid home one in the home case and this is a second one. By definition it would have to be on accounts with multiple home emails and one already identified in the first case.

Thanks in advance

SELECT

    A01.RecordId
    ,a01.AccountNumber
    ,A01.FamilyId
    ,case
        when A01.OrganizationName IS NULL OR Len(A01.OrganizationName) = 0
        then A01.FirstName + ' ' + A01.LastName
        else A01.OrganizationName
            end as 'Name'
    , case
        when (A07.Active = 1 and A07.EmailType = 'WORK'
            AND ((sum(case when A07.EmailType = 'WORK' then 1 else null end) = 1) --- there is only one work email
            OR (sum(case when A07.EmailType = 'WORK' then 1 else null end) > 1 and A07.UseAsPrimary = 1) --- multiple work emails but one is marked primary
                )
              )
        then A07.EmailAddress
        when A07.EmailType = 'WORK' then A07.EmailAddress --- one work email but not marked primary
        end as 'Work Email'
    ,case
       when (A07.Active = 1 and A07.EmailType = 'HOME'
            AND ((sum(case when A07.EmailType = 'HOME' then 1 else null end) = 1)
            OR (sum(case when A07.EmailType = 'HOME' then 1 else null end) > 1 and A07.UseAsPrimary = 1)
                )
              )
        then A07.EmailAddress
        when A07.EmailType = 'HOME' then A07.EmailAddress
        end as 'Home Email'
        ----------------
    , case
       when (A07.Active = 1 and A07.EmailType = 'HOME'
            AND ((sum(case when A07.EmailType = 'HOME' then 1 else null end) > 1
                and  A07.UseAsPrimary <> 1)
                )
              )
        then A07.EmailAddress
        --when A07.EmailType = 'HOME' then A07.EmailAddress
        end as 'Alternate Email'

  FROM A01_ACCOUNTMASTER A01
  left JOIN [dbo].[A07_AccountEmails] A07 on A01.AccountNumber = A07.AccountNumber

  where
    A01.[Status] = 'A'
  group by A01.AccountNumber, a01.RecordId, A01.FamilyId, A01.OrganizationName, A01.FirstName, A01.LastName
  --, A07.EmailAddress ,A07.Active,A07.EmailType, A07.UseAsPrimary

Body:
Maybe using window function sum() over partition

Not tested:

SELECT distinct -- replaced group by with distinct
  A01.RecordId,a01.AccountNumber,A01.FamilyId
 ,case
    when A01.OrganizationName IS NULL OR Len(A01.OrganizationName) = 0
      then A01.FirstName + ' ' + A01.LastName
    else A01.OrganizationName
  end as 'Name'
 ,case
    when (
      A07.Active = 1 and A07.EmailType = 'WORK'
      AND (
        (sum(case when A07.EmailType = 'WORK' then 1 else null end) over partition by (A01.AccountNumber)= 1) --- there is only one work email
        OR
        (sum(case when A07.EmailType = 'WORK' then 1 else null end) over partition by (A01.AccountNumber)> 1 and A07.UseAsPrimary = 1) --- multiple work emails but one is marked primary
      )
    )
      then A07.EmailAddress
    when A07.EmailType = 'WORK' then A07.EmailAddress --- one work email but not marked primary
  end as 'Work Email'
 ,case
    when (
      A07.Active = 1 and A07.EmailType = 'HOME'
      AND (
        (sum(case when A07.EmailType = 'HOME' then 1 else null end) over partition by (A01.AccountNumber) = 1)
        OR
        (sum(case when A07.EmailType = 'HOME' then 1 else null end) over partition by (A01.AccountNumber) > 1 and A07.UseAsPrimary = 1)
      )
    )
      then A07.EmailAddress
    when A07.EmailType = 'HOME' then A07.EmailAddress
  end as 'Home Email'
  ----------------
 ,case
    when (
      A07.Active = 1 and A07.EmailType = 'HOME'
      AND sum(case when A07.EmailType = 'HOME' then 1 else null end) over partition by (A01.AccountNumber) > 1
      and  A07.UseAsPrimary <> 1
    )
      then A07.EmailAddress
    --when A07.EmailType = 'HOME' then A07.EmailAddress
  end as 'Alternate Email'
FROM A01_ACCOUNTMASTER A01
  left JOIN [dbo].[A07_AccountEmails] A07 on A01.AccountNumber = A07.AccountNumber
  where A01.[Status] = 'A'
  -- group by A01.AccountNumber, a01.RecordId, A01.FamilyId, A01.OrganizationName, A01.FirstName, A01.LastName
  --, A07.EmailAddress ,A07.Active,A07.EmailType, A07.UseAsPrimary


问:
Podman support of target build?
DockerFile:

```<code>FROM scratch as stage1
RUN 1

FROM scratch as stage2
RUN 2

FROM scratch AS stage3
RUN 3
</code>```

If I run

```<code> docker  build --target stage2 .
</code>```

stage1 will be ignored. And stage2(RUN 2) will be called

But if I run

```<code>podman  build --target stage2 .
</code>```

stage1(RUN 1) will be called.

Why is podman ignoring the target specified? Is there a way to specify the target to Podman?

答:
Turned out target option in podman works differently than what I expected.

This is from release 1.7 of Buildah:
The buildah bud command now accepts a --target option which allows the build to only include the stages in the Dockerfile up to and including the specified stage.

So everything before the specified target(stage) will be built. (I wonder the reason for this implementation!?)

Title: Podman support of target build?

Body:
DockerFile:

FROM scratch as stage1
RUN 1

FROM scratch as stage2
RUN 2

FROM scratch AS stage3
RUN 3

If I run

 docker  build --target stage2 .

stage1 will be ignored. And stage2(RUN 2) will be called

But if I run

podman  build --target stage2 .

stage1(RUN 1) will be called.

Why is podman ignoring the target specified? Is there a way to specify the target to Podman?


问:
Outlook Macro New Message Loses Formatting
I am writing an outlook sub procedure that takes the currently selected email, parses it, and creates a new email message. The parsing is simple enough: Extract the email addresses from the first line of the message and then the rest of the body is the regular email body in the new message.

I am using this basic code for setting the body of the new message:

```<code>Set newMsg = Outlook.Application.CreateItem(olMailItem)
With newMsg
   .BodyFormat = olFormatHTML
   .Body = newBody
   '... set subject,etc
   .Display
</code>```

The problem is that the new message that is created loses all of the HTML formatting that the message I was copying the information from possessed ( and various font stylings). I tried setting the new message's body format to HTML (see code above), but that did not do the trick. Currently, the new message contains all of the textual data, but instead of the table, each cell's data is tab-delimited and the entire message body is in the same font.

答:
BodyFormat does not behave as expected. Instead, HTMLBody can be used as below to properly display the body in HTML format:

With newMsg
   .HTMLBody = newBody
   '... set subject,etc
   .Display

Body:
I am writing an outlook sub procedure that takes the currently selected email, parses it, and creates a new email message. The parsing is simple enough: Extract the email addresses from the first line of the message and then the rest of the body is the regular email body in the new message.

I am using this basic code for setting the body of the new message:

Set newMsg = Outlook.Application.CreateItem(olMailItem)
With newMsg
   .BodyFormat = olFormatHTML
   .Body = newBody
   '... set subject,etc
   .Display

The problem is that the new message that is created loses all of the HTML formatting that the message I was copying the information from possessed ( and various font stylings). I tried setting the new message's body format to HTML (see code above), but that did not do the trick. Currently, the new message contains all of the textual data, but instead of the table, each cell's data is tab-delimited and the entire message body is in the same font.


问:
How to pass @namespace to multiple Views in SwiftUI?
I'm playing with the new Xcode 12 beta & SwiftUi 2.0. .matchedGeometryEffect() modifier is great to do Hero animations. There is a new property @Namespace is introduced in SwiftUI. Its super cool. working awesome.

I was just wondering if there is any possibility to pass a Namespace variable to multiple Views?

Here is an example I'm working on,

```<code>struct HomeView: View {
    @Namespace var namespace
    @State var isDisplay = true

    var body: some View {
        ZStack {
            if isDisplay {
                VStack {
                    Image("share sheet")
                        .resizable()
                        .frame(width: 150, height: 100)
                        .matchedGeometryEffect(id: "img", in: namespace)
                    Spacer()
                }
                .frame(maxWidth: .infinity, maxHeight: .infinity)
                .background(Color.blue)
                .onTapGesture {
                    withAnimation {
                        self.isDisplay.toggle()
                    }
                }
            } else {
                VStack {
                    Spacer()
                    Image("share sheet")
                        .resizable()
                        .frame(width: 300, height: 200)
                        .matchedGeometryEffect(id: "img", in: namespace)
                }
                .frame(maxWidth: .infinity, maxHeight: .infinity)
                .background(Color.red)
                .onTapGesture {
                    withAnimation {
                        self.isDisplay.toggle()
                    }
                }
            }
        }
    }
}
</code>```

It is working fine.

But if I want to extract the Vstack as a SubView, Below picture shows that I have extracted the first VStack into a subview.

I'm getting a compliment Cannot find 'namespace' in scope

Is there a way to pass namespace across multiple Views?

答:
A warning free approach to inject the Namespace into the Environment is to create an ObservableObject, named something like NamespaceWrapper, to hold the Namespace once it's been created. This could look something like:

```<code>class NamespaceWrapper: ObservableObject {
    var namespace: Namespace.ID

    init(_ namespace: Namespace.ID) {
        self.namespace = namespace
    }
}
</code>```

You would then create and pass the Namespace like so:

```<code>struct ContentView: View {
    @Namespace var someNamespace

    var body: some View {
        Foo()
            .environmentObject(NamespaceWrapper(someNamespace))
    }
}

struct Foo: View {
    @EnvironmentObject var namespaceWrapper: NamespaceWrapper

    var body: some View {
        Text("Hey you guys!")
            .matchedGeometryEffect(id: "textView", in: namespaceWrapper.namespace)
    }
}
</code>```

Body:
I'm playing with the new Xcode 12 beta & SwiftUi 2.0. .matchedGeometryEffect() modifier is great to do Hero animations. There is a new property @Namespace is introduced in SwiftUI. Its super cool. working awesome.

I was just wondering if there is any possibility to pass a Namespace variable to multiple Views?

Here is an example I'm working on,

struct HomeView: View {
    @Namespace var namespace
    @State var isDisplay = true

    var body: some View {
        ZStack {
            if isDisplay {
                VStack {
                    Image("share sheet")
                        .resizable()
                        .frame(width: 150, height: 100)
                        .matchedGeometryEffect(id: "img", in: namespace)
                    Spacer()
                }
                .frame(maxWidth: .infinity, maxHeight: .infinity)
                .background(Color.blue)
                .onTapGesture {
                    withAnimation {
                        self.isDisplay.toggle()
                    }
                }
            } else {
                VStack {
                    Spacer()
                    Image("share sheet")
                        .resizable()
                        .frame(width: 300, height: 200)
                        .matchedGeometryEffect(id: "img", in: namespace)
                }
                .frame(maxWidth: .infinity, maxHeight: .infinity)
                .background(Color.red)
                .onTapGesture {
                    withAnimation {
                        self.isDisplay.toggle()
                    }
                }
            }
        }
    }
}

It is working fine.

But if I want to extract the Vstack as a SubView, Below picture shows that I have extracted the first VStack into a subview.

I'm getting a compliment Cannot find 'namespace' in scope

Is there a way to pass namespace across multiple Views?

Body:
A warning free approach to inject the Namespace into the Environment is to create an ObservableObject, named something like NamespaceWrapper, to hold the Namespace once it's been created. This could look something like:

class NamespaceWrapper: ObservableObject {
    var namespace: Namespace.ID

    init(_ namespace: Namespace.ID) {
        self.namespace = namespace
    }
}

You would then create and pass the Namespace like so:

struct ContentView: View {
    @Namespace var someNamespace

    var body: some View {
        Foo()
            .environmentObject(NamespaceWrapper(someNamespace))
    }
}

struct Foo: View {
    @EnvironmentObject var namespaceWrapper: NamespaceWrapper

    var body: some View {
        Text("Hey you guys!")
            .matchedGeometryEffect(id: "textView", in: namespaceWrapper.namespace)
    }
}


问:
Is there an easy way to enter/edit code in Rstudio? Avoiding repetition?
So I have the following code, as you can see this command will not run in R because it is missing a comma after each word and furthermore since these are characters I would need to enter a " before and after each word. Rather than going to each word and typing a " before and after and then a comma - is there an easy way to do this? I couldn't find a command that makes this easier from Rstudio's site - or I don't understand which one I need to use.

```<code>base_pckgs <- c(
    base
    compiler
    datasets
    graphics
    grDevices
    grid
    methods
    parallel
    splines
    stats
    stats4
    tcltk
    tools
    translations

)
</code>```

Desired Output (without actually typing in a " and , in each row.

答:
Check out the datapasta add-in on CRAN or at https://github.com/MilesMcBain/datapasta. It adds some handy tools to RStudio's Addins menu. One, for instance, will let you paste your long list of packages as a vector:

c("base", "compiler", "datasets", "graphics", "grDevices", "grid", "methods", "parallel", "splines", "stats", "stats4", "tcltk", "tools", "translations")

Body:
So I have the following code, as you can see this command will not run in R because it is missing a comma after each word and furthermore since these are characters I would need to enter a " before and after each word. Rather than going to each word and typing a " before and after and then a comma - is there an easy way to do this? I couldn't find a command that makes this easier from Rstudio's site - or I don't understand which one I need to use.

base_pckgs <- c(
    base
    compiler
    datasets
    graphics
    grDevices
    grid
    methods
    parallel
    splines
    stats
    stats4
    tcltk
    tools
    translations

)

Desired Output (without actually typing in a " and , in each row.


问:
Netsuite: Creating Usage Report by Period
I am trying to create a saved search that gives the quantity/sales amount in NetSuite for the previous months to track usage on an item, customer and sales rep level. I have somewhat of a solution however the way my formula is set up it is going off of the system date rather than the whole previous month(s). For example, if I ran the search today it would give me the usage from today (Feb 7) back to Jan 7, Dec 7 and Nov 7. But I know NetSuite has 'Period' as a date function and struggling to incorporate that instead.

My formula is below for an example.

NULLIF(CASE WHEN {trandate} > ADD_MONTHS(SYSDATE,-1) THEN CASE WHEN {type} = 'Invoice' THEN NVL({amount},0)*1 ELSE 0 END ELSE 0 END,0)

ADD_MONTHS(SYSDATE,-1) <---I change this to -2 and -3 to show previous 2 and 3 months as well

I am attempting to avoid doing 12 of these as a CASE WHEN posting period = P1 2021 THEN amount etc etc so we can have more of a rolling sales/quantity search.

Does not seem like NetSuite likes having to pull a point in time value, it likes to base searches/reports from the time it is run. But that could be being new'ish to NetSuite as we converted a few months ago.

Output of the saved search

Results with grouping and summarizing


问:
Branch Policy: Require atleast 1 Approval from specified approvers
We have 6 people on the project team: 1 Tech-lead and 1 Assistant Tech-lead.

In our branch policy we want to require that only the Tech-lead or Assistant Tech-lead can approve the pull request. We only need approval from one of them to avoid a bottleneck if the other one is on leave.

The problem is there are only 2 choices in the branch policy settings:

Specifying the number of required approvers (which will not work since normal developers would be able to approve as well)

Specifying the actual person to approve (which will not work since both of them will be required and cause a bottleneck when one is on leave)

Can someone please point us in the right direction?

答:
for those who are on Bitbucket:

These are available under Repository Settings->Workflow->Branch Permissions


问:
Django Admin change page: How can I put the save button set on the left, and delete button on the right?
Currently, I have the default setting.

How can I switch the positions of the save button sets and delete button while not affecting the mobile css layout (which I like to remain as itself)? What is the best way doing it?

Thank you!

答:
In templates/admin/base_site.html,

```<code>{% extends "admin/base_site.html" %}
{% load static %}

{% block extrahead %}
    <link rel="stylesheet" href="{% static 'css/admin/base.css' %}">
{% endblock %}
</code>```

In static/css/admin/base.css,

```<code>.submit-row p.deletelink-box {
    float: right;
}

.submit-row [type=submit] {
    float: left !important;
}

.submit-row [name=_save] {
    margin-left: 0;
}
</code>```

Then we will have

Body:
In templates/admin/base_site.html,

{% extends "admin/base_site.html" %}
{% load static %}

{% block extrahead %}
    <link rel="stylesheet" href="{% static 'css/admin/base.css' %}">
{% endblock %}

In static/css/admin/base.css,

.submit-row p.deletelink-box {
    float: right;
}

.submit-row [type=submit] {
    float: left !important;
}

.submit-row [name=_save] {
    margin-left: 0;
}

Then we will have


问:
Lunch Order Billing Menu
Alright so, i have got most of the things working except when i want to order something else like Pizza the Add-On items should change to Pepperoni, Sausage, Olives or Salad the Add-On items should change to  Croutons, Bacon bits, Bread stick but its not changing. Here is what i have got so far:

```<code>enter code here public partial class Form1 : Form
{
    decimal Subtotal;
    decimal Tax = 0.0775m;
    decimal OrderTotal;

    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        decimal add = 0m;
        if (chk1.Checked)
        {
            add++;
        }
        if (chk2.Checked)
        {
            add++;
        }
        if (chk3.Checked)
        {
            add++;
        }
        if (rdoHamburger.Checked)
        {
            decimal Hamburger = Convert.ToDecimal(rdoHamburger.Checked);
            Hamburger = 6.95m;

            Subtotal = Hamburger + (add * .75m);
            Tax = Subtotal * 0.0775m;
            OrderTotal = Tax + Subtotal;

            textBox1.Text = Subtotal.ToString("c");
            textBox2.Text = Tax.ToString("c");
            textBox3.Text = OrderTotal.ToString("c");

        }
        else if (rdoPizza.Checked)
        {

            decimal Pizza = Convert.ToDecimal(rdoPizza.Checked);
            Pizza = 5.95m;

            Subtotal = Pizza + (add * .50m);

            Tax = Subtotal * 0.00775m;

            OrderTotal = Tax + Subtotal;

            textBox1.Text = Subtotal.ToString("c");
            textBox2.Text = Tax.ToString("c");
            textBox3.Text = OrderTotal.ToString("c");

        }
        else if (rdoSalad.Checked)
        {

            decimal salad = Convert.ToDecimal(rdoSalad.Checked);
            salad = 4.95m;

            Subtotal = salad + (add * .25m);

            Tax = Subtotal * 0.0775m;
            OrderTotal = Tax + Subtotal;
            textBox1.Text = Subtotal.ToString("c");
            textBox2.Text = Tax.ToString("c");
            textBox3.Text = OrderTotal.ToString("c");
        }
    }

    private void groupBox1_Enter(object sender, EventArgs e)
    {
        if (rdoHamburger.Checked)
        {
            gbxAddOnItems.Text = "Add-on items ($.75 each)";
            chk1.Text = "Lettuce, tomato and ketchup";
            chk2.Text = "Ketchup , mustard and mayo";
            chk3.Text = "French fries";

            chk1.Checked = false;
            chk2.Checked = false;
            chk3.Checked = false;

            textBox1.Clear();
            textBox2.Clear();
            textBox3.Clear();

        }
        else if (rdoPizza.Checked)
        {
            gbxAddOnItems.Text = "Add-on items ($.50 each)";
            chk1.Text = "Pepperoni";
            chk2.Text = "Sausage";
            chk3.Text = "Olives";

            chk1.Checked = false;
            chk2.Checked = false;
            chk3.Checked = false;

            textBox1.Clear();
            textBox2.Clear();
            textBox3.Clear();

        }
        else if (rdoSalad.Checked)
        {
            gbxAddOnItems.Text = "Add-on items ($.25 each)";
            chk1.Text = "Croutons";
            chk2.Text = "Bacon bits";
            chk3.Text = "Bread Sticks";

            chk1.Checked = false;
            chk2.Checked = false;
            chk3.Checked = false;

            textBox1.Clear();
            textBox2.Clear();
            textBox3.Clear();
        }
        textBox1.Clear();
        textBox2.Clear();
        textBox3.Clear();
    }

    private void button2_Click(object sender, EventArgs e)
    {
        string message = "Thank You for Using Our Service!\n Would You Like use our service again?";
        DialogResult button =
            MessageBox.Show(message, "Dear Customer",
            MessageBoxButtons.YesNo,
            MessageBoxIcon.Information);

        if (button == DialogResult.No)
        {
            this.Close();
        }
        if (button == DialogResult.Yes)
        {
            MessageBox.Show("Thank You!! \n We Hope you will come Soon!", "Greeting      Message");
            this.Close();
        }

    }
}
</code>```

...

I would be grateful if anyone could help have 2 days left.

答: Have you tried this.refresh() or Application.DoEvents()?</p>

Title: Lunch Order Billing Menu

Body:
Alright so, i have got most of the things working except when i want to order something else like Pizza the Add-On items should change to Pepperoni, Sausage, Olives or Salad the Add-On items should change to  Croutons, Bacon bits, Bread stick but its not changing. Here is what i have got so far:

enter code here public partial class Form1 : Form
{
    decimal Subtotal;
    decimal Tax = 0.0775m;
    decimal OrderTotal;

    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        decimal add = 0m;
        if (chk1.Checked)
        {
            add++;
        }
        if (chk2.Checked)
        {
            add++;
        }
        if (chk3.Checked)
        {
            add++;
        }
        if (rdoHamburger.Checked)
        {
            decimal Hamburger = Convert.ToDecimal(rdoHamburger.Checked);
            Hamburger = 6.95m;

            Subtotal = Hamburger + (add * .75m);
            Tax = Subtotal * 0.0775m;
            OrderTotal = Tax + Subtotal;

            textBox1.Text = Subtotal.ToString("c");
            textBox2.Text = Tax.ToString("c");
            textBox3.Text = OrderTotal.ToString("c");

        }
        else if (rdoPizza.Checked)
        {

            decimal Pizza = Convert.ToDecimal(rdoPizza.Checked);
            Pizza = 5.95m;

            Subtotal = Pizza + (add * .50m);

            Tax = Subtotal * 0.00775m;

            OrderTotal = Tax + Subtotal;

            textBox1.Text = Subtotal.ToString("c");
            textBox2.Text = Tax.ToString("c");
            textBox3.Text = OrderTotal.ToString("c");

        }
        else if (rdoSalad.Checked)
        {

            decimal salad = Convert.ToDecimal(rdoSalad.Checked);
            salad = 4.95m;

            Subtotal = salad + (add * .25m);

            Tax = Subtotal * 0.0775m;
            OrderTotal = Tax + Subtotal;
            textBox1.Text = Subtotal.ToString("c");
            textBox2.Text = Tax.ToString("c");
            textBox3.Text = OrderTotal.ToString("c");
        }
    }

    private void groupBox1_Enter(object sender, EventArgs e)
    {
        if (rdoHamburger.Checked)
        {
            gbxAddOnItems.Text = "Add-on items ($.75 each)";
            chk1.Text = "Lettuce, tomato and ketchup";
            chk2.Text = "Ketchup , mustard and mayo";
            chk3.Text = "French fries";

            chk1.Checked = false;
            chk2.Checked = false;
            chk3.Checked = false;

            textBox1.Clear();
            textBox2.Clear();
            textBox3.Clear();

        }
        else if (rdoPizza.Checked)
        {
            gbxAddOnItems.Text = "Add-on items ($.50 each)";
            chk1.Text = "Pepperoni";
            chk2.Text = "Sausage";
            chk3.Text = "Olives";

            chk1.Checked = false;
            chk2.Checked = false;
            chk3.Checked = false;

            textBox1.Clear();
            textBox2.Clear();
            textBox3.Clear();

        }
        else if (rdoSalad.Checked)
        {
            gbxAddOnItems.Text = "Add-on items ($.25 each)";
            chk1.Text = "Croutons";
            chk2.Text = "Bacon bits";
            chk3.Text = "Bread Sticks";

            chk1.Checked = false;
            chk2.Checked = false;
            chk3.Checked = false;

            textBox1.Clear();
            textBox2.Clear();
            textBox3.Clear();
        }
        textBox1.Clear();
        textBox2.Clear();
        textBox3.Clear();
    }

    private void button2_Click(object sender, EventArgs e)
    {
        string message = "Thank You for Using Our Service!\n Would You Like use our service again?";
        DialogResult button =
            MessageBox.Show(message, "Dear Customer",
            MessageBoxButtons.YesNo,
            MessageBoxIcon.Information);

        if (button == DialogResult.No)
        {
            this.Close();
        }
        if (button == DialogResult.Yes)
        {
            MessageBox.Show("Thank You!! \n We Hope you will come Soon!", "Greeting      Message");
            this.Close();
        }

    }
}

...

I would be grateful if anyone could help have 2 days left.


问:
Installing --global windows-build-tools never completes
I am trying to install --global windows-build-tools by running below command

npm install --global windows-build-tools -verbose

No matter if I try through PowerShell or CMD (both as Administrator), the installation gets stuck in the same step.

npm info run windows-build-tools@5.2.2 postinstall node_modules/windows-build-tools node ./dist/index.js
[##################] | reify:resolve: info run windows-build-tools@5.2.2 postinstall node_modules/windows-build-tools node ./dist/index.js

Is there a reason why this might not complete?

答:
If you're having trouble installing windows-build-tools (which I had a problem with recently), you should roll back to version 4.0.0.

Run PowerShell as Administrator, and then type in the following command (assuming you have node and npm installed).

```<code>npm install --global windows-build-tools@4.0.0
</code>```

This process can take some time, so please be patient.

Built-in Node.js Build Tools

There are built-in Node.js build tools, so it is recommended to use this. In fact, if you go on the npm or GitHub page of the windows-build-tools package, it will say that you should use the Node.js build tools.

To do this, go to the official Node.js download website, and download the LTS version. Then, run the installer. At a point in the installation, it will have a checkbox that says Automatically install the recommended tools. Make sure to check that!

When you install it, it will also install Chocolatey, and install the build tools like the windows-build-tools package.

Even though both of these work, it is recommended to use the Node.js built tools!

Body:
If you're having trouble installing windows-build-tools (which I had a problem with recently), you should roll back to version 4.0.0.

Run PowerShell as Administrator, and then type in the following command (assuming you have node and npm installed).

npm install --global windows-build-tools@4.0.0

This process can take some time, so please be patient.

Built-in Node.js Build Tools

There are built-in Node.js build tools, so it is recommended to use this. In fact, if you go on the npm or GitHub page of the windows-build-tools package, it will say that you should use the Node.js build tools.

To do this, go to the official Node.js download website, and download the LTS version. Then, run the installer. At a point in the installation, it will have a checkbox that says Automatically install the recommended tools. Make sure to check that!

When you install it, it will also install Chocolatey, and install the build tools like the windows-build-tools package.

Even though both of these work, it is recommended to use the Node.js built tools!


问:
Change style to individual item React-Hooks
I want to create a button that when you click it opens a navbar with different colors that when the user presses one of the colors, the navbar is closed and the button it self take the color the user clicked on.

my code works, but I have different outcomes then what I expected

this is the outcome

the green dots all changed at once, i want that  only the dot on the item i clicked will change color

this is the code

    const colorLevelArr = ["rgb(236, 77, 77)", "rgb(241, 153, 70)", "rgb(255, 253, 151)", "rgb(147, 241, 135)","rgb(132, 220, 255)"];
    const [colorLevel, setColorLevel] = useState([]);
    const [colorLevelOpen, setcolorLevelOpen] = useState(null);

    const toggelColorLevel = (item) => {
    setcolorLevelOpen(preOpen => preOpen === item ? null : item)
}
const changeColorLevel = (index, item) => {
    setColorLevel(colorLevelArr[index])
    setcolorLevelOpen(preOpen => preOpen === item ? null : item)
}```
</div>
</div>
</p>
<p>and this is the code for the button</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code><button className="color_level_container"
onClick={() => toggelColorLevel(item)}
style={{
  backgroundColor:`${colorLevel}`,
      }}>
   {colorLevelOpen === item && (
   <div className="color_btn_container">
           {colorLevelArr.map((colorLevel, index)=>{
               return (
                  <div onClick={()=>{
                      toggelColorLevel(item)
                      changeColorLevel(index, item)
                      }
                  }
                   style={{
                       borderRadius:"100%",
                       border:"1px solid black",
                       width:"15px",
                       height:"15px",
                       backgroundColor:`${colorLevel}`,
                   }}>
                  </div>
               )
           })}
        </div>
        )}

</button></code>```

if someone can help me understand how to do it right,

and that the only color change  will be to the item I pressed

Thank you in advance

答:
it looks like you are using one state for the color, and use it for all the items.
the easiest way to fix it will be to create a different state for each button, and by so, each one will have its own color. this can be done by creating a component for the button which holds the state for the color, and when state changes, the color of the current component will change accordingly and wont affect the other button components.

I wrote a small example just for you to understand the idea:

const colorsList = ['red', 'yellow', 'blue', 'green'];

const App = () => {
  return (

      <ChangingColorButton />
      <ChangingColorButton />
      <ChangingColorButton />
      <ChangingColorButton />

  );
};

const ChangingColorButton = () => {
  const [color, setColor] = useState('black');

  return (
    <button
      onClick={() => setColor(colorsList[Math.floor(Math.random() * 3) + 1])}
      style={{ backgroundColor: color, marginRight: '8px' }}>
      Click to change color
    </button>
  );
};```

as you can see, i have a list of color and by clicking each button its background color change to random color form the list.

This example demonstrate how you can control each color for each button separately.

Body:
I want to create a button that when you click it opens a navbar with different colors that when the user presses one of the colors, the navbar is closed and the button it self take the color the user clicked on.

my code works, but I have different outcomes then what I expected

this is the outcome

the green dots all changed at once, i want that  only the dot on the item i clicked will change color

this is the code

    const colorLevelArr = ["rgb(236, 77, 77)", "rgb(241, 153, 70)", "rgb(255, 253, 151)", "rgb(147, 241, 135)","rgb(132, 220, 255)"];
    const [colorLevel, setColorLevel] = useState([]);
    const [colorLevelOpen, setcolorLevelOpen] = useState(null);

    const toggelColorLevel = (item) => {
    setcolorLevelOpen(preOpen => preOpen === item ? null : item)
}
const changeColorLevel = (index, item) => {
    setColorLevel(colorLevelArr[index])
    setcolorLevelOpen(preOpen => preOpen === item ? null : item)
}

and this is the code for the button

<button className="color_level_container"
onClick={() => toggelColorLevel(item)}
style={{
  backgroundColor:`${colorLevel}`,
      }}>
   {colorLevelOpen === item && (

           {colorLevelArr.map((colorLevel, index)=>{
               return (

{
                      toggelColorLevel(item)
                      changeColorLevel(index, item)
                      }
                  }
                   style={{
                       borderRadius:"100%",
                       border:"1px solid black",
                       width:"15px",
                       height:"15px",
                       backgroundColor:`${colorLevel}`,
                   }}>

               )
           })}

        )}

</button>

if someone can help me understand how to do it right,

and that the only color change  will be to the item I pressed

Thank you in advance

Body:
it looks like you are using one state for the color, and use it for all the items.
the easiest way to fix it will be to create a different state for each button, and by so, each one will have its own color. this can be done by creating a component for the button which holds the state for the color, and when state changes, the color of the current component will change accordingly and wont affect the other button components.

I wrote a small example just for you to understand the idea:

const colorsList = ['red', 'yellow', 'blue', 'green'];

const App = () => {
  return (
    <div style={{ margin: '100px' }}>
      <ChangingColorButton />
      <ChangingColorButton />
      <ChangingColorButton />
      <ChangingColorButton />
    </div>
  );
};

const ChangingColorButton = () => {
  const [color, setColor] = useState('black');

  return (
    <button
      onClick={() => setColor(colorsList[Math.floor(Math.random() * 3) + 1])}
      style={{ backgroundColor: color, marginRight: '8px' }}>
      Click to change color
    </button>
  );
};

as you can see, i have a list of color and by clicking each button its background color change to random color form the list.

This example demonstrate how you can control each color for each button separately.


问:
Convert this SQL Query to LINQ Query
I need to convert this SQL Query to LINQ Query, also I need to expose the SQL Select properties:

```<code>SELECT Problem.ProblemID, ProblemFactory.ObjectiveID, Objective.Name, ProblemFactory.Time, ProblemType.ProblemTypeName, ProblemFactory.OperationID,
                     ProblemFactory.Range1ID, ProblemFactory.Range2ID, ProblemFactory.Range3ID, ProblemFactory.Range4ID,
                     ProblemFactory.MissingNumber
FROM Problem INNER JOIN ProblemFactory ON Problem.ProblemFactoryID = ProblemFactory.ProblemFactoryID
             INNER JOIN ProblemType ON ProblemFactory.ProblemTypeID = ProblemType.ProblemTypeID
             INNER JOIN Objective ON Objective.ObjectiveID = ProblemFactory.ObjectiveID
</code>```

UPDATE 1:

This is what I have:

```<code>        var query = from problem in dc.Problem2s
                    from factory
                    in dc.ProblemFactories
                         .Where(v => v.ProblemFactoryID == problem.ProblemFactoryID)
                         .DefaultIfEmpty()
                    from ...
</code>```

And I'm using this example: What is the syntax for an inner join in LINQ to SQL?

答:
One of the benefits of an ORM like Linq-to-SQL is that we don't have to flatten our data to retrieve it from the database.  If you map your objects in the designer (i.e. if you have their relationships mapped), you should be able to retrieve just the Problems and then get their associated properties as required...

```<code>var problems = from problem in dc.Problem2s select problem;

foreach (var problem in problems)
{
    // you can work with the problem, its objective, and its problem type.
    problem.DoThings();
    var objective = problem.Objective;
    var type = problem.ProblemType;
}
</code>```

Thus you retain a logical data structure in your data layer, rather than anonymous types that can't easily be passed around.

Title: Convert this SQL Query to LINQ Query

Body:
I need to convert this SQL Query to LINQ Query, also I need to expose the SQL Select properties:

SELECT Problem.ProblemID, ProblemFactory.ObjectiveID, Objective.Name, ProblemFactory.Time, ProblemType.ProblemTypeName, ProblemFactory.OperationID,
                     ProblemFactory.Range1ID, ProblemFactory.Range2ID, ProblemFactory.Range3ID, ProblemFactory.Range4ID,
                     ProblemFactory.MissingNumber
FROM Problem INNER JOIN ProblemFactory ON Problem.ProblemFactoryID = ProblemFactory.ProblemFactoryID
             INNER JOIN ProblemType ON ProblemFactory.ProblemTypeID = ProblemType.ProblemTypeID
             INNER JOIN Objective ON Objective.ObjectiveID = ProblemFactory.ObjectiveID

UPDATE 1:

This is what I have:

        var query = from problem in dc.Problem2s
                    from factory
                    in dc.ProblemFactories
                         .Where(v => v.ProblemFactoryID == problem.ProblemFactoryID)
                         .DefaultIfEmpty()
                    from ...

And I'm using this example: What is the syntax for an inner join in LINQ to SQL?

Body:
One of the benefits of an ORM like Linq-to-SQL is that we don't have to flatten our data to retrieve it from the database.  If you map your objects in the designer (i.e. if you have their relationships mapped), you should be able to retrieve just the Problems and then get their associated properties as required...

var problems = from problem in dc.Problem2s select problem;

foreach (var problem in problems)
{
    // you can work with the problem, its objective, and its problem type.
    problem.DoThings();
    var objective = problem.Objective;
    var type = problem.ProblemType;
}

Thus you retain a logical data structure in your data layer, rather than anonymous types that can't easily be passed around.


问:
Not able to set/receive cookies cross-domain using Netlify and Heroku
I have run into the issue where I cannot set the cookie in the browser, due to the client being hosted at Netlify and server at Heroku. It worked fine on localhost, so it seems it has something to do with it being cross-domain now.

Having read multiple posts on this it seems like it might have to do with cors or how I'm setting the cookies to begin with.

I read somewhere that it might help adding secure: true and sameSite: "none" when setting the cookie, so I added them but it didn't help. I also have tried adding domain into the cookie when setting it, but it also didn't help unfortunately.

I'm using Chrome and have changed the setting from blocking third party cookies with icognito to allow all cookies, as I have read that this might be an issue sometimes. However it did not yield any new results either.

I have also read that it might require a proxy for whatever reason or that it could be solved by hosting both client and server on Heroku. I would prefer not having to do any of these things if possible, but any ideas are welcome.

Server side with Node js (express) hosted on Heroku:

```<code>const express = require("express");
const app = express();
require("dotenv").config();
const cors = require("cors");
const mysql = require("mysql");
const jwt = require("jsonwebtoken");
const cookieParser = require("cookie-parser");

// port for heroku if needed
const PORT = 3001;

// app objects instantiated on creation of the express server
app.use(
  cors({
    origin: [
      "https://examples.netlify.app",
      "http://localhost:3000",
    ],
    methods: ["GET", "POST", "DELETE"],
    credentials: true,
  })
);
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cookieParser());

/*
 * Handel user login
 */
app.post("/sign-in", (req, res) => {
  const { email, password } = req.body;

  sqlSelectAllUsers = "SELECT * FROM user_db WHERE email = ?";
  db.query(sqlSelectAllUsers, [email], (err, user) => {
    if (err) {
      res.send({ err: err });
    }

    if (user && user.length > 0) {
      // given the email check if the password is correct

      bcrypt.compare(password, user[0].password, (err, compareUser) => {
        if (compareUser) {
          //req.session.email = user;
          // create access token
          const accessToken = createAccessToken(user[0]);
          const refreshToken = createRefreshToken(user[0]);
          // create cookie and store it in users browser
          res.cookie("access-token", accessToken, {
            maxAge: 1000 * 60 * 30, // 30 min
            httpOnly: true, // hinder doing document.cookies as it will be httpOnly which will make it more safe
            secure: true,
            domain: "https://examples.netlify.app/",
            sameSite: "none",
          });
          res.cookie("refresh-token", refreshToken, {
            maxAge: 2.63e9, // approx 1 month
            httpOnly: true,
            secure: true,
            domain: "https://examples.netlify.app/",
            sameSite: "none",
          });

          // update refresh token in database
          const sqlUpdateToken =
            "UPDATE user_db SET refresh_token = ? WHERE email = ?";
          db.query(
            sqlUpdateToken,
            [refreshToken, user[0].email],
            (err, result) => {
              if (err) {
                res.send(err);
              }
              res.sendStatus(200);
            }
          );
        } else {
          res.send({ message: "Wrong email or password" });
        }
      });
    } else {
      res.send({ message: "Wrong email or password" });
    }
  });
});

app.listen(process.env.PORT || PORT, () => {
  console.log(`Server running on port ${PORT}`);
});
</code>```

Client side with React hosted on Netlify:

```<code>  export default function SignIn() {
  const history = useHistory();

  const handleSubmit = (event) => {
    event.preventDefault();
    const data = new FormData(event.currentTarget);
    // eslint-disable-next-line no-console
    axios
      .post(
        "https://example.herokuapp.com/sign-in",
        {
          email: data.get("email"),
          password: data.get("password"),
        },
        { withCredentials: "true" }
      )
      .then((response) => {
        //check if good response then give user a token for valid login
        if (response.data === "OK") {
          history.push("/");
          history.go(0);
        }
      });
  };
}

</code>```

答:
I ran into this issue a while ago and the short answer is:
Heroku won't set cookies for the domain *.herokuapp.com, thus making it impossible to use Netlify or other hostings for your frontend if your app depends on cookies. This is because herokuapp.com is included in the Mozilla Foundation’s Public Suffix List.

There's nothing code-wise that you can do about this.

If you want to try something, the solution I found (working with an Express Server and an Angular frontend) was to add a static route/folder to the Express Server where I would put the files generated by building the Angular app (the ng build --configuration production command). When you get those files, you git add them and make the push with the Heroku CLI.

By doing so, Heroku builds the Express Server, and the files you built beforehand with the Angular CLI are all hosted in the Heroku dyno. That way, the cookie gets set because is no longer cross-domain and the app works.

More information about why Heroku prevents this in this link of their documentation:
https://devcenter.heroku.com/articles/cookies-and-herokuapp-com

Edit: forgot to mention that my app used cookies because it implemented the "Local Strategy" of the Passport library. I didn't write any code to deal with cookies, but needed the hosting to be able to set them for my app to work.

Body:
I have run into the issue where I cannot set the cookie in the browser, due to the client being hosted at Netlify and server at Heroku. It worked fine on localhost, so it seems it has something to do with it being cross-domain now.

Having read multiple posts on this it seems like it might have to do with cors or how I'm setting the cookies to begin with.

I read somewhere that it might help adding secure: true and sameSite: "none" when setting the cookie, so I added them but it didn't help. I also have tried adding domain into the cookie when setting it, but it also didn't help unfortunately.

I'm using Chrome and have changed the setting from blocking third party cookies with icognito to allow all cookies, as I have read that this might be an issue sometimes. However it did not yield any new results either.

I have also read that it might require a proxy for whatever reason or that it could be solved by hosting both client and server on Heroku. I would prefer not having to do any of these things if possible, but any ideas are welcome.

Server side with Node js (express) hosted on Heroku:

const express = require("express");
const app = express();
require("dotenv").config();
const cors = require("cors");
const mysql = require("mysql");
const jwt = require("jsonwebtoken");
const cookieParser = require("cookie-parser");

// port for heroku if needed
const PORT = 3001;

// app objects instantiated on creation of the express server
app.use(
  cors({
    origin: [
      "https://examples.netlify.app",
      "http://localhost:3000",
    ],
    methods: ["GET", "POST", "DELETE"],
    credentials: true,
  })
);
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cookieParser());

/*
 * Handel user login
 */
app.post("/sign-in", (req, res) => {
  const { email, password } = req.body;

  sqlSelectAllUsers = "SELECT * FROM user_db WHERE email = ?";
  db.query(sqlSelectAllUsers, [email], (err, user) => {
    if (err) {
      res.send({ err: err });
    }

    if (user && user.length > 0) {
      // given the email check if the password is correct

      bcrypt.compare(password, user[0].password, (err, compareUser) => {
        if (compareUser) {
          //req.session.email = user;
          // create access token
          const accessToken = createAccessToken(user[0]);
          const refreshToken = createRefreshToken(user[0]);
          // create cookie and store it in users browser
          res.cookie("access-token", accessToken, {
            maxAge: 1000 * 60 * 30, // 30 min
            httpOnly: true, // hinder doing document.cookies as it will be httpOnly which will make it more safe
            secure: true,
            domain: "https://examples.netlify.app/",
            sameSite: "none",
          });
          res.cookie("refresh-token", refreshToken, {
            maxAge: 2.63e9, // approx 1 month
            httpOnly: true,
            secure: true,
            domain: "https://examples.netlify.app/",
            sameSite: "none",
          });

          // update refresh token in database
          const sqlUpdateToken =
            "UPDATE user_db SET refresh_token = ? WHERE email = ?";
          db.query(
            sqlUpdateToken,
            [refreshToken, user[0].email],
            (err, result) => {
              if (err) {
                res.send(err);
              }
              res.sendStatus(200);
            }
          );
        } else {
          res.send({ message: "Wrong email or password" });
        }
      });
    } else {
      res.send({ message: "Wrong email or password" });
    }
  });
});

app.listen(process.env.PORT || PORT, () => {
  console.log(`Server running on port ${PORT}`);
});

Client side with React hosted on Netlify:

  export default function SignIn() {
  const history = useHistory();

  const handleSubmit = (event) => {
    event.preventDefault();
    const data = new FormData(event.currentTarget);
    // eslint-disable-next-line no-console
    axios
      .post(
        "https://example.herokuapp.com/sign-in",
        {
          email: data.get("email"),
          password: data.get("password"),
        },
        { withCredentials: "true" }
      )
      .then((response) => {
        //check if good response then give user a token for valid login
        if (response.data === "OK") {
          history.push("/");
          history.go(0);
        }
      });
  };
}


问:
SupaBase Public URL - How to show all users avatar?
Framework: Next.js with SupaBase

Im trying to get all users avatar that are stored in a column in a table -> "Profiles"

I only get the image name "placeholder.png", how do I get the public URL, and map over it for each user?

This is my code

function Brugere({ profiler, url }) {
    return (

          {console.log(profiler)}
          {profiler.map((e, index) => (

{e.username}

          ))}

    );
}

export default Brugere;

export async function getServerSideProps() {
    const { data: profiler, error } = await supabase.from("profiles").select("*");

      {
        error ? console.log(error) : console.log(profiler);
      }

      return {
        props: {
          profiler,
        },
    };
}
```

Result:

答:
The bucket in SupaBase wasn't public!

You can check this by looking at you Bucket as seen here.

(Make it public, by hovering the bucket and clicket the 3 dots.!)

Body:
Framework: Next.js with SupaBase

Im trying to get all users avatar that are stored in a column in a table -> "Profiles"

I only get the image name "placeholder.png", how do I get the public URL, and map over it for each user?

This is my code

function Brugere({ profiler, url }) {
    return (

          {console.log(profiler)}
          {profiler.map((e, index) => (

{e.username}

          ))}

    );
}

export default Brugere;

export async function getServerSideProps() {
    const { data: profiler, error } = await supabase.from("profiles").select("*");

      {
        error ? console.log(error) : console.log(profiler);
      }

      return {
        props: {
          profiler,
        },
    };
}

Result:


答:
If you are wanting to load a list of libraries, then you could put the list into read.table, then turn it into a list, then use lapply to load all libraries.

```<code>read.table(text = "
  base
  compiler
  datasets
  graphics
  grDevices
  grid
  methods
  parallel
  splines
  stats
  stats4
  tcltk
  tools
  translations
  ") %>%
  .[,1] %>%
  lapply(., require, character.only = TRUE)
</code>```

Or if you are wanting a quick way to add quotes and commas to create a vector, then you can use a combination of scan and dput.

```<code>dput(scan(text = "
  base
  compiler
  datasets
  graphics
  grDevices
  grid
  methods
  parallel
  splines
  stats
  stats4
  tcltk
  tools
  translations
  ", what=""))

c("base", "compiler", "datasets", "graphics", "grDevices", "grid",
"methods", "parallel", "splines", "stats", "stats4", "tcltk",
"tools", "translations")
</code>```

This could also be piped into lapply too:

```<code>dput(scan(text = "
  base
  compiler
  datasets
  graphics
  grDevices
  grid
  methods
  parallel
  splines
  stats
  stats4
  tcltk
  tools
  translations
  ", what="")) %>%
  lapply(., require, character.only = TRUE)
</code>```

Title: Is there an easy way to enter/edit code in Rstudio? Avoiding repetition?

Body:
If you are wanting to load a list of libraries, then you could put the list into read.table, then turn it into a list, then use lapply to load all libraries.

read.table(text = "
  base
  compiler
  datasets
  graphics
  grDevices
  grid
  methods
  parallel
  splines
  stats
  stats4
  tcltk
  tools
  translations
  ") %>%
  .[,1] %>%
  lapply(., require, character.only = TRUE)

Or if you are wanting a quick way to add quotes and commas to create a vector, then you can use a combination of scan and dput.

dput(scan(text = "
  base
  compiler
  datasets
  graphics
  grDevices
  grid
  methods
  parallel
  splines
  stats
  stats4
  tcltk
  tools
  translations
  ", what=""))

c("base", "compiler", "datasets", "graphics", "grDevices", "grid",
"methods", "parallel", "splines", "stats", "stats4", "tcltk",
"tools", "translations")

This could also be piped into lapply too:

dput(scan(text = "
  base
  compiler
  datasets
  graphics
  grDevices
  grid
  methods
  parallel
  splines
  stats
  stats4
  tcltk
  tools
  translations
  ", what="")) %>%
  lapply(., require, character.only = TRUE)


问:
Problem with sphinx search when searching by second word in phrase
I have a sphinx index set up with a field that has the following data:

```<code>James Smith
</code>```

When I search for 'James' or 'James Smi', it will return the proper result, but when I search for 'James S' it doesn't return anything.

I also have a real time index (RT) and it has the same data in it and I'm able to search for 'James S' and it returns the proper result.

Here is what I have in my config file for the main index

```<code>min_word_len            = 1
html_strip              = 0
min_infix_len           = 2
expand_keywords   = 1
min_prefix_len    = 1
index_exact_words = 1
</code>```

答: Min_infix_len=2 means part word matches are only going to work for two letter queries or longer. The j does not match in part of word, only a standalone word. Because of min_word_len</p>

Body:
I have a sphinx index set up with a field that has the following data:

James Smith

When I search for 'James' or 'James Smi', it will return the proper result, but when I search for 'James S' it doesn't return anything.

I also have a real time index (RT) and it has the same data in it and I'm able to search for 'James S' and it returns the proper result.

Here is what I have in my config file for the main index

min_word_len            = 1
html_strip              = 0
min_infix_len           = 2
expand_keywords   = 1
min_prefix_len    = 1
index_exact_words = 1


问:
Javascript - I have a problem using toFixed() in (if else)
I am new to javascript.
I'm trying to code a simple program which has 2 variables, each one contains an average number of some calculations, and using if else it should print the variable which contains the higher average as the winner.

without using toFixed() there is no problem, the higher variable is the winner and its printed out, but when I use toFixed(), it prints the lower variable, not the higher one. why is that?
picture of the problem

here is the code:

const avgDolphins = ((96 + 108 + 89) / 3).toFixed(2);
const avgKoalas = ((88 + 91 + 911) / 3).toFixed(2);
console.log(`dolphins = ${avgDolphins} \nkoalas = ${avgKoalas}`)

if (avgDolphins > avgKoalas) {
    console.log(`Team Dolphins WON! with ${avgDolphins} Average score!`);
} else if (avgKoalas > avgDolphins) {
    console.log(`Team Koalas WON! with ${avgKoalas} Average score!`);
} else {
    console.log(`DRAW! Both teams got the same average score which is ${avgKoalas}`);
}
```

答:
Both .toPrecision(2) (Reference) and .toFixed(2) (Reference) will return a string. You can use a parseFloat arount your calculation to fix this.

So the resulting code will look like this:

const avgDolphins = parseFloat(((96 + 108 + 89) / 3).toFixed(2));
const avgKoalas = parseFloat(((88 + 91 + 911) / 3).toFixed(2));
console.log(`dolphins = ${avgDolphins} \nkoalas = ${avgKoalas}`)

if (avgDolphins > avgKoalas) {
    console.log(`Team Dolphins WON! with ${avgDolphins} Average score!`);
} else if (avgKoalas > avgDolphins) {
    console.log(`Team Koalas WON! with ${avgKoalas} Average score!`);
} else {
    console.log(`DRAW! Both teams got the same average score which is ${avgKoalas}`);
}
```


问:
how to put ad banner in j2me using lwuit?
I want to put a advertisement banner at the bottom of the screen of my j2me application.
How can i set a container fixed at a position so even if the page is scrolled that specific container will be still visible?
If not some other way to put up a ad banner above or below the command buttons.</p>

答:
Place the add image in a Button, set the layout of the form to BorderLayout and set the form to scrollable false. Place the button in BorderLayout.SOUTH and your content in a Container (that you can set to scrollable Y true) in the center e.g.:

```<code>myForm.setScrollable(false);
Button ad = new Button(adAction);
myForm.setLayout(new BorderLayout());
myForm.addComponent(BorderLayout.SOUTH, ad);
Container actualContent = new Container();
myForm.addComponent(BorderLayout.CENTER, actualContent);
actualContent.setScrollableY(true);
</code>```

Body:
Place the add image in a Button, set the layout of the form to BorderLayout and set the form to scrollable false. Place the button in BorderLayout.SOUTH and your content in a Container (that you can set to scrollable Y true) in the center e.g.:

myForm.setScrollable(false);
Button ad = new Button(adAction);
myForm.setLayout(new BorderLayout());
myForm.addComponent(BorderLayout.SOUTH, ad);
Container actualContent = new Container();
myForm.addComponent(BorderLayout.CENTER, actualContent);
actualContent.setScrollableY(true);


问:
How to use v-if, v-else inside of v-for properly in Vuejs?

<template>

      <BaseAccordian>
        <template v-slot:title>{{ box.name }}</template>
        <template v-slot:content>

 m.boxid == box.boxid && m.paintid == paint.paintid
                )
              "
            >
              <StatusComponent
                :box="box"
                :paint="paint"
                :matchingdata="matchingdata"
              />

        </template>
      </BaseAccordian>

</template>```

When i click of each checkbox, i am loading relevant data from box,paint array. by checking in matchingdata. Array.

Now, i want to show like, if no data found onclick of checkbox, i want to display a message as "no data found"

Issue with the below code is, if i place v-if at top and v-for and v-else data at the last then only few data is displaying

答:
The v-for is rendering for each 'box' in 'boxes', so for each box you should get a:

```<code><BaseAccordian>
  <template v-slot:title>{{ box.name }}</template>
  <template v-slot:content>
    <div v-for="paint in paints" :key="paint.id" class="line">
 {...}
    </div>
  </template>
</BaseAccordian>
</code>```

And for each paint in paints, this should render a div for each paint inside of every box.

The v-if and v-else-if and v-else will render their blocks conditionally on the predicates contained within them. I'm not sure where the array matchingdata comes from in your example, but if it contains an element that has the properties boxid and paintid that match box.boxid and paint.paintid then the predicate of matchingdata.some((m) => m.boxid == box.boxid && m.paintid == paint.paintid) will have been met and the associated div will be rendered; otherwise, the 'v-else' div will be rendered (if it were uncommented).

Your code will loop through each box in boxes, and for each box it will loop through each paint in paints to find an element in matchingdata that looks something like:

{
  boxid: ...,
  paintid: ...,
  ...,
}
```

The v-for and (v-if, v-else-if, v-else) blocks are not connected to each other. v-for represents a loop over which you will render an element for every item in the list. The v-if blocks will conditionally render elements to the page according to the predicates you define.

v-if, v-else-if, and v-else have to appear right after each other to be counted in the same logical block.

Body:
<template>

      <BaseAccordian>
        <template v-slot:title>{{ box.name }}</template>
        <template v-slot:content>

 m.boxid == box.boxid && m.paintid == paint.paintid
                )
              "
            >
              <StatusComponent
                :box="box"
                :paint="paint"
                :matchingdata="matchingdata"
              />

        </template>
      </BaseAccordian>

</template>

When i click of each checkbox, i am loading relevant data from box,paint array. by checking in matchingdata. Array.

Now, i want to show like, if no data found onclick of checkbox, i want to display a message as "no data found"

Issue with the below code is, if i place v-if at top and v-for and v-else data at the last then only few data is displaying

Body:
The v-for is rendering for each 'box' in 'boxes', so for each box you should get a:

<BaseAccordian>
  <template v-slot:title>{{ box.name }}</template>
  <template v-slot:content>
    <div v-for="paint in paints" :key="paint.id" class="line">
 {...}
    </div>
  </template>
</BaseAccordian>

And for each paint in paints, this should render a div for each paint inside of every box.

The v-if and v-else-if and v-else will render their blocks conditionally on the predicates contained within them. I'm not sure where the array matchingdata comes from in your example, but if it contains an element that has the properties boxid and paintid that match box.boxid and paint.paintid then the predicate of matchingdata.some((m) => m.boxid == box.boxid && m.paintid == paint.paintid) will have been met and the associated div will be rendered; otherwise, the 'v-else' div will be rendered (if it were uncommented).

Your code will loop through each box in boxes, and for each box it will loop through each paint in paints to find an element in matchingdata that looks something like:

{
  boxid: ...,
  paintid: ...,
  ...,
}

The v-for and (v-if, v-else-if, v-else) blocks are not connected to each other. v-for represents a loop over which you will render an element for every item in the list. The v-if blocks will conditionally render elements to the page according to the predicates you define.

v-if, v-else-if, and v-else have to appear right after each other to be counted in the same logical block.


问:
useEffect not updating on auth.currentUser change
I want to update my state whenever the user authentication state changes (in my navigation page):

```<code>import {auth} from '../firebase.js' // where auth is initialized with getAuth() from firebase/auth
const Navigation = () => {
    const [isAuthenticated, setIsAuthenticated] = useState(false);
    useEffect(()=>{
        console.log("Here"); // Gets logged on sign out but not on sign in
        setIsAuthenticated(Boolean(auth.currentUser));
    }, [auth.currentUser])
    return ({isAuthenticated ? <SomeComponent /> : <SomeComponent />})
}
</code>```

firebase.js

```<code>import { getAuth } from "firebase/auth";
const auth = getAuth(firebaseApp);
export {auth}
</code>```

Then in my login component I have the signing function which should be and is updating the value of auth.currentUser:

```<code>const signIn = ({ email, password }) => {
    signInWithEmailAndPassword(auth, email, password)
      .then((resp) => {
        console.log(auth.currentUser); // This is working, meaning auth.currentUser value has changed
      })
      .catch((err) => setFirebaseError(err));
};
</code>```

This works and gets executed whenever I sign out, but doesn't execute when a user signs in and I can't figure out why.

I know that the auth.currentUser variable is being updated since I print it out in the sign in function, but for some reason the useEffect does not recognize this and does not fire?

答:
Using auth.currentUser won't work because it's more or less a global variable exposed by firebase which will not trigger any sort of an update in react.

What you should rather do is subscribe to on onAuthStateChanged which will trigger whenever user logs in or out, and then use that to toggle your isAuthenticated flag.

For firebase v9

```<code>import { useState } from "react";
import { getAuth, onAuthStateChanged } from "firebase/auth";

const [isAuthenticated, setIsAuthenticated] = useState(false);

useEffect(() => {
  const auth = getAuth();

  const listener = onAuthStateChanged(auth, async (user) => {
    setIsAuthenticated(!!user);
  });

  return () => {
    listener();
  };
}, []);
</code>```

For firebase v8

```<code>import { useState } from "react";
import firebase from "firebase";

const [isAuthenticated, setIsAuthenticated] = useState(false);

useEffect(() => {
  const listener = firebase.auth().onAuthStateChanged(auth, async (user) => {
    setIsAuthenticated(!!user);
  });

  return () => {
    listener();
  };
}, []);
</code>```

Or even better, you can check out react-firebase-hooks or reactfire which provide a pretty nice set of hooks on top of firebase JS SDK.

Body:
I want to update my state whenever the user authentication state changes (in my navigation page):

import {auth} from '../firebase.js' // where auth is initialized with getAuth() from firebase/auth
const Navigation = () => {
    const [isAuthenticated, setIsAuthenticated] = useState(false);
    useEffect(()=>{
        console.log("Here"); // Gets logged on sign out but not on sign in
        setIsAuthenticated(Boolean(auth.currentUser));
    }, [auth.currentUser])
    return ({isAuthenticated ? <SomeComponent /> : <SomeComponent />})
}

firebase.js

import { getAuth } from "firebase/auth";
const auth = getAuth(firebaseApp);
export {auth}

Then in my login component I have the signing function which should be and is updating the value of auth.currentUser:

const signIn = ({ email, password }) => {
    signInWithEmailAndPassword(auth, email, password)
      .then((resp) => {
        console.log(auth.currentUser); // This is working, meaning auth.currentUser value has changed
      })
      .catch((err) => setFirebaseError(err));
};

This works and gets executed whenever I sign out, but doesn't execute when a user signs in and I can't figure out why.

I know that the auth.currentUser variable is being updated since I print it out in the sign in function, but for some reason the useEffect does not recognize this and does not fire?

Body:
Using auth.currentUser won't work because it's more or less a global variable exposed by firebase which will not trigger any sort of an update in react.

What you should rather do is subscribe to on onAuthStateChanged which will trigger whenever user logs in or out, and then use that to toggle your isAuthenticated flag.

For firebase v9

import { useState } from "react";
import { getAuth, onAuthStateChanged } from "firebase/auth";

const [isAuthenticated, setIsAuthenticated] = useState(false);

useEffect(() => {
  const auth = getAuth();

  const listener = onAuthStateChanged(auth, async (user) => {
    setIsAuthenticated(!!user);
  });

  return () => {
    listener();
  };
}, []);

For firebase v8

import { useState } from "react";
import firebase from "firebase";

const [isAuthenticated, setIsAuthenticated] = useState(false);

useEffect(() => {
  const listener = firebase.auth().onAuthStateChanged(auth, async (user) => {
    setIsAuthenticated(!!user);
  });

  return () => {
    listener();
  };
}, []);

Or even better, you can check out react-firebase-hooks or reactfire which provide a pretty nice set of hooks on top of firebase JS SDK.


问:
AWS Lambda with RDS Postgresql - Unknown Issue
I have been wrestling with this issue for 3 days now and cannot figure out what's wrong.  I set all my login credentials as environment variables in my Lambda function.  My RDS instance is open to publics and security groups also opens the ports for incoming and outgoing.

my PostgresQL code went to a tons of variations, the latest one is from this AWS Lambda NodeJS Connect to RDS Postgres Database

my current lambda code

```<code>const pg = require('pg')
const pool = new pg.Pool()

async function query (q) {
  const client = await pool.connect()
  let res
  try {
    await client.query('BEGIN')
    try {
      res = await client.query(q)
      await client.query('COMMIT')
    } catch (err) {
      await client.query('ROLLBACK')
      throw err
    }
  } finally {
    client.release()
  }
  return res
}

exports.handler = async (event, context, callback) => {
    try {
      const { rows } = await query("select 'thaison' as ")
      console.log(JSON.stringify(rows[0]))
      var response = {
          "statusCode": 200,
          "headers": {
              "Content-Type" : "application/json"
          },
          "body": JSON.stringify(rows),
          "isBase64Encoded": false
      };
      callback(null, response);
    } catch (err) {
      console.log('Database ' + err)
      callback(null, 'Database ' + err);
    }
};
</code>```

I can successfully do a console.log before and after pool.connect().  I can also console.log before client.query() but not after.  The problem is after client.query(), nothing is happening.  I checked Cloudwatch logs and metrics, nothing is on the logs and nothing is reported as errors.  The code must be failing somewhere but I cannot figure out where.  The response is null and I cannot get anything to log after the query, not even in the catch(err) block.  The last thing I did was changed the PG endpoint to something that does not even exist, and I am still not getting any errors.  This thing just silently fail.

What am I doing wrong?

答:
Since you are using Publicly Available = Yes, the DNS Name of the database will resolve to a public IP address. This means that the Lambda function requires Internet access.

This can be done by either NOT attaching the Lambda function to the VPC, or by attaching the Lambda function to a private subnet and then using a NAT Gateway in a public subnet to provide access to the Internet. The Security Group should permit access from 0.0.0.0/0 (which is very bad for security).

The more 'secure' way to configure such a system would be:

Use Publicly Available = No, which will only resolve the DNS Name of the RDS database to a private IP address

Attach the Lambda function to a subnet in the same VPC as the RDS database

Attach a Security Group to the Lambda function (Lambda-SG) that permits default "Allow All" outbound access

Attach a Security Group to the RDS database (RDS-SG) that permits Inbound access on port 5432 (PostgreSQL) with Source = Lambda-SG

That is, the RDS-SG specifically references Lambda-SG in its Inbound rules. This will permit the Lambda function to access the RDS database.

However, please note that the RDS database will only be accessible from within the VPC. You will not be able to connect to it from your own computer on the Internet (because it is more secure now). You can use a jump box with Port Forwarding to connect if desired.

Body:
I have been wrestling with this issue for 3 days now and cannot figure out what's wrong.  I set all my login credentials as environment variables in my Lambda function.  My RDS instance is open to publics and security groups also opens the ports for incoming and outgoing.

my PostgresQL code went to a tons of variations, the latest one is from this AWS Lambda NodeJS Connect to RDS Postgres Database

my current lambda code

const pg = require('pg')
const pool = new pg.Pool()

async function query (q) {
  const client = await pool.connect()
  let res
  try {
    await client.query('BEGIN')
    try {
      res = await client.query(q)
      await client.query('COMMIT')
    } catch (err) {
      await client.query('ROLLBACK')
      throw err
    }
  } finally {
    client.release()
  }
  return res
}

exports.handler = async (event, context, callback) => {
    try {
      const { rows } = await query("select 'thaison' as ")
      console.log(JSON.stringify(rows[0]))
      var response = {
          "statusCode": 200,
          "headers": {
              "Content-Type" : "application/json"
          },
          "body": JSON.stringify(rows),
          "isBase64Encoded": false
      };
      callback(null, response);
    } catch (err) {
      console.log('Database ' + err)
      callback(null, 'Database ' + err);
    }
};

I can successfully do a console.log before and after pool.connect().  I can also console.log before client.query() but not after.  The problem is after client.query(), nothing is happening.  I checked Cloudwatch logs and metrics, nothing is on the logs and nothing is reported as errors.  The code must be failing somewhere but I cannot figure out where.  The response is null and I cannot get anything to log after the query, not even in the catch(err) block.  The last thing I did was changed the PG endpoint to something that does not even exist, and I am still not getting any errors.  This thing just silently fail.

What am I doing wrong?