问:
How do I have in the result a single dictionary searched within a list of dictionaries in mongodb?
I have the following document in the nep_caixa_retaguarda collection

```<code>rs0:PRIMARY> db.atendimento_sara.findOne()
{
    '_id' : ObjectId('5cee9785d1805f2b288a1614'),
    'usu_nu_usuario_abertura' : 511773,
    'cxr_nu_caixa_retaguarda' : 23008369,
    'dataAberturaSP' : ISODate('2019-01-02T00:11:24Z'),
    'caixa' : [
            {
                    'usu_nu_usuario' : 108349,
                    'cax_nu_caixa' : 89792153,
                    'dataAberturaSP' : ISODate('2019-01-02T18:54:45Z')
            },
            {
                    'usu_nu_usuario' : 498100,
                    'cax_nu_caixa' : 89791110,
                    'dataAberturaSP' : ISODate('2019-01-02T15:43:33Z')
            },
            {
                    'usu_nu_usuario' : 511773,
                    'cax_nu_caixa' : 89771306,
                    'dataAberturaSP' : ISODate('2019-01-02T00:11:38Z')
            }
    ]
}
{
    '_id' : ObjectId('6fhj9785d1807f2c289a3616'),
    'usu_nu_usuario_abertura' : 511700,
    'cxr_nu_caixa_retaguarda' : 23008370,
    'dataAberturaSP' : ISODate('2019-01-02T00:15:24Z'),
    'caixa' : [
            {
                    'usu_nu_usuario' : 108300
                    'cax_nu_caixa' : 89792161,
                    'dataAberturaSP' : ISODate('2019-01-02T18:59:45Z')
            },
            {
                    'usu_nu_usuario' : 498103,
                    'cax_nu_caixa' : 89791177,
                    'dataAberturaSP' : ISODate('2019-01-02T15:40:33Z')
            },
            {
                    'usu_nu_usuario' : 511700,
                    'cax_nu_caixa' : 89771350,
                    'dataAberturaSP' : ISODate('2019-01-02T00:27:38Z')
            }
    ]
}
</code>```

I would like to select only the document that has the field 'cax_nu_caixa': 89771306

A tried  db.atendimento_sara.find({'caixa.cax_nu_caixa':89771306},{'cxr_nu_caixa_retaguarda':1,'caixa.cax_nu_caixa':1}).pretty()

returned

```<code>{
    '_id' : ObjectId('5cee9785d1805f2b288a1614'),
    'cxr_nu_caixa_retaguarda' : 23008369,
    'caixa' : [
            {
                    'cax_nu_caixa' : 89792153
            },
            {
                    'cax_nu_caixa' : 89791110
            },
            {
                    'cax_nu_caixa' : 89771306
            },
            {
                    'cax_nu_caixa' : 89788026
            },
            {
                    'cax_nu_caixa' : 89782847
            },
            {
                    'cax_nu_caixa' : 89787922
            },
            {
                    'cax_nu_caixa' : 89788272
            }
    ]
}
</code>```

but I want only this. How I do?

```<code>{
    '_id' : ObjectId('5cee9785d1805f2b288a1614'),
    'cxr_nu_caixa_retaguarda' : 23008369,
    'caixa' : [
            {
                    'cax_nu_caixa' : 89771306
            }
    ]
}
</code>```

And more,
And if I have one more level, as in the case below, where do I want to search for 'attend_nu': 100?

```<code>rs0:PRIMARY> db.atendimento_sara.findOne()
{
'_id' : ObjectId('5cee9785d1805f2b288a1614'),
'usu_nu_usuario_abertura' : 511773,
'cxr_nu_caixa_retaguarda' : 23008369,
'dataAberturaSP' : ISODate('2019-01-02T00:11:24Z'),
'caixa' : [
        {
                'usu_nu_usuario' : 108349,
                'cax_nu_caixa' : 89792153,
                'dataAberturaSP' : ISODate('2019-01-02T18:54:45Z')
                'atendimento': [{
                                                    'atend_nu' : 100,
                                                    'dataInicioSP' : ISODate('2019-01-02T18:54:45Z'),
                                                {
                                                    'atend_nu' : 101,
                                                    'dataInicioSP' : ISODate('2019-01-02T18:54:45Z'),
                                                {
                                                    'atend_nu' : 102,
                                                    'dataInicioSP' : ISODate('2019-01-02T18:54:45Z')

                                             ])
        },
        {
                'usu_nu_usuario' : 498100,
                'cax_nu_caixa' : 89791110,
                'dataAberturaSP' : ISODate('2019-01-02T15:43:33Z')
                'atendimento': [{
                                                    'atend_nu' : 104,
                                                    'dataInicioSP' : ISODate('2019-01-02T18:54:45Z'),
                                                {
                                                    'atend_nu' : 105,
                                                    'dataInicioSP' : ISODate('2019-01-02T18:54:45Z'),
                                                {
                                                    'atend_nu' : 106,
                                                    'dataInicioSP' : ISODate('2019-01-02T18:54:45Z')

                                             ])
        },
        {
                'usu_nu_usuario' : 511773,
                'cax_nu_caixa' : 89771306,
                'dataAberturaSP' : ISODate('2019-01-02T00:11:38Z')
                'atendimento': [{
                                                    'atend_nu' : 107,
                                                    'dataInicioSP' : ISODate('2019-01-02T18:54:45Z'),
                                                {
                                                    'atend_nu' : 108,
                                                    'dataInicioSP' : ISODate('2019-01-02T18:54:45Z'),
                                                {
                                                    'atend_nu' : 109,
                                                    'dataInicioSP' : ISODate('2019-01-02T18:54:45Z')

                                             ])
        }
]
}
</code>```

答:
You need aggregation for that. Try:

db.atendimento_sara.aggregate([
  {
    $match: {
      "caixa.cax_nu_caixa": 89771306
    }
  },
  {
    $unwind: "$caixa"
  },
  {
    $match: {
      "caixa.cax_nu_caixa": 89771306
    }
  },
  {
    $project: {
      cxr_nu_caixa_retaguarda: 1,
      "caixa.cax_nu_caixa": 1
    }
  }
])
```

Body:
I have the following document in the nep_caixa_retaguarda collection

rs0:PRIMARY> db.atendimento_sara.findOne()
{
    '_id' : ObjectId('5cee9785d1805f2b288a1614'),
    'usu_nu_usuario_abertura' : 511773,
    'cxr_nu_caixa_retaguarda' : 23008369,
    'dataAberturaSP' : ISODate('2019-01-02T00:11:24Z'),
    'caixa' : [
            {
                    'usu_nu_usuario' : 108349,
                    'cax_nu_caixa' : 89792153,
                    'dataAberturaSP' : ISODate('2019-01-02T18:54:45Z')
            },
            {
                    'usu_nu_usuario' : 498100,
                    'cax_nu_caixa' : 89791110,
                    'dataAberturaSP' : ISODate('2019-01-02T15:43:33Z')
            },
            {
                    'usu_nu_usuario' : 511773,
                    'cax_nu_caixa' : 89771306,
                    'dataAberturaSP' : ISODate('2019-01-02T00:11:38Z')
            }
    ]
}
{
    '_id' : ObjectId('6fhj9785d1807f2c289a3616'),
    'usu_nu_usuario_abertura' : 511700,
    'cxr_nu_caixa_retaguarda' : 23008370,
    'dataAberturaSP' : ISODate('2019-01-02T00:15:24Z'),
    'caixa' : [
            {
                    'usu_nu_usuario' : 108300
                    'cax_nu_caixa' : 89792161,
                    'dataAberturaSP' : ISODate('2019-01-02T18:59:45Z')
            },
            {
                    'usu_nu_usuario' : 498103,
                    'cax_nu_caixa' : 89791177,
                    'dataAberturaSP' : ISODate('2019-01-02T15:40:33Z')
            },
            {
                    'usu_nu_usuario' : 511700,
                    'cax_nu_caixa' : 89771350,
                    'dataAberturaSP' : ISODate('2019-01-02T00:27:38Z')
            }
    ]
}

I would like to select only the document that has the field 'cax_nu_caixa': 89771306

A tried  db.atendimento_sara.find({'caixa.cax_nu_caixa':89771306},{'cxr_nu_caixa_retaguarda':1,'caixa.cax_nu_caixa':1}).pretty()

returned

{
    '_id' : ObjectId('5cee9785d1805f2b288a1614'),
    'cxr_nu_caixa_retaguarda' : 23008369,
    'caixa' : [
            {
                    'cax_nu_caixa' : 89792153
            },
            {
                    'cax_nu_caixa' : 89791110
            },
            {
                    'cax_nu_caixa' : 89771306
            },
            {
                    'cax_nu_caixa' : 89788026
            },
            {
                    'cax_nu_caixa' : 89782847
            },
            {
                    'cax_nu_caixa' : 89787922
            },
            {
                    'cax_nu_caixa' : 89788272
            }
    ]
}

but I want only this. How I do?

{
    '_id' : ObjectId('5cee9785d1805f2b288a1614'),
    'cxr_nu_caixa_retaguarda' : 23008369,
    'caixa' : [
            {
                    'cax_nu_caixa' : 89771306
            }
    ]
}

And more,
And if I have one more level, as in the case below, where do I want to search for 'attend_nu': 100?

rs0:PRIMARY> db.atendimento_sara.findOne()
{
'_id' : ObjectId('5cee9785d1805f2b288a1614'),
'usu_nu_usuario_abertura' : 511773,
'cxr_nu_caixa_retaguarda' : 23008369,
'dataAberturaSP' : ISODate('2019-01-02T00:11:24Z'),
'caixa' : [
        {
                'usu_nu_usuario' : 108349,
                'cax_nu_caixa' : 89792153,
                'dataAberturaSP' : ISODate('2019-01-02T18:54:45Z')
                'atendimento': [{
                                                    'atend_nu' : 100,
                                                    'dataInicioSP' : ISODate('2019-01-02T18:54:45Z'),
                                                {
                                                    'atend_nu' : 101,
                                                    'dataInicioSP' : ISODate('2019-01-02T18:54:45Z'),
                                                {
                                                    'atend_nu' : 102,
                                                    'dataInicioSP' : ISODate('2019-01-02T18:54:45Z')

                                             ])
        },
        {
                'usu_nu_usuario' : 498100,
                'cax_nu_caixa' : 89791110,
                'dataAberturaSP' : ISODate('2019-01-02T15:43:33Z')
                'atendimento': [{
                                                    'atend_nu' : 104,
                                                    'dataInicioSP' : ISODate('2019-01-02T18:54:45Z'),
                                                {
                                                    'atend_nu' : 105,
                                                    'dataInicioSP' : ISODate('2019-01-02T18:54:45Z'),
                                                {
                                                    'atend_nu' : 106,
                                                    'dataInicioSP' : ISODate('2019-01-02T18:54:45Z')

                                             ])
        },
        {
                'usu_nu_usuario' : 511773,
                'cax_nu_caixa' : 89771306,
                'dataAberturaSP' : ISODate('2019-01-02T00:11:38Z')
                'atendimento': [{
                                                    'atend_nu' : 107,
                                                    'dataInicioSP' : ISODate('2019-01-02T18:54:45Z'),
                                                {
                                                    'atend_nu' : 108,
                                                    'dataInicioSP' : ISODate('2019-01-02T18:54:45Z'),
                                                {
                                                    'atend_nu' : 109,
                                                    'dataInicioSP' : ISODate('2019-01-02T18:54:45Z')

                                             ])
        }
]
}


来源: stackexchange

问:
JavaScript speechSynthesis.speak() without user activation is no longer allowed since M71
I used speechSynthesis API in this way:

```<code>speechSynthesis.speak(new SpeechSynthesisUtterance("hello world"));
</code>```

But right now I get error after update Google Chrome:

[Deprecation] speechSynthesis.speak() without user activation is no
  longer allowed since M71, around December 2018. See
  https://www.chromestatus.com/feature/5687444770914304 for more details
  speechSynthesisMessage @
  application-2c16c437c2795ae01c0a8852e5f8da58dad99d6e17814a31f1eea19922c5ebd2.js:147

How I can fix this issue and ask permission?

答:
I resorted to swal("Click OK to speak").then(() => speakButton.click()); (with https://sweetalert.js.org) -- https://patarapolw.github.io/tts-api/?q=你好&lang=zh-CN&rate=0.8

Note that if (confirm("Click OK to speak")) speakButton.click() doesn't work.

ContentLicense: CC BY-SA 4.0

Body:
I used speechSynthesis API in this way:

speechSynthesis.speak(new SpeechSynthesisUtterance("hello world"));

But right now I get error after update Google Chrome:

[Deprecation] speechSynthesis.speak() without user activation is no
  longer allowed since M71, around December 2018. See
  https://www.chromestatus.com/feature/5687444770914304 for more details
  speechSynthesisMessage @
  application-2c16c437c2795ae01c0a8852e5f8da58dad99d6e17814a31f1eea19922c5ebd2.js:147

How I can fix this issue and ask permission?


问:
Jquery toastr onHidden function
I am using jquery toastr.  So far everything is great. I can display and close toasts fine.
I want to be able to identify each toast uniquely. And use that unique identifier in the onHidden function.   Has anyone done this before? Is the better option to call a jquery on close event for the toastr class or div surrounding the closed toast?  </p>

```<code>    var mes = 'My name is Inigo Montoya.<input type="hidden" id="announcementId" value="1"/>' +
       '<input type="hidden" id="userId" value="'+ userid +'"/> ';

    var mes1 = 'Princess Bride<input type="hidden" id="announcementId2" value="2"/>'+
       '<input type="hidden" id="userId1" value="'+ userid +'"/> ';

    var mes2 = 'Man in Black<input type="hidden" id="announcementId2" value="3"/>'+
       '<input type="hidden" id="userId2" value="'+ userid +'"/> ';

   var mes3 = 'Inconcivable!<input type="hidden" id="announcementId3" value="4"/>'+
       '<input type="hidden" id="userId3" value="'+ userid +'"/> ';

toastr.options = {
  "closeButton": false,
  "debug": false,
  "positionClass": "toast-top-full-width",
  "showDuration": "300",
  "hideDuration": "1000",
  "timeOut": "0",
  "extendedTimeOut": "0",
  "showEasing": "swing",
  "hideEasing": "linear",
  "showMethod": "fadeIn",
  "hideMethod": "fadeOut"
};

toastr.options.onHidden = function(item) {
//GET UNIQUE TOAST ID'S HERE
        var val = 1;//$this.find("#announcemntId").val();
        alert("CLOSED " + item);
}

toastr.error(mes, "First Toast");
toastr.error(mes1, "Second Toast");
toastr.error(mes2, "Third Toast");
toastr.error(mes3, "Fourth Toast");
</code>```

答:
I didn't quite understand these answers, so i am adding my own. I used jquery to create an onclose function, (when someone clicks the toast-close button) like this - </p>

```<code>$('.toast-close-button').click(function() {
*someCodeHere
});
</code>```

ContentLicense: CC BY-SA 3.0

Title: Jquery toastr onHidden function

Body:
I am using jquery toastr.  So far everything is great. I can display and close toasts fine.
I want to be able to identify each toast uniquely. And use that unique identifier in the onHidden function.   Has anyone done this before? Is the better option to call a jquery on close event for the toastr class or div surrounding the closed toast?

    var mes = 'My name is Inigo Montoya.<input type="hidden" id="announcementId" value="1"/>' +
       '<input type="hidden" id="userId" value="'+ userid +'"/> ';

    var mes1 = 'Princess Bride<input type="hidden" id="announcementId2" value="2"/>'+
       '<input type="hidden" id="userId1" value="'+ userid +'"/> ';

    var mes2 = 'Man in Black<input type="hidden" id="announcementId2" value="3"/>'+
       '<input type="hidden" id="userId2" value="'+ userid +'"/> ';

   var mes3 = 'Inconcivable!<input type="hidden" id="announcementId3" value="4"/>'+
       '<input type="hidden" id="userId3" value="'+ userid +'"/> ';

toastr.options = {
  "closeButton": false,
  "debug": false,
  "positionClass": "toast-top-full-width",
  "showDuration": "300",
  "hideDuration": "1000",
  "timeOut": "0",
  "extendedTimeOut": "0",
  "showEasing": "swing",
  "hideEasing": "linear",
  "showMethod": "fadeIn",
  "hideMethod": "fadeOut"
};

toastr.options.onHidden = function(item) {
//GET UNIQUE TOAST ID'S HERE
        var val = 1;//$this.find("#announcemntId").val();
        alert("CLOSED " + item);
}

toastr.error(mes, "First Toast");
toastr.error(mes1, "Second Toast");
toastr.error(mes2, "Third Toast");
toastr.error(mes3, "Fourth Toast");

Body:
I didn't quite understand these answers, so i am adding my own. I used jquery to create an onclose function, (when someone clicks the toast-close button) like this -

$('.toast-close-button').click(function() {
*someCodeHere
});


问:
post_execution hook for a DAG in Airflow
Finding a way to execute a piece code after a specific DAG completes (success or failure, regardless)

Looking around the source code, I was able to extend BaseOperator and define a post_execution hook for Operators. Is there something similar for a DAG?

Edit:
My end goal is to publish the status of the DAG to a SQS queue.

答:
One option is to use trigger rules: Take an operator you need to execute your piece of code and make sure that it is the final operator in your DAG, then set the trigger_rule to 'all_done'.

This way, the operator will be executed independently of the success state of the previous operators.


问:
How to create classes in google spreadsheets
```<code>D               E           F
772597          49.36.00    30316
746554          39.33.00    35820
976942          44.46.00    142864
1075820         41.33.00    93708
</code>```

My dataset needs to be simplified, by that I mean turning numbers into classifications.
For example value less or equal to 99 = 1. 100-999 = 2. 1000-1999 = 3, etc.

I got this code for a column and it works great:

```<code>=ArrayFormula(1*(B2:B900*1,05<B3:B900))
</code>```

But the data in the other columns in the dataset needs to be turned into numeric classes.

I need a formula that transforms the data in column D to be replaced with 1, 2, 3... and same with the data in the other columns

答:
For Numeric columns, please try the likes of:</p>

```<code>=ArrayFormula(floor(log(D1:D))--(D1:D<10))
</code>```

Body:
D               E           F
772597          49.36.00    30316
746554          39.33.00    35820
976942          44.46.00    142864
1075820         41.33.00    93708

My dataset needs to be simplified, by that I mean turning numbers into classifications.
For example value less or equal to 99 = 1. 100-999 = 2. 1000-1999 = 3, etc.

I got this code for a column and it works great:

=ArrayFormula(1*(B2:B900*1,05<B3:B900))

But the data in the other columns in the dataset needs to be turned into numeric classes.

I need a formula that transforms the data in column D to be replaced with 1, 2, 3... and same with the data in the other columns

Body:
For Numeric columns, please try the likes of:

=ArrayFormula(floor(log(D1:D))--(D1:D<10))


问:
socket.io, io is not defined (JS Error)
I have just started with socket.io, its giving JS Error on client page

io is not defined

How to fix this ?

答: put  into your code

Title: socket.io, io is not defined (JS Error)

Body: put <script src="http://yournodeserver/socket.io/socket.io.js"></script> into your code


问:
Firebase multiple async requests returned via Promises
I have a Firebase function that is attempting to take an array of UIDs and return an array of User Objects.  I am trying to use Promise.all() to return all of the async results, but I am getting an empty array returned.  I am, however, getting the logged out results after the fact.

```<code>const fetchUserObjects = function(uids){
  let promises = []
  uids.forEach((uid) => {
    admin.database().ref(`/users/${uid}`).once("value")
    .then(function(dataSnapshot) {
      const userDataAll = dataSnapshot.val()
      const userData = {}
      userData.id = userDataAll.id
      userData.username = userDataAll.username
      userData.first = userDataAll.first
      userData.last = userDataAll.last

      promises.push(userData)
      console.log(userData)
    })
    .catch((error) => {
      // Re-throwing the error as an HttpsError so that the client gets the error details.
      throw new functions.https.HttpsError('unknown', error.message, error);
    });
  })

  return Promise.all(promises);

}

return fetchUserObjects(uids)
</code>```

答:
fetchUserObjects is always returning an empty array.  Nothing is ensuring that the async work started by once() is copmlete before you push values into the array.  Also notice that you're not actually pushing promises into that array.  You're pushing plain old JavaScript objects.  You need to push actual promises into the array instead, and you need to do it without having to wait for other promises to resolve.  Here's what it should look like instead:

```<code>const fetchUserObjects = function(uids){
  let promises = []
  uids.forEach((uid) => {
    const promise = admin.database().ref(`/users/${uid}`).once("value")
    .then(function(dataSnapshot) {
      const userDataAll = dataSnapshot.val()
      const userData = {}
      userData.id = userDataAll.id
      userData.username = userDataAll.username
      userData.first = userDataAll.first
      userData.last = userDataAll.last

      console.log(userData)
      return userData
    })
    .catch((error) => {
      // Re-throwing the error as an HttpsError so that the client gets the error details.
      throw new functions.https.HttpsError('unknown', error.message, error);
    });

    promises.push(promise)

  })

  return Promise.all(promises);

}
</code>```

Notice that a promise is immediately pushed into the promises array, and it will resolve with a userData object that was returned by the then callback.

Body:
I have a Firebase function that is attempting to take an array of UIDs and return an array of User Objects.  I am trying to use Promise.all() to return all of the async results, but I am getting an empty array returned.  I am, however, getting the logged out results after the fact.

const fetchUserObjects = function(uids){
  let promises = []
  uids.forEach((uid) => {
    admin.database().ref(`/users/${uid}`).once("value")
    .then(function(dataSnapshot) {
      const userDataAll = dataSnapshot.val()
      const userData = {}
      userData.id = userDataAll.id
      userData.username = userDataAll.username
      userData.first = userDataAll.first
      userData.last = userDataAll.last

      promises.push(userData)
      console.log(userData)
    })
    .catch((error) => {
      // Re-throwing the error as an HttpsError so that the client gets the error details.
      throw new functions.https.HttpsError('unknown', error.message, error);
    });
  })

  return Promise.all(promises);

}

return fetchUserObjects(uids)

Body:
fetchUserObjects is always returning an empty array.  Nothing is ensuring that the async work started by once() is copmlete before you push values into the array.  Also notice that you're not actually pushing promises into that array.  You're pushing plain old JavaScript objects.  You need to push actual promises into the array instead, and you need to do it without having to wait for other promises to resolve.  Here's what it should look like instead:

const fetchUserObjects = function(uids){
  let promises = []
  uids.forEach((uid) => {
    const promise = admin.database().ref(`/users/${uid}`).once("value")
    .then(function(dataSnapshot) {
      const userDataAll = dataSnapshot.val()
      const userData = {}
      userData.id = userDataAll.id
      userData.username = userDataAll.username
      userData.first = userDataAll.first
      userData.last = userDataAll.last

      console.log(userData)
      return userData
    })
    .catch((error) => {
      // Re-throwing the error as an HttpsError so that the client gets the error details.
      throw new functions.https.HttpsError('unknown', error.message, error);
    });

    promises.push(promise)

  })

  return Promise.all(promises);

}

Notice that a promise is immediately pushed into the promises array, and it will resolve with a userData object that was returned by the then callback.


问:
Vee-Validation for unique email address
I am storing emails in an array called 'emailsDB' and trying to check if the email being entered by the user in the email input field exists in the array.

The exact steps that I have followed are provided here - https://www.npmjs.com/package/vee-validate

However, on implementation I get an error in the console which says -

SyntaxError: import declarations may only appear at top level of a
  module

HTML code

```<code><div id="updateName" class="wrapper wrapper-right">
                <div class="wrapper-inner full-height">
                    <!--Contact Sec-->
                    <section>
                        <!--form sec-->
                        <section class="animated container-fluid align-center sec-ptop">
                            <h3 class="salutation">
                                Hey <span v-if='formData.Name.length'>{{formData.Name}}</span> <span v-else>There</span>, happy to hear from you.
                            </h3>
                            <div>
                                <form v-on:submit.prevent="validateBeforeSubmit" name="contactform" method="post" class="row form-horizontal" role="form" novalidate="true">
                                    <div class="form-group input--josh col-6">
                                        <div class="input-wrap">
                                            <input autocomplete="off" type="text" v-model="formData.Name" v-validate="'required'" id="Name" name="Name" placeholder="Name" class="form-control input__field input input__field--josh" :class="{'input': true, 'is-danger': errors.has('Name') }" />
                                            <i v-show="errors.has('Name')" class="fa fa-exclamation"></i>
                                            <label for="Name" class="input__label input__label input__label--josh input__label--josh-color-1 input__label--josh input__label--josh-color-1"></label>
                                        </div>
                                        <span v-show="errors.has('Name')" class="help is-danger">{{ errors.first('Name') }}</span>
                                    </div>
                                    <div class="form-group  input--josh col-6">
                                        <div class="input-wrap">
                                            <input autocomplete="off" type="email" v-model="formData.Email" v-validate="'required|email'" id="Email" name="Email" placeholder="Email" class="form-control input input__field input__field--josh" :class="{'input': true, 'is-danger': errors.has('Email') }">
                                            <i v-show="errors.has('Email')" class="fa fa-exclamation"></i>
                                            <label for="Email" class="input__label input__label--josh input__label--josh-color-1"></label>
                                        </div>
                                        <span v-show="errors.has('Email')" class="help is-danger">{{ errors.first('Email') }}</span>
                                    </div>
                                    <div class="form-group  input--josh col-12">
                                        <div class="input-wrap">
                                            <textarea rows="4" v-model="formData.Message" v-validate="'required'" id="Message" name="Message" placeholder="message" class="form-control input input__field input__field--josh" :class="{'input': true, 'is-danger': errors.has('Message') }"></textarea>
                                            <i v-show="errors.has('Message')" class="fa fa-exclamation"></i>
                                            <label for="Message" class="input__label input__label--josh input__label--josh-color-1"></label>
                                        </div>
                                        <span v-show="errors.has('Message')" class="help is-danger">{{ errors.first('Message') }}</span>
                                    </div>
                                    <div class="form-group col-12">
                                        <div class="align-center">
                                            <button type="submit" class="btn btn-default" data-ng-disabled="submitButtonDisabled">
                                                <span class="mask"></span>
                                                send
                                            </button>
                                        </div>
                                    </div>
                                </form>
                            </div>
                    </section>
                    <!--/Contact Sec-->
                </div>
            </div>
</code>```

Vue code

```<code>Vue.use(VeeValidate);
import { ValidationProvider } from 'vee-validate';
Vue.config.productionTip = false;
Vue.component('ValidationProvider', ValidationProvider);
const emailsDB = ["viveks.nair1988@gmail.com"];

var app = new Vue({
    el: '#updateName',
    mounted() {
        const isUnique = value =>
            new Promise(resolve => {
                setTimeout(() => {
                    if (emailsDB.indexOf(value) === -1) {
                        return resolve({
                            valid: true
                        });
                    }
                    return resolve({
                        valid: false,
                        data: {
                            message: `${value} has already reached out to me!`
                        }
                    });
                }, 200);
            });
        Validator.extend("unique", {
            validate: isUnique,
            getMessage: (field, params, data) => data.message
        });
    }
})
</code>```

Working example -
https://codesandbox.io/s/y3504yr0l1?initialpath=%2F%23%2Fbackend&module=%2Fsrc%2Fcomponents%2FBackend.vue

Image of what the result should be:
How the implementation should work

答:
The error import declarations may only appear at top level of a module means that when you use import in a script, no other instruction may appear before.

So, you need to move the Vue.use(VeeValidate); line after any import(s):

```<code>import { ValidationProvider } from 'vee-validate';
Vue.use(VeeValidate);
Vue.config.productionTip = false;
Vue.component('ValidationProvider', ValidationProvider);
const emailsDB = ["viveks.nair1988@gmail.com"];

...

</code>```

This has nothing to do with vee-validate itself.

Title: Vee-Validation for unique email address

Body:
I am storing emails in an array called 'emailsDB' and trying to check if the email being entered by the user in the email input field exists in the array.

The exact steps that I have followed are provided here - https://www.npmjs.com/package/vee-validate

However, on implementation I get an error in the console which says -

SyntaxError: import declarations may only appear at top level of a
  module

HTML code

                                Hey {{formData.Name}} There, happy to hear from you.

                                <form v-on:submit.prevent="validateBeforeSubmit" name="contactform" method="post" class="row form-horizontal" role="form" novalidate="true">

                                            <input autocomplete="off" type="text" v-model="formData.Name" v-validate="'required'" id="Name" name="Name" placeholder="Name" class="form-control input__field input input__field--josh" :class="{'input': true, 'is-danger': errors.has('Name') }" />

                                        {{ errors.first('Name') }}

                                            <input autocomplete="off" type="email" v-model="formData.Email" v-validate="'required|email'" id="Email" name="Email" placeholder="Email" class="form-control input input__field input__field--josh" :class="{'input': true, 'is-danger': errors.has('Email') }">

                                        {{ errors.first('Email') }}

                                            <textarea rows="4" v-model="formData.Message" v-validate="'required'" id="Message" name="Message" placeholder="message" class="form-control input input__field input__field--josh" :class="{'input': true, 'is-danger': errors.has('Message') }"></textarea>

                                        {{ errors.first('Message') }}

                                            <button type="submit" class="btn btn-default" data-ng-disabled="submitButtonDisabled">

                                                send
                                            </button>

                                </form>

Vue code

Vue.use(VeeValidate);
import { ValidationProvider } from 'vee-validate';
Vue.config.productionTip = false;
Vue.component('ValidationProvider', ValidationProvider);
const emailsDB = ["viveks.nair1988@gmail.com"];

var app = new Vue({
    el: '#updateName',
    mounted() {
        const isUnique = value =>
            new Promise(resolve => {
                setTimeout(() => {
                    if (emailsDB.indexOf(value) === -1) {
                        return resolve({
                            valid: true
                        });
                    }
                    return resolve({
                        valid: false,
                        data: {
                            message: `${value} has already reached out to me!`
                        }
                    });
                }, 200);
            });
        Validator.extend("unique", {
            validate: isUnique,
            getMessage: (field, params, data) => data.message
        });
    }
})

Working example -
https://codesandbox.io/s/y3504yr0l1?initialpath=%2F%23%2Fbackend&module=%2Fsrc%2Fcomponents%2FBackend.vue

Image of what the result should be:
How the implementation should work

Body:
The error import declarations may only appear at top level of a module means that when you use import in a script, no other instruction may appear before.

So, you need to move the Vue.use(VeeValidate); line after any import(s):

import { ValidationProvider } from 'vee-validate';
Vue.use(VeeValidate);
Vue.config.productionTip = false;
Vue.component('ValidationProvider', ValidationProvider);
const emailsDB = ["viveks.nair1988@gmail.com"];

...

This has nothing to do with vee-validate itself.


问:
Why is this ifelse statement producing NAs?
I am trying to create a new variable based on other variables in my dataset. I have used ifelse to do similar tasks, however when I have tried it this time I am getting NA when the condition is not met.

The variables I want to base the new variable on are all binary - "Yes" or "No". I want to the new variable to be coded "Yes" if any of the other variables are "Yes" and "No" if none of them are coded "Yes". When I run the ifelse, I get the expected number of "Yes", but what I would expect to be "No" is NA.

I have tried the following:

```<code>data$new <- ifelse(var1=="Yes" | var2=="Yes" | var3=="Yes","Yes","No")
</code>```

Any help would be greatly appreciated. I have changed the names of the data and put three variables in the example. There are actually 22 variables in total with very similar names, I tried to simplify the example. If seeing the actual data / code would be helpful I'll add this in.

Thanks!

答:
The == returns NA if there is any NA.  An option would be to cbind the variables 'var1', 'var2', 'var3' (not clear if it is a data.frame column or independent vectors), compare with "Yes", to create a logical matrix, use rowSums to get the sum of 'Yes' strings.  Note the na.rm = TRUE  which would take care of the NA elements (if any).  Using the row sums, check the value is greater than 0, then it is "Yes" or else "No"

```<code>ifelse(rowSums(cbind(var1, var2, var3)== "Yes"), na.rm = TRUE) > 0, "Yes", "No")
</code>```

To check why it is producing NA

```<code>v1 <- c("Yes", "No", NA)
v2 <- c("No", NA, "Yes")

(v1 == "Yes")|(v2 == "Yes")
#[1] TRUE   NA TRUE
</code>```

Body:
I am trying to create a new variable based on other variables in my dataset. I have used ifelse to do similar tasks, however when I have tried it this time I am getting NA when the condition is not met.

The variables I want to base the new variable on are all binary - "Yes" or "No". I want to the new variable to be coded "Yes" if any of the other variables are "Yes" and "No" if none of them are coded "Yes". When I run the ifelse, I get the expected number of "Yes", but what I would expect to be "No" is NA.

I have tried the following:

data$new <- ifelse(var1=="Yes" | var2=="Yes" | var3=="Yes","Yes","No")

Any help would be greatly appreciated. I have changed the names of the data and put three variables in the example. There are actually 22 variables in total with very similar names, I tried to simplify the example. If seeing the actual data / code would be helpful I'll add this in.

Thanks!

Body:
The == returns NA if there is any NA.  An option would be to cbind the variables 'var1', 'var2', 'var3' (not clear if it is a data.frame column or independent vectors), compare with "Yes", to create a logical matrix, use rowSums to get the sum of 'Yes' strings.  Note the na.rm = TRUE  which would take care of the NA elements (if any).  Using the row sums, check the value is greater than 0, then it is "Yes" or else "No"

ifelse(rowSums(cbind(var1, var2, var3)== "Yes"), na.rm = TRUE) > 0, "Yes", "No")

To check why it is producing NA

v1 <- c("Yes", "No", NA)
v2 <- c("No", NA, "Yes")

(v1 == "Yes")|(v2 == "Yes")
#[1] TRUE   NA TRUE


问:
Body of response from web-server has value "
```

How to fix this problem?

答:
What does your PHP file (I assume it's a php file) look like on the web-server?
The only thing it needs to output is the following:

```<code><?PHP
$data = [];
header('Content-Type: application/json');
http_response_code(200);
echo json_encode($data);
</code>```

Do not use html to output a json string for api requests.

Title: Body of response from web-server has value "<body><script language="javaScript">window.parent.document.cookie="Authorization=;path=/";

Body:
When I make GET request to web-server which is located in localhost by typing address in browser address field I get correct answer in json format. But when I make the same request from Android Studio I get response with status 200 (OK) but the value of body of this response is

How to fix this problem?

Body:
What does your PHP file (I assume it's a php file) look like on the web-server?
The only thing it needs to output is the following:

<?PHP
$data = [];
header('Content-Type: application/json');
http_response_code(200);
echo json_encode($data);

Do not use html to output a json string for api requests.


问:
Getting "System.Data.SqlClient is not supported on this platform" when launched as dotnet cli tool
We have a simple netcore 2.2 console application using DbContext from Microsoft.EntityFrameworkCore. When launched from console as is it works as expected.

However we decided to utilize it as a dotnet CLI tool. It's .csproj file contains:

```<code><Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp2.2</TargetFramework>
    <AssemblyName>dotnet-dbupdate</AssemblyName>
    <Title>Db Updater</Title>
    <Version>1.0.1</Version>
    <PackageId>DbUpdater</PackageId>
    <Product>DbUpdater</Product>
    <PackageVersion>1.0.1</PackageVersion>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="2.0.0" />
  </ItemGroup>
</Project>
</code>```

We pack it to our Nuget server with dotnet pack. Then in a target folder we've got the following .csproj file:

```<code><Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>netcoreapp2.2</TargetFramework>
  </PropertyGroup>
  <ItemGroup>
    <DotNetCliToolReference Include="DbUpdater" Version="1.0.1" />
  </ItemGroup>
</Project>
</code>```

From this folder we restore it and exec:

```<code>dotnet restore
dotnet dbupdate
</code>```

And suddenly, on DbSet's ToList method invocation we receive:

```<code>System.Data.SqlClient is not supported on this platform
</code>```

Definetely there is an issue with launching it as a dotnet CLI tool. However yet we failed to get what this issue is and how to solve it. Searching on the web did not give us any ideas what to try.

答:
Try to specify the .NET version to use for CLI:

dotnet dbupdate --fx-version 2.2.4

If the above does not work, also try with the other version you have installed (2.2.2).

In essence the version of .NET used to run from CLI, the target SDK of the console app and the package versions of the dependencies all have to match for incompatibility issues to be avoided.

Body:
We have a simple netcore 2.2 console application using DbContext from Microsoft.EntityFrameworkCore. When launched from console as is it works as expected.

However we decided to utilize it as a dotnet CLI tool. It's .csproj file contains:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp2.2</TargetFramework>
    <AssemblyName>dotnet-dbupdate</AssemblyName>
    <Title>Db Updater</Title>
    <Version>1.0.1</Version>
    <PackageId>DbUpdater</PackageId>
    <Product>DbUpdater</Product>
    <PackageVersion>1.0.1</PackageVersion>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="2.0.0" />
  </ItemGroup>
</Project>

We pack it to our Nuget server with dotnet pack. Then in a target folder we've got the following .csproj file:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>netcoreapp2.2</TargetFramework>
  </PropertyGroup>
  <ItemGroup>
    <DotNetCliToolReference Include="DbUpdater" Version="1.0.1" />
  </ItemGroup>
</Project>

From this folder we restore it and exec:

dotnet restore
dotnet dbupdate

And suddenly, on DbSet's ToList method invocation we receive:

System.Data.SqlClient is not supported on this platform

Definetely there is an issue with launching it as a dotnet CLI tool. However yet we failed to get what this issue is and how to solve it. Searching on the web did not give us any ideas what to try.


问:
How to encourage non-anonymous editing on MediaWiki?

Problem

At work we have a department wiki (running Mediawiki). Unfortunately several
persons edit without logging in, and that makes it very difficult to track
down editors to ask questions about the content.

There are two strategies to improve this

encourage logged in editing

discourage anonymous editing.

Encouraging

For this part, any tips are welcome. But of course there is always risks involved
in rewarding behaviours.

Discourage

I know that this must be kept low or else it will discourage any editing.
But something just slightly annoying would be nice to have.

[update]
I know it is possible to just disallow anonymous editing, but that will put a high barrier to any first time contribution (especially for people outside our department!), so I do not think that is an option.
[/update]

[update2]
Using LDAP or Active Directory does not solve the problem since the wiki is also accessible and used by external contractors.
[/update2]

[update3]
I am no longer working for this company. That does not mean that I completely have lost interest in this question, but from my current interest point the most valuable part is the "Did you forget to log in?" part below, and I will accept answers based on this part of the question.
[/update3]

Confirmation

One thought was to have an additional confirmation step for anonymous users -
"Are you really sure you want to submit this anonymously?", although with
such a question there is a risk that people will give up or resist editing. However,
if that question is re-phrased in a more diplomatic way as "Did you forget
to log in?" I think it will appear as much more acceptable. And besides that
will also capture those situations where the author did in fact forget to
log in, but actually would want to have his/her contributions credited
his/her user. This last point is by itself a good enough reason for wanting it.

Is this possible?

Delay

Another thought for something to be slightly annoying is to add an extra
forced delay after "save page" displaying something like "If you had logged
in you would not have to wait x seconds". Selecting a right x is difficult
because if it is to high it will be a barrier and if it too low might not
make any difference. But then I started thinking, what about starting at
zero and then add one second delay for each anonymous edit by a given IP
address in a given time frame? That way there will be no barrier for
starting to use the wiki, and by the time the delay is getting significant
the user has already contributed a lot so I think the outcome is much
more likely to be that the editor eventually creates a user rather than
giving up. This assumes IP addresses are rather static, but that is very
 typically is the case in a business network.

Is this possible?

答: I'd recommend checking out wikipatterns.org - a great site about the social aspects of wikis</p>

OwnerDisplayName: hlovdal

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: hlovdal

OwnerDisplayName: Kevin Davis


问:
efficiently aggregate large CSV file with multiple int columns
I have a large CSV file with some string type columns (dtype object) and other columns that are int64 type.

Both the string columns and the integer columns can be empty in the CSV. An empty value in the integer columns represent zero and an empty string should stay an empty string.

I want to aggregate all the integer columns over all the other columns.
What is the best approach for this?

The output should finally be a single CSV file that is aggregated.
The file might not fit into memory as a whole, which is why I tried to use Dask but I am having a hard time understanding how to do this.

This is a working pandas code for a small CSV that fits into memory:

```<code>import pandas as pd
df = pd.read_csv("input_file.csv", na_filter=False)
df[metrics_to_aggregate] = df[metrics_to_aggregate].fillna(0).apply(pd.to_numeric)
df = df.groupby(dimensions_to_aggregate, as_index=False).sum()
df.to_csv("output_file.csv", index=False)
</code>```

For example,input df can be something like:

```<code>  dimension1 dimension2 dimension3 metric1 metric2 metric3
0        foo        bar                  1       1
1        foo        bar                  2               2
2                   foo        bar       1       4       2
3        foo        bar     foobar               2       1
</code>```

Where the output df should be:

```<code>  dimension1 dimension2 dimension3  metric1  metric2  metric3
0                   foo        bar        1        4        2
1        foo        bar                   3        1        2
2        foo        bar     foobar      NaN        2        1
</code>```

Where:

```<code>metrics_to_aggregate=['metric1', 'metric2', 'metric3']
dimensions_to_aggregate=['dimension1', 'dimension2', 'dimension3']
</code>```

答:
If the file is unsorted it is hard to process without using a lot of memory: you need to keep a running aggregation for every key (list of dimension values) that appears in the file.  There might be a good way to do that but it depends on details like how many possibilities there are.  It might be possible to do the processing in chunks, and then process the chunks together but you're still going to need enough memory to store all the current key values being aggregated against.

A simple and fairly generic solution is to sort first. The unix sort command will happily sort files that are too large to fit into memory.  Then the sorted file can easily be processed in chunks.  Here's a sequence that shows the principle: you might need to change some details:

First, I extended your file a little to show what's going on and removed the header line (which sort will treat as data):

```<code>input_file.csv:
foo bar     1   1
a       a   9   9   9
z   z       8   8   8
a       a   9   9   9
foo bar     2       2
    foo bar 1   4   2
foo bar foobar      2   1
z   z       7   7   7
a       a   9   9   9
</code>```

Then I used the command:

```<code>sort input_file.csv -o input_file_sorted.csv --key=1,3
</code>```

This gave me:

```<code>input_file_sorted.csv
a       a   9   9   9
a       a   9   9   9
a       a   9   9   9
    foo bar 1   4   2
foo bar     1   1
foo bar     2       2
foo bar foobar      2   1
z   z       7   7   7
z   z       8   8   8
</code>```

Then I ran this Python program:

```<code>import csv

number_of_dims = 3
number_of_aggs = 3

def aggregate(agg, data):
    for i,d in enumerate(data):
        if d != "":
            agg[i] += int(d)
    return

with open("input_file_sorted.csv", newline="") as f1:
    with open("output_file,csv", "w", newline="") as f2:
        csv_reader = csv.reader(f1, delimiter='\t')
        csv_writer = csv.writer(f2, delimiter='\t')
        key = None
        agg = [0] * number_of_aggs
        for l in csv_reader:
            new_key = l[:number_of_dims]
            if key is None:
                key = new_key
            if key != new_key:
                csv_writer.writerow(key + agg)
                agg = [0] * number_of_aggs
                key = new_key
            aggregate(agg, l[number_of_dims:])
        csv_writer.writerow(key + agg)
</code>```

and that got me:

```<code>output_file.csv:
a       a   27  27  27
    foo bar 1   4   2
foo bar     3   1   2
foo bar foobar  0   2   1
z   z       15  15  15
</code>```

Hope that helps!

Body:
I have a large CSV file with some string type columns (dtype object) and other columns that are int64 type.

Both the string columns and the integer columns can be empty in the CSV. An empty value in the integer columns represent zero and an empty string should stay an empty string.

I want to aggregate all the integer columns over all the other columns.
What is the best approach for this?

The output should finally be a single CSV file that is aggregated.
The file might not fit into memory as a whole, which is why I tried to use Dask but I am having a hard time understanding how to do this.

This is a working pandas code for a small CSV that fits into memory:

import pandas as pd
df = pd.read_csv("input_file.csv", na_filter=False)
df[metrics_to_aggregate] = df[metrics_to_aggregate].fillna(0).apply(pd.to_numeric)
df = df.groupby(dimensions_to_aggregate, as_index=False).sum()
df.to_csv("output_file.csv", index=False)

For example,input df can be something like:

  dimension1 dimension2 dimension3 metric1 metric2 metric3
0        foo        bar                  1       1
1        foo        bar                  2               2
2                   foo        bar       1       4       2
3        foo        bar     foobar               2       1

Where the output df should be:

  dimension1 dimension2 dimension3  metric1  metric2  metric3
0                   foo        bar        1        4        2
1        foo        bar                   3        1        2
2        foo        bar     foobar      NaN        2        1

Where:

metrics_to_aggregate=['metric1', 'metric2', 'metric3']
dimensions_to_aggregate=['dimension1', 'dimension2', 'dimension3']

Body:
If the file is unsorted it is hard to process without using a lot of memory: you need to keep a running aggregation for every key (list of dimension values) that appears in the file.  There might be a good way to do that but it depends on details like how many possibilities there are.  It might be possible to do the processing in chunks, and then process the chunks together but you're still going to need enough memory to store all the current key values being aggregated against.

A simple and fairly generic solution is to sort first. The unix sort command will happily sort files that are too large to fit into memory.  Then the sorted file can easily be processed in chunks.  Here's a sequence that shows the principle: you might need to change some details:

First, I extended your file a little to show what's going on and removed the header line (which sort will treat as data):

input_file.csv:
foo bar     1   1
a       a   9   9   9
z   z       8   8   8
a       a   9   9   9
foo bar     2       2
    foo bar 1   4   2
foo bar foobar      2   1
z   z       7   7   7
a       a   9   9   9

Then I used the command:

sort input_file.csv -o input_file_sorted.csv --key=1,3

This gave me:

input_file_sorted.csv
a       a   9   9   9
a       a   9   9   9
a       a   9   9   9
    foo bar 1   4   2
foo bar     1   1
foo bar     2       2
foo bar foobar      2   1
z   z       7   7   7
z   z       8   8   8

Then I ran this Python program:

import csv

number_of_dims = 3
number_of_aggs = 3

def aggregate(agg, data):
    for i,d in enumerate(data):
        if d != "":
            agg[i] += int(d)
    return

with open("input_file_sorted.csv", newline="") as f1:
    with open("output_file,csv", "w", newline="") as f2:
        csv_reader = csv.reader(f1, delimiter='\t')
        csv_writer = csv.writer(f2, delimiter='\t')
        key = None
        agg = [0] * number_of_aggs
        for l in csv_reader:
            new_key = l[:number_of_dims]
            if key is None:
                key = new_key
            if key != new_key:
                csv_writer.writerow(key + agg)
                agg = [0] * number_of_aggs
                key = new_key
            aggregate(agg, l[number_of_dims:])
        csv_writer.writerow(key + agg)

and that got me:

output_file.csv:
a       a   27  27  27
    foo bar 1   4   2
foo bar     3   1   2
foo bar foobar  0   2   1
z   z       15  15  15

Hope that helps!


问:
Buttons not visible in the Layout Editor of Android Studio 3.4
Although many tutorials, videos, and books in Internet show the baseline edit. delete constraint and cycle chain mode  buttons (x, ab and chainbuttons) below the selected component in the Layout Editor, I can't see them in my updated Android Studio 3.4.  How is it possible? I can only do these operations with the context menu.

答:
You can find menu to toggle Baseline from context menu e.g

Activity Design View > Component Tree

 Component Tree">

Select button2 and right-click to bring up the Context menu on button2

Body:
You can find menu to toggle Baseline from context menu e.g

Activity Design View > Component Tree

Select button2 and right-click to bring up the Context menu on button2


问:
How to update react state that has object?
I have state in react that includes object called increment. Inside that object i have a property called count with a value of 0.
Does anyone know how to increment count value with a button click?

```<code>import React, { Component } from 'react';

class App extends Component {
  constructor(){
    super();

    this.state = {
      increment:{
        count:0
      }
    }

    this.handleClick = this.handleClick.bind(this)
  }

  handleClick() {

    this.setState(prevState => {
      return {
        increment.count: prevState.increment.count + 1
      }
    })
  }

  render() {

    return (
      <div>
          <h1>{this.state.increment.count}</h1>
          <button onClick={this.handleClick}>Change!</button>

      </div>
    )
  }
}

export default App;
</code>```

React gives me error called Parsing error: Unexpected token, expected ","

答:
Your syntax of updating state is wrong. you can't add key as increment.count. Here is correct syntax.</p>

```<code>handleClick() {

    this.setState(prevState => {
       return {
           increment: {
               count: prevState.increment.count + 1
           }
       }
    })
}
</code>```

Body:
I have state in react that includes object called increment. Inside that object i have a property called count with a value of 0.
Does anyone know how to increment count value with a button click?

import React, { Component } from 'react';

class App extends Component {
  constructor(){
    super();

    this.state = {
      increment:{
        count:0
      }
    }

    this.handleClick = this.handleClick.bind(this)
  }

  handleClick() {

    this.setState(prevState => {
      return {
        increment.count: prevState.increment.count + 1
      }
    })
  }

  render() {

    return (

{this.state.increment.count}

          <button onClick={this.handleClick}>Change!</button>

    )
  }
}

export default App;

React gives me error called Parsing error: Unexpected token, expected ","

Body:
Your syntax of updating state is wrong. you can't add key as increment.count. Here is correct syntax.

handleClick() {

    this.setState(prevState => {
       return {
           increment: {
               count: prevState.increment.count + 1
           }
       }
    })
}


问:
MYSQL server running query very slow on 1 Million records
I am using MYSQL to manage book library data, here is my main table

```<code>CREATE TABLE `book` (
`id` int(11) NOT NULL,
`bookId` int(11) DEFAULT NULL,
`pageNum` smallint(6) DEFAULT NULL,
`pageData` longtext
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
</code>```

Now when I run this query

```<code>SELECT c.id, c.bookId,c.pageNum, c.pageData, o.BookName FROM book c  left
join kotarbooks o on c.bookId=o.BookId WHERE pageData like '%[Search Word]%'"
</code>```

It takes about 3 minutes

and when I run query

```<code>SELECT * FROM book WHERE bookid=[bookid] AND pageNum=[pageNumber]
</code>```

it takes about 2 minutes
Is there any idea to speed up these queries?
Thanks a lot

答:
I run query SELECT * FROM book WHERE bookid=[bookid] AND pageNum=[pageNumber]
  it takes about 2 minutes

You could create index to speed up filtering:

```<code>CREATE INDEX idx ON book(bookid, pageNum);
</code>```

As for WHERE pageData like '%[Search Word]%' is not so trivial because you are searching using '%' at the beginning and it makes a query not SARGable.

Body:
I am using MYSQL to manage book library data, here is my main table

CREATE TABLE `book` (
`id` int(11) NOT NULL,
`bookId` int(11) DEFAULT NULL,
`pageNum` smallint(6) DEFAULT NULL,
`pageData` longtext
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

Now when I run this query

SELECT c.id, c.bookId,c.pageNum, c.pageData, o.BookName FROM book c  left
join kotarbooks o on c.bookId=o.BookId WHERE pageData like '%[Search Word]%'"

It takes about 3 minutes

and when I run query

SELECT * FROM book WHERE bookid=[bookid] AND pageNum=[pageNumber]

it takes about 2 minutes
Is there any idea to speed up these queries?
Thanks a lot

Body:
I run query SELECT * FROM book WHERE bookid=[bookid] AND pageNum=[pageNumber]
  it takes about 2 minutes

You could create index to speed up filtering:

CREATE INDEX idx ON book(bookid, pageNum);

As for WHERE pageData like '%[Search Word]%' is not so trivial because you are searching using '%' at the beginning and it makes a query not SARGable.


问:
How do I count distinct values from same id?
How do I count distinct values from a column if there are some duplicates for each ID?

I've tried COUNT, DISTINCT, CASE and everything but I can't count distinct values for each ID. I have a table like this.

```<code>ID          Symptom
1           Headache
1           Headache
1           Hematuria
1           Leg pain
1           Headache
2           Cough
2           Headache
2           Cough
3           Cough
3           Cough
3           Cough
</code>```

I want to obtain something like this.

```<code>ID    Symptom
1     Headache
1     Hematuria
1     Leg pain
2     Cough
2     Headache
3     Cough
</code>```

Or how do I obtain the total count? Like there are 5 distinct symtomps but not 11 symptoms (If I use DISTINCT I would obtain 4).

答:
Just group by those fields :

SELECT ID, Symptom
FROM Symptoms
GROUP BY ID, Symptom
```

Fiddle : http://sqlfiddle.com/#!18/48dde/2/0

Body:
How do I count distinct values from a column if there are some duplicates for each ID?

I've tried COUNT, DISTINCT, CASE and everything but I can't count distinct values for each ID. I have a table like this.

ID          Symptom
1           Headache
1           Headache
1           Hematuria
1           Leg pain
1           Headache
2           Cough
2           Headache
2           Cough
3           Cough
3           Cough
3           Cough

I want to obtain something like this.

ID    Symptom
1     Headache
1     Hematuria
1     Leg pain
2     Cough
2     Headache
3     Cough

Or how do I obtain the total count? Like there are 5 distinct symtomps but not 11 symptoms (If I use DISTINCT I would obtain 4).

Body:
Just group by those fields :

SELECT ID, Symptom
FROM Symptoms
GROUP BY ID, Symptom

Fiddle : http://sqlfiddle.com/#!18/48dde/2/0


问:
unexpected return type from list comprehension
I am teaching myself a bit of F# by doing a bit of simple matrix mathematics. I decided to write a set of simple functions for combining two matrices as I thought that this would be a good way of learning list comprehensions. However when I compile it my unit tests produce a type mismatch exception.

```<code>//return a column from the matrix as a list
let getColumn(matrix: list<list<double>>, column:int) =
    [for row in matrix do yield row.Item(column)]
//return a row from the matrix as a list
let getRow(matrix: list<list<double>>, column:int) =
    matrix.Item(column)
//find the minimum width of the matrices in order to avoid index out of range exceptions
let minWidth(matrix1: list<list<double>>,matrix2: list<list<double>>) =
    let width1 = [for row in matrix1 do yield row.Length] |> List.min
    let width2 = [for row in matrix2 do yield row.Length] |> List.min
    if width1 > width2 then width2 else width1
//find the minimum height of the matrices in order to avoid index out of range exceptions
let minHeight(matrix1: list<list<double>>,matrix2: list<list<double>>) =
    let height1 = matrix1.Length
    let height2 = matrix2.Length
    if height1 > height2 then height2 else height1
//combine the two matrices
let concat(matrix1: list<list<double>>,matrix2: list<list<double>>) =
    let width = minWidth(matrix1, matrix2)
    let height = minHeight(matrix1, matrix2)
    [for y in 0 .. height do yield [for x in 0 .. width do yield (List.fold2 (fun acc a b -> acc + (a*b)), getRow(matrix1, y), getColumn(matrix2, x))]]
</code>```

I was expecting the function to return a list of lists of type

```<code>double list list
</code>```

However what it actually returns looks more like some kind of lambda expression

```<code>((int -> int list -> int list -> int) * double list * double list) list list
</code>```

Can somebody tell me what is being returned, and how to force it to be evaluated into the list of lists that I originally expected?

答:
There's a short answer and a long answer to your question.

The short answer

The short version is that F# functions (like List.fold2) take multiple parameters not with commas the way you think they do, but with spaces in between. I.e., you should NOT call List.fold2 like this:

```<code>List.fold2 (function, list1, list2)
</code>```

but rather like this:

```<code>List.fold2 function list1 list2
</code>```

Now, if you just remove the commas in your List.fold2 call, you'll see that the compiler complains about your getRow(matrix1, y) call, and tells you to put parentheses around them. (And the outer pair of parentheses around List.fold2 isn't actually needed). So this:

```<code>(List.fold2 (fun acc a b -> acc + (a*b)), getRow(matrix1, y), getColumn(matrix2, x))
</code>```

Needs to turn into this:

```<code>List.fold2 (fun acc a b -> acc + (a*b)) (getRow(matrix1, y)) (getColumn(matrix2, x))
</code>```

The long answer

The way F# functions take multiple parameters is actually very different from most other languages such as C#. In fact, all F# functions take exactly one parameter! "But wait," you're probably thinking right now, "you just now showed me the syntax for F# functions taking multiple parameters!" Yes, I did. What's going on under the hood is a combination of currying and partial application. I'd write a long explanation, but Scott Wlaschin has already written one, that's much better than I could have written, so I'll just point you to the https://fsharpforfunandprofit.com/series/thinking-functionally.html series to help you understand what's going on here. (The sections on currying and partial application are the ones you want, but I'd recommend reading the series in order because the later parts build on concepts introduced in earlier parts).

And yes, this "long" answer appears shorter than the "short" answer, but if you go read that series (and then the rest of Scott Wlaschin's excellent site), you'll find that it's much longer than the short answer. :-)

If you have more questions, I'll be happy to try to explain.

Body:
I am teaching myself a bit of F# by doing a bit of simple matrix mathematics. I decided to write a set of simple functions for combining two matrices as I thought that this would be a good way of learning list comprehensions. However when I compile it my unit tests produce a type mismatch exception.

//return a column from the matrix as a list
let getColumn(matrix: list<list<double>>, column:int) =
    [for row in matrix do yield row.Item(column)]
//return a row from the matrix as a list
let getRow(matrix: list<list<double>>, column:int) =
    matrix.Item(column)
//find the minimum width of the matrices in order to avoid index out of range exceptions
let minWidth(matrix1: list<list<double>>,matrix2: list<list<double>>) =
    let width1 = [for row in matrix1 do yield row.Length] |> List.min
    let width2 = [for row in matrix2 do yield row.Length] |> List.min
    if width1 > width2 then width2 else width1
//find the minimum height of the matrices in order to avoid index out of range exceptions
let minHeight(matrix1: list<list<double>>,matrix2: list<list<double>>) =
    let height1 = matrix1.Length
    let height2 = matrix2.Length
    if height1 > height2 then height2 else height1
//combine the two matrices
let concat(matrix1: list<list<double>>,matrix2: list<list<double>>) =
    let width = minWidth(matrix1, matrix2)
    let height = minHeight(matrix1, matrix2)
    [for y in 0 .. height do yield [for x in 0 .. width do yield (List.fold2 (fun acc a b -> acc + (a*b)), getRow(matrix1, y), getColumn(matrix2, x))]]

I was expecting the function to return a list of lists of type

double list list

However what it actually returns looks more like some kind of lambda expression

((int -> int list -> int list -> int) * double list * double list) list list

Can somebody tell me what is being returned, and how to force it to be evaluated into the list of lists that I originally expected?

Body:
There's a short answer and a long answer to your question.

The short answer

The short version is that F# functions (like List.fold2) take multiple parameters not with commas the way you think they do, but with spaces in between. I.e., you should NOT call List.fold2 like this:

List.fold2 (function, list1, list2)

but rather like this:

List.fold2 function list1 list2

Now, if you just remove the commas in your List.fold2 call, you'll see that the compiler complains about your getRow(matrix1, y) call, and tells you to put parentheses around them. (And the outer pair of parentheses around List.fold2 isn't actually needed). So this:

(List.fold2 (fun acc a b -> acc + (a*b)), getRow(matrix1, y), getColumn(matrix2, x))

Needs to turn into this:

List.fold2 (fun acc a b -> acc + (a*b)) (getRow(matrix1, y)) (getColumn(matrix2, x))

The long answer

The way F# functions take multiple parameters is actually very different from most other languages such as C#. In fact, all F# functions take exactly one parameter! "But wait," you're probably thinking right now, "you just now showed me the syntax for F# functions taking multiple parameters!" Yes, I did. What's going on under the hood is a combination of currying and partial application. I'd write a long explanation, but Scott Wlaschin has already written one, that's much better than I could have written, so I'll just point you to the https://fsharpforfunandprofit.com/series/thinking-functionally.html series to help you understand what's going on here. (The sections on currying and partial application are the ones you want, but I'd recommend reading the series in order because the later parts build on concepts introduced in earlier parts).

And yes, this "long" answer appears shorter than the "short" answer, but if you go read that series (and then the rest of Scott Wlaschin's excellent site), you'll find that it's much longer than the short answer. :-)

If you have more questions, I'll be happy to try to explain.


问:
Get position with variable and then modify specific object in mongodb
How can I make this query use my variable instead of the hard coded 0?</p>

```<code>let pos = 0;

{$set: {'answers.0.acknowledged': data}}
</code>```

答:
Usually you choices are template literals, Array.join, String.concat etc:

let pos = 0;
let data = 'data';

let query = {$set: {[['answers.', pos,'.acknowledged'].join('')]: data}}

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

<p>With String.concat:</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>let pos = 0;
let data = 'data';
let query = {$set: {['answers.'.concat(pos,'.acknowledged')]: data}}
console.log(query);</code>```

Array.join, String.concat has a much better browsers support where template literals do not. If they were to be used @ the client side. In your case if you are using them at the back end you probably have nothing to worry about.

Body:
How can I make this query use my variable instead of the hard coded 0?

let pos = 0;

{$set: {'answers.0.acknowledged': data}}

Body:
Usually you choices are template literals, Array.join, String.concat etc:

let pos = 0;
let data = 'data';

let query = {$set: {[['answers.', pos,'.acknowledged'].join('')]: data}}

console.log(query);

With String.concat:

let pos = 0;
let data = 'data';
let query = {$set: {['answers.'.concat(pos,'.acknowledged')]: data}}
console.log(query);

Array.join, String.concat has a much better browsers support where template literals do not. If they were to be used @ the client side. In your case if you are using them at the back end you probably have nothing to worry about.


问:
Casting a generic dictionary containing a generic dictionary
I have:

```<code>var someConcreteInstance = new Dictionary<string, Dictionary<string, bool>>();
</code>```

and I wish to cast it to an interface version, i.e.:

```<code>someInterfaceInstance = (IDictionary<string, IDictionary<string, bool>>)someConcreteInstance;
</code>```

'someInterfaceInstance' is a public property:

```<code>IDictionary<string, IDictionary<string, bool>> someInterfaceInstance { get; set; }
</code>```

This compiles correctly, but throws a runtime casting error.

```<code>Unable to cast object of type 'System.Collections.Generic.Dictionary`2[System.String,System.Collections.Generic.Dictionary`2[System.String,System.Boolean]]' to type 'System.Collections.Generic.IDictionary`2[System.String,System.Collections.Generic.IDictionary`2[System.String,System.Boolean]]'.
</code>```

What am I missing? (Problems with the nested generic type/Property?)

答:
IDictionary does not support covariance.

Look here
IDictionary<TKey, TValue> in .NET 4 not covariant

Body:
I have:

var someConcreteInstance = new Dictionary<string, Dictionary<string, bool>>();

and I wish to cast it to an interface version, i.e.:

someInterfaceInstance = (IDictionary<string, IDictionary<string, bool>>)someConcreteInstance;

'someInterfaceInstance' is a public property:

IDictionary<string, IDictionary<string, bool>> someInterfaceInstance { get; set; }

This compiles correctly, but throws a runtime casting error.

Unable to cast object of type 'System.Collections.Generic.Dictionary`2[System.String,System.Collections.Generic.Dictionary`2[System.String,System.Boolean]]' to type 'System.Collections.Generic.IDictionary`2[System.String,System.Collections.Generic.IDictionary`2[System.String,System.Boolean]]'.

What am I missing? (Problems with the nested generic type/Property?)


问:
Calendar - Apply search filter on appointments (Subject)
I am using the EWS Java api 2.0 to read appointments on a Calendar mailbox.
It works fine but my problem is to filter the appointments by its subject description, which I am not succeeding.
At the moment I am using CalendarView to retrieve the appointments,
something like this:

```<code>CalendarFolder cf = CalendarFolder.bind(service, WellKnownFolderName.Calendar);
CalendarView view = new CalendarView(startDate, endDate);
FindItemsResults<Appointment> findResults3 = cf.findAppointments(view);
</code>```

I know that the Item class provides a method which I can apply a search filter, but it does return occurrences of a recurring series.

Something like that:

```<code>ItemView itemView = new ItemView(50);
SearchFilter searchFilter = new SearchFilter.ContainsSubstring(ItemSchema.Subject, "OK");
FindItemsResults<Item> findResults = service.findItems(WellKnownFolderName.Calendar, searchFilter, itemView);
</code>```

Does anyone have an idea how to fix that?

Thanks and regards

答:
Keep in mind that instances of a recurring appointment (even if they are exceptions) do not physically exist, so they cannot be possibly returned by FindItems().

What you probably want is the GetUserAvailability operation (exposed by the ExchangeService.GetUserAvailability Method ) in Detailed mode.

Body:
I am using the EWS Java api 2.0 to read appointments on a Calendar mailbox.
It works fine but my problem is to filter the appointments by its subject description, which I am not succeeding.
At the moment I am using CalendarView to retrieve the appointments,
something like this:

CalendarFolder cf = CalendarFolder.bind(service, WellKnownFolderName.Calendar);
CalendarView view = new CalendarView(startDate, endDate);
FindItemsResults<Appointment> findResults3 = cf.findAppointments(view);

I know that the Item class provides a method which I can apply a search filter, but it does return occurrences of a recurring series.

Something like that:

ItemView itemView = new ItemView(50);
SearchFilter searchFilter = new SearchFilter.ContainsSubstring(ItemSchema.Subject, "OK");
FindItemsResults<Item> findResults = service.findItems(WellKnownFolderName.Calendar, searchFilter, itemView);

Does anyone have an idea how to fix that?

Thanks and regards


答:
```<code>handleClick() {
    this.setState(prevState => ({
        increment: {
            count: prevState.increment.count + 1
        },
    })
}
</code>```

Title: How to update react state that has object?


问:
Time of the day greeting code won't work in a am/pm format
Yea so the problem is simple and I assume the solution should also be simple but I am a complete newb so no clue how it works. The code below won't work if the source of the time is in an am pm format, any idea how to make it work in both cases?</p>

```<code>var today = new Date ();
var hourNow = today.getHours();
var greeting;

if (hourNow > 18) {
  greeting = 'Good Evening!';
} else if (hourNow > 12) {
  greeting = 'Good Afternoon!';
} else if (hourNow > 0) {
  greeting = 'Good morning!';
} else {
  greeting = 'Welcome!';
}

document.write('<h1>' + greeting + '</h1>');
</code>```

答:
I found the issue. The way I understand it, to the JS code the 12:59 is still 12 thus "Good morning!". So I have to set the hourNow one hour earlier. Like this:

```<code>   var today = new Date();
    var hourNow = today.getHours();
    var greeting;

    if (hourNow > 16) {
      greeting = 'Good Evening!';
    } else if (hourNow > 11) {
      greeting = 'Good Afternoon!';
    } else if (hourNow > 0) {
      greeting = 'Good morning!';
    } else {
      greeting = 'Welcome!';
    }

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

This way I will get Good Afternoon! after 12pm and Good Evening! after 5pm

Body:
Yea so the problem is simple and I assume the solution should also be simple but I am a complete newb so no clue how it works. The code below won't work if the source of the time is in an am pm format, any idea how to make it work in both cases?

var today = new Date ();
var hourNow = today.getHours();
var greeting;

if (hourNow > 18) {
  greeting = 'Good Evening!';
} else if (hourNow > 12) {
  greeting = 'Good Afternoon!';
} else if (hourNow > 0) {
  greeting = 'Good morning!';
} else {
  greeting = 'Welcome!';
}

document.write('
' + greeting + '
');

Body:
I found the issue. The way I understand it, to the JS code the 12:59 is still 12 thus "Good morning!". So I have to set the hourNow one hour earlier. Like this:

   var today = new Date();
    var hourNow = today.getHours();
    var greeting;

    if (hourNow > 16) {
      greeting = 'Good Evening!';
    } else if (hourNow > 11) {
      greeting = 'Good Afternoon!';
    } else if (hourNow > 0) {
      greeting = 'Good morning!';
    } else {
      greeting = 'Welcome!';
    }

    console.log(greeting);

This way I will get Good Afternoon! after 12pm and Good Evening! after 5pm


问:
Combine 2 collections (keep the similar ones)
I've several collections, I want to keep only the elements that are present in each collection.

I went through the available methods, but I didn't find anything that would match.

```<code>$candidatesByConsultant = Consultant::find(request('consultant_id'))->candidates;
$candidatesByCreation = Candidate::whereBetween('created_at',[Carbon::parse(request('meeting_since')), Carbon::parse(request('meeting_to'))])->get();
</code>```

Do you have any idea? :)

答:
The built-in for this is $collection->intersect($other), but you can also achieve the desired result with a simple custom filter:

```<code>$left  = collect([Model::find(1), Model::find(2), Model::find(3)]);
$right = collect([Model::find(1), Model::find(3), Model::find(5)]);

$result = $left->filter(function ($value, $key) use ($right) {
    return $right->contains(function ($v, $k) use ($value) {
        return $v->id === $value->id;
    });
});
</code>```

This will perform model comparison by id. It is not very performant though. Another approach would be to retrieve two arrays of ids, intersect them and filter the merged sets based on this list:

```<code>$left   = collect([Model::find(1), Model::find(2), Model::find(3)]);
$right  = collect([Model::find(1), Model::find(3), Model::find(5)]);
$merged = $left->merge($right);

$ids = array_intersect($left->pluck('id')->toArray(), $right->pluck('id')->toArray());

$result = $merged->filter(function ($value, $key) use ($ids) {
    return in_array($value->id, $ids);
});
</code>```

Body:
I've several collections, I want to keep only the elements that are present in each collection.

I went through the available methods, but I didn't find anything that would match.

$candidatesByConsultant = Consultant::find(request('consultant_id'))->candidates;
$candidatesByCreation = Candidate::whereBetween('created_at',[Carbon::parse(request('meeting_since')), Carbon::parse(request('meeting_to'))])->get();

Do you have any idea? :)

Body:
The built-in for this is $collection->intersect($other), but you can also achieve the desired result with a simple custom filter:

$left  = collect([Model::find(1), Model::find(2), Model::find(3)]);
$right = collect([Model::find(1), Model::find(3), Model::find(5)]);

$result = $left->filter(function ($value, $key) use ($right) {
    return $right->contains(function ($v, $k) use ($value) {
        return $v->id === $value->id;
    });
});

This will perform model comparison by id. It is not very performant though. Another approach would be to retrieve two arrays of ids, intersect them and filter the merged sets based on this list:

$left   = collect([Model::find(1), Model::find(2), Model::find(3)]);
$right  = collect([Model::find(1), Model::find(3), Model::find(5)]);
$merged = $left->merge($right);

$ids = array_intersect($left->pluck('id')->toArray(), $right->pluck('id')->toArray());

$result = $merged->filter(function ($value, $key) use ($ids) {
    return in_array($value->id, $ids);
});


问:
Make Item go the bottom using Flexbox and Material UI
I am trying to add Unassigned Text to the bottom of my Container, as shown in this mockup:

Below is the code, that I have so far. I am struggling to get the border between the play button working too. I have tried the usual css: bottom:0 and position:relevant Along with Flexbox but it doesn't seem to want to go to the very bottom of the container.

```<code> const styles = theme => ({
  root: {
    flexGrow: 1,
    overflow: 'hidden',
    padding: theme.spacing(0, 3),
  },
  paper: {
    maxWidth: 800,
    margin: `${theme.spacing(2)}px auto`,
    padding: theme.spacing(2),
  },
  textField: {
    marginLeft: theme.spacing(1),
    marginRight: theme.spacing(1),
    width: 200,
  },
  playButton: {
    display: "flex",
    flexDirection: "column",
    justifyContent: "center",
    alignItems: "center",
    position: "relative",
    "& .playButton": {
      position: "absolute",
      top: "60%",
      left: "-55px",
      transform: "translateY(-50%)",
    },
      "& .star-rating": {
        "& .fa-star": {
          "&:hover": {
            "&::before": {
              content: "\f005",
              color: "yellow"
            }
          }
        }
      },
    },
});

function Tasks(props) {
  const { classes } = props;
  return (
    <div className={classes.root}>
      <Paper className={classes.paper}>
        <Grid container spacing={2}>
          <Grid item xs={12} sm container>
            <Grid item xs container direction="column" spacing={2}>
              <Grid item xs>
              <div className="name-label">
              Name
              </div>
              <Typography variant="h6" gutterBottom>
              {props.name}
              </Typography>
              <div className="form-divider"></div>
                <Typography variant="body2" color="textSecondary">
                {props.description}
                </Typography>
              </Grid>
            </Grid>
            <Grid item classes={{ root: props.classes.playButton}}>
    <Grid item xs={3} className="playButton">
      <i class="far fa-play-circle fa-2x"></i>
    </Grid>
    <div className="workers-assigned-label">
      Workers Assigned
    </div>
    <Typography variant="h6" gutterBottom>
        0/25
      </Typography>
      <div class="star-rating">
        <label class="far fa-star fa-2x"></label>
        <label class="far fa-star fa-2x"></label>
        <label class="far fa-star fa-2x"></label>
      </div>
    <div className="dropdown-menu">
  <h5>Unnassigned</h5>
</div>
  </Grid>
          </Grid>
        </Grid>
      </Paper>
    </div>
  );
}

export default withStyles(styles)(Tasks);
</code>```

Any input would be great.

答:
I would recommend starting with a Grid 'skeleton' that looks something like:

```<code><Grid container>
  <Grid item container xs={8} direction="column" justify="flex-start">
    // Left column contents, with each row as a <Grid item>
  </Grid>
  <Fab className={classes.fab}><PlayIcon /><Fab>
  <Grid item container xs={4} direction="column" justify="space-between" className={classes.right}>
    // Right column contents, with each row as a <Grid item>
  </Grid>
</Grid>
</code>```

The direction=column will help you position items vertically within each container.  The justify=space-between will ensure that your first item is at the top of the container and your last item (the unassigned text) is at the bottom.

The "right" css class looks like:

```<code>right: {
  borderLeft: `1px solid ${theme.palette.grey[500]}`,
  position: "relative"
}
</code>```

You can give it a position of "relative" to make it easier to position the fab relative to the column.  The "fab" class looks like:

```<code>fab: {
  position: "absolute",
  margin: "auto",
  top: 0,
  bottom: 0,
  left: -28
}
</code>```

The margin, top, and bottom properties help center the fab vertically, and the left is a bit of a hack based on the dimensions of the fab to center it over the border.

Here's a working draft that brings everything together: https://codesandbox.io/s/tender-torvalds-dlbke?fontsize=14

Body:
I am trying to add Unassigned Text to the bottom of my Container, as shown in this mockup:

Below is the code, that I have so far. I am struggling to get the border between the play button working too. I have tried the usual css: bottom:0 and position:relevant Along with Flexbox but it doesn't seem to want to go to the very bottom of the container.

 const styles = theme => ({
  root: {
    flexGrow: 1,
    overflow: 'hidden',
    padding: theme.spacing(0, 3),
  },
  paper: {
    maxWidth: 800,
    margin: `${theme.spacing(2)}px auto`,
    padding: theme.spacing(2),
  },
  textField: {
    marginLeft: theme.spacing(1),
    marginRight: theme.spacing(1),
    width: 200,
  },
  playButton: {
    display: "flex",
    flexDirection: "column",
    justifyContent: "center",
    alignItems: "center",
    position: "relative",
    "& .playButton": {
      position: "absolute",
      top: "60%",
      left: "-55px",
      transform: "translateY(-50%)",
    },
      "& .star-rating": {
        "& .fa-star": {
          "&:hover": {
            "&::before": {
              content: "\f005",
              color: "yellow"
            }
          }
        }
      },
    },
});

function Tasks(props) {
  const { classes } = props;
  return (

      <Paper className={classes.paper}>
        <Grid container spacing={2}>
          <Grid item xs={12} sm container>
            <Grid item xs container direction="column" spacing={2}>
              <Grid item xs>

              Name

              <Typography variant="h6" gutterBottom>
              {props.name}
              </Typography>

                <Typography variant="body2" color="textSecondary">
                {props.description}
                </Typography>
              </Grid>
            </Grid>
            <Grid item classes={{ root: props.classes.playButton}}>
    <Grid item xs={3} className="playButton">

    </Grid>

      Workers Assigned

    <Typography variant="h6" gutterBottom>
        0/25
      </Typography>

Unnassigned

  </Grid>
          </Grid>
        </Grid>
      </Paper>

  );
}

export default withStyles(styles)(Tasks);

Any input would be great.

Body:
I would recommend starting with a Grid 'skeleton' that looks something like:

<Grid container>
  <Grid item container xs={8} direction="column" justify="flex-start">
    // Left column contents, with each row as a <Grid item>
  </Grid>
  <Fab className={classes.fab}><PlayIcon /><Fab>
  <Grid item container xs={4} direction="column" justify="space-between" className={classes.right}>
    // Right column contents, with each row as a <Grid item>
  </Grid>
</Grid>

The direction=column will help you position items vertically within each container.  The justify=space-between will ensure that your first item is at the top of the container and your last item (the unassigned text) is at the bottom.

The "right" css class looks like:

right: {
  borderLeft: `1px solid ${theme.palette.grey[500]}`,
  position: "relative"
}

You can give it a position of "relative" to make it easier to position the fab relative to the column.  The "fab" class looks like:

fab: {
  position: "absolute",
  margin: "auto",
  top: 0,
  bottom: 0,
  left: -28
}

The margin, top, and bottom properties help center the fab vertically, and the left is a bit of a hack based on the dimensions of the fab to center it over the border.

Here's a working draft that brings everything together: https://codesandbox.io/s/tender-torvalds-dlbke?fontsize=14


问:
Singleton initialization
I implemented the Singleton design pattern in my code.

Suppose it is:

```<code>class Singleton
{
  Singleton () {}
  static Singleton* s;
public:
  static Singleton* Get () {
    if (!s)
      s = new Singleton ();
    return s;
  }
};
</code>```

What puzzles me is the 'initialization' of this pattern.
In the .cpp I put:

```<code>SingletonPointer* SingletonClass::s (0);
</code>```

But I don't understand how is it possible to <s>access</s> define s, as it is private.
How's that possible?

TIA,
Jir

答:
The private variables can be accessed by all methods of a class. The only place you are accessing the s variable is in method Get() which belongs to the same class.

If you want to access the s from outside, you can't do it directly, but you have to call the Get() method (which is public) and that method will actually return s for you.

Usage:

```<code>Singleton * s = SingletonClass::Get();
</code>```

Title: Singleton initialization

Body:
I implemented the Singleton design pattern in my code.

Suppose it is:

class Singleton
{
  Singleton () {}
  static Singleton* s;
public:
  static Singleton* Get () {
    if (!s)
      s = new Singleton ();
    return s;
  }
};

What puzzles me is the 'initialization' of this pattern.
In the .cpp I put:

SingletonPointer* SingletonClass::s (0);

But I don't understand how is it possible to <s>access</s> define s, as it is private.
How's that possible?

TIA,
Jir

Body:
The private variables can be accessed by all methods of a class. The only place you are accessing the s variable is in method Get() which belongs to the same class.

If you want to access the s from outside, you can't do it directly, but you have to call the Get() method (which is public) and that method will actually return s for you.

Usage:

Singleton * s = SingletonClass::Get();


问:
jquery Date picker jquery to UK format
I am using the Jquery datepicker from the website to allow users to select date and was wondering if it would be possible for the displayed date to be shown is the UK format of the date for example 22nd September 2012 is shown in the uk as 22/09/2012 while in American format its 09/22/2012  </p>

答:
As per @user2903379 question to @campervancoder answer:

```<code>$('#datepicker').datepicker({ dateFormat: 'dd-mm-yy' });
</code>```

Will change the order of day/month/year

```<code>$('#datepicker').datepicker({ format: 'dd-mm-yyyy' });
</code>```

Will also change the / (slash) between values to a - (hyphen) so that the date is represented in the same way that it is stored in MySQL (albeit back-to-front). Note that I also had to use the 4 letter year representation otherwise the datepicker only returned a 2 digit year.

Title: jquery Date picker jquery to UK format

Body:
As per @user2903379 question to @campervancoder answer:

$('#datepicker').datepicker({ dateFormat: 'dd-mm-yy' });

Will change the order of day/month/year

$('#datepicker').datepicker({ format: 'dd-mm-yyyy' });

Will also change the / (slash) between values to a - (hyphen) so that the date is represented in the same way that it is stored in MySQL (albeit back-to-front). Note that I also had to use the 4 letter year representation otherwise the datepicker only returned a 2 digit year.


问:
How to generate all possible permutations of two numbers with value n in python?
I want to get permutations for two numbers upto n repetitions in python code.

Example:

a = 10, b = 100 and given n = 3

Now I want output like:

```<code>(10, 10, 10),
(10, 10, 100),
(10, 100, 10),
(10, 100, 100),
(100, 10, 10),
(100, 10, 100),
(100, 100, 10),
(100, 100, 100)
</code>```

I tried itertools permutations but wont helpful. Anyone please give me a solution.

答:
You can use itertools:</p>

```<code>from itertools import product

nums = [10, 100]
n = 3

ans = list(product(nums, repeat=n))
print(ans)
</code>```

Body:
I want to get permutations for two numbers upto n repetitions in python code.

Example:

a = 10, b = 100 and given n = 3

Now I want output like:

(10, 10, 10),
(10, 10, 100),
(10, 100, 10),
(10, 100, 100),
(100, 10, 10),
(100, 10, 100),
(100, 100, 10),
(100, 100, 100)

I tried itertools permutations but wont helpful. Anyone please give me a solution.

Body:
You can use itertools:

from itertools import product

nums = [10, 100]
n = 3

ans = list(product(nums, repeat=n))
print(ans)


问:
How to fit a lot of header within cell width using VBA?
I have copied approximately 88 columns of content from another spreadsheet. The problem is the headers are too big and they are not showing in the column cell properly. So, I had to go to each cell and press Alt+Enter each time. I want to use a macro that will do it automatically.

I am using Microsoft Excel 2016 version.

```<code>Sub Fit_Headers()

   'Fit_Headers Macro

    Range("BI13").Select
    ActiveCell.FormulaR1C1 = "ACTUAL SAMPLE " & Chr(10) & "FABRIC INHOUSE DATE"
    Range("BJ13").Select
End Sub
</code>```

I used "Record Macro" to record what I am doing in one cell. How can I modify it so I can use it for remaining cells?`

答:
I don't understand very well your ask.
Do you want apply the formula "ACTUAL SAMPLE " & Chr(10) & "FABRIC INHOUSE DATE" for a different cells ?

Like this :

```<code>Sub test()
    For Each c In Range("A1:B20").Cells
        c.FormulaR1C1 = "ACTUAL SAMPLE " & Chr(10) & "FABRIC INHOUSE DATE"
    Next c
End Sub
</code>```

Body:
I have copied approximately 88 columns of content from another spreadsheet. The problem is the headers are too big and they are not showing in the column cell properly. So, I had to go to each cell and press Alt+Enter each time. I want to use a macro that will do it automatically.

I am using Microsoft Excel 2016 version.

Sub Fit_Headers()

   'Fit_Headers Macro

    Range("BI13").Select
    ActiveCell.FormulaR1C1 = "ACTUAL SAMPLE " & Chr(10) & "FABRIC INHOUSE DATE"
    Range("BJ13").Select
End Sub

I used "Record Macro" to record what I am doing in one cell. How can I modify it so I can use it for remaining cells?`

Body:
I don't understand very well your ask.
Do you want apply the formula "ACTUAL SAMPLE " & Chr(10) & "FABRIC INHOUSE DATE" for a different cells ?

Like this :

Sub test()
    For Each c In Range("A1:B20").Cells
        c.FormulaR1C1 = "ACTUAL SAMPLE " & Chr(10) & "FABRIC INHOUSE DATE"
    Next c
End Sub


Title: How to generate all possible permutations of two numbers with value n in python?

Body:
You can use itertools.product and set a repeat of 3:

from itertools import product
a, b = 10, 100
n = 3

list(product([a,b], repeat=n))

[(10, 10, 10),
 (10, 10, 100),
 (10, 100, 10),
 (10, 100, 100),
 (100, 10, 10),
 (100, 10, 100),
 (100, 100, 10),
 (100, 100, 100)]


问:
Is there any way to send celery app.task logs into stackdriver?
I tried to send celery tasks logs which is created by default logging Python module into Stackdriver (google cloud platform) but I am missing something.

At the current state, all logs pushed but I am missing logs where created inside the tasks Python files.

```<code>class Logger(object):
    def __init__(self, log_level):
        formatter = CustomJsonFormatter(
            '(timestamp)(level)(name)(created)(process)(msecs)(message)'
        )
        formatter.json_ensure_ascii = False
        logger = logging.getLogger()
        logger.setLevel(log_level)
        client = google.cloud.logging.Client.from_service_account_json(
           'key.json')
        # StreamHandler
        # sh = logging.StreamHandler()
        sh = CloudLoggingHandler(client)
        sh.setLevel(log_level)
        sh.setFormatter(formatter)
        logger.addHandler(sh)

from app.utils.logger import Logger
from celery.signals import setup_logging
@setup_logging.connect
def initialize_logger(*args, **kwargs):
    Logger(log_level=log_level)
</code>```

答:
Try this instead:</p>

```<code>class Logger(object):
    def __init__(self, log_level):
        formatter = CustomJsonFormatter(
            '(timestamp)(level)(name)(created)(process)(msecs)(message)'
        )
        formatter.json_ensure_ascii = False
        logger = logging.getLogger()
        logger.setLevel(log_level)

        client = google.cloud.logging.Client.from_service_account_json(
           'key.json')
        log_handler = client.get_default_handler()
        cloud_logger = logging.getLogger("cloudLogger")
        cloud_logger.setLevel(log_level)
        cloud_logger.setFormatter(formatter)
        cloud_logger.addHandler(log_handler)
</code>```

Body:
I tried to send celery tasks logs which is created by default logging Python module into Stackdriver (google cloud platform) but I am missing something.

At the current state, all logs pushed but I am missing logs where created inside the tasks Python files.

class Logger(object):
    def __init__(self, log_level):
        formatter = CustomJsonFormatter(
            '(timestamp)(level)(name)(created)(process)(msecs)(message)'
        )
        formatter.json_ensure_ascii = False
        logger = logging.getLogger()
        logger.setLevel(log_level)
        client = google.cloud.logging.Client.from_service_account_json(
           'key.json')
        # StreamHandler
        # sh = logging.StreamHandler()
        sh = CloudLoggingHandler(client)
        sh.setLevel(log_level)
        sh.setFormatter(formatter)
        logger.addHandler(sh)

from app.utils.logger import Logger
from celery.signals import setup_logging
@setup_logging.connect
def initialize_logger(*args, **kwargs):
    Logger(log_level=log_level)

Body:
Try this instead:

class Logger(object):
    def __init__(self, log_level):
        formatter = CustomJsonFormatter(
            '(timestamp)(level)(name)(created)(process)(msecs)(message)'
        )
        formatter.json_ensure_ascii = False
        logger = logging.getLogger()
        logger.setLevel(log_level)

        client = google.cloud.logging.Client.from_service_account_json(
           'key.json')
        log_handler = client.get_default_handler()
        cloud_logger = logging.getLogger("cloudLogger")
        cloud_logger.setLevel(log_level)
        cloud_logger.setFormatter(formatter)
        cloud_logger.addHandler(log_handler)