问:
Extract specific values from stdClass Object
I have the following stdClass Object contained within $response:

```<code>stdClass Object ( [domain] => stdClass Object ( [id] => d1111111 [spamscore] => 75 [rejectscore] => 200 ) [domainalias] => Array ( ) [wildcard] => Array ( ) [catchall] => Array ( ) [forward] => Array ( ) [mailbox] => Array (

[0] => stdClass Object ( [highEmailNotification] => [id] => m1111111 [lastPasswordChange] => 2020-02-19T22:41:12+00:00 [local] => mailbox1 [lowEmailNotification] => [quotaMB] => 10240 [receive] => 1 [rejectscore] => [send] => 1 [spamscore] => [usageMB] => 0 [enabled] => 1 )

[1] => stdClass Object ( [highEmailNotification] => [id] => m2222222 [lastPasswordChange] => 2020-02-17T15:46:21+00:00 [local] => mailbox2 [lowEmailNotification] => [quotaMB] => 10240 [receive] => 1 [rejectscore] => [send] => 1 [spamscore] => [usageMB] => 0 [enabled] => 1 )

[2] => stdClass Object ( [highEmailNotification] => [id] => m3333333 [lastPasswordChange] => 2020-02-19T15:00:36+00:00 [local] => mailbox3 [lowEmailNotification] => [quotaMB] => 1024 [receive] => 1 [rejectscore] => 0 [send] => 1 [spamscore] => 75 [usageMB] => 0 [enabled] => 1 ) ) [spamblacklist] => Array ( ) [spamwhitelist] => Array ( ) [responder] => Array ( ) [name] => domain.com )
</code>```

I need to convert it into an array and extract particular values, i.e. [id] and [local] from it.

Speed is also an issue, as this array will grow to thousands of items, so if there is other, quicker way than 'foreach' it would be better.

I used some suggestions from here, such as:

```<code>$array = json_decode(json_encode($response), True);

foreach ($array as $var)
{
    echo $var['id'] . ' - ' . $var['local'] . "<br>";
}
</code>```

and got partial success with the results:

d1111111 -

-

-

-

-
i - i

(so it found the very first [id] value)

it however missed the most important values I am after.

What I need to get is:

m1111111 - mailbox1

m2222222 - mailbox2

m3333333 - mailbox3

Any suggestions are greatly appreciated.

答:
The values you're trying to print is in a nested array within $response.

Try this.

```<code>$array = json_decode(json_encode($response['mailbox']), True);

foreach ($array as $var)
{
    echo $var['id'] . ' - ' . $var['local'] . "<br>";
}
</code>```

Body:
I have the following stdClass Object contained within $response:

stdClass Object ( [domain] => stdClass Object ( [id] => d1111111 [spamscore] => 75 [rejectscore] => 200 ) [domainalias] => Array ( ) [wildcard] => Array ( ) [catchall] => Array ( ) [forward] => Array ( ) [mailbox] => Array (

[0] => stdClass Object ( [highEmailNotification] => [id] => m1111111 [lastPasswordChange] => 2020-02-19T22:41:12+00:00 [local] => mailbox1 [lowEmailNotification] => [quotaMB] => 10240 [receive] => 1 [rejectscore] => [send] => 1 [spamscore] => [usageMB] => 0 [enabled] => 1 )

[1] => stdClass Object ( [highEmailNotification] => [id] => m2222222 [lastPasswordChange] => 2020-02-17T15:46:21+00:00 [local] => mailbox2 [lowEmailNotification] => [quotaMB] => 10240 [receive] => 1 [rejectscore] => [send] => 1 [spamscore] => [usageMB] => 0 [enabled] => 1 )

[2] => stdClass Object ( [highEmailNotification] => [id] => m3333333 [lastPasswordChange] => 2020-02-19T15:00:36+00:00 [local] => mailbox3 [lowEmailNotification] => [quotaMB] => 1024 [receive] => 1 [rejectscore] => 0 [send] => 1 [spamscore] => 75 [usageMB] => 0 [enabled] => 1 ) ) [spamblacklist] => Array ( ) [spamwhitelist] => Array ( ) [responder] => Array ( ) [name] => domain.com )

I need to convert it into an array and extract particular values, i.e. [id] and [local] from it.

Speed is also an issue, as this array will grow to thousands of items, so if there is other, quicker way than 'foreach' it would be better.

I used some suggestions from here, such as:

$array = json_decode(json_encode($response), True);

foreach ($array as $var)
{
    echo $var['id'] . ' - ' . $var['local'] . "
";
}

and got partial success with the results:

d1111111 -

-

-

-

-
i - i

(so it found the very first [id] value)

it however missed the most important values I am after.

What I need to get is:

m1111111 - mailbox1

m2222222 - mailbox2

m3333333 - mailbox3

Any suggestions are greatly appreciated.

Body:
The values you're trying to print is in a nested array within $response.

Try this.

$array = json_decode(json_encode($response['mailbox']), True);

foreach ($array as $var)
{
    echo $var['id'] . ' - ' . $var['local'] . "<br>";
}


来源: stackexchange

问:
Summing up selected row duplicates
I have data that looks like this.

I wish to sum up the value column for rows that have the same name, time, and site. In this case, rows 3 and 4 would be summed, and rows 5 and 7 would be summed up.

I wish for the resulting data frame to look like this.

example data:

```<code>    name = c('a', 'a', 'b' , 'b', 'c', 'c', 'c', 'd')
    time = c(1,2,1,1,3,3,3,4)
    site = c('A', 'A', 'A', 'A','B', 'D','B', 'E')
    value = c(5,8,1,0,7,0,8,10)

mock = data.frame(name, time,site,value)
</code>```

答:
You can use base R aggregate to make it, i.e.,

```<code>> aggregate(value~.,mock,sum)
  name time site value
1    a    1    A     5
2    b    1    A     1
3    a    2    A     8
4    c    3    B    15
5    c    3    D     0
6    d    4    E    10
</code>```

ContentLicense: CC BY-SA 4.0

Title: Summing up selected row duplicates

Body:
I have data that looks like this.

I wish to sum up the value column for rows that have the same name, time, and site. In this case, rows 3 and 4 would be summed, and rows 5 and 7 would be summed up.

I wish for the resulting data frame to look like this.

example data:

    name = c('a', 'a', 'b' , 'b', 'c', 'c', 'c', 'd')
    time = c(1,2,1,1,3,3,3,4)
    site = c('A', 'A', 'A', 'A','B', 'D','B', 'E')
    value = c(5,8,1,0,7,0,8,10)

mock = data.frame(name, time,site,value)

Body:
You can use base R aggregate to make it, i.e.,

> aggregate(value~.,mock,sum)
  name time site value
1    a    1    A     5
2    b    1    A     1
3    a    2    A     8
4    c    3    B    15
5    c    3    D     0
6    d    4    E    10


问:
React natives LINKING component works fine in debug but in android release doesn't response
I want to get token by deep link to browser , every thing is ok in
debug but in release build nothing happen ,  I have checked the logcat
in android studio; here is my error in image . My Component

My environment :

```<code>react native version : 0.59.9
node version : v12.14.1
npm version : 6.13.4
gradle plugin version :3.4.0
gradle version : 5.4.1
</code>```

I have tried these steps :

Turn off minified

Resolved assets problem

Bundle assets then ./gradlew assemblerelease

Also try with android studio signed build

My Gradle
My LogCat Error

答: You can't refer to via HTTP Protocol to any URI in your production-app. It has to be HTTPS

Body:
I want to get token by deep link to browser , every thing is ok in
debug but in release build nothing happen ,  I have checked the logcat
in android studio; here is my error in image . My Component

My environment :

react native version : 0.59.9
node version : v12.14.1
npm version : 6.13.4
gradle plugin version :3.4.0
gradle version : 5.4.1

I have tried these steps :

Turn off minified

Resolved assets problem

Bundle assets then ./gradlew assemblerelease

Also try with android studio signed build

My Gradle
My LogCat Error


问:
Handle no internet connection axios, react native app (without NetInfo)
I have a screen where image from API rerender every N second. And I would like to handle situation when user didn't connected to the Internet. I was trying to solve this through state, but it's not working. How can i solve this problem?</p>

```<code>const [imgUrl, setImgUrl] = useState();
const [err, setErr] = useState(false);

const getImage = () =>
        Axios.get('https://dog.ceo/api/breeds/image/random')
            .then(response => {
                if (response.status >= 200 && response.status < 300) {
                    return response.data;
                } else {
                    setErr(true);
                }
            })
            .then(data => setImgUrl(data.message))
            .catch(err=>console.warn(err));

useEffect(() => {
 getImage();
}, []);

useEffect(() => {
  const timer = setInterval(getImage, value * 1000);
  return () => clearInterval(timer);
}, [value]);

return (
  <View>
    {err === false ? <Image style={styles.img} source={{ uri: `${imgUrl}` }} /> : <View><Text> please, check your network connection! </Text></View>}
  </View>
  <Text>{value}</Text>
  <Slider value={value} onValueChange={(sliderValue) => setValue(sliderValue)} />

);
</code>```

答:
in your catch block of the Axois.post, also call setErr(true);

```<code> Axios.get('https://dog.ceo/api/breeds/image/random')
            .then(response => {
                if (response.status >= 200 && response.status < 300) {
                    return response.data;
                } else {
                    setErr(true);
                }
            })
            .then(data => setImgUrl(data.message))
            .catch(err=>setErr(true)) // Changed;
</code>```

because if there is no internet axois will throw an error and the catch block will be invoked insted of the then block

Body:
I have a screen where image from API rerender every N second. And I would like to handle situation when user didn't connected to the Internet. I was trying to solve this through state, but it's not working. How can i solve this problem?

const [imgUrl, setImgUrl] = useState();
const [err, setErr] = useState(false);

const getImage = () =>
        Axios.get('https://dog.ceo/api/breeds/image/random')
            .then(response => {
                if (response.status >= 200 && response.status < 300) {
                    return response.data;
                } else {
                    setErr(true);
                }
            })
            .then(data => setImgUrl(data.message))
            .catch(err=>console.warn(err));

useEffect(() => {
 getImage();
}, []);

useEffect(() => {
  const timer = setInterval(getImage, value * 1000);
  return () => clearInterval(timer);
}, [value]);

return (
  <View>
    {err === false ? <Image style={styles.img} source={{ uri: `${imgUrl}` }} /> : <View><Text> please, check your network connection! </Text></View>}
  </View>
  <Text>{value}</Text>
  <Slider value={value} onValueChange={(sliderValue) => setValue(sliderValue)} />

);

Body:
in your catch block of the Axois.post, also call setErr(true);

 Axios.get('https://dog.ceo/api/breeds/image/random')
            .then(response => {
                if (response.status >= 200 && response.status < 300) {
                    return response.data;
                } else {
                    setErr(true);
                }
            })
            .then(data => setImgUrl(data.message))
            .catch(err=>setErr(true)) // Changed;

because if there is no internet axois will throw an error and the catch block will be invoked insted of the then block


问:
Get Text content of 3rd
 element inside
 element
I have some HTML / JS code looking like this.

    var bTags = document.getElementsByClassName("Wrapper");
    var kind = bTags[0];
    console.log(kind);
    console.log(kind.childNodes[4].text);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="Wrapper">
        <h3 class="date" id="date">{{date}}</h3>
    <div class="descriptionWrapper">
        <p class="jobDescription">{{job}}</p>
        <p class="jobAreaDescription">{{jobArea}}</p>
        <p class="placeDescription">{{ort}}</p>
        <p class="kindDescription">{{anstellung}}</p>
    </div>
    <div class="jobLink">
        {{#custom_link jobLink}}
            {{linkText}}
        {{/custom_link}}
    </div>
</div></code>```

In my example the "console.log(kind);" successfully logs the HTML object. Here its not working of course because its not defined.
But somehow the childNodes[0-4].text is undefined. I just want to access the text of the p element with the class "placeDescription" of this specific parentNode.

答:
```<code>const el = document.querySelector('.Wrapper p:nth-of-type(3)');
if (el) {
 console.log(el.textContent)
}
</code>```

Title: Get Text content of 3rd <p> element inside <div> element

Body:
I have some HTML / JS code looking like this.

    var bTags = document.getElementsByClassName("Wrapper");
    var kind = bTags[0];
    console.log(kind);
    console.log(kind.childNodes[4].text);

{{date}}

{{job}}

{{jobArea}}

{{ort}}

{{anstellung}}

        {{#custom_link jobLink}}
            {{linkText}}
        {{/custom_link}}

In my example the "console.log(kind);" successfully logs the HTML object. Here its not working of course because its not defined.
But somehow the childNodes[0-4].text is undefined. I just want to access the text of the p element with the class "placeDescription" of this specific parentNode.


问:
cant see the actual map when using google maps api
```<code><!DOCTYPE>
</code>```

```<code><style type="text/css">
  body {
    margin: 0;
    padding: 10px 20px 20px;
    font-family: Arial;
    font-size: 16px;
  }

  #map-container {
    padding: 6px;
    border-width: 1px;
    border-style: solid;
    border-color: #ccc #ccc #999 #ccc;
    -webkit-box-shadow: rgba(64, 64, 64, 0.5) 0 2px 5px;
    -moz-box-shadow: rgba(64, 64, 64, 0.5) 0 2px 5px;
    box-shadow: rgba(64, 64, 64, 0.1) 0 2px 5px;
    width: 100%;
  }

  #map {
    width: 100%;
    height: 98%;
  }

</style>

<script src="http://maps.google.com/maps/api/js?sensor=false"></script>

<script type="text/javascript" src="data/weblandmark.json"></script>
<script type="text/javascript" src="js/markerclusterer.js"></script>

<script type="text/javascript">
  function initialize() {
    var center = new google.maps.LatLng(48.133333, 11.566667);

    var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 3,
      center: center,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });

    var markers = [];
    for (var i = 0; i < 100; i++) {
      var dataPhoto = data.weblandmarks[i];
      var latLng = new google.maps.LatLng(dataPhoto.latitude,
          dataPhoto.longitude);
      var marker = new google.maps.Marker({
        position: latLng
      });
      markers.push(marker);
    }
    var markerCluster = new MarkerClusterer (map, markers);
  }
</script>
</code>```

I am using maps api with markercluster to show many places
I can see the zoom bar, and also the cluster generated by markercluster but not the actual map image
why?

答:
You could try making your map like this:

```<code>//The options for the google map
var mapOptions = {
    zoom: 3,
    center: center,
    mapTypeId: google.maps.MapTypeId.ROADMAP //Or whatever you want
};

var map = new google.maps.Map(document.getElementById('#map'), mapOptions);
</code>```

This is nitpicky but it makes it alot easier to work with the map if you have to add a lot of information to it later (markers/listeners/zooms after load)

ContentLicense: CC BY-SA 3.0

Body:
<!DOCTYPE>

I am using maps api with markercluster to show many places
I can see the zoom bar, and also the cluster generated by markercluster but not the actual map image
why?

Body:
You could try making your map like this:

//The options for the google map
var mapOptions = {
    zoom: 3,
    center: center,
    mapTypeId: google.maps.MapTypeId.ROADMAP //Or whatever you want
};

var map = new google.maps.Map(document.getElementById('#map'), mapOptions);

This is nitpicky but it makes it alot easier to work with the map if you have to add a lot of information to it later (markers/listeners/zooms after load)


问:
Datatable serverside does not allow to reinitialise
Hi I am using Datatable Server Side to my Website, I did a search but when I push in the button search, It works BUT it shows me that Datatable can not reinitialise, where is the problem in the code? Because It works but it displays that alert that it's annoying... First part of my code I just create a function to take all the data of the datatabse without a filter, then it comes the datatable and then the filter..

Thanks!

```<code>    fill_datatable();

    function fill_datatable(folio_filter = '', branch_office_filter = '', rut_filter = '', type_filter = '', status_filter = '', dte_filter = '')
    {
        $('#datatable_bill_track').DataTable({
            "processing": true,
            "serverSide": true,
            "searching" : false,
            "language": {
                    "sProcessing":     "Procesando...",
                    "sLengthMenu":     "Mostrar _MENU_ registros",
                    "sZeroRecords":    "No se encontraron resultados",
                    "sEmptyTable":     "Ningún dato disponible en esta tabla",
                    "sInfo":           "Mostrando registros del _START_ al _END_ de un total de _TOTAL_ registros",
                    "sInfoEmpty":      "Mostrando registros del 0 al 0 de un total de 0 registros",
                    "sInfoFiltered":   "(filtrado de un total de _MAX_ registros)",
                    "sInfoPostFix":    "",
                    "sSearch":         "Buscar: ",
                    "sUrl":            "",
                    "sInfoThousands":  ",",
                    "sLoadingRecords": "Cargando...",
                     "oPaginate": {
                        "sFirst":    "Primero",
                        "sLast":     "Último",
                        "sNext":     "Siguiente",
                        "sPrevious": "Anterior"
                    },
                    "oAria": {
                        "sSortAscending":  ": Activar para ordenar la columna de manera ascendente",
                        "sSortDescending": ": Activar para ordenar la columna de manera descendente"
                    },
                },
            "ajax":{
                     "url": "{{ url('bill_track/fetch') }}",
                     "dataType": "json",
                     "type": "POST",
                     "data":{
                      _token: "{{csrf_token()}}", folio_filter: folio_filter, branch_office_filter: branch_office_filter, rut_filter: rut_filter, type_filter: type_filter, status_filter: status_filter, dte_filter: dte_filter
                     }
                   },
            "columns": [
                { "data": "id_bill_track" },
                { "data": "branch_office" },
                { "data": "folio" },
                { "data": "client_supplier" },
                { "data": "liquid_amount" },
                { "data": "gross_amount" },
                { "data": "dte_type" },
                { "data": "type" },
                { "data": "status" },
                { "data": "bill_date" },
                { "data": "buttons" }
            ]

        });
    }

    $('#filter').click(function(){
        var folio_filter = $('#folio_filter').val();
        var branch_office_filter = $('#branch_office_filter').val();
        var rut_filter = $('#rut_filter').val();
        var type_filter = $('#type_filter').val();
        var status_filter = $('#status_filter').val();
        var dte_filter = $('#dte_filter').val();

        if(folio_filter != '' || branch_office_filter != '' || rut_filter != '' || type_filter != '' || status_filter != '' || dte_filter != '')
        {
            $('#datatable_bill_track').DataTable().destroy();
            fill_datatable(folio_filter, branch_office_filter, rut_filter, type_filter, status_filter, dte_filter);
        }
        else
        {
            $('#datatable_bill_track').DataTable().destroy();
            fill_datatable();
        }
    });
</code>```

答:
Does it work if instead of

```<code>$('#datatable_bill_track').DataTable().destroy();
</code>```

you put

```<code>destroy: true
</code>```

in your DataTable options?

Body:
Hi I am using Datatable Server Side to my Website, I did a search but when I push in the button search, It works BUT it shows me that Datatable can not reinitialise, where is the problem in the code? Because It works but it displays that alert that it's annoying... First part of my code I just create a function to take all the data of the datatabse without a filter, then it comes the datatable and then the filter..

Thanks!

    fill_datatable();

    function fill_datatable(folio_filter = '', branch_office_filter = '', rut_filter = '', type_filter = '', status_filter = '', dte_filter = '')
    {
        $('#datatable_bill_track').DataTable({
            "processing": true,
            "serverSide": true,
            "searching" : false,
            "language": {
                    "sProcessing":     "Procesando...",
                    "sLengthMenu":     "Mostrar _MENU_ registros",
                    "sZeroRecords":    "No se encontraron resultados",
                    "sEmptyTable":     "Ningún dato disponible en esta tabla",
                    "sInfo":           "Mostrando registros del _START_ al _END_ de un total de _TOTAL_ registros",
                    "sInfoEmpty":      "Mostrando registros del 0 al 0 de un total de 0 registros",
                    "sInfoFiltered":   "(filtrado de un total de _MAX_ registros)",
                    "sInfoPostFix":    "",
                    "sSearch":         "Buscar: ",
                    "sUrl":            "",
                    "sInfoThousands":  ",",
                    "sLoadingRecords": "Cargando...",
                     "oPaginate": {
                        "sFirst":    "Primero",
                        "sLast":     "Último",
                        "sNext":     "Siguiente",
                        "sPrevious": "Anterior"
                    },
                    "oAria": {
                        "sSortAscending":  ": Activar para ordenar la columna de manera ascendente",
                        "sSortDescending": ": Activar para ordenar la columna de manera descendente"
                    },
                },
            "ajax":{
                     "url": "{{ url('bill_track/fetch') }}",
                     "dataType": "json",
                     "type": "POST",
                     "data":{
                      _token: "{{csrf_token()}}", folio_filter: folio_filter, branch_office_filter: branch_office_filter, rut_filter: rut_filter, type_filter: type_filter, status_filter: status_filter, dte_filter: dte_filter
                     }
                   },
            "columns": [
                { "data": "id_bill_track" },
                { "data": "branch_office" },
                { "data": "folio" },
                { "data": "client_supplier" },
                { "data": "liquid_amount" },
                { "data": "gross_amount" },
                { "data": "dte_type" },
                { "data": "type" },
                { "data": "status" },
                { "data": "bill_date" },
                { "data": "buttons" }
            ]

        });
    }

    $('#filter').click(function(){
        var folio_filter = $('#folio_filter').val();
        var branch_office_filter = $('#branch_office_filter').val();
        var rut_filter = $('#rut_filter').val();
        var type_filter = $('#type_filter').val();
        var status_filter = $('#status_filter').val();
        var dte_filter = $('#dte_filter').val();

        if(folio_filter != '' || branch_office_filter != '' || rut_filter != '' || type_filter != '' || status_filter != '' || dte_filter != '')
        {
            $('#datatable_bill_track').DataTable().destroy();
            fill_datatable(folio_filter, branch_office_filter, rut_filter, type_filter, status_filter, dte_filter);
        }
        else
        {
            $('#datatable_bill_track').DataTable().destroy();
            fill_datatable();
        }
    });

Body:
Does it work if instead of

$('#datatable_bill_track').DataTable().destroy();

you put

destroy: true

in your DataTable options?


问:
JavaScript: Display positive numbers with the plus sign
How would I display positive number such as 3 as +3 and negative numbers such -5 as -5? So, as follows:

1, 2, 3 goes into +1, +2, +3

but if those are

-1, -2, -3 then goes into -1, -2, -3

答:
Modern syntax solution.

It also includes a space between sign and number:

```<code>function getNumberWithSign(input) {
  if (input === 0) {
    return "0"
  }

  const sign = input < 0 ? '-' : '+';

  return `${sign} ${Math.abs(input)}`;
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Modern syntax solution.

It also includes a space between sign and number:

function getNumberWithSign(input) {
  if (input === 0) {
    return "0"
  }

  const sign = input < 0 ? '-' : '+';

  return `${sign} ${Math.abs(input)}`;
}


问:
Why does `substitute` work in multiple lines, but not in a single line?
I was attempting to answer this nice question about creating a non-standard evaluating function for a data.table object, doing a grouped sum. Akrun came up with a lovely answer which I'll simplify here:

```<code>akrun <- function(data, var, group){
 var <- substitute(var)
 group <- substitute(group)
 data[, sum(eval(var)), by = group]
}

library(data.table)
mt = as.data.table(mtcars)
akrun(mt, cyl, mpg)
#    group    V1
# 1:     6 138.2
# 2:     4 293.3
# 3:     8 211.4
</code>```

I was also working on an answer, and had close to the same answer, but with the substitutes inline with the rest. Mine results in an error:

```<code>gregor = function(data, var, group) {
  data[, sum(eval(substitute(var))), by = substitute(group)]
}

gregor(mt, mpg, cyl)
# Error in `[.data.table`(data, , sum(eval(substitute(var))), by = substitute(group)) :
#  'by' or 'keyby' must evaluate to vector or list of vectors
#  (where 'list' includes data.table and data.frame which are lists, too)
</code>```

At its face, my function is a simple substitution of Akrun's. Why doesn't it work?

Note that both substitutions cause problems, as shown here:

```<code>gregor_1 = function(data, var, group) {
  var = substitute(var)
  data[,sum(eval(var)),
       by = substitute(group)]
}
gregor_1(mt, mpg, cyl)
# Same error as above

gregor_2 = function(data, var, group) {
  group = substitute(group)
  data[,sum(eval(substitute(var))),
       by = group]
}
gregor_2(mt, mpg, cyl)
# Error in eval(substitute(var)) : object 'mpg' not found
</code>```

答:
data.table uses NSE because it needs to analyse/manipulate the by argument before choosing if it will evaluate it or not (if you give it a symbol for example it won't evaluate it).

A consequence is that if the argument needs to be evaluated it should be evaluated in the right environment and this is the function's responsibility. data.table evaluates its by argument in the data, not in the calling environment.

In most cases you don't see the issue as the symbol will be evaluated in the parent environment if not found, but substitute() is more sensitive.

See example below :

fun <- function(x){
  standard_eval(x)
  non_standard_eval_safe(x)
  non_standard_eval_not_safe(x)
}

standard_eval          <- function(expr) print(expr)

non_standard_eval_safe <- function(expr) {
  expr <- bquote(print(.(substitute(expr)))) # will be quote(print(x)) in our example
  eval.parent(expr)
}

non_standard_eval_not_safe <- function(expr) {
  expr <- bquote(print(.(substitute(expr))))  # will be quote(print(x)) in our example
  eval(expr)
}

standard_eval(1+1)
#> [1] 2

non_standard_eval_safe(1+1)
#> [1] 2

non_standard_eval_not_safe(1+1)
#> [1] 2

fun(1+1)
#> [1] 2
#> [1] 2
#> Error in print(x): object 'x' not found

```

Created on 2020-02-20 by the reprex package (v0.3.0)

Body:
I was attempting to answer this nice question about creating a non-standard evaluating function for a data.table object, doing a grouped sum. Akrun came up with a lovely answer which I'll simplify here:

akrun <- function(data, var, group){
 var <- substitute(var)
 group <- substitute(group)
 data[, sum(eval(var)), by = group]
}

library(data.table)
mt = as.data.table(mtcars)
akrun(mt, cyl, mpg)
#    group    V1
# 1:     6 138.2
# 2:     4 293.3
# 3:     8 211.4

I was also working on an answer, and had close to the same answer, but with the substitutes inline with the rest. Mine results in an error:

gregor = function(data, var, group) {
  data[, sum(eval(substitute(var))), by = substitute(group)]
}

gregor(mt, mpg, cyl)
# Error in `[.data.table`(data, , sum(eval(substitute(var))), by = substitute(group)) :
#  'by' or 'keyby' must evaluate to vector or list of vectors
#  (where 'list' includes data.table and data.frame which are lists, too)

At its face, my function is a simple substitution of Akrun's. Why doesn't it work?

Note that both substitutions cause problems, as shown here:

gregor_1 = function(data, var, group) {
  var = substitute(var)
  data[,sum(eval(var)),
       by = substitute(group)]
}
gregor_1(mt, mpg, cyl)
# Same error as above

gregor_2 = function(data, var, group) {
  group = substitute(group)
  data[,sum(eval(substitute(var))),
       by = group]
}
gregor_2(mt, mpg, cyl)
# Error in eval(substitute(var)) : object 'mpg' not found

Body:
data.table uses NSE because it needs to analyse/manipulate the by argument before choosing if it will evaluate it or not (if you give it a symbol for example it won't evaluate it).

A consequence is that if the argument needs to be evaluated it should be evaluated in the right environment and this is the function's responsibility. data.table evaluates its by argument in the data, not in the calling environment.

In most cases you don't see the issue as the symbol will be evaluated in the parent environment if not found, but substitute() is more sensitive.

See example below :

fun <- function(x){
  standard_eval(x)
  non_standard_eval_safe(x)
  non_standard_eval_not_safe(x)
}

standard_eval          <- function(expr) print(expr)

non_standard_eval_safe <- function(expr) {
  expr <- bquote(print(.(substitute(expr)))) # will be quote(print(x)) in our example
  eval.parent(expr)
}

non_standard_eval_not_safe <- function(expr) {
  expr <- bquote(print(.(substitute(expr))))  # will be quote(print(x)) in our example
  eval(expr)
}

standard_eval(1+1)
#> [1] 2

non_standard_eval_safe(1+1)
#> [1] 2

non_standard_eval_not_safe(1+1)
#> [1] 2

fun(1+1)
#> [1] 2
#> [1] 2
#> Error in print(x): object 'x' not found

Created on 2020-02-20 by the reprex package (v0.3.0)


问:
Skip blank rows in 2D string array effectively
Consider 2D array like this one:

With the following code the empty rows are skipped:

```<code>public static string[,] SkipBlankRows(this string[,] array2D)
{
    var columns = array2D.GetLength(1);
    var rows = array2D.GetLength(0);
    var temp = new List<string[]>();

    for (var r = 0; r < rows; r++)
    {
        var row = new string[columns];
        for (var c = 0; c < columns; c++)
        {
            row[c] = array2D[r, c];
        }
        if (row.All(itm => string.IsNullOrWhiteSpace(itm)))
            continue;
        temp.Add(row);
    }

    string[,] result = new string[temp.Count(), columns];
    rows = temp.Count();

    for (int r = 0; r < rows; r++)
    {
        var row = temp[r];
        for (var c = 0; c < row.Length; c++)
        {
            result[r,c]=row[c];
        }
    }
    return result;
}
</code>```

Usage:

```<code>void Main()
{
    var x = new string[,] { { "", "", "" }, { "", "X", "" }, { "X", "X", "X" }, { "", "", "" }, {"X","","X"}, {"X","X","X"}};
    var y = x.SkipBlankRows();
}
</code>```

Result:

The result should be 2D-array of string where the blank rows will not be there.

The code looks awkward to me, is it possible to do it better e.g. to involve linq?

答:
It depends on what you want your output to look like, do you just want to skip over the blank strings and have a list of values? Or do you want your data to still be in the multi-dimentional array?

If your answer to this question is "the second one" then your code is fine.

If you just want a list of all of the values out of the multi-dimentional array you could write something like:

```<code>public static IEnumerable<string> SkipBlankRows(this string[,] array2D)
{
    return (from string s in array2D where !string.IsNullOrWhiteSpace(s) select s);
}
</code>```

This returns a flat structure of values from the array.

Hope this helps

Body:
Consider 2D array like this one:

With the following code the empty rows are skipped:

public static string[,] SkipBlankRows(this string[,] array2D)
{
    var columns = array2D.GetLength(1);
    var rows = array2D.GetLength(0);
    var temp = new List<string[]>();

    for (var r = 0; r < rows; r++)
    {
        var row = new string[columns];
        for (var c = 0; c < columns; c++)
        {
            row[c] = array2D[r, c];
        }
        if (row.All(itm => string.IsNullOrWhiteSpace(itm)))
            continue;
        temp.Add(row);
    }

    string[,] result = new string[temp.Count(), columns];
    rows = temp.Count();

    for (int r = 0; r < rows; r++)
    {
        var row = temp[r];
        for (var c = 0; c < row.Length; c++)
        {
            result[r,c]=row[c];
        }
    }
    return result;
}

Usage:

void Main()
{
    var x = new string[,] { { "", "", "" }, { "", "X", "" }, { "X", "X", "X" }, { "", "", "" }, {"X","","X"}, {"X","X","X"}};
    var y = x.SkipBlankRows();
}

Result:

The result should be 2D-array of string where the blank rows will not be there.

The code looks awkward to me, is it possible to do it better e.g. to involve linq?

Body:
It depends on what you want your output to look like, do you just want to skip over the blank strings and have a list of values? Or do you want your data to still be in the multi-dimentional array?

If your answer to this question is "the second one" then your code is fine.

If you just want a list of all of the values out of the multi-dimentional array you could write something like:

public static IEnumerable<string> SkipBlankRows(this string[,] array2D)
{
    return (from string s in array2D where !string.IsNullOrWhiteSpace(s) select s);
}

This returns a flat structure of values from the array.

Hope this helps


问:
How do I write an arrow function in ES6 recursively?
Arrow functions in ES6 do not have an arguments property and therefore arguments.callee will not work and would anyway not work in strict mode even if just an anonymous function was being used.

Arrow functions cannot be named, so the named functional expression trick can not be used.

So... How does one write a recursive arrow function? That is an arrow function that recursively calls itself based on certain conditions and so on of-course?

答:
TL;DR:

```<code>const rec = f => f((...xs) => rec(f)(...xs));
</code>```

There are many answers here with variations on a proper Y -- but that's a bit redundant...  The thing is that the usual way Y is explained is "what if there is no recursion", so Y itself cannot refer to itself.  But since the goal here is a practical combinator, there's no reason to do that.  There's this answer that defines rec using itself, but it's complicated and kind of ugly since it adds an argument instead of currying.

The simple recursively-defined Y is

```<code>const rec = f => f(rec(f));
</code>```

but since JS isn't lazy, the above adds the necessary wrapping.

Body:
TL;DR:

const rec = f => f((...xs) => rec(f)(...xs));

There are many answers here with variations on a proper Y -- but that's a bit redundant...  The thing is that the usual way Y is explained is "what if there is no recursion", so Y itself cannot refer to itself.  But since the goal here is a practical combinator, there's no reason to do that.  There's this answer that defines rec using itself, but it's complicated and kind of ugly since it adds an argument instead of currying.

The simple recursively-defined Y is

const rec = f => f(rec(f));

but since JS isn't lazy, the above adds the necessary wrapping.


问:
https for localhost:8080
I am trying to develop a facebook app written in Python running on Google App Engine, so i need to make my http://localhost:8080 to https://localhost:8080 since facebook is asking for a Secure Canvas URL
how can i make https in localhost:8080 ?</p>

答:
From the docs:

The development web server does not
  support HTTPS connections. It ignores
  the secure parameter, so paths
  intended for use with HTTPS can be
  tested using regular HTTP connections
  to the development web server.

You can star issue 960 to request that support be added. Until then, my advice would be to run Apache or lighttpd as a proxy to the development server, and enable HTTPS on the front-end service only.

Title: https for localhost:8080


问:
Filter array of objects by common properties
Is it possible in some way to filter let's say such an array of object arrays:

```<code>[[{id: 1}, {id: 2}, {id: 3}], [{id:6}, {id: 2}], [{id: 2}, {id: 1}, {id: 9}, {id: 3}]]
</code>```

To get array of objects which all arrays have the same property (id), so in this case it output will be:

```<code>[{id: 2}] // becasue this id is the same in all three subarrays
</code>```

I've only try intersectionBy from loadash but it seems to work in completely other way :/

答:
I would take one array (it's enough to take one because if the property is not there its already not common), in this example I'm taking the first one but probably more efficient will be picking the shortest one.

iterate over the array and check for each object if its common to all other arrays.

const arr = [[{id: 1}, {id: 2}, {id: 3}], [{id:6}, {id: 2}], [{id: 2}, {id: 1}, {id: 9}, {id: 3}]];

let firstArray = arr.shift();

const result = firstArray.reduce((common, item)=>{
  if (arr.every(inner => inner.some(_item => _item.id === item.id))) {
    common.push(item);
  }

  return common;
},[])

console.log(result);```

Body:
Is it possible in some way to filter let's say such an array of object arrays:

[[{id: 1}, {id: 2}, {id: 3}], [{id:6}, {id: 2}], [{id: 2}, {id: 1}, {id: 9}, {id: 3}]]

To get array of objects which all arrays have the same property (id), so in this case it output will be:

[{id: 2}] // becasue this id is the same in all three subarrays

I've only try intersectionBy from loadash but it seems to work in completely other way :/


问:
Why hiding part of the HTML when using media-query does not work
Trying to practice I have created a landing page mock up and trying to hide an element in css media query.

```<code>@media (max-width:800){

 .right-pane{
    display: none;
    }
}
</code>```

But it does not work when resizing the screen.
Would appreciate your feedback

https://codepen.io/yanivlt/pen/eYNdKRV

答:
Try adding px to the max-width parameter.

Using your example, this should work:

```<code>@media (max-width:800px){
  .right-pane {
    display: none;
  }
}
</code>```

Body:
Trying to practice I have created a landing page mock up and trying to hide an element in css media query.

@media (max-width:800){

 .right-pane{
    display: none;
    }
}

But it does not work when resizing the screen.
Would appreciate your feedback

https://codepen.io/yanivlt/pen/eYNdKRV

Body:
Try adding px to the max-width parameter.

Using your example, this should work:

@media (max-width:800px){
  .right-pane {
    display: none;
  }
}


问:
Reset a JSON Extractor Parameter Value after exiting the While Controller - JMeter
Attempting to create a request with JMeter where the request has to retry until a JSON variable ($.result.status) of the response meets the expected result. In detail, the request should retry untill the value of the variable turns into "completed" from "pending" state.

For this I have used to a While Controller with the following JS condition. It works perfectly in the 1st iteration/loop and exits the While-Controller once the resultStatus turned into "completed"

```<code>${__javaScript("${resultStatus}" == "pending" || "${resultStatus}" != "completed" || "${resultStatus}" == "" )}
</code>```

But, from the 2nd loop onward the While-Controller is getting skipped.

I assume the reason was because the resultStatus variable was assigned to "completed" along with the exit for the While-Controller in the 1st loop and remains as it is when it comes to the While controller in the second loop. Therefore the condition is getting false..

With that assumption, I tried vars.remove for BeanShellPostProcessor in While-Controller with following code snippet. But it didn't resolve my issue.

```<code>String x = vars.get("resultStatus");
if ( x == "completed"){
vars.remove("resultStatus", "completed");}
</code>```

Below is the structure of the Jmeter Tree.

Red Box : While Controller

Red Arrow Point : Response Variable Change

from Pending to Completed and Step-in to Loop 2

Could it be the reason I assumed for this issue of skipping the While controller from 2nd loop?
 If it is; What is approach I should take to clear the variable value?

If it is not the reason I assumed, Can I kindly get assisted with the reason and a solution?

答:
JSR223 Sampler will solve this as mentioned in the previous comment.Just to remove the confusion Reset does not change the status we should use the desired value we want the variable to be updated with .

Below is the info from the java docs
    put(String key, String value)
Creates or updates a variable with a String value.

In my case below solution worked for me
vars.put("status","PENDING")

Body:
Attempting to create a request with JMeter where the request has to retry until a JSON variable ($.result.status) of the response meets the expected result. In detail, the request should retry untill the value of the variable turns into "completed" from "pending" state.

For this I have used to a While Controller with the following JS condition. It works perfectly in the 1st iteration/loop and exits the While-Controller once the resultStatus turned into "completed"

${__javaScript("${resultStatus}" == "pending" || "${resultStatus}" != "completed" || "${resultStatus}" == "" )}

But, from the 2nd loop onward the While-Controller is getting skipped.

I assume the reason was because the resultStatus variable was assigned to "completed" along with the exit for the While-Controller in the 1st loop and remains as it is when it comes to the While controller in the second loop. Therefore the condition is getting false..

With that assumption, I tried vars.remove for BeanShellPostProcessor in While-Controller with following code snippet. But it didn't resolve my issue.

String x = vars.get("resultStatus");
if ( x == "completed"){
vars.remove("resultStatus", "completed");}

Below is the structure of the Jmeter Tree.

Red Box : While Controller

Red Arrow Point : Response Variable Change

from Pending to Completed and Step-in to Loop 2

Could it be the reason I assumed for this issue of skipping the While controller from 2nd loop?
 If it is; What is approach I should take to clear the variable value?

If it is not the reason I assumed, Can I kindly get assisted with the reason and a solution?


问:
Want to Color Each Potted Cluster a Different Color
I'm trying to color each cluster plotted from DBscan a different color. I created a color list and tried to have the code iterate through each cluster and plot it a different color, but it colors all the clusters the same color which is the last color from the color list (purple). Help would be appreciated.

```<code>import pandas as pd
from sklearn.cluster import DBSCAN
from collections import Counter
from sklearn.neighbors import NearestNeighbors
from matplotlib import pyplot as plt
import matplotlib
matplotlib.use('TkAgg')

eps = 4.3

model  = DBSCAN(eps            = eps,
                min_samples    = 210,
                metric         = 'euclidean'
                )

data = model.fit(plotting_data)

X          = plotting_data['X']
Y          = plotting_data['Y']

clusters = data.fit_predict(plotting_data)
print(clusters)

clust_df = pd.DataFrame(plotting_data)

clusters = (clust_df[data.labels_ != -1])

labels = data.labels_
num_clusters = len(set(labels))
print(num_clusters)

color_list = ['green', 'blue', 'red', 'yellow',  'orange',  'magenta', 'cyan', 'purple']
labels = data.labels_
num_clusters = len(set(labels))

i = 0
for col in zip(color_list):
    plt.scatter(clusters['X'],
                clusters['Y'],
                c = col

                )
    i += 1

plt.title("Clusters: " + str(num_clusters), fontsize = 13)

plt.show()

</code>```

[![enter image description here][1]][1]

答:
I think this would work:</p>

```<code>color_list = np.array(['green', 'blue', 'red', 'yellow',  'orange',  'magenta', 'cyan', 'purple'])

plt.scatter(clusters['X'], clusters['Y'], c = color_list[labels])
plt.show()
</code>```

Body:
I'm trying to color each cluster plotted from DBscan a different color. I created a color list and tried to have the code iterate through each cluster and plot it a different color, but it colors all the clusters the same color which is the last color from the color list (purple). Help would be appreciated.

import pandas as pd
from sklearn.cluster import DBSCAN
from collections import Counter
from sklearn.neighbors import NearestNeighbors
from matplotlib import pyplot as plt
import matplotlib
matplotlib.use('TkAgg')

eps = 4.3

model  = DBSCAN(eps            = eps,
                min_samples    = 210,
                metric         = 'euclidean'
                )

data = model.fit(plotting_data)

X          = plotting_data['X']
Y          = plotting_data['Y']

clusters = data.fit_predict(plotting_data)
print(clusters)

clust_df = pd.DataFrame(plotting_data)

clusters = (clust_df[data.labels_ != -1])

labels = data.labels_
num_clusters = len(set(labels))
print(num_clusters)

color_list = ['green', 'blue', 'red', 'yellow',  'orange',  'magenta', 'cyan', 'purple']
labels = data.labels_
num_clusters = len(set(labels))

i = 0
for col in zip(color_list):
    plt.scatter(clusters['X'],
                clusters['Y'],
                c = col

                )
    i += 1

plt.title("Clusters: " + str(num_clusters), fontsize = 13)

plt.show()

[![enter image description here][1]][1]

Body:
I think this would work:

color_list = np.array(['green', 'blue', 'red', 'yellow',  'orange',  'magenta', 'cyan', 'purple'])

plt.scatter(clusters['X'], clusters['Y'], c = color_list[labels])
plt.show()


问:
Getting wrong values when I stitch 2 shorts back into an unsigned long
I am doing BLE communications with an Arduino Board and an FPGA.
I have this requirement which restraints me from changing the packet structure (the packet structure is basically short data types). Thus, to send a timestamp (form millis()) over, I have to split an unsigned long into 2 shorts on the Arduino side and stitch it back up on the FPGA side (python).

This is the implementation which I have:

  // Arduino code in c++
  unsigned long t = millis();
  // bitmask to get bits 1-16
  short LSB = (short) (t & 0x0000FFFF);
  // bitshift to get bits 17-32
  short MSB = (short) (t >> 16);

  // I then send the packet with MSB and LSB values

```

<pre class="lang-py prettyprint-override"><code>  # FPGA python code to stitch it back up (I receive the packet and extract the MSB and LSB)
  MSB = data[3]
  LSB = data[4]
  data = MSB << 16 | LSB
</code>```

Now the issue is that my output for data on the FPGA side is sometimes negative, which tells me that I must have missed something somewhere as timestamps are not negative. Does any one know why ?

When I transfer other data in the packet (i.e. other short values and not the timestamp), I am able to receive them as expected, so the problem most probably lies in the conversion that I did and not the sending/receiving of data.

答: you probably need/want to first convert the long to network byte order using hotnl

Body:
I am doing BLE communications with an Arduino Board and an FPGA.
I have this requirement which restraints me from changing the packet structure (the packet structure is basically short data types). Thus, to send a timestamp (form millis()) over, I have to split an unsigned long into 2 shorts on the Arduino side and stitch it back up on the FPGA side (python).

This is the implementation which I have:

  // Arduino code in c++
  unsigned long t = millis();
  // bitmask to get bits 1-16
  short LSB = (short) (t & 0x0000FFFF);
  // bitshift to get bits 17-32
  short MSB = (short) (t >> 16);

  // I then send the packet with MSB and LSB values

  # FPGA python code to stitch it back up (I receive the packet and extract the MSB and LSB)
  MSB = data[3]
  LSB = data[4]
  data = MSB << 16 | LSB

Now the issue is that my output for data on the FPGA side is sometimes negative, which tells me that I must have missed something somewhere as timestamps are not negative. Does any one know why ?

When I transfer other data in the packet (i.e. other short values and not the timestamp), I am able to receive them as expected, so the problem most probably lies in the conversion that I did and not the sending/receiving of data.


问:
Return top 2 and bottom 1 columns of ranked dataframe pandas
I'm trying to return row-wise the top two records by value, and the bottom record by value as additional columns, or a separate dataframe entirely (either or).

Lets say I have the following dataframe of values:

```<code>example = pd.DataFrame({'a':[3, 8, 5, 3, 2, 1, 3],
                        'b':[6, 5, 8, 0, 3, 2, 1],
                        'c':[1, 4, 5, 3, 6, 2, 7],
                        'd':[4, 6, 5, 3, 9, 11, 3],
                        'e':[8, 0, 5, 2, 1, 1, 3]})
example

   a  b  c   d  e
0  3  6  1   4  8
1  8  5  4   6  0
2  5  8  5   5  5
3  3  0  3   3  2
4  2  3  6   9  1
5  1  2  2  11  1
6  3  1  7   3  3
</code>```

Since I want to find the top values, I end up ranking this dataframe, columnwise with no repeating in rank.

```<code>rank_df = example.rank(axis=1, method='first', ascending=False)
rank_df

     a    b    c    d    e
0  4.0  2.0  5.0  3.0  1.0
1  1.0  3.0  4.0  2.0  5.0
2  2.0  1.0  3.0  4.0  5.0
3  1.0  5.0  2.0  3.0  4.0
4  4.0  3.0  2.0  1.0  5.0
5  4.0  2.0  3.0  1.0  5.0
6  2.0  5.0  1.0  3.0  4.0
</code>```

Now lastly, I would like to pull in the column names for the ranks, and pull out into a dataframe the top two and bottom one. For example, row 0 has rank 1 in column e, rank 2 in column b, and rank 5 in column c, so the three columns would be e, b, c.

Expected Output:

```<code>   top_1, top_2, bottom_1
0  e      b      c
1  a      d      e
2  b      a      e
3  a      c      b
4  d      c      e
5  d      b      e
6  c      a      b
</code>```

答:
Use numpy.argsort for positions of sorted values and get columns names by indexing:

```<code>a = example.columns.to_numpy()[(-example).to_numpy().argsort()]
#if use lower version of pandas
#a = example.columns.values[(-example).values.argsort()]
print(a)

[['e' 'b' 'd' 'a' 'c']
 ['a' 'd' 'b' 'c' 'e']
 ['b' 'a' 'c' 'd' 'e']
 ['a' 'c' 'd' 'e' 'b']
 ['d' 'c' 'b' 'a' 'e']
 ['d' 'b' 'c' 'a' 'e']
 ['c' 'a' 'd' 'e' 'b']]
</code>```

And then select first, second and last column and convert to DataFrame:

```<code>df = pd.DataFrame(a[:, [0,1,-1]], index=df.index, columns=['top_1', 'top_2', 'bottom_1'])
print (df)
  top_1 top_2 bottom_1
0     e     b        c
1     a     d        e
2     b     a        e
3     a     c        b
4     d     c        e
5     d     b        e
6     c     a        b
</code>```

Body:
I'm trying to return row-wise the top two records by value, and the bottom record by value as additional columns, or a separate dataframe entirely (either or).

Lets say I have the following dataframe of values:

example = pd.DataFrame({'a':[3, 8, 5, 3, 2, 1, 3],
                        'b':[6, 5, 8, 0, 3, 2, 1],
                        'c':[1, 4, 5, 3, 6, 2, 7],
                        'd':[4, 6, 5, 3, 9, 11, 3],
                        'e':[8, 0, 5, 2, 1, 1, 3]})
example

   a  b  c   d  e
0  3  6  1   4  8
1  8  5  4   6  0
2  5  8  5   5  5
3  3  0  3   3  2
4  2  3  6   9  1
5  1  2  2  11  1
6  3  1  7   3  3

Since I want to find the top values, I end up ranking this dataframe, columnwise with no repeating in rank.

rank_df = example.rank(axis=1, method='first', ascending=False)
rank_df

     a    b    c    d    e
0  4.0  2.0  5.0  3.0  1.0
1  1.0  3.0  4.0  2.0  5.0
2  2.0  1.0  3.0  4.0  5.0
3  1.0  5.0  2.0  3.0  4.0
4  4.0  3.0  2.0  1.0  5.0
5  4.0  2.0  3.0  1.0  5.0
6  2.0  5.0  1.0  3.0  4.0

Now lastly, I would like to pull in the column names for the ranks, and pull out into a dataframe the top two and bottom one. For example, row 0 has rank 1 in column e, rank 2 in column b, and rank 5 in column c, so the three columns would be e, b, c.

Expected Output:

   top_1, top_2, bottom_1
0  e      b      c
1  a      d      e
2  b      a      e
3  a      c      b
4  d      c      e
5  d      b      e
6  c      a      b

Body:
Use numpy.argsort for positions of sorted values and get columns names by indexing:

a = example.columns.to_numpy()[(-example).to_numpy().argsort()]
#if use lower version of pandas
#a = example.columns.values[(-example).values.argsort()]
print(a)

[['e' 'b' 'd' 'a' 'c']
 ['a' 'd' 'b' 'c' 'e']
 ['b' 'a' 'c' 'd' 'e']
 ['a' 'c' 'd' 'e' 'b']
 ['d' 'c' 'b' 'a' 'e']
 ['d' 'b' 'c' 'a' 'e']
 ['c' 'a' 'd' 'e' 'b']]

And then select first, second and last column and convert to DataFrame:

df = pd.DataFrame(a[:, [0,1,-1]], index=df.index, columns=['top_1', 'top_2', 'bottom_1'])
print (df)
  top_1 top_2 bottom_1
0     e     b        c
1     a     d        e
2     b     a        e
3     a     c        b
4     d     c        e
5     d     b        e
6     c     a        b


问:
In pandas, how should one add age-range columns?
Let's say I've got a simple DataFrame that details when people have been playing music through their lives, like this:

```<code>import pandas as pd

df = pd.DataFrame(
    [[15,  8,  7],
     [20, 10, 10],
     [35, 15, 20],
     [50, 12, 38]],
    columns=['current age', 'age started playing music', 'years playing music'])
</code>```

How should one add additional columns that break down the number of years playing music they've had in each decade of their lives? For example, if the columns added were 0-10, 10-20, 20-30 etc., then the first person would have had 2 years of playing music in their first decade, 5 in their second, 0 in their third etc.

答:
You can also try this using pd.cut and value_counts:

```<code>df.join(df.apply(lambda x: pd.cut(np.arange(x['age started playing music'],
                                            x['current age']),
                                  bins=[0, 9, 19, 29, 39, 49],
                                  labels=['0-10', '10-20',
                                          '20-30', '30-40',
                                          '40+'])
                             .value_counts(),
                 axis=1))
</code>```

Output:

```<code>   current age  age started playing music  years playing music  0-10  10-20  20-30  30-40  40+
0           15                          8                    7     2      5      0      0    0
1           20                         10                   10     0     10      0      0    0
2           35                         15                   20     0      5     10      5    0
3           50                         12                   38     0      8     10     10   10
</code>```

Body:
Let's say I've got a simple DataFrame that details when people have been playing music through their lives, like this:

import pandas as pd

df = pd.DataFrame(
    [[15,  8,  7],
     [20, 10, 10],
     [35, 15, 20],
     [50, 12, 38]],
    columns=['current age', 'age started playing music', 'years playing music'])

How should one add additional columns that break down the number of years playing music they've had in each decade of their lives? For example, if the columns added were 0-10, 10-20, 20-30 etc., then the first person would have had 2 years of playing music in their first decade, 5 in their second, 0 in their third etc.

Body:
You can also try this using pd.cut and value_counts:

df.join(df.apply(lambda x: pd.cut(np.arange(x['age started playing music'],
                                            x['current age']),
                                  bins=[0, 9, 19, 29, 39, 49],
                                  labels=['0-10', '10-20',
                                          '20-30', '30-40',
                                          '40+'])
                             .value_counts(),
                 axis=1))

Output:

   current age  age started playing music  years playing music  0-10  10-20  20-30  30-40  40+
0           15                          8                    7     2      5      0      0    0
1           20                         10                   10     0     10      0      0    0
2           35                         15                   20     0      5     10      5    0
3           50                         12                   38     0      8     10     10   10


问:
How to add avicap32.dll into VS2010
I'm writing a small code in C# using visual studio 2010 express. I'm trying to add avicap32.dll from C:\WINDOWS\system32 to the "References" but getting an error saying that "A reference to 'C:\WINDOWS\system32\avicap32.dll' could not be added. Please make sure that the file is accessible, and that is a valid assembly or COM component". How to get rid of this?

thanks in advance,

Sri

答:
I am not familiar with this library itself, but I've seen this error many times before when trying to work with 3rd party libraries.  Assuming you've done the diligence in making sure that things are, in fact, accessible and this is not a permissions problem (double check!), this happens when the referenced dll doesn't the .net metadata in it.  Sometimes VS can 'figure it out' even if the metadata isn't explicitly present, but oftentimes it can't. This could be for a number of reasons, but most commonly it's because the dll was written in unmanaged code, like C++.

The solutions to this problem are always in a little bit of flux depending on the specifics of the DLL you're trying to use, and I don't really have too many details on this library you're trying to add.  I picked up a few forum posts that will hopefully set you on the right track, but if not please comment with some extra details so we've got more information to help out.  (Pages: 1 2 3)

Title: How to add avicap32.dll into VS2010


问:
How do I find the newest file in a directory using a PowerShell script?
If, for example, I have a directory which contains the following files:

```<code>Test-20120626-1023.txt
Test-20120626-0710.txt
Test-20120626-2202.txt
Test-20120626-1915.txt
Test-20120626-1142.txt
</code>```

As you can see, each file name contains the time of creation which is in a sortable format.

How do I find the name of the latest file name (in this case Test-20120626-2202.txt) and store it in variable?

Note: The directory path is also stored in a variable if it makes any difference.

答:
I use this to get last updated files. Easy to write.</p>

```<code>ls | sort LastWriteTime
</code>```

Body:
If, for example, I have a directory which contains the following files:

Test-20120626-1023.txt
Test-20120626-0710.txt
Test-20120626-2202.txt
Test-20120626-1915.txt
Test-20120626-1142.txt

As you can see, each file name contains the time of creation which is in a sortable format.

How do I find the name of the latest file name (in this case Test-20120626-2202.txt) and store it in variable?

Note: The directory path is also stored in a variable if it makes any difference.

Body:
I use this to get last updated files. Easy to write.

ls | sort LastWriteTime


问:
get latest state value after setState hook within async await block in react
I have a dropdown which when changes calls api to fetch data using useEffect hook:

```<code>const [selectedComplianceFilter, setComplianceFilter] = useState("all");

useEffect(() => {
  if (selectedComplianceFilter === "all") {
    fetchFullReport();
  } else {
    fetchReportByCompliance(selectedComplianceFilter);
  }
}, [selectedComplianceFilter]);

<select
  name="compliance"
  className="custom-select w-auto"
  onChange={e => setComplianceFilter(e.target.value)}
>
  <option value="all">All</option>
  {compliances.map((compliance, i) => (
    <option key={i} value={compliance}>
      {compliance}
    </option>
  ))}
</select>
</code>```

I have another useEffect hook which calls another api which returns scan status

```<code>useEffect(() => {
  fetchCompliances();

  let intervalId;

  getScanStatus(0);
  fetchFullReport();

  intervalId = setInterval(() => {
    getScanStatus(intervalId);
  }, 10000);

  return () => {
    componentDidUnmount.current = true;
    clearInterval(intervalId);
  };
}, []);
</code>```

This is the function to fetch scan status:

```<code>const [scanStatus, setScanStatus] = useState("");
const [lastUpdated, setLastUpdated] = useState();
const [reports, setReports] = useState([]);

const getScanStatus = async intervalId => {
  const resp = await API.get(SCAN_STATUS_URL);

  if (resp && resp.status) {
    const { scanStatus = "", lastModifiedDate = "" } = resp.data || {};

    const isValidDate = moment(lastModifiedDate).isValid();

    if (!componentDidUnmount.current) {
      setScanStatus(scanStatus);
      isValidDate && setLastUpdated(getFormattedDateTime(lastModifiedDate));
      if (scanStatus === "COMPLETED") {
        clearInterval(intervalId);

        console.log("selectedComplianceFilter", selectedComplianceFilter); // <== returns old state i.e., 'all' but should be latest selected option.

        if (selectedComplianceFilter === "all") {
          fetchFullReport();
        } else {
          fetchReportByCompliance();
        }
      }
    }
  }
};
</code>```

Now what happens is when page loads fetchFullReport(); renders the table. Now when the dropdown is changed fetchReportByCompliance(); is called to filter the table and table gets updated with fewer rows now.

Meanwhile getScanStatus is called on every 10 second interval and as soon as the api returns status = 'COMPLETED' and the interval is stopped and the table gets updated with new data (fetchFullReport();) and all the table rows are back which is a weird behavior as dropdown filter still has selected option other than ALL option. So, when new data arrives as soon as scan is completed to update the table I added an if condition to update table based on selectedComplianceFilter value.

But when the getScanStatus function api returns status = 'COMPLETED' the value of selectedComplianceFilter is still 'all' but the dropdown has another option selected. I am s assuming it is because of async await block which still holds the previous value of selectedComplianceFilter state.

How do I get the latest value of selectedComplianceFilter state when getScanStatus executes in the future as it is asynchronous?

答:
What about wrapping your code in a useEffect block which fires when scanStatus changes? For example:

```<code>useEffect(() => {
    if (scanStatus === "COMPLETED") {
        if (selectedComplianceFilter === "all") {
            fetchFullReport();
        } else {
            fetchReportByCompliance();
        }
   }
}, [scanStatus]);
</code>```

Body:
I have a dropdown which when changes calls api to fetch data using useEffect hook:

const [selectedComplianceFilter, setComplianceFilter] = useState("all");

useEffect(() => {
  if (selectedComplianceFilter === "all") {
    fetchFullReport();
  } else {
    fetchReportByCompliance(selectedComplianceFilter);
  }
}, [selectedComplianceFilter]);

<select
  name="compliance"
  className="custom-select w-auto"
  onChange={e => setComplianceFilter(e.target.value)}
>
  <option value="all">All</option>
  {compliances.map((compliance, i) => (
    <option key={i} value={compliance}>
      {compliance}
    </option>
  ))}
</select>

I have another useEffect hook which calls another api which returns scan status

useEffect(() => {
  fetchCompliances();

  let intervalId;

  getScanStatus(0);
  fetchFullReport();

  intervalId = setInterval(() => {
    getScanStatus(intervalId);
  }, 10000);

  return () => {
    componentDidUnmount.current = true;
    clearInterval(intervalId);
  };
}, []);

This is the function to fetch scan status:

const [scanStatus, setScanStatus] = useState("");
const [lastUpdated, setLastUpdated] = useState();
const [reports, setReports] = useState([]);

const getScanStatus = async intervalId => {
  const resp = await API.get(SCAN_STATUS_URL);

  if (resp && resp.status) {
    const { scanStatus = "", lastModifiedDate = "" } = resp.data || {};

    const isValidDate = moment(lastModifiedDate).isValid();

    if (!componentDidUnmount.current) {
      setScanStatus(scanStatus);
      isValidDate && setLastUpdated(getFormattedDateTime(lastModifiedDate));
      if (scanStatus === "COMPLETED") {
        clearInterval(intervalId);

        console.log("selectedComplianceFilter", selectedComplianceFilter); // <== returns old state i.e., 'all' but should be latest selected option.

        if (selectedComplianceFilter === "all") {
          fetchFullReport();
        } else {
          fetchReportByCompliance();
        }
      }
    }
  }
};

Now what happens is when page loads fetchFullReport(); renders the table. Now when the dropdown is changed fetchReportByCompliance(); is called to filter the table and table gets updated with fewer rows now.

Meanwhile getScanStatus is called on every 10 second interval and as soon as the api returns status = 'COMPLETED' and the interval is stopped and the table gets updated with new data (fetchFullReport();) and all the table rows are back which is a weird behavior as dropdown filter still has selected option other than ALL option. So, when new data arrives as soon as scan is completed to update the table I added an if condition to update table based on selectedComplianceFilter value.

But when the getScanStatus function api returns status = 'COMPLETED' the value of selectedComplianceFilter is still 'all' but the dropdown has another option selected. I am s assuming it is because of async await block which still holds the previous value of selectedComplianceFilter state.

How do I get the latest value of selectedComplianceFilter state when getScanStatus executes in the future as it is asynchronous?

Body:
What about wrapping your code in a useEffect block which fires when scanStatus changes? For example:

useEffect(() => {
    if (scanStatus === "COMPLETED") {
        if (selectedComplianceFilter === "all") {
            fetchFullReport();
        } else {
            fetchReportByCompliance();
        }
   }
}, [scanStatus]);


问:
Find any negative values in a given set of dataframes and replace whole column with np.nan
I have a large dataframe and I want to search 144 of the columns to check if there are any negative values in them. If there is even one negative value in a column, I want to replace the whole column with np.nan. I then want to use the new version of the dataframe for later analysis.

I've tried a varied of methods but can't seem to find one that works. I think this is almost there but I can't seem to find a solution to what I'm trying to do.

```<code>clean_data_df.loc[clean_data_df.cols < 0, cols] = np.nan   #cols is a list of the column names I want to check
null_columns=clean_data_df.columns[clean_data_df.isnull().any(axis=1)]
clean_data_df[null_columns] = np.nan
</code>```

When I run the above code I get the following error: AttributeError: 'DataFrame' object has no attribute 'cols'

Thanks in advance!

答:
You could use a loop to iterate over the columns:

```<code>for i in col:
   if df[i].isna().any():
       df[i] = np.nan
</code>```

Minumum reproducible example:

```<code>df = pd.DataFrame({'a':[1,2,np.nan], 'b':[np.nan,1,np.nan],'c':[1,2,3]})
for i in df:
    if df[i].isna().any():
        df[i] = np.nan
print(df)
</code>```

Output:

```<code>    a   b  c
0 NaN NaN  1
1 NaN NaN  2
2 NaN NaN  3
</code>```

Body:
I have a large dataframe and I want to search 144 of the columns to check if there are any negative values in them. If there is even one negative value in a column, I want to replace the whole column with np.nan. I then want to use the new version of the dataframe for later analysis.

I've tried a varied of methods but can't seem to find one that works. I think this is almost there but I can't seem to find a solution to what I'm trying to do.

clean_data_df.loc[clean_data_df.cols < 0, cols] = np.nan   #cols is a list of the column names I want to check
null_columns=clean_data_df.columns[clean_data_df.isnull().any(axis=1)]
clean_data_df[null_columns] = np.nan

When I run the above code I get the following error: AttributeError: 'DataFrame' object has no attribute 'cols'

Thanks in advance!

Body:
You could use a loop to iterate over the columns:

for i in col:
   if df[i].isna().any():
       df[i] = np.nan

Minumum reproducible example:

df = pd.DataFrame({'a':[1,2,np.nan], 'b':[np.nan,1,np.nan],'c':[1,2,3]})
for i in df:
    if df[i].isna().any():
        df[i] = np.nan
print(df)

Output:

    a   b  c
0 NaN NaN  1
1 NaN NaN  2
2 NaN NaN  3


问:
PowerShell Get-WinEvent Data Query
Trying to write a script to retrieve all the details for events being triggered for a certain issue.

The events that have been seen within the event viewer have no Event ID's etc. that would help to filter the results.

The only data I can potential use is contained within the EventData section with "Married"

```<code>Get-WinEvent @{LogName='Application';Level=2} | Where {$_.ProviderName -eq 'BizTalk Server' -and $_.Message -contains 'Marri'}
</code>```

I'm not sure if the $_.Message is looking at the EventData section.. any advice?

答:
I don't know where in eventdata "married" is, but in powershell 6 you can do something like this and use -filterhashtable on eventdata named data fields.  Providername can be in the hashtable as well.

```<code>Get-WinEvent @{LogName='Application'; Level=2;
  providername='biztalk server'; status='married'}
</code>```

An example that works for me:

```<code>get-winevent @{ logname = 'application'; param2 = 'suppressduplicateduration' }
</code>```

Title: PowerShell Get-WinEvent Data Query

Body:
Trying to write a script to retrieve all the details for events being triggered for a certain issue.

The events that have been seen within the event viewer have no Event ID's etc. that would help to filter the results.

The only data I can potential use is contained within the EventData section with "Married"

Get-WinEvent @{LogName='Application';Level=2} | Where {$_.ProviderName -eq 'BizTalk Server' -and $_.Message -contains 'Marri'}

I'm not sure if the $_.Message is looking at the EventData section.. any advice?

Body:
I don't know where in eventdata "married" is, but in powershell 6 you can do something like this and use -filterhashtable on eventdata named data fields.  Providername can be in the hashtable as well.

Get-WinEvent @{LogName='Application'; Level=2;
  providername='biztalk server'; status='married'}

An example that works for me:

get-winevent @{ logname = 'application'; param2 = 'suppressduplicateduration' }


问:
How to get index with known value as string in arraylist?
I have ArrayList with multi dimensional values in Structure as ArrayList

```<code>Structure
(0)=> Mstructure.ABCD
       Area (these are value of ABCD)
       Name
(1)=> Mstructure.EFGH
           Area
           Name
</code>```

I want to know the index of string ABCD.

I tried

```<code>Dim myIndex as Integer = Structure.IndexOf("ABCD")
Dim myIndex = Array.IndexOf(Structure.ToArray(), myString)
</code>```

This returned only -1. I want to get 0 if string is ABCD

EDITED

Structure is defined as ArrayList. I can iterate over it if I use loop e.g

```<code>Structure(i).GetType().Name = "ABCD"
</code>```

I have checked if it exists in the ArrayList

```<code>Dim result = Structure.ToArray().Any(Function(x) x.ToString().Contains("ABCD"))
</code>```

But I want to know the index of the multidimensional ArrayList without looping it. I want to get the index of Mstructure.ABCD. Msttructure.ABCD has values inside it but without knowing those values I want to get the index value.

```<code>(0){Mstructure.ABCD}
(1){Mstructure.EFGH}
(2){Mstructure.IJKL}
</code>```

答: hhmmm i would use collections instead, or create an object with multi collections to make it easier for me... Have you thought of that?</p>

Body:
I have ArrayList with multi dimensional values in Structure as ArrayList

Structure
(0)=> Mstructure.ABCD
       Area (these are value of ABCD)
       Name
(1)=> Mstructure.EFGH
           Area
           Name

I want to know the index of string ABCD.

I tried

Dim myIndex as Integer = Structure.IndexOf("ABCD")
Dim myIndex = Array.IndexOf(Structure.ToArray(), myString)

This returned only -1. I want to get 0 if string is ABCD

EDITED

Structure is defined as ArrayList. I can iterate over it if I use loop e.g

Structure(i).GetType().Name = "ABCD"

I have checked if it exists in the ArrayList

Dim result = Structure.ToArray().Any(Function(x) x.ToString().Contains("ABCD"))

But I want to know the index of the multidimensional ArrayList without looping it. I want to get the index of Mstructure.ABCD. Msttructure.ABCD has values inside it but without knowing those values I want to get the index value.

(0){Mstructure.ABCD}
(1){Mstructure.EFGH}
(2){Mstructure.IJKL}


问:
Creating subscription for future Date
We are facing an issue with subscription schedule, We want to create a subscription with future date and it seems possible through scheduling.

However we want to know the how it can be done , as we are facing issues with the API

We can create a schedule on existing subscription but when adding start_date to it the API throws error.

There is no option to assign a schedule to existing subscription.

When we create a schedule with future date it doesn't assign any subscription id.

There is no webhook that can let us know when the subscription is created for a subscription schedule in future.

答:
For a Subscription that doesn't exist yet and you want to start at some future date, there are two options:

Use a free trial period that ends on the date you want the "real" Subscription to start.

Schedule your own servers to make a call on the given date to create the Subscription then.

Stripe doesn't provide a way to "make a request in the future". SubscriptionSchedules are for scheduling changes to existing Subscriptions.

Title: Creating subscription for future Date


问:
VueJs way to detect a mobile device, when we need to render two different views, with respect to the device type
I need to change the number of elements to show in my grid view with respect to the device type. For mobile views and for desktop views. I went through so many suggetions like

check device screen size

check device type

and finally I ended up checking the device type inside a method.

```<code>methods: {
  isMobile() {
    if (screen.width <= 760) {
      return true
    } else {
      return false
    }
  },
},
</code>```

and I used isMobile() method to define my conditon for each device. My question is how can I use this isMobile() method as computed property as I only return a boolean value. And is it ok to use like this without a even listner. Because it's so far working fine. But I'm looking for a more unified solution as I'm new to VueJs. Thanks in advance.

答: Great article that shows a couple of different ways to do this in JavaScript right here</p>

Body:
I need to change the number of elements to show in my grid view with respect to the device type. For mobile views and for desktop views. I went through so many suggetions like

check device screen size

check device type

and finally I ended up checking the device type inside a method.

methods: {
  isMobile() {
    if (screen.width <= 760) {
      return true
    } else {
      return false
    }
  },
},

and I used isMobile() method to define my conditon for each device. My question is how can I use this isMobile() method as computed property as I only return a boolean value. And is it ok to use like this without a even listner. Because it's so far working fine. But I'm looking for a more unified solution as I'm new to VueJs. Thanks in advance.


问:
How to check if a object code is 16/32 bit?
Is there any way by which we can identify that a .obj file and .exe file is 16/32 bit?

Basically I want to create a smart linker, that will automatically identify which linker do the given file names need to be passed to.

Preferred Language: C (it can be different, if needed)

I am looking for some solution that can read the bytes of an .exe/the code of an .obj file and then determine if it's 16/32 bit. Even an algorithm would too do.

Note: I know both object code and a executable are two different entities.

答:
All of this information is encoded in the binary object according to the relevant Application Binary Interface (ABI).

The current Linux ABI is the Executable and Linkable Format (ELF), and you can query a specific binary file using a tool such as readelf or objdump.

The current Windows ABI is the Portable Executable (PE) format. I'm not familiar with the toolset here but a quick google search suggests there are programs that function the same as readelf:

http://www.pe-explorer.com/peexplorer-tour.htm

Here's the Microsoft specification of the PE format:

https://learn.microsoft.com/en-us/windows/win32/debug/pe-format

However, neither of those formats support 16-bit binaries anymore. The older ABI format is called "a.out" for Linux, which can be read and queried with objdump (I'm not sure about readelf). The older Windows/DOS formats are called MZ and NE. Again, I'm not familiar with the tool support for these older Windows formats.

Wikipedia has a pretty comprehensive list of all the popular executable file formats that have been used, with links to more info:

https://en.wikipedia.org/wiki/Comparison_of_executable_file_formats


问:
find exact word in Flutter, Dart
Is there any way to find the exact word or character in Dart?

```<code>List<Type> _media = [
    Device(one: 'abc', two: 'News'),
    Device(one: 'bc', two: 'Television')
];
</code>```

Since I am trying to query values in class
my code is like this

```<code>  String Query(String value) {
    return _media
        .where((medium) => medium.one.toLowerCase().contains(value.toLowerCase()))
        .map((medium) => (medium.two)).toString();
</code>```

If I put 'bc' as value, the result I expect to get is 'Television' not 'News'
It may be because I used contain.

Regex seems to be working but my code doesn't work at all :(

```<code>  RegExp regExp = new RegExp(
    r"(?<![\w\d])abc(?![\w\d])",
    caseSensitive: false,
    multiLine: false,
  );

  String Query(String value) {
    return _media
        .where((medium) => medium.one.toLowerCase().regExp.hasMatch(value))
        .map((medium) => (medium.two)).toString();

</code>```

Would you guys help me find a solution? :)

答:
String does not have a regExp attribute, that's why it does not work. You should call hasMatch() on the regExp object:

```<code>_media.where((medium) => regExp.hasMatch(medium.one))
</code>```

(you don't need toLowerCase() because your regexp is already case insensitive)

But if all you need is the string match, you can do just that:

```<code>_media.where((medium) => medium.one.toLowerCase() == value)
</code>```

Title: find exact word in Flutter, Dart

Body:
Is there any way to find the exact word or character in Dart?

List<Type> _media = [
    Device(one: 'abc', two: 'News'),
    Device(one: 'bc', two: 'Television')
];

Since I am trying to query values in class
my code is like this

  String Query(String value) {
    return _media
        .where((medium) => medium.one.toLowerCase().contains(value.toLowerCase()))
        .map((medium) => (medium.two)).toString();

If I put 'bc' as value, the result I expect to get is 'Television' not 'News'
It may be because I used contain.

Regex seems to be working but my code doesn't work at all :(

  RegExp regExp = new RegExp(
    r"(?<![\w\d])abc(?![\w\d])",
    caseSensitive: false,
    multiLine: false,
  );

  String Query(String value) {
    return _media
        .where((medium) => medium.one.toLowerCase().regExp.hasMatch(value))
        .map((medium) => (medium.two)).toString();

Would you guys help me find a solution? :)

Body:
String does not have a regExp attribute, that's why it does not work. You should call hasMatch() on the regExp object:

_media.where((medium) => regExp.hasMatch(medium.one))

(you don't need toLowerCase() because your regexp is already case insensitive)

But if all you need is the string match, you can do just that:

_media.where((medium) => medium.one.toLowerCase() == value)


问:
Does creating a CTE in this case helps?
I have a query written very poorly in SQL Server 2008

```<code>UPDATE  PatientChartImages
SET     PatientChartImages.IsLockDown = @IsLockdown
WHERE   PatientChartImages.IsLockDown = @IsNotLockdown
    AND PatientChartId IN (
    SELECT  PatientCharts.PatientChartId
    FROM    PatientCharts
    WHERE   ( PatientCharts.ChartStatusID = @ChartCompletedStatusID
              OR PatientCharts.ChartStatusID = @ChartOnBaseStatusID
            )
            AND PatientCharts.IsLockDown = @IsNotLockdown
            AND PatientCharts.CompletedOn IS NOT NULL
            AND DATEDIFF(MINUTE, PatientCharts.CompletedOn, GETUTCDATE()) >= ( SELECT
                                                          tf.LockUpInterval
                                                          FROM
                                                          @tblFacCOnf tf
                                                          WHERE
                                                          tf.facilityId = PatientCharts.FacilityId
                                                          ) )
</code>```

This query locks the main table and results in TimeOut. IF i create a CTE first of all the updateable records and then update the main table by joining to the CTE. Will it help ??

答: One additional thing I might suggest if the other suggestions don't get you enough speed is not to use a table variable. Temp Tables are often faster for large data sets and can be indexed if need be. </p>

Title: Does creating a CTE in this case helps?

Body:
I have a query written very poorly in SQL Server 2008

UPDATE  PatientChartImages
SET     PatientChartImages.IsLockDown = @IsLockdown
WHERE   PatientChartImages.IsLockDown = @IsNotLockdown
    AND PatientChartId IN (
    SELECT  PatientCharts.PatientChartId
    FROM    PatientCharts
    WHERE   ( PatientCharts.ChartStatusID = @ChartCompletedStatusID
              OR PatientCharts.ChartStatusID = @ChartOnBaseStatusID
            )
            AND PatientCharts.IsLockDown = @IsNotLockdown
            AND PatientCharts.CompletedOn IS NOT NULL
            AND DATEDIFF(MINUTE, PatientCharts.CompletedOn, GETUTCDATE()) >= ( SELECT
                                                          tf.LockUpInterval
                                                          FROM
                                                          @tblFacCOnf tf
                                                          WHERE
                                                          tf.facilityId = PatientCharts.FacilityId
                                                          ) )

This query locks the main table and results in TimeOut. IF i create a CTE first of all the updateable records and then update the main table by joining to the CTE. Will it help ??


问:
Push a div to the right
I'm coding a menu in french but I need to move all the buttons (Home, About us...) to the right.

I tried with float: right; but it doesn't work.

Here is my Result :

My Result

The  Home, Informations, etc.. are in a div. It's this div that i want to push right !

My Objective :

My Objective

My Code:

/*

            ==============================
            NAVBAR
            ==============================

            */

.container {
  width: 80%;
  margin: 0 auto;
}

header {
  background: #9ebd11/*55d6aa*/
  ;
}

header::after {
  content: '';
  display: table;
  clear: both;
}

.logo {
  float: left;
  /*padding: 10px 0;*/
}

nav {
  float: right;
}

nav #navbar-ul {
  margin: 0;
  padding: 0;
  list-style: none;
}

nav .navbar-li {
  display: inline-block;
  margin-left: 70px;
  padding-top: 23px;
  position: relative;
}

nav .navbar-button {
  color: #444;
  text-decoration: none;
  text-transform: uppercase;
  font-size: 14px;
}

nav .navbar-button:hover {
  color: #000;
}

nav .navbar-button::before {
  content: '';
  display: block;
  height: 5px;
  background-color: #444;
  position: absolute;
  top: 0;
  width: 0%;
  transition: all ease-in-out 250ms;
}

nav .navbar-button:hover::before {
  width: 100%;
}

nav #register-li {
  /*display: inline-block;*/
  margin-left: 70px;
  padding-top: 23px;
  position: relative;
}

nav #register-button {
  color: #fff;
  text-decoration: none;
  text-transform: uppercase;
  font-size: 14px;
}

nav #login-li {
  /*display: inline-block;*/
  margin-left: 70px;
  padding-top: 23px;
  position: relative;
}

nav #login-button {
  color: #fff;
  text-decoration: none;
  text-transform: uppercase;
  font-size: 14px;
}

ul {
  list-style-type: none;
}

nav,
.container {
  display: flex;
}

.connection {
  line-height: 2;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><header>
  <div class="container">

    <h1 class="logo">
      <img src="images/Logo/logo_gp_.png" width="100" alt="Description de l'image">
    </h1>

    <nav>
      <ul id="navbar-ul">
        <li class="navbar-li">Home</li>
        <li class="navbar-li">Informations</li>
        <li class="navbar-li">About us</li>
      </ul>
      <ul class="connection">
        <li>S'inscrire</li>
        <li>Se connecter</li>
      </ul>
    </nav>
  </div>
</header></code>```

Thanks

答:
Bootstrap's "Container" class has a max-width of something like 1800px(not certain of exact px count).

Try using "container-fluid". This should allow the nav items to move to the far right but will probably move your logo to the far left because of your .logo float-left css.

You can give the logo a margin-left that works for you.

Edit: I just noticed you've defined your own .container class in the css. And margin set to 0 auto. This is going to center your content within the container class and give you max width of 80% so your content won't reach the far right side of the browser unless you set this items to "position:absolute" and then give them the necessary margins.

Title: Push a div to the right

Body:
I'm coding a menu in french but I need to move all the buttons (Home, About us...) to the right.

I tried with float: right; but it doesn't work.

Here is my Result :

My Result

The  Home, Informations, etc.. are in a div. It's this div that i want to push right !

My Objective :

My Objective

My Code:

/*

            ==============================
            NAVBAR
            ==============================

            */

.container {
  width: 80%;
  margin: 0 auto;
}

header {
  background: #9ebd11/*55d6aa*/
  ;
}

header::after {
  content: '';
  display: table;
  clear: both;
}

.logo {
  float: left;
  /*padding: 10px 0;*/
}

nav {
  float: right;
}

nav #navbar-ul {
  margin: 0;
  padding: 0;
  list-style: none;
}

nav .navbar-li {
  display: inline-block;
  margin-left: 70px;
  padding-top: 23px;
  position: relative;
}

nav .navbar-button {
  color: #444;
  text-decoration: none;
  text-transform: uppercase;
  font-size: 14px;
}

nav .navbar-button:hover {
  color: #000;
}

nav .navbar-button::before {
  content: '';
  display: block;
  height: 5px;
  background-color: #444;
  position: absolute;
  top: 0;
  width: 0%;
  transition: all ease-in-out 250ms;
}

nav .navbar-button:hover::before {
  width: 100%;
}

nav #register-li {
  /*display: inline-block;*/
  margin-left: 70px;
  padding-top: 23px;
  position: relative;
}

nav #register-button {
  color: #fff;
  text-decoration: none;
  text-transform: uppercase;
  font-size: 14px;
}

nav #login-li {
  /*display: inline-block;*/
  margin-left: 70px;
  padding-top: 23px;
  position: relative;
}

nav #login-button {
  color: #fff;
  text-decoration: none;
  text-transform: uppercase;
  font-size: 14px;
}

ul {
  list-style-type: none;
}

nav,
.container {
  display: flex;
}

.connection {
  line-height: 2;
}

Home

Informations

About us

S'inscrire

Se connecter

Thanks


问:
Calculate multiple columns based on threshold
data

```<code>data=data.frame("student"=c(1,2,3,4,5),
"score1"=c(77,NA,52,99,89),
"score2"=c(95,89,79,89,73),
"score3"=c(92,52,73,64,90),
"score4"=c(84,57,78,81,66),
"score1x"=c(0,NA,0,1,1),
"score2x"=c(1,1,0,1,0),
"score3x"=c(1,0,0,0,1),
"score4x"=c(1,0,0,1,0))
</code>```

I have data with student id and score1-score4 and hope to create score1x-score4x in a simple fast way. The rule is if say score1 is less than 80 then score1x is 0 otherwise it is 1.
I can do this by: data$score1x=ifelse(score1<80,0,1) but am wondering is there a way to do this for all of them at the same time to create score1x-score4x more quickly?

答:
You could use this dplyr solution which creates new variables for columns with "score" in the name using mutate_at(), then uses rename_at() to change "_x" to "x" at the end of the column names:

```<code>library(dplyr)

data[1:5] %>%
  mutate_at(vars(contains("score")), list(x = ~as.integer(. > 80))) %>%
  rename_at(vars(contains("_x")), ~gsub("_", "", ., fixed = T))

  student score1 score2 score3 score4 score1x score2x score3x score4x
1       1     77     95     92     84       0       1       1       1
2       2     NA     89     52     57      NA       1       0       0
3       3     52     79     73     78       0       0       0       0
4       4     99     89     64     81       1       1       0       1
5       5     89     73     90     66       1       0       1       0
</code>```

Body:
data

data=data.frame("student"=c(1,2,3,4,5),
"score1"=c(77,NA,52,99,89),
"score2"=c(95,89,79,89,73),
"score3"=c(92,52,73,64,90),
"score4"=c(84,57,78,81,66),
"score1x"=c(0,NA,0,1,1),
"score2x"=c(1,1,0,1,0),
"score3x"=c(1,0,0,0,1),
"score4x"=c(1,0,0,1,0))

I have data with student id and score1-score4 and hope to create score1x-score4x in a simple fast way. The rule is if say score1 is less than 80 then score1x is 0 otherwise it is 1.
I can do this by: data$score1x=ifelse(score1<80,0,1) but am wondering is there a way to do this for all of them at the same time to create score1x-score4x more quickly?

Body:
You could use this dplyr solution which creates new variables for columns with "score" in the name using mutate_at(), then uses rename_at() to change "_x" to "x" at the end of the column names:

library(dplyr)

data[1:5] %>%
  mutate_at(vars(contains("score")), list(x = ~as.integer(. > 80))) %>%
  rename_at(vars(contains("_x")), ~gsub("_", "", ., fixed = T))

  student score1 score2 score3 score4 score1x score2x score3x score4x
1       1     77     95     92     84       0       1       1       1
2       2     NA     89     52     57      NA       1       0       0
3       3     52     79     73     78       0       0       0       0
4       4     99     89     64     81       1       1       0       1
5       5     89     73     90     66       1       0       1       0


问:
How to skip @Param in @Query if is null or empty in Spring Data JPA
```<code>@Query(value = "Select f from Documents f " +
        "RIGHT JOIN f.documentStatus ds " +
        "where f.billingAccount.accountId  in :billingAccountIdList " +
        " and ds.statusCode in :paymentStatuses" +
        " and f.paymentDate < :paymentDate")
List<FinancialDocumentEntity> getFinancialDocumentsOverdue(@Param("billingAccountIdList")List<String> billingAccountIdList,
                                                           @Param("paymentStatuses") List<String> paymentStatuses,
                                                           @Param("paymentDate") Date paymentDate);
</code>```

I have query like above. It is possible to skip searching param for example @Param("paymentStatuses") in query method if is null or is empty ?

答:
Try changing

```<code>" and ds.statusCode in :paymentStatuses"
</code>```

into

```<code>" and (COALESCE(:paymentStatuses, null) is null or ds.statusCode in :paymentStatuses)"
</code>```

This solution will work for the empty list, null list, and a list with items 1 or more.

Body:
@Query(value = "Select f from Documents f " +
        "RIGHT JOIN f.documentStatus ds " +
        "where f.billingAccount.accountId  in :billingAccountIdList " +
        " and ds.statusCode in :paymentStatuses" +
        " and f.paymentDate < :paymentDate")
List<FinancialDocumentEntity> getFinancialDocumentsOverdue(@Param("billingAccountIdList")List<String> billingAccountIdList,
                                                           @Param("paymentStatuses") List<String> paymentStatuses,
                                                           @Param("paymentDate") Date paymentDate);

I have query like above. It is possible to skip searching param for example @Param("paymentStatuses") in query method if is null or is empty ?

Body:
Try changing

" and ds.statusCode in :paymentStatuses"

into

" and (COALESCE(:paymentStatuses, null) is null or ds.statusCode in :paymentStatuses)"

This solution will work for the empty list, null list, and a list with items 1 or more.


问:
SelectedIndexChanged not firing in asp.net usercontrol
.net 4.0, ASP.net, vb.net.

I've got a usercontrol that is using an obout combo box.  The obout is a cascading combobox that has 3 levels to it.  when something it selected from the third level of the combobox, it is suppose to fire off a selectedIndexChanged event.  This happens the first time that I select the usercontrol.  The problem is if i want to go back and select something different.  The selectedIndexChanged doesn't fire.  I've set breakpoints and the

```<code>AddHandler ComboBox3.SelectedIndexChanged, AddressOf ComboBox3_SelectedIndexChanged
</code>```

runs just like it did the first time i select the usercontrol.  But the selectedIndex just doesn't fire the second go around.  Was wondering what i'm doing wrong.

Here is the selectedIndexChanged that is not firing

```<code>Sub ComboBox3_SelectedIndexChanged(ByVal sender As Object, ByVal e As ComboBoxItemEventArgs)
    Dim Oc As New Dempsey.ClassIndex_Controller
    Dim O As New Dempsey.ClassIndex
    oClassIndexs = Oc.GetClassIndexData(CInt(ComboBox1.SelectedValue))
    For Each O In oClassIndexs
    Next
    ClassSearchResults = o
    RaiseEvent myClassificationSearch(oClassIndexs, e)
End Sub
</code>```

I'll add whatever other code you might want to see... but didn't want to make the post too long.

thanks
shannon

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
some more info.. as mentioned above, this is a cascading combobox.  So combobox1 has values of say 1,2,3, Combobox 2 gets it's data filtered depending on what you select on combobox1.

Well.. i've noticed that if i select 1 in combobox 1 the first time through, things work as expected.  If on the second round i select something other than 1 in combobox1, the event fires.  However, if i select 1 in combobox 1 on the second round through, the event does not fire.

This is not the way i need it to work because it could be that the second time through, i need to select the same value in combobox1 but a different value in combobox2.  Any idea what i can do to get around this... since it would appear that it's working the way it should.

i mention it above.. but i'm using an Obout combox control
thanks

答: I doubt, when your dropdown selection changed, your dropdown again binded somewhere, perhaps in the page load event and it lost the chance for the SelectedIndex Changed event to be fired.

Body:
.net 4.0, ASP.net, vb.net.

I've got a usercontrol that is using an obout combo box.  The obout is a cascading combobox that has 3 levels to it.  when something it selected from the third level of the combobox, it is suppose to fire off a selectedIndexChanged event.  This happens the first time that I select the usercontrol.  The problem is if i want to go back and select something different.  The selectedIndexChanged doesn't fire.  I've set breakpoints and the

AddHandler ComboBox3.SelectedIndexChanged, AddressOf ComboBox3_SelectedIndexChanged

runs just like it did the first time i select the usercontrol.  But the selectedIndex just doesn't fire the second go around.  Was wondering what i'm doing wrong.

Here is the selectedIndexChanged that is not firing

Sub ComboBox3_SelectedIndexChanged(ByVal sender As Object, ByVal e As ComboBoxItemEventArgs)
    Dim Oc As New Dempsey.ClassIndex_Controller
    Dim O As New Dempsey.ClassIndex
    oClassIndexs = Oc.GetClassIndexData(CInt(ComboBox1.SelectedValue))
    For Each O In oClassIndexs
    Next
    ClassSearchResults = o
    RaiseEvent myClassificationSearch(oClassIndexs, e)
End Sub

I'll add whatever other code you might want to see... but didn't want to make the post too long.

thanks
shannon

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
some more info.. as mentioned above, this is a cascading combobox.  So combobox1 has values of say 1,2,3, Combobox 2 gets it's data filtered depending on what you select on combobox1.

Well.. i've noticed that if i select 1 in combobox 1 the first time through, things work as expected.  If on the second round i select something other than 1 in combobox1, the event fires.  However, if i select 1 in combobox 1 on the second round through, the event does not fire.

This is not the way i need it to work because it could be that the second time through, i need to select the same value in combobox1 but a different value in combobox2.  Any idea what i can do to get around this... since it would appear that it's working the way it should.

i mention it above.. but i'm using an Obout combox control
thanks