问:
Can I hide only the Bootstrap Modal's content?
Is there a way to only hide the content of the modal, not the modal itself, so when I click next, it shows the content from the next modal, but it doesn't reopen the next modal, but changes only to the content.
There's a code of JQuery which creates the Modals accord to the amount of array elements in a text file and a function with which I try to change the Modal content with next/previous buttons

```<code>$("#Modals_"+index).each(function () {
    var currentModal = $(this);
    // Modal next
    currentModal.find('.btn-next').click(function () {
        currentModal.modal('hide');
        currentModal.closest("div[id^='Modals_']").nextAll("div[id^='Modals_']").first().modal('show');
    });
    //Modal previous
    currentModal.find('.btn-prev').click(function () {
        currentModal.modal('hide');
        currentModal.closest("div[id^='Modals_']").prevAll("div[id^='Modals_']").first().modal('show');
    });
});
</code>```

"```<button class=\"btn modal-button\" data-toggle=\"modal\" id=\"buttonOn_" + index + "\" data-target=\"#Modals_" + index + "\" value=\"open Modal\"></button>\n" +
"     <h3 class=\"modal-title_" + index + "\"></h3>\n" +
"```\n" +
"
\n" +
"
\n" +
"
\n" +
"
\n" +
"            \n" +
"

\n" +
"

\n" +
"            <button class=\"btn-prev\" id=\"previous_"+index+"\" onclick=\"\">Previous</button>\n" +
"            <button class=\"btn-next\" id=\"next_"+index+"\" onclick=\"\">Next</button>\n" +
"            <button type=\"button\" class=\"btn btn-default\" data-dismiss=\"modal\" style='color: white;'>Close</button>\n" +
"
\n" +
"
\n" +
"
\n" +
"
\n");
```

<pre class="lang-js prettyprint-override"><code>Array
(
    [0] => Array
        (
            [nameLV] => Loku līnijas mezgls
            [descriptionLV] => Mezgls, kas izskatās pēc loka
            [nameEN] => Bowline knot
            [descriptionEN] => Angliski
            [nameRU] => Узел носовой линии
            [descriptionRU] => Krieviski
            [Image] => bowline.png
        )

    [1] => Array
        (
            [nameLV] => Astoņnieku mezgls
            [descriptionLV] => Mezgls 8 formā
            [nameEN] => Figure Eight knot
            [descriptionEN] => Angliski
            [nameRU] => Восьмерка узел
            [descriptionRU] => Krieviski
            [Image] => figureEight.png
        )

    [2] => Array
        (
            [nameLV] => Makšķernieku mezgls
            [descriptionLV] => Izmanto tikai un vienīgi copermaņi
            [nameEN] => Fishermans knot
            [descriptionEN] => Used only and just only by fishermen fisherweman gender neutral
            [nameRU] => Copermanskij uzel
            [descriptionRU] => Tolko copermanski nuzno etot uzel
            [Image] => FishermansStyle.png
        )

    [3] => Array
        (
            [nameLV] => Sakabes mezgls
            [descriptionLV] => Mezgls ko izmanto lai sakabinātu lietas
            [nameEN] => Bunt Line Hitch knot
            [descriptionEN] => Angliski
            [nameRU] => Узел сцепления
            [descriptionRU] => Krieviski
            [Image] => buntlineHitch.png
        )

)
LV
EN
</code>```

That is the array which is returned in php when I call back the .txt file with Json encoded data.

答:
Here I have tried to solve your problem with one model, which is working fine, I can understand that your client is requesting for multiple modals but it's just code duplication and rework. just check this with json if it can help you out.

var json = [{
 "title": "title1",
 "image": "image1",
 "description": "description1"
}, {
 "title": "title2",
 "image": "image2",
 "description": "description2"
}];

$(function() {
  $("#next-btn").on("click", function() {
      var currentId = $(document).find("#position").val();
      id = $("#"+currentId).next();
      nextId = id.data("json")
      btnId = id.attr("id");
      if(nextId!==undefined) {
        openModal(nextId, btnId);
      } else {
        alert("last");
      }
  });

  $("#prev-btn").on("click", function() {
      var currentId = $(document).find("#position").val();
      id = $("#"+currentId).prev();
      prevId = id.data("json");
      btnId = id.attr("id");
      if(prevId!==undefined) {
        openModal(prevId, btnId);
      } else {
        alert("first");
      }
  });

  $(".openmodal").on("click", function() {
      openModal($(this).data("json"), $(this).attr('id'));
  });
});

function openModal(id, btnId) {
    var js = json[id];
    title = js.title;
    image = js.image;
    description = js.description;
    $("#position").val(btnId);
    $(".modal-title").html(title);
    $(".modal-body").html("image"+image+", description"+description);
    $("#myModal").modal('show');
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" />
<div id="myModal" class="modal fade" tabindex="-1" role="dialog">
  <div class="modal-dialog">
  <div class="modal-content">
 <div class="modal-header">
  <button type="button" class="close" data-dismiss="modal">×</button>
  <h3 class="modal-title">Heading</h3>
 </div>
 <div class="modal-body">

 </div>
 <div class="modal-footer">
    <input type="text" name="current" value="" id="position" />
  <button id="prev-btn" class="btn btn-warning">Prev</button>
        <button id="next-btn" class="btn btn-primary">Next</button>
  <button class="btn btn-default" data-dismiss="modal">Close</button>
 </div>
   </div>
  </div>
</div>

<input type="button" id="btn1" name="modal-open" data-json=0 class="openmodal btn btn-success" value="Open Model1" />

<input type="button" id="btn2" name="modal-open" data-json=1 class="openmodal btn btn-success" value="Open Model2" /></code>```

Body:
Is there a way to only hide the content of the modal, not the modal itself, so when I click next, it shows the content from the next modal, but it doesn't reopen the next modal, but changes only to the content.
There's a code of JQuery which creates the Modals accord to the amount of array elements in a text file and a function with which I try to change the Modal content with next/previous buttons

$("#Modals_"+index).each(function () {
    var currentModal = $(this);
    // Modal next
    currentModal.find('.btn-next').click(function () {
        currentModal.modal('hide');
        currentModal.closest("div[id^='Modals_']").nextAll("div[id^='Modals_']").first().modal('show');
    });
    //Modal previous
    currentModal.find('.btn-prev').click(function () {
        currentModal.modal('hide');
        currentModal.closest("div[id^='Modals_']").prevAll("div[id^='Modals_']").first().modal('show');
    });
});

"
<button class=\"btn modal-button\" data-toggle=\"modal\" id=\"buttonOn_" + index + "\" data-target=\"#Modals_" + index + "\" value=\"open Modal\"></button>\n" +
"

\n" +
"
\n" +
"
\n" +
"
\n" +
"
\n" +
"
\n" +
"            \n" +
"

\n" +
"

\n" +
"            <button class=\"btn-prev\" id=\"previous_"+index+"\" onclick=\"\">Previous</button>\n" +
"            <button class=\"btn-next\" id=\"next_"+index+"\" onclick=\"\">Next</button>\n" +
"            <button type=\"button\" class=\"btn btn-default\" data-dismiss=\"modal\" style='color: white;'>Close</button>\n" +
"
\n" +
"
\n" +
"
\n" +
"
\n");

Array
(
    [0] => Array
        (
            [nameLV] => Loku līnijas mezgls
            [descriptionLV] => Mezgls, kas izskatās pēc loka
            [nameEN] => Bowline knot
            [descriptionEN] => Angliski
            [nameRU] => Узел носовой линии
            [descriptionRU] => Krieviski
            [Image] => bowline.png
        )

    [1] => Array
        (
            [nameLV] => Astoņnieku mezgls
            [descriptionLV] => Mezgls 8 formā
            [nameEN] => Figure Eight knot
            [descriptionEN] => Angliski
            [nameRU] => Восьмерка узел
            [descriptionRU] => Krieviski
            [Image] => figureEight.png
        )

    [2] => Array
        (
            [nameLV] => Makšķernieku mezgls
            [descriptionLV] => Izmanto tikai un vienīgi copermaņi
            [nameEN] => Fishermans knot
            [descriptionEN] => Used only and just only by fishermen fisherweman gender neutral
            [nameRU] => Copermanskij uzel
            [descriptionRU] => Tolko copermanski nuzno etot uzel
            [Image] => FishermansStyle.png
        )

    [3] => Array
        (
            [nameLV] => Sakabes mezgls
            [descriptionLV] => Mezgls ko izmanto lai sakabinātu lietas
            [nameEN] => Bunt Line Hitch knot
            [descriptionEN] => Angliski
            [nameRU] => Узел сцепления
            [descriptionRU] => Krieviski
            [Image] => buntlineHitch.png
        )

)
LV
EN

That is the array which is returned in php when I call back the .txt file with Json encoded data.

Body:
Here I have tried to solve your problem with one model, which is working fine, I can understand that your client is requesting for multiple modals but it's just code duplication and rework. just check this with json if it can help you out.

var json = [{
 "title": "title1",
 "image": "image1",
 "description": "description1"
}, {
 "title": "title2",
 "image": "image2",
 "description": "description2"
}];

$(function() {
  $("#next-btn").on("click", function() {
      var currentId = $(document).find("#position").val();
      id = $("#"+currentId).next();
      nextId = id.data("json")
      btnId = id.attr("id");
      if(nextId!==undefined) {
        openModal(nextId, btnId);
      } else {
        alert("last");
      }
  });

  $("#prev-btn").on("click", function() {
      var currentId = $(document).find("#position").val();
      id = $("#"+currentId).prev();
      prevId = id.data("json");
      btnId = id.attr("id");
      if(prevId!==undefined) {
        openModal(prevId, btnId);
      } else {
        alert("first");
      }
  });

  $(".openmodal").on("click", function() {
      openModal($(this).data("json"), $(this).attr('id'));
  });
});

function openModal(id, btnId) {
    var js = json[id];
    title = js.title;
    image = js.image;
    description = js.description;
    $("#position").val(btnId);
    $(".modal-title").html(title);
    $(".modal-body").html("image"+image+", description"+description);
    $("#myModal").modal('show');
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" />
<div id="myModal" class="modal fade" tabindex="-1" role="dialog">
  <div class="modal-dialog">
  <div class="modal-content">
 <div class="modal-header">
  <button type="button" class="close" data-dismiss="modal">×</button>
  <h3 class="modal-title">Heading</h3>
 </div>
 <div class="modal-body">

 </div>
 <div class="modal-footer">
    <input type="text" name="current" value="" id="position" />
  <button id="prev-btn" class="btn btn-warning">Prev</button>
        <button id="next-btn" class="btn btn-primary">Next</button>
  <button class="btn btn-default" data-dismiss="modal">Close</button>
 </div>
   </div>
  </div>
</div>

<input type="button" id="btn1" name="modal-open" data-json=0 class="openmodal btn btn-success" value="Open Model1" />

<input type="button" id="btn2" name="modal-open" data-json=1 class="openmodal btn btn-success" value="Open Model2" />


来源: stackexchange

问:
Firebase Querying many child based on one attribute value from one of them
My Firebase storge

from the image above, I want to get all the milk powder based on the barcode of one of them

```<code>var query: Query = FirebaseDatabase.getInstance().getReference("Barcode")
                    .orderByChild("itemBarcode")
                    .equalTo(read)
</code>```

where 'read' is the barcode number I only get one item,
I want instead to get all the item type and wight based on barcode number
like:
 SELECT itemWieght, itemName, itemPrice FROM barcode WHERE itemBarcode.itemType = itemType or something like this

EDIT :

here is my part of the code if that's helps

```<code>var query: Query = FirebaseDatabase.getInstance().getReference("Barcode")
                    .orderByChild("itemBarcode")
                    .equalTo(read)

                //Adapter
                query.addValueEventListener(object : ValueEventListener {
                    override fun onCancelled(p0: DatabaseError) {

                    }

                    override fun onDataChange(p0: DataSnapshot) {
                        myBarcodeArray?.clear()
                        for (r in p0.children) {
                            var infoHolder = r.getValue(BarcodeInfo::class.java)

                            myBarcodeArray!!.add(infoHolder!!)
                        }
                        val infoAdapter = BarcodeResultAdapter(applicationContext, myBarcodeArray!!)
                        view.listOfBarcodeResult.adapter = infoAdapter
                    }
                })
</code>```

EDIT 2:
I tried also to use 2 queries, but it shows empty results

```<code>myDataRef?.child("Barcode")?.orderByChild("itemBarcode")?.equalTo(read)?.addListenerForSingleValueEvent(object : ValueEventListener{
                    override fun onCancelled(p0: DatabaseError) {

                    }
                    override fun onDataChange(p0: DataSnapshot) {
                        var result = p0.getValue(BarcodeInfo::class.java)
                        myDataRef?.child("Barcode")?.orderByChild(result?.itemWeight.toString())?.equalTo(read)?.addValueEventListener(object : ValueEventListener{
                            override fun onCancelled(p0: DatabaseError) {
                            }
                            override fun onDataChange(p0: DataSnapshot) {
                                for (r in p0.children){
                                    var holder = r.getValue(BarcodeInfo::class.java)
                                    myBarcodeArray!!.add(holder!!)
                                }
                                val infoAdapter = BarcodeResultAdapter(applicationContext, myBarcodeArray!!)
                                view.listOfBarcodeResult.adapter = infoAdapter
                            }
                        })
                    }
                })
</code>```

答:
I did it by using "Kiet Phan" advice and used 2 query statement like this :

```<code>var query: Query = FirebaseDatabase.getInstance().getReference("Barcode")
                    .orderByChild("itemBarcode")
                    .equalTo(read)
                query.addValueEventListener(object : ValueEventListener {
                    override fun onCancelled(p0: DatabaseError) {}
                    override fun onDataChange(p0: DataSnapshot) {
                        myBarcodeArray?.clear()
                        for (r in p0.children) {
                            var infoHolder = r.getValue(BarcodeInfo::class.java)
                            type = infoHolder?.itemType.toString()
                        }
                        var query2: Query = FirebaseDatabase.getInstance().getReference("Barcode")
                            .orderByChild("itemType")
                            .equalTo(type)
                        query2.addValueEventListener(object : ValueEventListener{
                            override fun onCancelled(p0: DatabaseError) {}

                            override fun onDataChange(p0: DataSnapshot) {
                                for (r in p0.children) {
                                    var infoHolder = r.getValue(BarcodeInfo::class.java)
                                    type = infoHolder?.itemType.toString()
                                    myBarcodeArray!!.add(infoHolder!!)
                                }
                                val infoAdapter = BarcodeResultAdapter(applicationContext, myBarcodeArray!!)
                                view.listOfBarcodeResult.adapter = infoAdapter
                            }
                        })
                    }
                })
</code>```

thanks to everyone for help

ContentLicense: CC BY-SA 4.0

Body:
My Firebase storge

from the image above, I want to get all the milk powder based on the barcode of one of them

var query: Query = FirebaseDatabase.getInstance().getReference("Barcode")
                    .orderByChild("itemBarcode")
                    .equalTo(read)

where 'read' is the barcode number I only get one item,
I want instead to get all the item type and wight based on barcode number
like:
 SELECT itemWieght, itemName, itemPrice FROM barcode WHERE itemBarcode.itemType = itemType or something like this

EDIT :

here is my part of the code if that's helps

var query: Query = FirebaseDatabase.getInstance().getReference("Barcode")
                    .orderByChild("itemBarcode")
                    .equalTo(read)

                //Adapter
                query.addValueEventListener(object : ValueEventListener {
                    override fun onCancelled(p0: DatabaseError) {

                    }

                    override fun onDataChange(p0: DataSnapshot) {
                        myBarcodeArray?.clear()
                        for (r in p0.children) {
                            var infoHolder = r.getValue(BarcodeInfo::class.java)

                            myBarcodeArray!!.add(infoHolder!!)
                        }
                        val infoAdapter = BarcodeResultAdapter(applicationContext, myBarcodeArray!!)
                        view.listOfBarcodeResult.adapter = infoAdapter
                    }
                })

EDIT 2:
I tried also to use 2 queries, but it shows empty results

myDataRef?.child("Barcode")?.orderByChild("itemBarcode")?.equalTo(read)?.addListenerForSingleValueEvent(object : ValueEventListener{
                    override fun onCancelled(p0: DatabaseError) {

                    }
                    override fun onDataChange(p0: DataSnapshot) {
                        var result = p0.getValue(BarcodeInfo::class.java)
                        myDataRef?.child("Barcode")?.orderByChild(result?.itemWeight.toString())?.equalTo(read)?.addValueEventListener(object : ValueEventListener{
                            override fun onCancelled(p0: DatabaseError) {
                            }
                            override fun onDataChange(p0: DataSnapshot) {
                                for (r in p0.children){
                                    var holder = r.getValue(BarcodeInfo::class.java)
                                    myBarcodeArray!!.add(holder!!)
                                }
                                val infoAdapter = BarcodeResultAdapter(applicationContext, myBarcodeArray!!)
                                view.listOfBarcodeResult.adapter = infoAdapter
                            }
                        })
                    }
                })

Body:
I did it by using "Kiet Phan" advice and used 2 query statement like this :

var query: Query = FirebaseDatabase.getInstance().getReference("Barcode")
                    .orderByChild("itemBarcode")
                    .equalTo(read)
                query.addValueEventListener(object : ValueEventListener {
                    override fun onCancelled(p0: DatabaseError) {}
                    override fun onDataChange(p0: DataSnapshot) {
                        myBarcodeArray?.clear()
                        for (r in p0.children) {
                            var infoHolder = r.getValue(BarcodeInfo::class.java)
                            type = infoHolder?.itemType.toString()
                        }
                        var query2: Query = FirebaseDatabase.getInstance().getReference("Barcode")
                            .orderByChild("itemType")
                            .equalTo(type)
                        query2.addValueEventListener(object : ValueEventListener{
                            override fun onCancelled(p0: DatabaseError) {}

                            override fun onDataChange(p0: DataSnapshot) {
                                for (r in p0.children) {
                                    var infoHolder = r.getValue(BarcodeInfo::class.java)
                                    type = infoHolder?.itemType.toString()
                                    myBarcodeArray!!.add(infoHolder!!)
                                }
                                val infoAdapter = BarcodeResultAdapter(applicationContext, myBarcodeArray!!)
                                view.listOfBarcodeResult.adapter = infoAdapter
                            }
                        })
                    }
                })

thanks to everyone for help


问:
How do I change the color of the outputs of the bupaR packages (e.g. a process map)?
I would like to change the color of the plots that bupaR and adjacent packages output. They always use a blue color. So far I have managed to recolor the nodes of a process_map, but I would also like to color the edges and all other plots.

Further, the processmonitR/edeaR package creates dashboards, which I would like to recolor. The colors seem to be hardcoded (see here)

Example output with default colors:

```<code>library(dplyr)
library(bupaR)
library(shiny)

patients %>% process_map

patients %>% process_map(type = frequency("absolute", color_scale = "Oranges"))

patients %>% precedence_matrix %>% plot

patients %>% plotly_trace_explorer
</code>```

答: Use scale_fill = scale_fill_discrete(h = c(0, 310) + 50, l = 50, c = 150). Check the documentation for function arguments.

Body:
I would like to change the color of the plots that bupaR and adjacent packages output. They always use a blue color. So far I have managed to recolor the nodes of a process_map, but I would also like to color the edges and all other plots.

Further, the processmonitR/edeaR package creates dashboards, which I would like to recolor. The colors seem to be hardcoded (see here)

Example output with default colors:

library(dplyr)
library(bupaR)
library(shiny)

patients %>% process_map

patients %>% process_map(type = frequency("absolute", color_scale = "Oranges"))

patients %>% precedence_matrix %>% plot

patients %>% plotly_trace_explorer


问:
PHP - Mutidimensional array diff
i would like to ask for your help since I'm having difficulty resolving this matter. I had created a function to facilitate on array diff but it does not suffice to my needs. Thanks and more power!

```<code><?php
   $arraySession = array(
      'sampleA' => array('1', '2', '3'),
      'sampleB' => array('1', '2', '3'),
   );

$arrayPost = array(
    'sampleA' => array('1'),
    'sampleB' => array('1','2'),
);
</code>```

result should be:

```<code>array(
   'sampleA' => array('2', '3')
   'sampleB' => array('3'),
)
</code>```

my existing function:

```<code>    public function array_diff_multidimensional($session, $post) {
      $result = array();
      foreach($session as $sKey => $sValue){
          foreach($post as $pKey => $pValue) {
              if((string) $sKey == (string) $pKey) {
                  $result[$sKey] = array_diff($sValue, $pValue);
              } else {
                  $result[$sKey] = $sValue;
              }
          }
      }
      return $result;
    }
</code>```

Any help would be much appreciated! Happy coding!

答:
You want something more or less like this:</p>

```<code>public function array_diff_multidimensional($arr1, $arr2) {
    $answer = array();
    foreach($arr1 as $k1 => $v1) {
        // is the key present in the second array?
        if (!array_key_exists($k1, $arr2)) {
           $answer[$k1] = $v1;
           continue;
        }

        // PHP makes all arrays into string "Array", so if both items
        // are arrays, recursively test them before the string check
        if (is_array($v1) && is_array($arr2[$k1])) {
            $answer[$k1] = array_diff_multidimensional($v1, $arr2[$k1]);
            continue;
        }

        // do the array_diff string check
        if ((string)$arr1[$k1] === (string)$arr2[$k1]) {
            continue;
        }

        // since both values are not arrays, and they don't match,
        // simply add the $arr1 value to match the behavior of array_diff
        // in the PHP core
        $answer[$k1] = $v1;
    }

    // done!
    return $answer;
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: PHP - Mutidimensional array diff

Body:
i would like to ask for your help since I'm having difficulty resolving this matter. I had created a function to facilitate on array diff but it does not suffice to my needs. Thanks and more power!

<?php
   $arraySession = array(
      'sampleA' => array('1', '2', '3'),
      'sampleB' => array('1', '2', '3'),
   );

$arrayPost = array(
    'sampleA' => array('1'),
    'sampleB' => array('1','2'),
);

result should be:

array(
   'sampleA' => array('2', '3')
   'sampleB' => array('3'),
)

my existing function:

    public function array_diff_multidimensional($session, $post) {
      $result = array();
      foreach($session as $sKey => $sValue){
          foreach($post as $pKey => $pValue) {
              if((string) $sKey == (string) $pKey) {
                  $result[$sKey] = array_diff($sValue, $pValue);
              } else {
                  $result[$sKey] = $sValue;
              }
          }
      }
      return $result;
    }

Any help would be much appreciated! Happy coding!

Body:
You want something more or less like this:

public function array_diff_multidimensional($arr1, $arr2) {
    $answer = array();
    foreach($arr1 as $k1 => $v1) {
        // is the key present in the second array?
        if (!array_key_exists($k1, $arr2)) {
           $answer[$k1] = $v1;
           continue;
        }

        // PHP makes all arrays into string "Array", so if both items
        // are arrays, recursively test them before the string check
        if (is_array($v1) && is_array($arr2[$k1])) {
            $answer[$k1] = array_diff_multidimensional($v1, $arr2[$k1]);
            continue;
        }

        // do the array_diff string check
        if ((string)$arr1[$k1] === (string)$arr2[$k1]) {
            continue;
        }

        // since both values are not arrays, and they don't match,
        // simply add the $arr1 value to match the behavior of array_diff
        // in the PHP core
        $answer[$k1] = $v1;
    }

    // done!
    return $answer;
}


问:
Complex sorting by single colum in R
I am trying to sort a data frame by codes contained in one column.

The logic behind these code is:

S/number/number/number/digit (e.g. S120B). The numbers are not always 3 (e.g. S10K) and the letters are not always present (e.g. S2).

The first code is S1, and the list goes until S999, where it turns to S1A. Then it goes to S999A and then turns to S1B, and so on.

Furthermore, there are also codes inside thare are totally different, as W23, E100, etc that should go together.

How can I order the dataframe according to this pretty sick ordering scheme?

MWE: codes <- c(S1, S20D, S550C, S88A, S420K, E44, W22)

答:
Following your directions, this is a customized function:

```<code>codes <- c("S1", "S20D", "E44", "S550C", "S88A", "S420K", "W22")
complex_order <- function(codes) {
  # Create empty order vector
  final_order <- rep(NA,length(codes))
  # First into account codes that do not match the S convention
  not_in_convention <- !tolower(substr(codes,1,1)) == "s"
  final_order[(length(codes)-sum(not_in_convention)+1):length(codes)] <- which(not_in_convention)

  # Then check the ones that has a letter at the end
  letter_at_end <- tolower(substr(codes,nchar(codes),nchar(codes))) %in% letters & !not_in_convention
  for (idx in which(letter_at_end)) {
    lettr <- tolower(substr(codes[idx],nchar(codes[idx]),nchar(codes[idx])))
    lettr_value <- which(lettr == letters) * 1000 # Every letter means 1000 positions ahead
    codes[idx] <- paste0("S",as.character(lettr_value))
  }

  # Now that we have all in the same code, order the values
  values <- as.numeric(tolower(substr(codes[!not_in_convention],2,nchar(codes[!not_in_convention]))))
  final_order[order(values)] <- which(!not_in_convention)
  final_order
}
codes[complex_order(codes)]
[1] "S1"    "S88A"  "S550C" "S20D"  "S420K" "E44"   "W22"
</code>```

Hope it helps!

Title: Complex sorting by single colum in R

Body:
Following your directions, this is a customized function:

codes <- c("S1", "S20D", "E44", "S550C", "S88A", "S420K", "W22")
complex_order <- function(codes) {
  # Create empty order vector
  final_order <- rep(NA,length(codes))
  # First into account codes that do not match the S convention
  not_in_convention <- !tolower(substr(codes,1,1)) == "s"
  final_order[(length(codes)-sum(not_in_convention)+1):length(codes)] <- which(not_in_convention)

  # Then check the ones that has a letter at the end
  letter_at_end <- tolower(substr(codes,nchar(codes),nchar(codes))) %in% letters & !not_in_convention
  for (idx in which(letter_at_end)) {
    lettr <- tolower(substr(codes[idx],nchar(codes[idx]),nchar(codes[idx])))
    lettr_value <- which(lettr == letters) * 1000 # Every letter means 1000 positions ahead
    codes[idx] <- paste0("S",as.character(lettr_value))
  }

  # Now that we have all in the same code, order the values
  values <- as.numeric(tolower(substr(codes[!not_in_convention],2,nchar(codes[!not_in_convention]))))
  final_order[order(values)] <- which(!not_in_convention)
  final_order
}
codes[complex_order(codes)]
[1] "S1"    "S88A"  "S550C" "S20D"  "S420K" "E44"   "W22"

Hope it helps!


问:
Proper way to handle CosmosDb Mongo 429 error with Polly
I deploy an application on azure web apps who interract with a CosmosDB database using the mongoDb driver in .netCore 3.

Following this documentation I have to set a retry policy in order to handle the 429 error code when the RU/s are not available. I can't find a proper way to handle the policy with Polly given the fact that I haven't seen one the error display when the 429 error happends.

The only proper way to do it is by using the following Policy :

```<code>_retryPolicy = Policy
.Handle<MongoCommandException>(r => r.Message.Contains("Request rate is large"))
.WaitAndRetry(3, i => TimeSpan.FromSeconds(1));
</code>```

And here is the use of the Polly policy :

```<code>   public long CountProjetByProjectNumber(string projectNumber)
    {
        long result = 0;
        _retryPolicy.Execute(() =>
        {
            result = _mongoCollection.CountDocuments(x => x.ProjectNumber == projectNumber);
        });
        return result;
    }
</code>```

Do someone have the correct error display when the 429 exception happends in CosmosDb with the Mongodb driver or can someone show me the way he handled it properly.

答:
There is actually a few more exceptions you'll have to handle in order to properly handle rate limiting and timeouts - especially when using the newer MongoDB V3.6 endpoint (as opposed to the older V3.2 endpoint).

For V3.2 Endpoints: The two exceptions you care about is the MongoCommandException and MongoExecutionTimeoutException. The
  MongoCommandException includes a BsonDocument property in its
  Result field. This document has a StatusCode you can use to detect 429. That said, from my testing, I also found that I had to handle Http Service Unavailable (1) and Operation Exceeded Time Limit
  (50) status codes.

For V3.6 Endpoints: You probably also want to handle MongoWriteException and MongoBulkWriteException. These exceptions
  include a RetryAfterMs= value in the exception message (not
  always though!). Unfortunately, this value does not seem to be
  directly exposed via a class property - most likely because this is
  a CosmosDB specific feature and thus does not map to the MongoDB
  driver defined exceptions.

The below code is implemented in .NET Standard 2.0 and should give you more than a good starting point. You will definitely want to tweak some of the constants based on your circumstances and testing.

```<code>    public static class Policies
    {
        public const int HttpThrottleErrorCode = 429;
        public const int HttpServiceIsUnavailable = 1;
        public const int HttpOperationExceededTimeLimit = 50;
        public const int RateLimitCode = 16500;
        public const string RetryAfterToken = "RetryAfterMs=";
        public const int MaxRetries = 10;
        public static readonly int RetryAfterTokenLength = RetryAfterToken.Length;

        private static readonly Random JitterSeed = new Random();

        public static readonly IAsyncPolicy NoPolicy = Policy.NoOpAsync();

        public static Func<int, TimeSpan> SleepDurationProviderWithJitter(double exponentialBackoffInSeconds, int maxBackoffTimeInSeconds) => retryAttempt
            => TimeSpan.FromSeconds(Math.Min(Math.Pow(exponentialBackoffInSeconds, retryAttempt), maxBackoffTimeInSeconds)) // exponential back-off: 2, 4, 8 etc
               + TimeSpan.FromMilliseconds(JitterSeed.Next(0, 1000)); // plus some jitter: up to 1 second

        public static readonly Func<int, TimeSpan> DefaultSleepDurationProviderWithJitter =
            SleepDurationProviderWithJitter(1.5, 23);

        public static readonly IAsyncPolicy MongoCommandExceptionPolicy = Policy
            .Handle<MongoCommandException>(e =>
            {
                if (e.Code != RateLimitCode || !(e.Result is BsonDocument bsonDocument))
                {
                    return false;
                }

                if (bsonDocument.TryGetValue("StatusCode", out var statusCode) && statusCode.IsInt32)
                {
                    switch (statusCode.AsInt32)
                    {
                        case HttpThrottleErrorCode:
                        case HttpServiceIsUnavailable:
                        case HttpOperationExceededTimeLimit:
                            return true;
                        default:
                            return false;
                    }
                }

                if (bsonDocument.TryGetValue("IsValid", out var isValid) && isValid.IsBoolean)
                {
                    return isValid.AsBoolean;
                }

                return true;
            })
            .WaitAndRetryAsync(
                retryCount: MaxRetries,
                DefaultSleepDurationProviderWithJitter
            );

        public static readonly IAsyncPolicy ExecutionTimeoutPolicy = Policy
            .Handle<MongoExecutionTimeoutException>(e =>
                e.Code == RateLimitCode || e.Code == HttpOperationExceededTimeLimit
            )
            .WaitAndRetryAsync(
                retryCount: MaxRetries,
                DefaultSleepDurationProviderWithJitter
            );

        public static readonly IAsyncPolicy MongoWriteExceptionPolicy = Policy
            .Handle<MongoWriteException>(e =>
            {
                return e.WriteError?.Code == RateLimitCode
                       || (e.InnerException is MongoBulkWriteException bulkException &&
                           bulkException.WriteErrors.Any(error => error.Code == RateLimitCode));
            })
            .WaitAndRetryAsync(
                retryCount: MaxRetries,
                sleepDurationProvider: (retryAttempt, e, ctx) =>
                {
                    var timeToWaitInMs = ExtractTimeToWait(e.Message);
                    if (!timeToWaitInMs.HasValue && e.InnerException != null)
                    {
                        timeToWaitInMs = ExtractTimeToWait(e.InnerException.Message);
                    }
                    return timeToWaitInMs ?? DefaultSleepDurationProviderWithJitter(retryAttempt);
                },
                onRetryAsync: (e, ts, i, ctx) => Task.CompletedTask
            );

        public static readonly IAsyncPolicy MongoBulkWriteExceptionPolicy = Policy
            .Handle<MongoBulkWriteException>(e =>
            {
                return e.WriteErrors.Any(error => error.Code == RateLimitCode);
            })
            .WaitAndRetryAsync(
                retryCount: MaxRetries,
                sleepDurationProvider: (retryAttempt, e, ctx) =>
                {
                    var timeToWaitInMs = ExtractTimeToWait(e.Message);
                    return timeToWaitInMs ?? DefaultSleepDurationProviderWithJitter(retryAttempt);
                },
                onRetryAsync: (e, ts, i, ctx) => Task.CompletedTask
            );

        /// <summary>
        /// It doesn't seem like RetryAfterMs is a property value - so unfortunately, we have to extract it from a string... (crazy??!)
        /// </summary>
        private static TimeSpan? ExtractTimeToWait(string messageToParse)
        {
            var retryPos = messageToParse.IndexOf(RetryAfterToken, StringComparison.OrdinalIgnoreCase);
            if (retryPos >= 0)
            {
                retryPos += RetryAfterTokenLength;
                var endPos = messageToParse.IndexOf(',', retryPos);
                if (endPos > 0)
                {
                    var timeToWaitInMsString = messageToParse.Substring(retryPos, endPos - retryPos);
                    if (Int32.TryParse(timeToWaitInMsString, out int timeToWaitInMs))
                    {
                        return TimeSpan.FromMilliseconds(timeToWaitInMs)
                               + TimeSpan.FromMilliseconds(JitterSeed.Next(100, 1000));
                    }
                }
            }
            return default;
        }

        /// <summary>
        /// Use this policy if your CosmosDB MongoDB endpoint is V3.2
        /// </summary>
        public static readonly IAsyncPolicy DefaultPolicyForMongo3_2 = Policy.WrapAsync(MongoCommandExceptionPolicy, ExecutionTimeoutPolicy);

        /// <summary>
        /// Use this policy if your CosmosDB MongoDB endpoint is V3.6 or V3.2
        /// </summary>
        public static readonly IAsyncPolicy DefaultPolicyForMongo3_6 = Policy.WrapAsync(MongoCommandExceptionPolicy, ExecutionTimeoutPolicy, MongoWriteExceptionPolicy, MongoBulkWriteExceptionPolicy);
    }

    public static IAsyncPolicy DefaultPolicy { get; set; } = Policies.DefaultPolicyForMongo3_6;
</code>```

Body:
I deploy an application on azure web apps who interract with a CosmosDB database using the mongoDb driver in .netCore 3.

Following this documentation I have to set a retry policy in order to handle the 429 error code when the RU/s are not available. I can't find a proper way to handle the policy with Polly given the fact that I haven't seen one the error display when the 429 error happends.

The only proper way to do it is by using the following Policy :

_retryPolicy = Policy
.Handle<MongoCommandException>(r => r.Message.Contains("Request rate is large"))
.WaitAndRetry(3, i => TimeSpan.FromSeconds(1));

And here is the use of the Polly policy :

   public long CountProjetByProjectNumber(string projectNumber)
    {
        long result = 0;
        _retryPolicy.Execute(() =>
        {
            result = _mongoCollection.CountDocuments(x => x.ProjectNumber == projectNumber);
        });
        return result;
    }

Do someone have the correct error display when the 429 exception happends in CosmosDb with the Mongodb driver or can someone show me the way he handled it properly.

Body:
There is actually a few more exceptions you'll have to handle in order to properly handle rate limiting and timeouts - especially when using the newer MongoDB V3.6 endpoint (as opposed to the older V3.2 endpoint).

For V3.2 Endpoints: The two exceptions you care about is the MongoCommandException and MongoExecutionTimeoutException. The
  MongoCommandException includes a BsonDocument property in its
  Result field. This document has a StatusCode you can use to detect 429. That said, from my testing, I also found that I had to handle Http Service Unavailable (1) and Operation Exceeded Time Limit
  (50) status codes.

For V3.6 Endpoints: You probably also want to handle MongoWriteException and MongoBulkWriteException. These exceptions
  include a RetryAfterMs= value in the exception message (not
  always though!). Unfortunately, this value does not seem to be
  directly exposed via a class property - most likely because this is
  a CosmosDB specific feature and thus does not map to the MongoDB
  driver defined exceptions.

The below code is implemented in .NET Standard 2.0 and should give you more than a good starting point. You will definitely want to tweak some of the constants based on your circumstances and testing.

    public static class Policies
    {
        public const int HttpThrottleErrorCode = 429;
        public const int HttpServiceIsUnavailable = 1;
        public const int HttpOperationExceededTimeLimit = 50;
        public const int RateLimitCode = 16500;
        public const string RetryAfterToken = "RetryAfterMs=";
        public const int MaxRetries = 10;
        public static readonly int RetryAfterTokenLength = RetryAfterToken.Length;

        private static readonly Random JitterSeed = new Random();

        public static readonly IAsyncPolicy NoPolicy = Policy.NoOpAsync();

        public static Func<int, TimeSpan> SleepDurationProviderWithJitter(double exponentialBackoffInSeconds, int maxBackoffTimeInSeconds) => retryAttempt
            => TimeSpan.FromSeconds(Math.Min(Math.Pow(exponentialBackoffInSeconds, retryAttempt), maxBackoffTimeInSeconds)) // exponential back-off: 2, 4, 8 etc
               + TimeSpan.FromMilliseconds(JitterSeed.Next(0, 1000)); // plus some jitter: up to 1 second

        public static readonly Func<int, TimeSpan> DefaultSleepDurationProviderWithJitter =
            SleepDurationProviderWithJitter(1.5, 23);

        public static readonly IAsyncPolicy MongoCommandExceptionPolicy = Policy
            .Handle<MongoCommandException>(e =>
            {
                if (e.Code != RateLimitCode || !(e.Result is BsonDocument bsonDocument))
                {
                    return false;
                }

                if (bsonDocument.TryGetValue("StatusCode", out var statusCode) && statusCode.IsInt32)
                {
                    switch (statusCode.AsInt32)
                    {
                        case HttpThrottleErrorCode:
                        case HttpServiceIsUnavailable:
                        case HttpOperationExceededTimeLimit:
                            return true;
                        default:
                            return false;
                    }
                }

                if (bsonDocument.TryGetValue("IsValid", out var isValid) && isValid.IsBoolean)
                {
                    return isValid.AsBoolean;
                }

                return true;
            })
            .WaitAndRetryAsync(
                retryCount: MaxRetries,
                DefaultSleepDurationProviderWithJitter
            );

        public static readonly IAsyncPolicy ExecutionTimeoutPolicy = Policy
            .Handle<MongoExecutionTimeoutException>(e =>
                e.Code == RateLimitCode || e.Code == HttpOperationExceededTimeLimit
            )
            .WaitAndRetryAsync(
                retryCount: MaxRetries,
                DefaultSleepDurationProviderWithJitter
            );

        public static readonly IAsyncPolicy MongoWriteExceptionPolicy = Policy
            .Handle<MongoWriteException>(e =>
            {
                return e.WriteError?.Code == RateLimitCode
                       || (e.InnerException is MongoBulkWriteException bulkException &&
                           bulkException.WriteErrors.Any(error => error.Code == RateLimitCode));
            })
            .WaitAndRetryAsync(
                retryCount: MaxRetries,
                sleepDurationProvider: (retryAttempt, e, ctx) =>
                {
                    var timeToWaitInMs = ExtractTimeToWait(e.Message);
                    if (!timeToWaitInMs.HasValue && e.InnerException != null)
                    {
                        timeToWaitInMs = ExtractTimeToWait(e.InnerException.Message);
                    }
                    return timeToWaitInMs ?? DefaultSleepDurationProviderWithJitter(retryAttempt);
                },
                onRetryAsync: (e, ts, i, ctx) => Task.CompletedTask
            );

        public static readonly IAsyncPolicy MongoBulkWriteExceptionPolicy = Policy
            .Handle<MongoBulkWriteException>(e =>
            {
                return e.WriteErrors.Any(error => error.Code == RateLimitCode);
            })
            .WaitAndRetryAsync(
                retryCount: MaxRetries,
                sleepDurationProvider: (retryAttempt, e, ctx) =>
                {
                    var timeToWaitInMs = ExtractTimeToWait(e.Message);
                    return timeToWaitInMs ?? DefaultSleepDurationProviderWithJitter(retryAttempt);
                },
                onRetryAsync: (e, ts, i, ctx) => Task.CompletedTask
            );

        /// <summary>
        /// It doesn't seem like RetryAfterMs is a property value - so unfortunately, we have to extract it from a string... (crazy??!)
        /// </summary>
        private static TimeSpan? ExtractTimeToWait(string messageToParse)
        {
            var retryPos = messageToParse.IndexOf(RetryAfterToken, StringComparison.OrdinalIgnoreCase);
            if (retryPos >= 0)
            {
                retryPos += RetryAfterTokenLength;
                var endPos = messageToParse.IndexOf(',', retryPos);
                if (endPos > 0)
                {
                    var timeToWaitInMsString = messageToParse.Substring(retryPos, endPos - retryPos);
                    if (Int32.TryParse(timeToWaitInMsString, out int timeToWaitInMs))
                    {
                        return TimeSpan.FromMilliseconds(timeToWaitInMs)
                               + TimeSpan.FromMilliseconds(JitterSeed.Next(100, 1000));
                    }
                }
            }
            return default;
        }

        /// <summary>
        /// Use this policy if your CosmosDB MongoDB endpoint is V3.2
        /// </summary>
        public static readonly IAsyncPolicy DefaultPolicyForMongo3_2 = Policy.WrapAsync(MongoCommandExceptionPolicy, ExecutionTimeoutPolicy);

        /// <summary>
        /// Use this policy if your CosmosDB MongoDB endpoint is V3.6 or V3.2
        /// </summary>
        public static readonly IAsyncPolicy DefaultPolicyForMongo3_6 = Policy.WrapAsync(MongoCommandExceptionPolicy, ExecutionTimeoutPolicy, MongoWriteExceptionPolicy, MongoBulkWriteExceptionPolicy);
    }

    public static IAsyncPolicy DefaultPolicy { get; set; } = Policies.DefaultPolicyForMongo3_6;


问:
mySQL disappearing records after insert
I have a weird thing happen to me lately. I work on MySQL database and using phpMyAdmin to help manage it. Recently I wanted to make a copy of a table using select as an insert, as I noticed that most records in the table were duplicates, and wanted to create a new clean table without repeating records.

INSERT INTO `newTable` (SELECT * FROM `oldTable` GROUP BY `uniqueVal`)

and got a message that 63959 were copied successfully (note, select above cuts down 146383 records to 63959).
Now the weird part, when I run query:

SELECT * FROM `newTable` it returns only 56207 rows.

but query like this:

SELECT COUNT(*) FROM `newTable` returns correct number (63959) as well as

SELECT * FROM `newTable` GROUP BY `id` returns 63959 rows.

Now I'm new to managing databases, but I'm pretty sure that shouldn't happen, did I insert data incorrectly, did anyone had a similar issue and how did you resolve it? Please help as I don't know where to begin to fix such an issue.

答:
The MySQL engine is randomly picking values and probably you don't want that.

The subquery:

```<code>SELECT * FROM oldTable GROUP BY `uniqueVal`
</code>```

though accepted by MySQL is not a valid SQL query and is producing issues.

All columns not present in the GROUP BY clause must be aggregated, by using SUM(), MIN(), MAX(), etc.

Rephrase your query and try again.

Title: mySQL disappearing records after insert

Body:
The MySQL engine is randomly picking values and probably you don't want that.

The subquery:

SELECT * FROM oldTable GROUP BY `uniqueVal`

though accepted by MySQL is not a valid SQL query and is producing issues.

All columns not present in the GROUP BY clause must be aggregated, by using SUM(), MIN(), MAX(), etc.

Rephrase your query and try again.


问:
How User account be locked for 30 min after 5 unsuccessful login attempts with asp.net?
I am using asp.net membership provider for managing users. I have a requirement to lock user accounts for 30 mins after 5 unsuccessful attempts. How should I do that using asp.net membership provider on the server side?

Also I want that 'Passwords should expire after 3 months', 'Last 10 used passwords should be remembered'. Is there any way to solve these requirements.

答: Create custom membership provider. There You can implement all needed functionality, see sample: http://msdn.microsoft.com/en-us/library/44w5aswa.aspx</p>


问:
Spring - Get request header without using @RequestHeader annotation
My code is currently implemented like so:

```<code>fun test(@RequestHeader key: String) { ... }
</code>```

But I wan't to remove the parameter, so it's something like this:

```<code>fun test() { request.headers("key") ... }
</code>```

Is this possible with Spring?

答:
Autowire HttpServletRequest in your class and use it within the functions defined in the class for example:

```<code>class MyClass {
   @Autowired
   lateinit var request: HttpServletRequest

   fun test() { request.getHeader("key") ... }
}
</code>```

Body:
My code is currently implemented like so:

fun test(@RequestHeader key: String) { ... }

But I wan't to remove the parameter, so it's something like this:

fun test() { request.headers("key") ... }

Is this possible with Spring?

Body:
Autowire HttpServletRequest in your class and use it within the functions defined in the class for example:

class MyClass {
   @Autowired
   lateinit var request: HttpServletRequest

   fun test() { request.getHeader("key") ... }
}


问:
AWS CLI: Copy certain number of files from each bucket to local
I'm trying to download the first (just to give an example) 10 files from every bucket.
I'm new to this, I've read aws cli's documentation but couldn't find anything about this.</p>

答:
The awscli has two broad sets of functions for S3: aws s3 and aws s3api. The former is higher level (it includes sync features, for example) while the lower maps closely to the underlying S3 APIs.

You can script a simple solution that uses aws s3api list-objects --max-items 10 to get a list of at most 10 objects from the bucket, and then copies them one-by-one.


问:
Pointer to implementation (PIMPL) in Qt
I made a Dll with MSVS and used pimpl method successfuly exactly like below:

Dll include file:

```<code>#include <memory>

#define DllExport __declspec( dllexport )

namespace M
{
    class P
    {
    public:
        DllExport P(/*some arguments*/);
        DllExport ~P();
        DllExport int aFunction (/* some arguments*/);

    private:
        class C;
        std::unique_ptr<C> mc;
    };
}
</code>```

The private include file:

```<code>namespace M
{
    class P::C
    {
        public:
         # Other variables and functions which are not needed to be exported...
    }
}
</code>```

And the cpp file:

```<code>DllExport M::P::P(/*some arguments*/):mc(std::make_unique<C>())
{
# ...
}
DllExport M::P::~P(){ }

DllExport int M::P::aFunction (/* some arguments*/)
{
#...
}
</code>```

Now I want to implement such method in Qt creator. What changes I should make?

(I guess I have to use QScopedPointer instead of unique_ptr but what is best implementation form for that?)

PS: I set clang as compiler.

答:
Your code looks find and it should be independent from the IDE.
You can use this, but i think this is what you are searching for.</p>

Title: Pointer to implementation (PIMPL) in Qt

Body:
I made a Dll with MSVS and used pimpl method successfuly exactly like below:

Dll include file:

#include <memory>

#define DllExport __declspec( dllexport )

namespace M
{
    class P
    {
    public:
        DllExport P(/*some arguments*/);
        DllExport ~P();
        DllExport int aFunction (/* some arguments*/);

    private:
        class C;
        std::unique_ptr<C> mc;
    };
}

The private include file:

namespace M
{
    class P::C
    {
        public:
         # Other variables and functions which are not needed to be exported...
    }
}

And the cpp file:

DllExport M::P::P(/*some arguments*/):mc(std::make_unique<C>())
{
# ...
}
DllExport M::P::~P(){ }

DllExport int M::P::aFunction (/* some arguments*/)
{
#...
}

Now I want to implement such method in Qt creator. What changes I should make?

(I guess I have to use QScopedPointer instead of unique_ptr but what is best implementation form for that?)

PS: I set clang as compiler.


问:
Problems setting up an association in Rails
I have a Post model and a User model.  Users can love posts, this information is kept in a separate Love model rather than directly on the post because the User has to be able to see a record of the post's they've liked.

I have a migration like this:

```<code>    create_table :loves do |t|
      t.references :post, null: false, foreign_key: true
      t.references :user, null: false, foreign_key: true
    end
</code>```

User.rb

```<code>  has_many :loves
</code>```

Post.rb

```<code>  has_many :loves
</code>```

Love.rb

```<code>class Love < ApplicationRecord
  belongs_to :user
  has_one :dinner
end

</code>```

This association does not seem to work, whenever I try to love a post I get this error:

```<code>uninitialized constant User::Lofe
</code>```

I realize the word "Lofe" may seem like a typo of Love, which is what I thought but I've searched through the entire codebase and there is no instance of Lofe.

In Rails console if I type User.first.love I will get an error suggesting Did you mean? loves this seems to indicate that the association exists (works with both Users and Dinners) but if I then type User.first.loves it will throw the same Uninitialized constant error.

答: I did a little research and the problem is with Rails inflection engine. As you can see here: https://twitter.com/andypike/status/578214888465657856 and here: https://rails.lighthouseapp.com/projects/8994/tickets/2407-inflector-singularising-loves-to-lofe-but-pluralizing-love-to-loves apparently when using the word love you need to configure it by hand in config/initizers/inflections.rb

Body:
I have a Post model and a User model.  Users can love posts, this information is kept in a separate Love model rather than directly on the post because the User has to be able to see a record of the post's they've liked.

I have a migration like this:

    create_table :loves do |t|
      t.references :post, null: false, foreign_key: true
      t.references :user, null: false, foreign_key: true
    end

User.rb

  has_many :loves

Post.rb

  has_many :loves

Love.rb

class Love < ApplicationRecord
  belongs_to :user
  has_one :dinner
end

This association does not seem to work, whenever I try to love a post I get this error:

uninitialized constant User::Lofe

I realize the word "Lofe" may seem like a typo of Love, which is what I thought but I've searched through the entire codebase and there is no instance of Lofe.

In Rails console if I type User.first.love I will get an error suggesting Did you mean? loves this seems to indicate that the association exists (works with both Users and Dinners) but if I then type User.first.loves it will throw the same Uninitialized constant error.


问:
I keep getting this error for my program: VM178 SortLib.js:71 Uncaught TypeError: Cannot read property 'length' of undefined
I am trying to implement the Merge Sort Algorithm visually using HTML and Javascript. My output for the Merge Sort Implementation works as planned, but I keep on getting an error in my terminal window.

```<code>//Merge Sort Algorithm Implementation

//Function for dividing array into two sub problems
divide = (array) => {
    if (array.length < 2) {
        return array
    }
        const mid = Math.floor(array.length / 2)
        const smallOne = array.slice(0, mid)
        const smallTwo = array.slice(mid)
        return sort(divide(smallOne), divide(smallTwo))
    }

//Function for sorting array
sort = (smallOne, smallTwo) => {
    const sorted = []
    while (smallOne.length && smallTwo.length) {
        if (smallOne[0] <= smallTwo[0]) {
            sorted.push(smallOne.shift())
        } else {
            sorted.push(smallTwo.shift())
            }
        }
    const output = [...sorted, ...smallOne, ...smallTwo]
    console.log(output)
    return output
    }

//Functiom for merge sort
mergeSort = (array) => {
return sort(divide(array))
}

</code>```

Here's a picture of my error in the console

答:
Second parameter is missing

mergeSort = (array) => {
  return sort(divide(array), ????)
}```

Body:
I am trying to implement the Merge Sort Algorithm visually using HTML and Javascript. My output for the Merge Sort Implementation works as planned, but I keep on getting an error in my terminal window.

//Merge Sort Algorithm Implementation

//Function for dividing array into two sub problems
divide = (array) => {
    if (array.length < 2) {
        return array
    }
        const mid = Math.floor(array.length / 2)
        const smallOne = array.slice(0, mid)
        const smallTwo = array.slice(mid)
        return sort(divide(smallOne), divide(smallTwo))
    }

//Function for sorting array
sort = (smallOne, smallTwo) => {
    const sorted = []
    while (smallOne.length && smallTwo.length) {
        if (smallOne[0] <= smallTwo[0]) {
            sorted.push(smallOne.shift())
        } else {
            sorted.push(smallTwo.shift())
            }
        }
    const output = [...sorted, ...smallOne, ...smallTwo]
    console.log(output)
    return output
    }

//Functiom for merge sort
mergeSort = (array) => {
return sort(divide(array))
}

Here's a picture of my error in the console


答:
I think you can just call divide from mergeSort, As sort is expecting two variables and the sort call in mergeSort is called finally with already sorted output with a single parameter ..

mergeSort = (array) => {
return divide(array);
}```

Title: I keep getting this error for my program: VM178 SortLib.js:71 Uncaught TypeError: Cannot read property 'length' of undefined


问:
Need to clean users01.dbf in Oracle 12c
I have Oracle Database 12c in a docker container. At one point, the space in the tablespace expanded (the users01.dbf file became 32GB in size) and I made a new file for this tablespace - users02.dbf. I analyzed the tables and indexes that occupy the most space and made them truncate. I see that the size of the largest tables and indexes has decreased, but the users01.dbf and users02.dbf files remain the same size:

users01.dbf 32G

users02.dbf 8.8G

Here is a screenshot:

Left size before, right after truncate command. How can I clean or reduce the size of users01.dbf and users02.dbf files and not break the database.

答:
I am using the one query to find out the actual size that can be shrunk from the data file.

I am using it for almost 4 years and I don't know from where I got it but Yes, I got that script from one of the good blogs of the oracle.

Following script will generate the series of command which can be executed on DB to shrunk the data file or we can say reclaim the free space from the data file (only if more than 1 MB can be reclaimed) to perfect size without any error.

```<code>set linesize 1000 pagesize 0 feedback off trimspool on
with
 hwm as (
  -- get highest block id from each datafiles ( from x$ktfbue as we don't need all joins from dba_extents )
  select /*+ materialize */ ktfbuesegtsn ts#,ktfbuefno relative_fno,max(ktfbuebno+ktfbueblks-1) hwm_blocks
  from sys.x$ktfbue group by ktfbuefno,ktfbuesegtsn
 ),
 hwmts as (
  -- join ts# with tablespace_name
  select name tablespace_name,relative_fno,hwm_blocks
  from hwm join v$tablespace using(ts#)
 ),
 hwmdf as (
  -- join with datafiles, put 5M minimum for datafiles with no extents
  select file_name,nvl(hwm_blocks*(bytes/blocks),5*1024*1024) hwm_bytes,bytes,autoextensible,maxbytes
  from hwmts right join dba_data_files using(tablespace_name,relative_fno)
 )
select
 case when autoextensible='YES' and maxbytes>=bytes
 then -- we generate resize statements only if autoextensible can grow back to current size
  '/* reclaim '||to_char(ceil((bytes-hwm_bytes)/1024/1024),999999)
   ||'M from '||to_char(ceil(bytes/1024/1024),999999)||'M */ '
   ||'alter database datafile '''||file_name||''' resize '||ceil(hwm_bytes/1024/1024)||'M;'
 else -- generate only a comment when autoextensible is off
  '/* reclaim '||to_char(ceil((bytes-hwm_bytes)/1024/1024),999999)
   ||'M from '||to_char(ceil(bytes/1024/1024),999999)
   ||'M after setting autoextensible maxsize higher than current size for file '
   || file_name||' */'
 end SQL
from hwmdf
where
 bytes-hwm_bytes>1024*1024 -- resize only if at least 1MB can be reclaimed
order by bytes-hwm_bytes desc
/
</code>```

It will generate the commands something like the following:

```<code>/* reclaim    1934M from    2048M */ alter database datafile 'C:\APP\TEJASH\VIRTUAL\ORADATA\ORCL\DATAFILE\TEJASH_DATAFILE_01.DBF' resize 115M;
/* reclaim     158M from     200M */ alter database datafile 'C:\APP\TEJASH\VIRTUAL\ORADATA\ORCL\DATAFILE\UNDO_DF_02.DBF' resize 43M;
/* reclaim      59M from    1060M */ alter database datafile 'C:\APP\TEJASH\VIRTUAL\ORADATA\ORCL\DATAFILE\O1_MF_SYSAUX_G9K5LYTT_.DBF' resize 1002M;
/* reclaim       3M from     840M */ alter database datafile 'C:\APP\TEJASH\VIRTUAL\ORADATA\ORCL\DATAFILE\O1_MF_SYSTEM_G9K5KK2J_.DBF' resize 838M;
</code>```

You can directly execute all of them and you do not have to worry about calculating anything by yourself.

Please note that this script will work on the data files for which autoextensible is ON

I hope this will help you out.

Cheers!!

Title: Need to clean users01.dbf in Oracle 12c

Body:
I am using the one query to find out the actual size that can be shrunk from the data file.

I am using it for almost 4 years and I don't know from where I got it but Yes, I got that script from one of the good blogs of the oracle.

Following script will generate the series of command which can be executed on DB to shrunk the data file or we can say reclaim the free space from the data file (only if more than 1 MB can be reclaimed) to perfect size without any error.

set linesize 1000 pagesize 0 feedback off trimspool on
with
 hwm as (
  -- get highest block id from each datafiles ( from x$ktfbue as we don't need all joins from dba_extents )
  select /*+ materialize */ ktfbuesegtsn ts#,ktfbuefno relative_fno,max(ktfbuebno+ktfbueblks-1) hwm_blocks
  from sys.x$ktfbue group by ktfbuefno,ktfbuesegtsn
 ),
 hwmts as (
  -- join ts# with tablespace_name
  select name tablespace_name,relative_fno,hwm_blocks
  from hwm join v$tablespace using(ts#)
 ),
 hwmdf as (
  -- join with datafiles, put 5M minimum for datafiles with no extents
  select file_name,nvl(hwm_blocks*(bytes/blocks),5*1024*1024) hwm_bytes,bytes,autoextensible,maxbytes
  from hwmts right join dba_data_files using(tablespace_name,relative_fno)
 )
select
 case when autoextensible='YES' and maxbytes>=bytes
 then -- we generate resize statements only if autoextensible can grow back to current size
  '/* reclaim '||to_char(ceil((bytes-hwm_bytes)/1024/1024),999999)
   ||'M from '||to_char(ceil(bytes/1024/1024),999999)||'M */ '
   ||'alter database datafile '''||file_name||''' resize '||ceil(hwm_bytes/1024/1024)||'M;'
 else -- generate only a comment when autoextensible is off
  '/* reclaim '||to_char(ceil((bytes-hwm_bytes)/1024/1024),999999)
   ||'M from '||to_char(ceil(bytes/1024/1024),999999)
   ||'M after setting autoextensible maxsize higher than current size for file '
   || file_name||' */'
 end SQL
from hwmdf
where
 bytes-hwm_bytes>1024*1024 -- resize only if at least 1MB can be reclaimed
order by bytes-hwm_bytes desc
/

It will generate the commands something like the following:

/* reclaim    1934M from    2048M */ alter database datafile 'C:\APP\TEJASH\VIRTUAL\ORADATA\ORCL\DATAFILE\TEJASH_DATAFILE_01.DBF' resize 115M;
/* reclaim     158M from     200M */ alter database datafile 'C:\APP\TEJASH\VIRTUAL\ORADATA\ORCL\DATAFILE\UNDO_DF_02.DBF' resize 43M;
/* reclaim      59M from    1060M */ alter database datafile 'C:\APP\TEJASH\VIRTUAL\ORADATA\ORCL\DATAFILE\O1_MF_SYSAUX_G9K5LYTT_.DBF' resize 1002M;
/* reclaim       3M from     840M */ alter database datafile 'C:\APP\TEJASH\VIRTUAL\ORADATA\ORCL\DATAFILE\O1_MF_SYSTEM_G9K5KK2J_.DBF' resize 838M;

You can directly execute all of them and you do not have to worry about calculating anything by yourself.

Please note that this script will work on the data files for which autoextensible is ON

I hope this will help you out.

Cheers!!


问:
SQL connection string for embedded database in Visual Studio solution
I am starting with SQL Server in Visual Studio and have a problem, most probably with my connection string.

I am not installing SQL Server on my computer (there are several reasons for that) but created inside my solution a SQL project. Then, in another project I am attempting to connect to this database using some googled examples, but can't manage to connect. I frequently see that there's a user and password used to connect to the db, but in my case, thus there is no installation but an embedded SQL project, I can't work it out...

My connection string looks like this:

```<code>sqlConnectionString = @"Data Source = MyComputerName;initial catalog=DatabaseStudents";
</code>```

Can anyone let me know if this kind of installation is even possible?

Thanks

答:
This should be in your web.config if you're looking for a simple answer</p>

```<code><add name="YourDBContext"
   connectionString="Data Source=(LocalDb)\ServerName;Initial Catalog=DatabaseName;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\DatabaseFile.mdf"
   providerName="System.Data.SqlClient" />
</code>```

Body:
I am starting with SQL Server in Visual Studio and have a problem, most probably with my connection string.

I am not installing SQL Server on my computer (there are several reasons for that) but created inside my solution a SQL project. Then, in another project I am attempting to connect to this database using some googled examples, but can't manage to connect. I frequently see that there's a user and password used to connect to the db, but in my case, thus there is no installation but an embedded SQL project, I can't work it out...

My connection string looks like this:

sqlConnectionString = @"Data Source = MyComputerName;initial catalog=DatabaseStudents";

Can anyone let me know if this kind of installation is even possible?

Thanks

Body:
This should be in your web.config if you're looking for a simple answer

<add name="YourDBContext"
   connectionString="Data Source=(LocalDb)\ServerName;Initial Catalog=DatabaseName;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\DatabaseFile.mdf"
   providerName="System.Data.SqlClient" />


问:
Invalid Bundle, The bundle contains disallowed nested bundles, contains disallowed file 'Frameworks'
I added a shared framework to share code between app and watch extension. Later I removed the shared framework since it cause lots of problems. I can build
and run my app on iphone and watch. However when I submit to app store, I see these two errors:

ERROR ITMS-90205: "Invalid Bundle. The bundle at 'xxx WatchKit Extension.appex' contains disallowed nested bundles."

ERROR ITMS-90206: "Invalid Bundle. The bundle at 'xxx WatchKit Extension.appex' contains disallowed file 'Frameworks'."

I have tried all the solutions mentioned on stackoverflow(this , this, this) None of them works for me.  How do I fix the error?  Errors message from apple really doesn't give a clue what I should to.

答:
I had a today extension which uses a custom framework I implemented it.

I tried all the solutions but nothing worked for me.

I needed the custom framework only in the today extension, so I linked and embedded this framework in the today extension only.

What the error is saying is:

that the bundle contains disallowed frameworks

Today extension should not embed any framework, shall only link to it.

So I removed the framework from the today extension and added it to the parent app.

Note that:

the parent app should use this framework since it's added to it, an import shall do the job.


问:
Text above two images
I want to place one text above two images. I am using the layout given below but the text is not coming on the top.

Any help pls -

```<code><?xml version="1.0" encoding="utf-8"?>
 <ScrollView android:id="@+id/ScrollView01"
android:layout_width="fill_parent" android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="fill_parent"
    android:layout_height="fill_parent" android:background="@drawable/layout"
    android:gravity="center">

    <TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical" android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:gravity="top">

        <TableRow android:weightSum="100">
            <TextView android:id="@+id/imageText" android:layout_width="wrap_content"
                android:layout_height="wrap_content" android:gravity="top"
                android:textStyle="bold" android:typeface="sans" android:text="TWO"
                android:layout_weight="100"></TextView>
        </TableRow>
    </TableLayout>

    <TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical" android:layout_width="fill_parent"
        android:layout_height="fill_parent">

        <TableRow android:weightSum="100">
            <ImageView android:id="@+id/image1" android:layout_width="wrap_content"
                android:layout_height="wrap_content" android:src="@drawable/girrafe"
                android:visibility="visible" android:gravity="center"
                android:layout_weight="50" />
            <ImageView android:id="@+id/image1" android:layout_width="wrap_content"
                android:layout_height="wrap_content" android:src="@drawable/girrafe"
                android:layout_weight="50" />
        </TableRow>
    </TableLayout>

</LinearLayout>
</ScrollView>
</code>```

答:
try this...
its simpler...</p>

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="match_parent" android:orientation="vertical" android:gravity="center_horizontal">
    <TextView android:text="TextView" android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView>
    <LinearLayout android:layout_width="match_parent" android:id="@+id/linearLayout1" android:layout_height="wrap_content">
        <ImageView android:layout_width="wrap_content" android:id="@+id/imageView1" android:src="@drawable/icon" android:layout_height="wrap_content" android:layout_weight="1"></ImageView>
        <ImageView android:layout_width="wrap_content" android:id="@+id/imageView2" android:src="@drawable/icon" android:layout_height="wrap_content" android:layout_weight="1"></ImageView>
    </LinearLayout>
</LinearLayout>
</code>```

Title: Text above two images

Body:
I want to place one text above two images. I am using the layout given below but the text is not coming on the top.

Any help pls -

<?xml version="1.0" encoding="utf-8"?>
 <ScrollView android:id="@+id/ScrollView01"
android:layout_width="fill_parent" android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="fill_parent"
    android:layout_height="fill_parent" android:background="@drawable/layout"
    android:gravity="center">

    <TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical" android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:gravity="top">

        <TableRow android:weightSum="100">
            <TextView android:id="@+id/imageText" android:layout_width="wrap_content"
                android:layout_height="wrap_content" android:gravity="top"
                android:textStyle="bold" android:typeface="sans" android:text="TWO"
                android:layout_weight="100"></TextView>
        </TableRow>
    </TableLayout>

    <TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical" android:layout_width="fill_parent"
        android:layout_height="fill_parent">

        <TableRow android:weightSum="100">
            <ImageView android:id="@+id/image1" android:layout_width="wrap_content"
                android:layout_height="wrap_content" android:src="@drawable/girrafe"
                android:visibility="visible" android:gravity="center"
                android:layout_weight="50" />
            <ImageView android:id="@+id/image1" android:layout_width="wrap_content"
                android:layout_height="wrap_content" android:src="@drawable/girrafe"
                android:layout_weight="50" />
        </TableRow>
    </TableLayout>

</LinearLayout>
</ScrollView>

Body:
try this...
its simpler...

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="match_parent" android:orientation="vertical" android:gravity="center_horizontal">
    <TextView android:text="TextView" android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView>
    <LinearLayout android:layout_width="match_parent" android:id="@+id/linearLayout1" android:layout_height="wrap_content">
        <ImageView android:layout_width="wrap_content" android:id="@+id/imageView1" android:src="@drawable/icon" android:layout_height="wrap_content" android:layout_weight="1"></ImageView>
        <ImageView android:layout_width="wrap_content" android:id="@+id/imageView2" android:src="@drawable/icon" android:layout_height="wrap_content" android:layout_weight="1"></ImageView>
    </LinearLayout>
</LinearLayout>


问:
Karate: Match JSON Array responses where the order of array is different in each hit
I have a scenario where a portion of the response arrays is the response from a child API.
child API response looks like below, but there is no specific order. And I need to check whether the child API response is present in the parent API(irrespective of the order of the elements in the child API). I followed this Karate - Match two dynamic responses thread but its not working in my case.</p>

```<code>* def response1 =

    """
   {
    "array1": [
        {
            "element": {
                "id": "A1",
                "array11": [
                    {
                        "uid": "u123",
                        "gid": [
                            "g1"
                        ]
                    }
                ]
            }
        },
        {
            "element": {
                "id": "A2",
                "array11": [
                    {
                        "uid": "u124",
                        "gid": [
                            "g2"
                        ]
                    }
                ]
            }
        }
    ]
}
"""
* def response2 =

    """
 {
    "array1": [
        {
            "element": {
                "id": "A2",
                "array11": [
                    {
                        "uid": "u124",
                        "gid": [
                            "g2"
                        ]
                    }
                ]
            }
        },
        {
            "element": {
                "id": "A1",
                "array11": [
                    {
                        "uid": "u123",
                        "gid": [
                            "g1"
                        ]
                    }
                ]
            }
        }

    ]
}
    """
</code>```

答:
This is a one liner :)

```<code>* match response2.array1 contains response1.array1
</code>```

Guess what, you don't have to match pure JSON all the time, using child-sections is fine.

But also read this specific part of the docs: https://github.com/intuit/karate#contains-short-cuts

And this example: https://github.com/intuit/karate/blob/master/karate-demo/src/test/java/demo/graphql/graphql.feature

Body:
I have a scenario where a portion of the response arrays is the response from a child API.
child API response looks like below, but there is no specific order. And I need to check whether the child API response is present in the parent API(irrespective of the order of the elements in the child API). I followed this Karate - Match two dynamic responses thread but its not working in my case.

* def response1 =

    """
   {
    "array1": [
        {
            "element": {
                "id": "A1",
                "array11": [
                    {
                        "uid": "u123",
                        "gid": [
                            "g1"
                        ]
                    }
                ]
            }
        },
        {
            "element": {
                "id": "A2",
                "array11": [
                    {
                        "uid": "u124",
                        "gid": [
                            "g2"
                        ]
                    }
                ]
            }
        }
    ]
}
"""
* def response2 =

    """
 {
    "array1": [
        {
            "element": {
                "id": "A2",
                "array11": [
                    {
                        "uid": "u124",
                        "gid": [
                            "g2"
                        ]
                    }
                ]
            }
        },
        {
            "element": {
                "id": "A1",
                "array11": [
                    {
                        "uid": "u123",
                        "gid": [
                            "g1"
                        ]
                    }
                ]
            }
        }

    ]
}
    """

Body:
This is a one liner :)

* match response2.array1 contains response1.array1

Guess what, you don't have to match pure JSON all the time, using child-sections is fine.

But also read this specific part of the docs: https://github.com/intuit/karate#contains-short-cuts

And this example: https://github.com/intuit/karate/blob/master/karate-demo/src/test/java/demo/graphql/graphql.feature


问:
'_Wherenode was nullptr' when adding to static std::map
I've been following this tutorial / example on creating a self-registering type in C++17. But I've run into a problem: Upon a type's attempt to register, my program terminates with the error read access violation. _Wherenode was nullptr. This error occurs in the standard library's std::_Tree<std::Tmap_traits<...>::_Lbound method.

This is my source code, nearly identical to that on the page (with some tweaks to fix errors the original code had:)

```<code>class Entity { ... }; // Contents irrelevant

class EntityTypeFactory {
public:
    using TCreateMethod = std::function<Entity* ()>;

    EntityTypeFactory() = delete;

    static Entity* Create(const std::string& type);

    static bool Register(const std::string& name, TCreateMethod func);

private:
    static std::map<std::string, TCreateMethod> s_methods;
};

#define REG_ENT(TYPE) class TYPE##Creator { private: static bool s_created; }; \
bool TYPE##Creator::s_created = EntityTypeFactory::Register(#TYPE, []() -> Entity* { return new TYPE(); });

std::map<std::string, EntityTypeFactory::TCreateMethod>* EntityTypeFactory::s_methods;

Entity* EntityTypeFactory::Create(const std::string& type)
{
    if (s_methods == nullptr) return nullptr;

    return (*s_methods)[type]();
}

bool EntityTypeFactory::Register(const std::string& name, TCreateMethod func)
{
    if (s_methods == nullptr)
        s_methods = new std::map<std::string, TCreateMethod>();

    (*s_methods)[name] = func;
    return true;
}

class Foo : public Entity {}; // Contents irrelevant

REG_ENT(Foo)
</code>```

Edit: This seems to have to do with the linking order, as if I place my test implementation Foo in a source file which would occur earlier than Entity when sorted alphabetically (as this seems to be VC++'s way of choosing link order), it fails, but if I place this implementation in a file which is linked after, it works as intended. I still am not sure how to make it work universally though.

答:
As correctly pointed out in your Edit, the problem lies in the order of initialization, i.e. what happens before the main method is invoked.

In the same file (compilation unit to be precise) you can rely on the order of execution of constructors for static objects to match the order they appear in your source code.

When your program is made by multiple compilation units, the order in which compilation units are constructed is up to the implementation.

There's a way to achieve your goal since the compiler first initializes all static storage and then invokes static object constructors - you need to make sure that every time you access static std::map<std::string, TCreateMethod> s_methods; it is properly initialized. You can achieve this by declaring it static within a method. E.g.:

static std::map<std::string, TCreateMethod>& methods()
{
    static std::map<std::string, TCreateMethod> singleton;
    return singleton;
}
```

This ensures that the first time this function is called, the map object (named singleton) is constructed and it is returned.

This technique, sometimes referred to as Meyer's Singleton is called lazy evaluation, meaning that required operations are delayed up to the last minute just before they are needed.

(I found a great and detailed explanation about C++ static initialization here: https://pabloariasal.github.io/2020/01/02/static-variable-initialization/)

Body:
I've been following this tutorial / example on creating a self-registering type in C++17. But I've run into a problem: Upon a type's attempt to register, my program terminates with the error read access violation. _Wherenode was nullptr. This error occurs in the standard library's std::_Tree<std::Tmap_traits<...>::_Lbound method.

This is my source code, nearly identical to that on the page (with some tweaks to fix errors the original code had:)

class Entity { ... }; // Contents irrelevant

class EntityTypeFactory {
public:
    using TCreateMethod = std::function<Entity* ()>;

    EntityTypeFactory() = delete;

    static Entity* Create(const std::string& type);

    static bool Register(const std::string& name, TCreateMethod func);

private:
    static std::map<std::string, TCreateMethod> s_methods;
};

#define REG_ENT(TYPE) class TYPE##Creator { private: static bool s_created; }; \
bool TYPE##Creator::s_created = EntityTypeFactory::Register(#TYPE, []() -> Entity* { return new TYPE(); });

std::map<std::string, EntityTypeFactory::TCreateMethod>* EntityTypeFactory::s_methods;

Entity* EntityTypeFactory::Create(const std::string& type)
{
    if (s_methods == nullptr) return nullptr;

    return (*s_methods)[type]();
}

bool EntityTypeFactory::Register(const std::string& name, TCreateMethod func)
{
    if (s_methods == nullptr)
        s_methods = new std::map<std::string, TCreateMethod>();

    (*s_methods)[name] = func;
    return true;
}

class Foo : public Entity {}; // Contents irrelevant

REG_ENT(Foo)

Edit: This seems to have to do with the linking order, as if I place my test implementation Foo in a source file which would occur earlier than Entity when sorted alphabetically (as this seems to be VC++'s way of choosing link order), it fails, but if I place this implementation in a file which is linked after, it works as intended. I still am not sure how to make it work universally though.

Body:
As correctly pointed out in your Edit, the problem lies in the order of initialization, i.e. what happens before the main method is invoked.

In the same file (compilation unit to be precise) you can rely on the order of execution of constructors for static objects to match the order they appear in your source code.

When your program is made by multiple compilation units, the order in which compilation units are constructed is up to the implementation.

There's a way to achieve your goal since the compiler first initializes all static storage and then invokes static object constructors - you need to make sure that every time you access static std::map<std::string, TCreateMethod> s_methods; it is properly initialized. You can achieve this by declaring it static within a method. E.g.:

static std::map<std::string, TCreateMethod>& methods()
{
    static std::map<std::string, TCreateMethod> singleton;
    return singleton;
}

This ensures that the first time this function is called, the map object (named singleton) is constructed and it is returned.

This technique, sometimes referred to as Meyer's Singleton is called lazy evaluation, meaning that required operations are delayed up to the last minute just before they are needed.

(I found a great and detailed explanation about C++ static initialization here: https://pabloariasal.github.io/2020/01/02/static-variable-initialization/)


问:
Validating accuracy on time-series data with an atypical ending
I'm working on a project to predict demand for a product based on past historical data for multiple stores. I have data from multiple stores over a 5 year period. I split the 5-year time series into overlapping subsequences and use the last 18 months to predict the next 3 and I'm able to make predictions. However, I've run into a problem in choosing a cross-validation method.

I want to have a holdout test split, and use some sort of cross-validation for training my model and tuning parameters. However, the last year of the data was a recession where almost all demand suffered. When I use the last 20% (time-wise) of the data as a holdout set, my test score is very low compared to my OOF cross-validation scores, even though I am using a timeseriessplit CV. This is very likely to be caused by this recession being new behavior, and the model can't predict these strong downswings since it has never seen them before.

The solution I'm thinking of is using a random 20% of the data as a holdout, and a shuffled Kfold as cross-validation. Since I am not feeding any information about when the sequence started into the model except the starting month (1 to 12) of the sequence (to help the model explain seasonality), my theory is that the model should not overfit this data based on that. If all types of economy are present in the data, the results of the model should extrapolate to new data too.

I would like a second opinion on this, do you think my assumptions are correct? Is there a different way to solve this problem?

答:
Your overall assumption is correct in that you can probably take random chunks of time to form your training and testing set. However, when doing it this way, you need to be careful. Rather than predicting the raw values of the next 3 months from the prior 18 months, I would predict the relative increase/decrease of sales in the next 3 months vs. the mean of the past 18 months.

(see here)
http://people.stern.nyu.edu/churvich/Forecasting/Handouts/CourantTalk2.pdf

Otherwise, the correlation between the next 3 months with your prior 18 months data might give you a misleading impression about the accuracy of your model


问:
API Gateway with Static Elastic IP
Hi We have an aws API gateway configured with lambda and now want to integrate with a vendor wherein vendor want us to provide him with a Static IP against the API Gateway that we have. As per my knowledge API gateway serves request through Dynamic Elastic IP which are listed here

Is there a way to achieve this other than putting a forward proxy or NLB.

答:
You cannot get a static IP if you are using a public API Gateway endpoint (Regional or Edge-optimized). The IPs allocated for APIs in any AWS region can be changed at any time and are a very wide range.

However, if you were to use a private API Gateway endpoint, you could use the below set up -

```<code>Client --> NLB(public static IP) --> VPC endpoint for API Gateway --> Private API
</code>```

The execute-api VPC endpoint have a fixed IP address allocated from the VPC CIDR range. Having a NLB as a front-end(with a public static IP), you can add these IP addresses as targets in your NLB config.

Title: API Gateway with Static Elastic IP

Body:
You cannot get a static IP if you are using a public API Gateway endpoint (Regional or Edge-optimized). The IPs allocated for APIs in any AWS region can be changed at any time and are a very wide range.

However, if you were to use a private API Gateway endpoint, you could use the below set up -

Client --> NLB(public static IP) --> VPC endpoint for API Gateway --> Private API

The execute-api VPC endpoint have a fixed IP address allocated from the VPC CIDR range. Having a NLB as a front-end(with a public static IP), you can add these IP addresses as targets in your NLB config.


问:
fgets() function doesn't recognise the data
I'm currently building my own shell.
I managed to make ls function using scanf() and now I'm on cd. But I realized that cd has space between cd and file so I changed scanf() to fgets().

The space problem has been solved but another problem came out. Even though I typed correctly, the program won't work.

```<code>char command[MAX_LEN];
int result = 1;
char *pwd[MAX_LEN];

do {
    printf("%s > ", getcwd(pwd, 100));
    fgets(command, 100, stdin);

    if(!strcmp("cd", command))
        change_dir();

    if(!strcmp("ls", command))
        list_dir();

} while(strcmp("exit", command));

return 0;
</code>```

What is wrong with my code? Can you please tell me why it's happening?

答:
fgets reads up to size-1 chars (in your case 100-1 so 99) and places a '\0' at the end of the string, so when you type "ls" in stdin and hit enter, fgets will receive "ls\n" since enter creates a \n char, and the command will be "ls\n\0"
since the \0 indicates the end of the string we can ignore this here for now.

When you strcmp("ls",command), you are comparing "ls" with the string in command that ends before \0 so "ls\n" since "ls" and "ls\n" are not the same, it will fail.

As others already have said, you could either add \n to your compare strings, or remove the \n
since you may be planning to add more to the line after your cd or ls, you could look into string seperation e.g. with strtok()

Body:
I'm currently building my own shell.
I managed to make ls function using scanf() and now I'm on cd. But I realized that cd has space between cd and file so I changed scanf() to fgets().

The space problem has been solved but another problem came out. Even though I typed correctly, the program won't work.

char command[MAX_LEN];
int result = 1;
char *pwd[MAX_LEN];

do {
    printf("%s > ", getcwd(pwd, 100));
    fgets(command, 100, stdin);

    if(!strcmp("cd", command))
        change_dir();

    if(!strcmp("ls", command))
        list_dir();

} while(strcmp("exit", command));

return 0;

What is wrong with my code? Can you please tell me why it's happening?


问:
Spark Streaming df.writeStream generate no output
I am using hdp sandbox 2.6.4 and I have a spark configured on my local machine (host machine).

I have logged into the docker image using shell and have started a simple console consumer. And I am trying to consume that with Spark on my local machine (not docker container). it's not giving any error. however, it's not giving any output either.

```<code> def main(args: Array[String]): Unit = {
    val spark = SparkSession.builder.appName("demo")
      .master("local[*]")
      .getOrCreate()
    spark.sparkContext.setLogLevel("WARN")
    import spark.implicits._
    val df = spark.readStream.
                      format("kafka").
                      option("kafka.bootstrap.servers", "localhost:6667").
                      option("subscribe", "test").
                      load()

    val query = df.writeStream
      .outputMode("append")
      .format("console")
      .start()

    query.awaitTermination()

  }
</code>```

if I log in to docker image and start another console producer I am able to consume all the messages.   I have checked the port and it's open from docker to host machine.

答: I suspect that the advertised.listeners of the kafka brokers within the Docker container within the VM are not configured for external connections </p>

Body:
I am using hdp sandbox 2.6.4 and I have a spark configured on my local machine (host machine).

I have logged into the docker image using shell and have started a simple console consumer. And I am trying to consume that with Spark on my local machine (not docker container). it's not giving any error. however, it's not giving any output either.

 def main(args: Array[String]): Unit = {
    val spark = SparkSession.builder.appName("demo")
      .master("local[*]")
      .getOrCreate()
    spark.sparkContext.setLogLevel("WARN")
    import spark.implicits._
    val df = spark.readStream.
                      format("kafka").
                      option("kafka.bootstrap.servers", "localhost:6667").
                      option("subscribe", "test").
                      load()

    val query = df.writeStream
      .outputMode("append")
      .format("console")
      .start()

    query.awaitTermination()

  }

if I log in to docker image and start another console producer I am able to consume all the messages.   I have checked the port and it's open from docker to host machine.


问:
how to Print some values from a 3d array
i have this array here and i tried to print some of the info i need but it print it all

```<code>int customer=1
int Item=2

     CPR[customer]=new int[Item][2];

     for (int i = 0; i < Item; i++) {
             for (int j = 0; j <2; j++) {
                System.out.print((CPR[customer][i][j]=scanner.nextInt());
</code>```

it's equal to the Scanner which is reading from a file  and its output like this

```<code>2 8
4 5
</code>```

i just need to print the 8 and 5 how can i get it ?

答:
Use an if statement to print only the second item:

```<code>int customer=1
int Item=2

CPR[customer]=new int[Item][2];

for (int i = 0; i < Item; i++) {
    for (int j = 0; j <2; j++) {
        CPR[customer][i][j] = scanner.nextInt();
        if (j == 1) {
            System.out.print(CPR[customer][i][j]);
        }
     }
}
</code>```

Body:
i have this array here and i tried to print some of the info i need but it print it all

int customer=1
int Item=2

     CPR[customer]=new int[Item][2];

     for (int i = 0; i < Item; i++) {
             for (int j = 0; j <2; j++) {
                System.out.print((CPR[customer][i][j]=scanner.nextInt());

it's equal to the Scanner which is reading from a file  and its output like this

2 8
4 5

i just need to print the 8 and 5 how can i get it ?

Body:
Use an if statement to print only the second item:

int customer=1
int Item=2

CPR[customer]=new int[Item][2];

for (int i = 0; i < Item; i++) {
    for (int j = 0; j <2; j++) {
        CPR[customer][i][j] = scanner.nextInt();
        if (j == 1) {
            System.out.print(CPR[customer][i][j]);
        }
     }
}