问:
Why does my method overwrite positions in my array
So I have this method here

```<code>    while(oMenu == 1 || oMenu == 2){
            oMeny = Kbd.readInt("\nClick 1 to make an account\nClick 2 to login\nClick 3 to exit the program");
            if(oMeny == 1){
                for(int i = 0; Account[i] != null; i++){
                    if(Account[i] == null){
                        pos = i;
                    }
                }

                Account[pos] = new Account();

            }

            if(oMeny == 2){
                String s = Kbd.readString("Input your accountnumber: ");
                for(int i = 0; Account[i] != null; i++){
                    if(Account[i] != null && s.equals(Account[i].getAccountNumber())){
                        System.out.println("Welcome!");
                         // Here is rest of my code , the "inner" menu that works menyMetod(iMeny,mMeny);
                    }
                    else{
                        System.out.println("There are no accounts with that given accountnumber!");
                    }
                }
            }

        }
    }
</code>```

I want to understand why if I access the oMeny == 1 and make 2 accounts Why I can't seem to access the first one I make but rather the latest one? It seems that somehow my array "overwrites" the first empty position. Basically I want to find the first empty position in my array, so in the first case it's always index 0 and then the next time I make an account again, it should be Index 1 logically.

EDIT : Heres my code for the Account class

```<code>public class Account{

private int money, transactions;
private String AccountNumber;

public Account(){
    money = Kbd.readInt("\nHow much money do you want to put in?");
    AccountNumber = Kbd.readString("\nWhat account number do you want?");
}
</code>```

答:
You did not show the declaration or initialization of pos, so I think it is not working how you expect because you do not go into the for loop where Account[i] is null to set pos.  Try this</p>

```<code> if(oMenu == 1){
    int pos = 0;
    while (Account[pos] != null && pos < Account.length)
        pos++;
    if (pos < Account.length)
        Account[pos] = new Account();
    else{
         //expand array and add account or throw error
    }
 }

</code>```

Body:
So I have this method here

    while(oMenu == 1 || oMenu == 2){
            oMeny = Kbd.readInt("\nClick 1 to make an account\nClick 2 to login\nClick 3 to exit the program");
            if(oMeny == 1){
                for(int i = 0; Account[i] != null; i++){
                    if(Account[i] == null){
                        pos = i;
                    }
                }

                Account[pos] = new Account();

            }

            if(oMeny == 2){
                String s = Kbd.readString("Input your accountnumber: ");
                for(int i = 0; Account[i] != null; i++){
                    if(Account[i] != null && s.equals(Account[i].getAccountNumber())){
                        System.out.println("Welcome!");
                         // Here is rest of my code , the "inner" menu that works menyMetod(iMeny,mMeny);
                    }
                    else{
                        System.out.println("There are no accounts with that given accountnumber!");
                    }
                }
            }

        }
    }

I want to understand why if I access the oMeny == 1 and make 2 accounts Why I can't seem to access the first one I make but rather the latest one? It seems that somehow my array "overwrites" the first empty position. Basically I want to find the first empty position in my array, so in the first case it's always index 0 and then the next time I make an account again, it should be Index 1 logically.

EDIT : Heres my code for the Account class

public class Account{

private int money, transactions;
private String AccountNumber;

public Account(){
    money = Kbd.readInt("\nHow much money do you want to put in?");
    AccountNumber = Kbd.readString("\nWhat account number do you want?");
}

Body:
You did not show the declaration or initialization of pos, so I think it is not working how you expect because you do not go into the for loop where Account[i] is null to set pos.  Try this

 if(oMenu == 1){
    int pos = 0;
    while (Account[pos] != null && pos < Account.length)
        pos++;
    if (pos < Account.length)
        Account[pos] = new Account();
    else{
         //expand array and add account or throw error
    }
 }


来源: stackexchange

问:
Can I rely on my compiler to diagnose type mismatches within a TU?
On a search through the spec, it appears that my compiler isn't required to diagnose such mistakes as

```<code>extern int a;
extern float a;
</code>```

I previously thought that my compiler needs to diagnose that, but the spec says (emphasis added by me)

After all adjustments of types (during which typedefs (7.1.3) are replaced by their definitions), the types speciﬁed by all declarations referring to a given variable or function shall be identical, except that declarations for an array object can specify array types that differ by the presence or absence of a major array bound (8.3.4). A violation of this rule on type identity does not require a diagnostic.

And in fact, I found cases where compilers don't care. For example, GCC and clang accept the following

```<code>void g() { int f(); }
void h() { float f(); }
</code>```

Since a violation of a rule for which no diagnostic is required means that the entire program requires no diagnostic at all anymore, it means that the following ill-formed program doesn't require a diagnostic either (see 1.4p2). Fortunately, both GCC and Clang diagnose them.

```<code>int f();
float f();
</code>```

The behavior of this code at translation time is effectively undefined. What is the reason for this? Why can the spec not require such cases to be rejected and require these to be diagnosed?

答:
I think the rule you're quoting is talking about the whole program. A diagnostic isn't required if one TU has extern int a; and another has extern float a; because separate translation makes it impossible - the problem can only be detected at link time at best.

But if both declarations occur within a single TU I'm sure a diagnostic is required. Perhaps by 3.3/4? That (roughly) requires that all declarations of a name in one scope refer to the same entity.

ContentLicense: CC BY-SA 3.0

Body:
On a search through the spec, it appears that my compiler isn't required to diagnose such mistakes as

extern int a;
extern float a;

I previously thought that my compiler needs to diagnose that, but the spec says (emphasis added by me)

After all adjustments of types (during which typedefs (7.1.3) are replaced by their definitions), the types speciﬁed by all declarations referring to a given variable or function shall be identical, except that declarations for an array object can specify array types that differ by the presence or absence of a major array bound (8.3.4). A violation of this rule on type identity does not require a diagnostic.

And in fact, I found cases where compilers don't care. For example, GCC and clang accept the following

void g() { int f(); }
void h() { float f(); }

Since a violation of a rule for which no diagnostic is required means that the entire program requires no diagnostic at all anymore, it means that the following ill-formed program doesn't require a diagnostic either (see 1.4p2). Fortunately, both GCC and Clang diagnose them.

int f();
float f();

The behavior of this code at translation time is effectively undefined. What is the reason for this? Why can the spec not require such cases to be rejected and require these to be diagnosed?


问:
Autofilling an input field using JQuery
I have the following form:

```<code><form method='post' id='myform'>

    <div class="typeahead__container">
        <div class="typeahead__field">
            <input type="text" class="item" placeholder="Item" id='item' name='input_val'>
        </div>
    </div>

    <input type="text" class="id" placeholder="ID" id='item-id' name='input_val'>

    <button name="button" type="submit" class="btn btn-primary btn-sm f-14 mr-1">SUBMIT</button>
</form>
</code>```

And the following function to handle live search:

```<code>$(document).ready(function(){

  // Defining the local dataset
  $.getJSON('http://127.0.0.1:8000/tst/', function(data) {
    console.log(data)

    let data = {
        "results": [
          { "item": "First",  "id": "1847" },
          { "item": "Second", "id": "4442" },
          { "item": "Third",  "id": "3847" }
        ]
    };

    //LIVE-SEARCH
    $(() => {

      $('#item').typeahead({
        source: {
          data: data.results.map(record => record.item)
        },
        callback: {
          onInit: function($el) {
            console.log(`Typeahead initiated on: ${$el.prop('tagName')}#${$el.attr('id')}`);
          }
        }
      });

    });
    //END LIVE-SEARCH

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

I want to add another function to fill the default value of the input field item-id according to what the user chooses on the input field item. So, for example, if the user writes First, JQuery should set the default value of item-id to 1847 (see my previous block of code).

How can i do that? Am i supposed to do that inside my live search function or should i use another function?

答:
Looking at your code, I assume you are using Bootstrap Typeahead which uses an updater callback that we can use in this situation.

I hosted this static Json to bring a solution with a close syntax.

Solution 1 : Using Bootstrap Typeahead (may be useful to someone else)

$(document).ready(function(){

    $('input#item').typeahead({

     source:  function (query, process) {
        return $.get('https://api.myjson.com/bins/hi1oo', function (data) {
          //console.log(data);
          //data = $.parseJSON(data);
             return process(data.results);
         });
     },
        display : 'item',
        displayText: function(data){ return data.item;},
        val :  function(data){ return data;},

        updater: function (data) {

            $('#item-id').val(data.id);
            return data.item;
            }

 });
});```
<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" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-3-typeahead/4.0.2/bootstrap3-typeahead.min.js" integrity="sha256-LOnFraxKlOhESwdU/dX+K0GArwymUDups0czPWLEg4E=" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<form method='post' id='myform'>

    <div class="typeahead__container">
        <div class="typeahead__field">
            <input type="text" class="item" placeholder="Item" id='item' name='input_val' autocomplete="off">
        </div>
    </div>

    <input type="text" class="id" placeholder="ID" id='item-id' name='input_val'>

    <button name="button" type="submit" class="btn btn-primary btn-sm f-14 mr-1">SUBMIT</button>
</form></code>```

P.S : If your json is a result of a real-time search query where you look for item names and get this kind of data. Then you better change the source into something like following :

```<code>source:  function (query, process) {
return $.get('inc/ajaxh.php', { query: query }, function (data) {
        return process(data.results);
    });
},
</code>```

Solution 2 : using jQuery Typeahead

This one uses the callback onClickAfter. Notice that I made some changes on how you are mapping your data' response array and choose what to be displayed then use the item.id in the callback function.

$(document).ready(function(){

  // Defining the local dataset
  $.getJSON('https://api.myjson.com/bins/hi1oo', function(data) {

    //LIVE-SEARCH
    $(() => {

      $('#item').typeahead({
        source: {
          //data: data.results.map(record => record.item)
          data: data.results
        },
        display: ["item"],
        callback: {
            //I called it itemx to avoid confusion with available "#item"
            onClickAfter: function (node, a, itemx, event) {
                $('#item-id').val(itemx.id);
                //alert('click');
        }
    }
      });

    });
    //END LIVE-SEARCH

  });
});```
<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://cdnjs.cloudflare.com/ajax/libs/jquery-typeahead/2.11.0/jquery.typeahead.min.js" integrity="sha256-q6QA5qUPfpeuxzP5D/wCMcvsYDsV6kQi5/tti+lcmlk=" crossorigin="anonymous"></script>
<form method='post' id='myform'>

    <div class="typeahead__container">
        <div class="typeahead__field">
            <input type="text" class="item" placeholder="Item" id='item' name='input_val'>
        </div>
    </div>

    <input type="text" class="id" placeholder="ID" id='item-id' name='input_val'>

    <button name="button" type="submit" class="btn btn-primary btn-sm f-14 mr-1">SUBMIT</button>
</form></code>```

ContentLicense: CC BY-SA 4.0

Title: Autofilling an input field using JQuery

Body:
I have the following form:

<form method='post' id='myform'>

            <input type="text" class="item" placeholder="Item" id='item' name='input_val'>

    <input type="text" class="id" placeholder="ID" id='item-id' name='input_val'>

    <button name="button" type="submit" class="btn btn-primary btn-sm f-14 mr-1">SUBMIT</button>
</form>

And the following function to handle live search:

$(document).ready(function(){

  // Defining the local dataset
  $.getJSON('http://127.0.0.1:8000/tst/', function(data) {
    console.log(data)

    let data = {
        "results": [
          { "item": "First",  "id": "1847" },
          { "item": "Second", "id": "4442" },
          { "item": "Third",  "id": "3847" }
        ]
    };

    //LIVE-SEARCH
    $(() => {

      $('#item').typeahead({
        source: {
          data: data.results.map(record => record.item)
        },
        callback: {
          onInit: function($el) {
            console.log(`Typeahead initiated on: ${$el.prop('tagName')}#${$el.attr('id')}`);
          }
        }
      });

    });
    //END LIVE-SEARCH

  });
});

I want to add another function to fill the default value of the input field item-id according to what the user chooses on the input field item. So, for example, if the user writes First, JQuery should set the default value of item-id to 1847 (see my previous block of code).

How can i do that? Am i supposed to do that inside my live search function or should i use another function?

Body:
Looking at your code, I assume you are using Bootstrap Typeahead which uses an updater callback that we can use in this situation.

I hosted this static Json to bring a solution with a close syntax.

Solution 1 : Using Bootstrap Typeahead (may be useful to someone else)

$(document).ready(function(){

    $('input#item').typeahead({

     source:  function (query, process) {
        return $.get('https://api.myjson.com/bins/hi1oo', function (data) {
          //console.log(data);
          //data = $.parseJSON(data);
             return process(data.results);
         });
     },
        display : 'item',
        displayText: function(data){ return data.item;},
        val :  function(data){ return data;},

        updater: function (data) {

            $('#item-id').val(data.id);
            return data.item;
            }

 });
});

<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" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-3-typeahead/4.0.2/bootstrap3-typeahead.min.js" integrity="sha256-LOnFraxKlOhESwdU/dX+K0GArwymUDups0czPWLEg4E=" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<form method='post' id='myform'>

    <div class="typeahead__container">
        <div class="typeahead__field">
            <input type="text" class="item" placeholder="Item" id='item' name='input_val' autocomplete="off">
        </div>
    </div>

    <input type="text" class="id" placeholder="ID" id='item-id' name='input_val'>

    <button name="button" type="submit" class="btn btn-primary btn-sm f-14 mr-1">SUBMIT</button>
</form>

P.S : If your json is a result of a real-time search query where you look for item names and get this kind of data. Then you better change the source into something like following :

source:  function (query, process) {
return $.get('inc/ajaxh.php', { query: query }, function (data) {
        return process(data.results);
    });
},

Solution 2 : using jQuery Typeahead

This one uses the callback onClickAfter. Notice that I made some changes on how you are mapping your data' response array and choose what to be displayed then use the item.id in the callback function.

$(document).ready(function(){

  // Defining the local dataset
  $.getJSON('https://api.myjson.com/bins/hi1oo', function(data) {

    //LIVE-SEARCH
    $(() => {

      $('#item').typeahead({
        source: {
          //data: data.results.map(record => record.item)
          data: data.results
        },
        display: ["item"],
        callback: {
            //I called it itemx to avoid confusion with available "#item"
            onClickAfter: function (node, a, itemx, event) {
                $('#item-id').val(itemx.id);
                //alert('click');
        }
    }
      });

    });
    //END LIVE-SEARCH

  });
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-typeahead/2.11.0/jquery.typeahead.min.js" integrity="sha256-q6QA5qUPfpeuxzP5D/wCMcvsYDsV6kQi5/tti+lcmlk=" crossorigin="anonymous"></script>
<form method='post' id='myform'>

    <div class="typeahead__container">
        <div class="typeahead__field">
            <input type="text" class="item" placeholder="Item" id='item' name='input_val'>
        </div>
    </div>

    <input type="text" class="id" placeholder="ID" id='item-id' name='input_val'>

    <button name="button" type="submit" class="btn btn-primary btn-sm f-14 mr-1">SUBMIT</button>
</form>


问:
Two Inputs side by side CSS
I'm currently practicing some WebDev and I'm working on an interactive food pyramid. I've been able to align the other inputs but the inputs on top of the triangle are giving me trouble, I've tried everything from floats to flex and inline blocks. Nothing seems to work, any help would be greatly appreciated.

function incrementValue1() {
  let value = parseInt(document.getElementById('number1').value, 10);
  value = isNaN(value) ? 0 : value;
  value++;
  document.getElementById('number1').value = value;
}

function decrementValue1() {
  let value = parseInt(document.getElementById('number1').value, 10);
  value = isNaN(value) ? 0 : value;
  if (value > 0) {
    value--;
  }
  document.getElementById('number1').value = value;
}

function incrementValue2() {
  let value = parseInt(document.getElementById('number2').value, 10);
  value = isNaN(value) ? 0 : value;
  value++;
  document.getElementById('number2').value = value;
}

function decrementValue2() {
  let value = parseInt(document.getElementById('number2').value, 10);
  value = isNaN(value) ? 0 : value;
  if (value > 0) {
    value--;
  }
  document.getElementById('number2').value = value;
}

function incrementValue3() {
  let value = parseInt(document.getElementById('number3').value, 10);
  value = isNaN(value) ? 0 : value;
  value++;
  document.getElementById('number3').value = value;
}

function decrementValue3() {
  let value = parseInt(document.getElementById('number3').value, 10);
  value = isNaN(value) ? 0 : value;
  if (value > 0) {
    value--;
  }
  document.getElementById('number3').value = value;
}

function incrementValue4() {
  let value = parseInt(document.getElementById('number4').value, 10);
  value = isNaN(value) ? 0 : value;
  value++;
  document.getElementById('number4').value = value;
}

function decrementValue4() {
  let value = parseInt(document.getElementById('number4').value, 10);
  value = isNaN(value) ? 0 : value;
  if (value > 0) {
    value--;
  }
  document.getElementById('number4').value = value;
}

function incrementValue5() {
  let value = parseInt(document.getElementById('number5').value, 10);
  value = isNaN(value) ? 0 : value;
  value++;
  document.getElementById('number5').value = value;
}

function decrementValue5() {
  let value = parseInt(document.getElementById('number5').value, 10);
  value = isNaN(value) ? 0 : value;
  if (value > 0) {
    value--;
  }
  document.getElementById('number5').value = value;
}

function incrementValue6() {
  let value = parseInt(document.getElementById('number6').value, 10);
  value = isNaN(value) ? 0 : value;
  value++;
  document.getElementById('number6').value = value;
}

function decrementValue6() {
  let value = parseInt(document.getElementById('number6').value, 10);
  value = isNaN(value) ? 0 : value;
  if (value > 0) {
    value--;
  }
  document.getElementById('number6').value = value;
}

var colors = ["red", "blue", "green", "yellow", "purple", "gold", "pink", "grey", "turquoise", "aqua"];
var i = 0;
var selectedColor;

function changeColour() {
  selectedColor = colors[i];
  document.getElementById("number" + 1).style.backgroundColor = selectedColor;
  i++;
  if (i > colors.length)
    i = 0;
}

function printDate() {
  let value = document.getElementById("date").value;
  document.getElementById("check").innerHTML = "Date: " + value;
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.container {
  text-align: center;
  position: relative;
  top: 40%;
}

.inside-text1 {
  display: none;
  position: absolute;
  top: 20px;
  left: 248px;
  text-align: center;
  bottom: -65px;
}

.inside-text {
  display: none;
  position: relative;
  text-align: center;
  bottom: -25px;
}

.inside-text6 {
  display: none;
  position: relative;
  text-align: center;
  bottom: -120px;
  /*float: left;*/
}

#p6 {
  border-bottom: 200px solid blue;
  border-left: 100px solid transparent;
  border-right: 100px solid transparent;
  height: 0;
  width: 0;
  margin-right: auto;
  margin-left: auto;
}

#p5-5 {
  border-bottom: 20px solid white;
  border-left: 45px solid transparent;
  border-right: 45px solid transparent;
  height: 0;
  width: 10px;
  margin-right: auto;
  margin-left: auto;
}

#p5 {
  border-bottom: 80px solid black;
  border-left: 45px solid transparent;
  border-right: 45px solid transparent;
  height: 0;
  width: 220px;
  margin-right: auto;
  margin-left: auto;
}

#p4-5 {
  border-bottom: 20px solid white;
  border-left: 45px solid transparent;
  border-right: 45px solid transparent;
  height: 0;
  width: 240px;
  margin-right: auto;
  margin-left: auto;
}

#p4 {
  border-bottom: 80px solid purple;
  border-left: 45px solid transparent;
  border-right: 45px solid transparent;
  height: 0;
  width: 330px;
  margin-right: auto;
  margin-left: auto;
}

#p3 {
  border-bottom: 80px solid green;
  border-left: 45px solid transparent;
  border-right: 45px solid transparent;
  height: 0;
  width: 420px;
  margin-right: auto;
  margin-left: auto;
}

#p2 {
  border-bottom: 80px solid yellow;
  border-left: 45px solid transparent;
  border-right: 45px solid transparent;
  height: 0;
  width: 510px;
  margin-right: auto;
  margin-left: auto;
}

#p1 {
  position: relative;
  top: 40%;
  border-bottom: 80px solid red;
  border-left: 45px solid transparent;
  border-right: 45px solid transparent;
  height: 0;
  width: 600px;
  margin-right: auto;
  margin-left: auto;
}

#p1:hover .inside-text1 {
  display: block;
}

#p2:hover .inside-text {
  display: block;
}

#p3:hover .inside-text {
  display: block;
}

#p4:hover .inside-text {
  display: block;
}

#p5:hover .inside-text {
  display: block;
}

#p6:hover .inside-text6 {
  display: block;
}

.button {
  margin-right: auto;
  margin-left: auto;
  position: relative;
}

#b1 {
  display: inline-block;
  height: 25px;
  width: 30px;
  border-radius: 50%;
  border: solid red;
  text-align: center;
}

#number1 {
  display: inline-block;
  height: 25px;
  width: 25px;
  border-radius: 50%;
  border: solid red;
  background-color: grey;
  text-align: center;
}

#b2 {
  display: inline-block;
  height: 25px;
  width: 30px;
  border-radius: 50%;
  border: solid red;
  text-align: center;
}

#b3 {
  display: inline-block;
  height: 25px;
  width: 30px;
  border-radius: 50%;
  border: solid red;
  text-align: center;
}

#number2 {
  display: inline-block;
  height: 25px;
  width: 25px;
  border-radius: 50%;
  border: solid red;
  text-align: center;
}

#b4 {
  display: inline-block;
  height: 25px;
  width: 30px;
  border-radius: 50%;
  border: solid red;
  text-align: center;
}

#b5 {
  display: inline-block;
  height: 25px;
  width: 30px;
  border-radius: 50%;
  border: solid red;
  text-align: center;
}

#number3 {
  display: inline-block;
  height: 25px;
  width: 25px;
  border-radius: 50%;
  border: solid red;
  text-align: center;
}

#b6 {
  display: inline-block;
  height: 25px;
  width: 30px;
  border-radius: 50%;
  border: solid red;
  text-align: center;
}

#b7 {
  display: inline-block;
  height: 25px;
  width: 30px;
  border-radius: 50%;
  border: solid red;
  text-align: center;
}

#number4 {
  display: inline-block;
  height: 25px;
  width: 25px;
  border-radius: 50%;
  border: solid red;
  text-align: center;
}

#b8 {
  display: inline-block;
  height: 25px;
  width: 30px;
  border-radius: 50%;
  border: solid red;
  text-align: center;
}

#b9 {
  display: inline-block;
  height: 25px;
  width: 30px;
  border-radius: 50%;
  border: solid red;
  text-align: center;
}

#number5 {
  display: inline-block;
  height: 25px;
  width: 25px;
  border-radius: 50%;
  border: solid red;
  text-align: center;
}

#b10 {
  display: inline-block;
  height: 25px;
  width: 30px;
  border-radius: 50%;
  border: solid red;
  text-align: center;
}

#b11 {
  /*display: inline-flex;*/
  float: left;
  height: 25px;
  width: 30px;
  border-radius: 50%;
  border: solid red;
  text-align: center;
}

#number6 {
  /*display: inline-flex;*/
  float: left;
  height: 25px;
  width: 25px;
  border-radius: 50%;
  border: solid red;
  text-align: center;
}

#b12 {
  /*display: inline-flex;*/
  float: left;
  height: 25px;
  width: 30px;
  border-radius: 50%;
  border: solid red;
  text-align: center;
}

#check {
  display: block;
  position: center;
  height: 25px;
  width: 125px;
  /*border-radius: 50%;*/
  border: solid red;
  text-align: center;
}</code>```

      <input type="button" onclick="decrementValue6()" value="-" id="b11" />
      <input type="text" id="number6" value="0" />
      <input type="button" onclick="incrementValue6()" value="+" id="b12" />

      <form>
        <input type="button" onclick="decrementValue5()" value="-" id="b9" />
        <input type="text" id="number5" value="1" />
        <input type="button" onclick="incrementValue5()" value="+" id="b10" />
      </form>

      <form>
        <input type="button" onclick="decrementValue4()" value="-" id="b7" />
        <input type="text" id="number4" value="2" />
        <input type="button" onclick="incrementValue4();" value="+" id="b8" />
      </form>

      <form>
        <input type="button" onclick="decrementValue3()" value="-" id="b5" />
        <input type="text" id="number3" value="3" />
        <input type="button" onclick="incrementValue3()" value="+" id="b6" />
      </form>

      <form>
        <input type="button" onclick="decrementValue2()" value="-" id="b3" />
        <input type="text" id="number2" value="4" />
        <input type="button" onclick="incrementValue2()" value="+" id="b4" />
      </form>

      <form>
        <input type="button" onclick="decrementValue1('number6');changeColour()" value="-" id="b2" />
        <input type="text" id="number1" value="6" />
        <input type="button" onclick="incrementValue1();changeColour()" value="+" id="b1" />
      </form>

Enter Date of Submission:
<input type="date" id="date" value="0" />
<input type="button" onclick="printDate()" value="Record" />

```

答:
Try changing the following css and change the translate to make it center.
https://jsfiddle.net/Luodqwhc/

#p6:hover .inside-text6 {
    display: flex;
    align-items: center;
    transform: translate(-42px, -25px);
}```

Title: Two Inputs side by side CSS

Body:
I'm currently practicing some WebDev and I'm working on an interactive food pyramid. I've been able to align the other inputs but the inputs on top of the triangle are giving me trouble, I've tried everything from floats to flex and inline blocks. Nothing seems to work, any help would be greatly appreciated.

function incrementValue1() {
  let value = parseInt(document.getElementById('number1').value, 10);
  value = isNaN(value) ? 0 : value;
  value++;
  document.getElementById('number1').value = value;
}

function decrementValue1() {
  let value = parseInt(document.getElementById('number1').value, 10);
  value = isNaN(value) ? 0 : value;
  if (value > 0) {
    value--;
  }
  document.getElementById('number1').value = value;
}

function incrementValue2() {
  let value = parseInt(document.getElementById('number2').value, 10);
  value = isNaN(value) ? 0 : value;
  value++;
  document.getElementById('number2').value = value;
}

function decrementValue2() {
  let value = parseInt(document.getElementById('number2').value, 10);
  value = isNaN(value) ? 0 : value;
  if (value > 0) {
    value--;
  }
  document.getElementById('number2').value = value;
}

function incrementValue3() {
  let value = parseInt(document.getElementById('number3').value, 10);
  value = isNaN(value) ? 0 : value;
  value++;
  document.getElementById('number3').value = value;
}

function decrementValue3() {
  let value = parseInt(document.getElementById('number3').value, 10);
  value = isNaN(value) ? 0 : value;
  if (value > 0) {
    value--;
  }
  document.getElementById('number3').value = value;
}

function incrementValue4() {
  let value = parseInt(document.getElementById('number4').value, 10);
  value = isNaN(value) ? 0 : value;
  value++;
  document.getElementById('number4').value = value;
}

function decrementValue4() {
  let value = parseInt(document.getElementById('number4').value, 10);
  value = isNaN(value) ? 0 : value;
  if (value > 0) {
    value--;
  }
  document.getElementById('number4').value = value;
}

function incrementValue5() {
  let value = parseInt(document.getElementById('number5').value, 10);
  value = isNaN(value) ? 0 : value;
  value++;
  document.getElementById('number5').value = value;
}

function decrementValue5() {
  let value = parseInt(document.getElementById('number5').value, 10);
  value = isNaN(value) ? 0 : value;
  if (value > 0) {
    value--;
  }
  document.getElementById('number5').value = value;
}

function incrementValue6() {
  let value = parseInt(document.getElementById('number6').value, 10);
  value = isNaN(value) ? 0 : value;
  value++;
  document.getElementById('number6').value = value;
}

function decrementValue6() {
  let value = parseInt(document.getElementById('number6').value, 10);
  value = isNaN(value) ? 0 : value;
  if (value > 0) {
    value--;
  }
  document.getElementById('number6').value = value;
}

var colors = ["red", "blue", "green", "yellow", "purple", "gold", "pink", "grey", "turquoise", "aqua"];
var i = 0;
var selectedColor;

function changeColour() {
  selectedColor = colors[i];
  document.getElementById("number" + 1).style.backgroundColor = selectedColor;
  i++;
  if (i > colors.length)
    i = 0;
}

function printDate() {
  let value = document.getElementById("date").value;
  document.getElementById("check").innerHTML = "Date: " + value;
}

.container {
  text-align: center;
  position: relative;
  top: 40%;
}

.inside-text1 {
  display: none;
  position: absolute;
  top: 20px;
  left: 248px;
  text-align: center;
  bottom: -65px;
}

.inside-text {
  display: none;
  position: relative;
  text-align: center;
  bottom: -25px;
}

.inside-text6 {
  display: none;
  position: relative;
  text-align: center;
  bottom: -120px;
  /*float: left;*/
}

#p6 {
  border-bottom: 200px solid blue;
  border-left: 100px solid transparent;
  border-right: 100px solid transparent;
  height: 0;
  width: 0;
  margin-right: auto;
  margin-left: auto;
}

#p5-5 {
  border-bottom: 20px solid white;
  border-left: 45px solid transparent;
  border-right: 45px solid transparent;
  height: 0;
  width: 10px;
  margin-right: auto;
  margin-left: auto;
}

#p5 {
  border-bottom: 80px solid black;
  border-left: 45px solid transparent;
  border-right: 45px solid transparent;
  height: 0;
  width: 220px;
  margin-right: auto;
  margin-left: auto;
}

#p4-5 {
  border-bottom: 20px solid white;
  border-left: 45px solid transparent;
  border-right: 45px solid transparent;
  height: 0;
  width: 240px;
  margin-right: auto;
  margin-left: auto;
}

#p4 {
  border-bottom: 80px solid purple;
  border-left: 45px solid transparent;
  border-right: 45px solid transparent;
  height: 0;
  width: 330px;
  margin-right: auto;
  margin-left: auto;
}

#p3 {
  border-bottom: 80px solid green;
  border-left: 45px solid transparent;
  border-right: 45px solid transparent;
  height: 0;
  width: 420px;
  margin-right: auto;
  margin-left: auto;
}

#p2 {
  border-bottom: 80px solid yellow;
  border-left: 45px solid transparent;
  border-right: 45px solid transparent;
  height: 0;
  width: 510px;
  margin-right: auto;
  margin-left: auto;
}

#p1 {
  position: relative;
  top: 40%;
  border-bottom: 80px solid red;
  border-left: 45px solid transparent;
  border-right: 45px solid transparent;
  height: 0;
  width: 600px;
  margin-right: auto;
  margin-left: auto;
}

#p1:hover .inside-text1 {
  display: block;
}

#p2:hover .inside-text {
  display: block;
}

#p3:hover .inside-text {
  display: block;
}

#p4:hover .inside-text {
  display: block;
}

#p5:hover .inside-text {
  display: block;
}

#p6:hover .inside-text6 {
  display: block;
}

.button {
  margin-right: auto;
  margin-left: auto;
  position: relative;
}

#b1 {
  display: inline-block;
  height: 25px;
  width: 30px;
  border-radius: 50%;
  border: solid red;
  text-align: center;
}

#number1 {
  display: inline-block;
  height: 25px;
  width: 25px;
  border-radius: 50%;
  border: solid red;
  background-color: grey;
  text-align: center;
}

#b2 {
  display: inline-block;
  height: 25px;
  width: 30px;
  border-radius: 50%;
  border: solid red;
  text-align: center;
}

#b3 {
  display: inline-block;
  height: 25px;
  width: 30px;
  border-radius: 50%;
  border: solid red;
  text-align: center;
}

#number2 {
  display: inline-block;
  height: 25px;
  width: 25px;
  border-radius: 50%;
  border: solid red;
  text-align: center;
}

#b4 {
  display: inline-block;
  height: 25px;
  width: 30px;
  border-radius: 50%;
  border: solid red;
  text-align: center;
}

#b5 {
  display: inline-block;
  height: 25px;
  width: 30px;
  border-radius: 50%;
  border: solid red;
  text-align: center;
}

#number3 {
  display: inline-block;
  height: 25px;
  width: 25px;
  border-radius: 50%;
  border: solid red;
  text-align: center;
}

#b6 {
  display: inline-block;
  height: 25px;
  width: 30px;
  border-radius: 50%;
  border: solid red;
  text-align: center;
}

#b7 {
  display: inline-block;
  height: 25px;
  width: 30px;
  border-radius: 50%;
  border: solid red;
  text-align: center;
}

#number4 {
  display: inline-block;
  height: 25px;
  width: 25px;
  border-radius: 50%;
  border: solid red;
  text-align: center;
}

#b8 {
  display: inline-block;
  height: 25px;
  width: 30px;
  border-radius: 50%;
  border: solid red;
  text-align: center;
}

#b9 {
  display: inline-block;
  height: 25px;
  width: 30px;
  border-radius: 50%;
  border: solid red;
  text-align: center;
}

#number5 {
  display: inline-block;
  height: 25px;
  width: 25px;
  border-radius: 50%;
  border: solid red;
  text-align: center;
}

#b10 {
  display: inline-block;
  height: 25px;
  width: 30px;
  border-radius: 50%;
  border: solid red;
  text-align: center;
}

#b11 {
  /*display: inline-flex;*/
  float: left;
  height: 25px;
  width: 30px;
  border-radius: 50%;
  border: solid red;
  text-align: center;
}

#number6 {
  /*display: inline-flex;*/
  float: left;
  height: 25px;
  width: 25px;
  border-radius: 50%;
  border: solid red;
  text-align: center;
}

#b12 {
  /*display: inline-flex;*/
  float: left;
  height: 25px;
  width: 30px;
  border-radius: 50%;
  border: solid red;
  text-align: center;
}

#check {
  display: block;
  position: center;
  height: 25px;
  width: 125px;
  /*border-radius: 50%;*/
  border: solid red;
  text-align: center;
}

      <input type="button" onclick="decrementValue6()" value="-" id="b11" />
      <input type="text" id="number6" value="0" />
      <input type="button" onclick="incrementValue6()" value="+" id="b12" />

      <form>
        <input type="button" onclick="decrementValue5()" value="-" id="b9" />
        <input type="text" id="number5" value="1" />
        <input type="button" onclick="incrementValue5()" value="+" id="b10" />
      </form>

      <form>
        <input type="button" onclick="decrementValue4()" value="-" id="b7" />
        <input type="text" id="number4" value="2" />
        <input type="button" onclick="incrementValue4();" value="+" id="b8" />
      </form>

      <form>
        <input type="button" onclick="decrementValue3()" value="-" id="b5" />
        <input type="text" id="number3" value="3" />
        <input type="button" onclick="incrementValue3()" value="+" id="b6" />
      </form>

      <form>
        <input type="button" onclick="decrementValue2()" value="-" id="b3" />
        <input type="text" id="number2" value="4" />
        <input type="button" onclick="incrementValue2()" value="+" id="b4" />
      </form>

      <form>
        <input type="button" onclick="decrementValue1('number6');changeColour()" value="-" id="b2" />
        <input type="text" id="number1" value="6" />
        <input type="button" onclick="incrementValue1();changeColour()" value="+" id="b1" />
      </form>

Enter Date of Submission:
<input type="date" id="date" value="0" />
<input type="button" onclick="printDate()" value="Record" />


问:
Handler "ExtensionlessUrlHandler-Integrated-4.0" has a bad module "ManagedPipelineHandler" in its module list
To be honest, I've tried to turn a dirty trick on IIS and just when I thought that I was going to get away with it, I realized my workaround doesn't work. Here's what I've tried to do:

1) I have ASP.NET application which has Preloader class that inherits IProcessHostPreloadClient and does all the heavy initialization in Preload method implementation (application is complex and it's a part of an enormous system, so it requires approximately 2 minutes to establish connections to all necessary services and pre-instantiate some Unity registrations).

2) I have a lot of work that needs to be done on application shutdown (unsubscribing, disconnecting, disposing,...), and I guess the best place to do it is in *Application_End* method located in Global.asax.

3) Everything works just fine when I have user activity (first request after the Application Pool that contains aforementioned web application is started will cause *Application_Start* to be called and afterwards *Application_End* is called on Application Pool stop or recycle), but problems occur when there is no user activity and application tries to restart itself after being active for 48 hours (configured requirement). Since there was no requests, application officially didn't get started. Ergo, it can't be gracefully stopped since *Application_End* won't be called.

4) Now comes the messy part... I've tried to make a GET request from code at the end of the Preload method, and it worked. But this solution seemed bad to me, even though it worked. So, I've tried a lot of things, and the last thing I tried was this:

```<code>SimpleWorkerRequest swr = new SimpleWorkerRequest(string.Empty, string.Empty, tw);
HttpRuntime.ProcessRequest(swr);
</code>```

... and that has done it's purpose. *Application_Start* was called, (I've checked response, it was containing login page that was supposed to be displayed in initial request) and on Application Pool shutdown application ended gracefully by doing necessary work in *Application_End*.

BUT

After the application was started (preloaded and initiated) in this manner, this is what happened when I wanted to reach application via Web browser:

HTTP Error 500.21 - Internal Server Error
  Handler "ExtensionlessUrlHandler-Integrated-4.0" has a bad module "ManagedPipelineHandler" in its module list

I am unable to figure this out. Can anybody tell me why this happens and how to fix it?

If I don't figure this out, I will go back to first solution (sending GET request from code) but this problem will bug me since I don't even have an idea what's wrong.

答: Installing .NET 4.7 worked for me. I only had 3.5 installed prior.

Body:
To be honest, I've tried to turn a dirty trick on IIS and just when I thought that I was going to get away with it, I realized my workaround doesn't work. Here's what I've tried to do:

1) I have ASP.NET application which has Preloader class that inherits IProcessHostPreloadClient and does all the heavy initialization in Preload method implementation (application is complex and it's a part of an enormous system, so it requires approximately 2 minutes to establish connections to all necessary services and pre-instantiate some Unity registrations).

2) I have a lot of work that needs to be done on application shutdown (unsubscribing, disconnecting, disposing,...), and I guess the best place to do it is in *Application_End* method located in Global.asax.

3) Everything works just fine when I have user activity (first request after the Application Pool that contains aforementioned web application is started will cause *Application_Start* to be called and afterwards *Application_End* is called on Application Pool stop or recycle), but problems occur when there is no user activity and application tries to restart itself after being active for 48 hours (configured requirement). Since there was no requests, application officially didn't get started. Ergo, it can't be gracefully stopped since *Application_End* won't be called.

4) Now comes the messy part... I've tried to make a GET request from code at the end of the Preload method, and it worked. But this solution seemed bad to me, even though it worked. So, I've tried a lot of things, and the last thing I tried was this:

SimpleWorkerRequest swr = new SimpleWorkerRequest(string.Empty, string.Empty, tw);
HttpRuntime.ProcessRequest(swr);

... and that has done it's purpose. *Application_Start* was called, (I've checked response, it was containing login page that was supposed to be displayed in initial request) and on Application Pool shutdown application ended gracefully by doing necessary work in *Application_End*.

BUT

After the application was started (preloaded and initiated) in this manner, this is what happened when I wanted to reach application via Web browser:

HTTP Error 500.21 - Internal Server Error
  Handler "ExtensionlessUrlHandler-Integrated-4.0" has a bad module "ManagedPipelineHandler" in its module list

I am unable to figure this out. Can anybody tell me why this happens and how to fix it?

If I don't figure this out, I will go back to first solution (sending GET request from code) but this problem will bug me since I don't even have an idea what's wrong.


问:
Changing an item in a list with a text document
I have a problem where i'm running a function that should check through the lines in the text document, find the username that matches, and chagne the 2nd sintem in the list with each line (its a password reset program). The text document normally looks like this:

```<code>test test
username password
hello hi
</code>```

This is the code i've tried. reset_username was taken when logging in.(I've also included the login function for example)

password change function:

```<code>def password_change():
    for _ in open('info.txt', 'r').readlines():
        login_info = _.split()
        if reset_username == login_info[0]:
            login_info[1] = [password_reenter_txt.get()]
            menu_window()
</code>```

Login function:

```<code>def txt_file_log_in():

    try:
        for _ in open('info.txt', 'r').readlines():
            login_info = _.split() #split on the space made and store result with 2 strings
            if username_enter_txt.get() == login_info[0] and password_enter_txt.get() == login_info[1]:
                password_fault_report.configure(text='User name and Password Correct')

                global reset_username
                reset_username = username_enter_txt.get()

                messagebox.showinfo('Success', 'You have successfully logged in!')#pop up window informing user for sign up.
                login_window.destroy()
                final_window()

        password_fault_report.configure(text='User name or password incorrect,')

    except:
        password_fault_report.configure(text='No accounts found, you need to sign in first...')
</code>```

The error i'm having is that it will run the function and run the menu window, however it doesn't change the document at all.

I am a beginner in tk, python so it could be a very stupid mistake so sorry. Also if iv'e made a mistake in the post, also let me know :)

答:
The value 'r' in an open statement allows to your "READ ONLY" the file. In order to write to the file you want to use 'w' but keep in mind this will write the file and delete everything that was there before so we want to make sure we write everything back to the file.

We can accomplish this by using a list to store all values and updated as needed.

Example code:

```<code>def password_change(reset_username, password_reenter_txt):
    # Create empty list to hold file data.
    login_info = []
    with open('some_file', 'r') as data:
        for _ in data.readlines():
            login_info.append(_.split())
    print(login_info)
    # Check values in list and update if condition true.
    for sub_list in login_info:
        if len(sub_list) > 0:
            if reset_username == sub_list[0]:
                sub_list[1] = password_reenter_txt

    # write new values of list to file if previous condition met.
    with open('some_file', 'w') as data:
        for sub_list in login_info:
            if len(sub_list) > 0:
                data.write('{} {}\n'.format(sub_list[0], sub_list[1]))

for i in range(9):
    password_change('name' + str(i+1), 'pass')

# Check new values in file.
with open('some_file', 'r') as data:
    for _ in data.readlines():
        print(_.strip('\n'))
</code>```

Test file data used:

```<code>name1 pass1
name2 pass1
name3 pass1
name4 pass1
name5 pass1
name6 pass1
name7 pass1
name8 pass1
name9 pass1
</code>```

Results:

```<code>name1 new_pass
name2 new_pass
name3 new_pass
name4 new_pass
name5 new_pass
name6 new_pass
name7 new_pass
name8 new_pass
name9 new_pass
</code>```

Body:
I have a problem where i'm running a function that should check through the lines in the text document, find the username that matches, and chagne the 2nd sintem in the list with each line (its a password reset program). The text document normally looks like this:

test test
username password
hello hi

This is the code i've tried. reset_username was taken when logging in.(I've also included the login function for example)

password change function:

def password_change():
    for _ in open('info.txt', 'r').readlines():
        login_info = _.split()
        if reset_username == login_info[0]:
            login_info[1] = [password_reenter_txt.get()]
            menu_window()

Login function:

def txt_file_log_in():

    try:
        for _ in open('info.txt', 'r').readlines():
            login_info = _.split() #split on the space made and store result with 2 strings
            if username_enter_txt.get() == login_info[0] and password_enter_txt.get() == login_info[1]:
                password_fault_report.configure(text='User name and Password Correct')

                global reset_username
                reset_username = username_enter_txt.get()

                messagebox.showinfo('Success', 'You have successfully logged in!')#pop up window informing user for sign up.
                login_window.destroy()
                final_window()

        password_fault_report.configure(text='User name or password incorrect,')

    except:
        password_fault_report.configure(text='No accounts found, you need to sign in first...')

The error i'm having is that it will run the function and run the menu window, however it doesn't change the document at all.

I am a beginner in tk, python so it could be a very stupid mistake so sorry. Also if iv'e made a mistake in the post, also let me know :)

Body:
The value 'r' in an open statement allows to your "READ ONLY" the file. In order to write to the file you want to use 'w' but keep in mind this will write the file and delete everything that was there before so we want to make sure we write everything back to the file.

We can accomplish this by using a list to store all values and updated as needed.

Example code:

def password_change(reset_username, password_reenter_txt):
    # Create empty list to hold file data.
    login_info = []
    with open('some_file', 'r') as data:
        for _ in data.readlines():
            login_info.append(_.split())
    print(login_info)
    # Check values in list and update if condition true.
    for sub_list in login_info:
        if len(sub_list) > 0:
            if reset_username == sub_list[0]:
                sub_list[1] = password_reenter_txt

    # write new values of list to file if previous condition met.
    with open('some_file', 'w') as data:
        for sub_list in login_info:
            if len(sub_list) > 0:
                data.write('{} {}\n'.format(sub_list[0], sub_list[1]))

for i in range(9):
    password_change('name' + str(i+1), 'pass')

# Check new values in file.
with open('some_file', 'r') as data:
    for _ in data.readlines():
        print(_.strip('\n'))

Test file data used:

name1 pass1
name2 pass1
name3 pass1
name4 pass1
name5 pass1
name6 pass1
name7 pass1
name8 pass1
name9 pass1

Results:

name1 new_pass
name2 new_pass
name3 new_pass
name4 new_pass
name5 new_pass
name6 new_pass
name7 new_pass
name8 new_pass
name9 new_pass


问:
Is there a way to recover objects from a set in the same order as passed?
I need to recover the elements of a java Set collection interface in the same order they were passed into the set.

How is it possible in java

答:
```<code>public class SimpleLinkedHashSetExample {

  public static void main(String[] args) {
    //create object of LinkedHashSet
    LinkedHashSet lhashSet = new LinkedHashSet();

    /*
      Add an Object to LinkedHashSet using
      boolean add(Object obj) method of Java LinkedHashSet class.
      This method adds an element to LinkedHashSet if it is not
      already present in LinkedHashSet.
      It returns true if the element was added to LinkedHashSet, false otherwise.
    */

    lhashSet.add(new Integer("1"));
    lhashSet.add(new Integer("2"));
    lhashSet.add(new Integer("3"));

    /*
      Please note that add method accepts Objects. Java Primitive values CAN NOT
      be added directly to LinkedHashSet. It must be converted to corrosponding
      wrapper class first.
    */

    System.out.println("LinkedHashSet contains.." + lhashSet);
  }
}

/*
Output of the program would be
LinkedHashSet contains..[1, 2, 3]
*/
</code>```

You can use LinkedhashSet above is the example.

Body:
public class SimpleLinkedHashSetExample {

  public static void main(String[] args) {
    //create object of LinkedHashSet
    LinkedHashSet lhashSet = new LinkedHashSet();

    /*
      Add an Object to LinkedHashSet using
      boolean add(Object obj) method of Java LinkedHashSet class.
      This method adds an element to LinkedHashSet if it is not
      already present in LinkedHashSet.
      It returns true if the element was added to LinkedHashSet, false otherwise.
    */

    lhashSet.add(new Integer("1"));
    lhashSet.add(new Integer("2"));
    lhashSet.add(new Integer("3"));

    /*
      Please note that add method accepts Objects. Java Primitive values CAN NOT
      be added directly to LinkedHashSet. It must be converted to corrosponding
      wrapper class first.
    */

    System.out.println("LinkedHashSet contains.." + lhashSet);
  }
}

/*
Output of the program would be
LinkedHashSet contains..[1, 2, 3]
*/

You can use LinkedhashSet above is the example.


问:
error: invalid conversion from ‘int’ to enum c++
I am getting "error: invalid conversion from ‘int’ to ‘num'" when i compile the below sample code in c++. Typecasting it with enum name doesn't help.

```<code>#include <iostream>
using namespace std;
typedef enum
{
    NUM_ZERO = 0,
    NUM_ONE = 1,
    NUM_TWO = 2,
    NUM_THREE = 4
} num;

int main()
{
    num* numFlag;
    *numFlag |= static_cast<num>(NUM_TWO);
    return 0;
}
</code>```

Please let me know if anyone knows how to resolve this.

答:
Syntactically speaking,

```<code>*numFlag |= static_cast<num>(NUM_TWO);
</code>```

is equivalent to

```<code>*numFlag = (*numFlag | static_cast<num>(NUM_TWO));
</code>```

That explains the compiler warning/error. You would need to cast the result of the | operator.

```<code>*numFlag = static_cast<num>(*numFlag | NUM_TWO);
</code>```

To make it work, you should use

```<code>int main()
{
    // Make numFlag an object instead of a pointer.
    // Initialize it.
    num numFlag = NUM_ZERO;

    // Perform the bitwise |
    numFlag = static_cast<num>(numFlag | NUM_TWO);

    return 0;
}
</code>```

Body:
I am getting "error: invalid conversion from ‘int’ to ‘num'" when i compile the below sample code in c++. Typecasting it with enum name doesn't help.

#include <iostream>
using namespace std;
typedef enum
{
    NUM_ZERO = 0,
    NUM_ONE = 1,
    NUM_TWO = 2,
    NUM_THREE = 4
} num;

int main()
{
    num* numFlag;
    *numFlag |= static_cast<num>(NUM_TWO);
    return 0;
}

Please let me know if anyone knows how to resolve this.

Body:
Syntactically speaking,

*numFlag |= static_cast<num>(NUM_TWO);

is equivalent to

*numFlag = (*numFlag | static_cast<num>(NUM_TWO));

That explains the compiler warning/error. You would need to cast the result of the | operator.

*numFlag = static_cast<num>(*numFlag | NUM_TWO);

To make it work, you should use

int main()
{
    // Make numFlag an object instead of a pointer.
    // Initialize it.
    num numFlag = NUM_ZERO;

    // Perform the bitwise |
    numFlag = static_cast<num>(numFlag | NUM_TWO);

    return 0;
}


问:
docker-compose --build cannot find python executable but docker run does
I've created several docker images to each serve a simple flask app, I've tested that these run as expected when using the docker run command. Now I am trying to connect these services using docker-compose and when I run docker-compose up --build I get the following error:
Cannot start service lungs: OCI runtime create failed: container_linux.go:346: starting container process caused "exec: "python\": executable file not found in $PATH": unknown.

If I run the same container in interactive mode and check the PATH, I can see it pointing to the correct python executable. My dockerfile contains:

```<code>FROM base_private_image # sets up a user and miniconda on ubuntu
USER root
ADD ./ ./ . # copy flask code into image
RUN pip install flask requests
USER user # setup in the base_private_image, we need our containers not to run as root
CMD ["python", "app.py"] # I've tried many variations of this CMD, all with the same result
</code>```

example of docker-compose.yml contents

```<code>version: '3'
services:
  central_service:
      build: ./central_service
      restart: always
      environment:
         - PATH=/home/user/miniconda3/bin/:$PATH
      ports:
        - '5010:5010'
      expose:
        - 5010

</code>```

can anyone point out what functional difference between docker-compose and docker run might be causing this? I can't find any issue with the miniconda or python install or the PATH, so I'm thinking it must be something under the hood in docker-compose?

editing to add:
dockerfile that works, docker-compose can find python:

```<code>FROM python:3.7.6-slim

RUN mkdir /trigger_app
WORKDIR /trigger_app

COPY requirements.txt ./
RUN pip install -r requirements.txt

ADD . ./

EXPOSE 6000

CMD flask run --host=0.0.0.0 --port=6000
</code>```

答:
Try to set your PATH environment variable inside the Dockerfile

```<code>ENV PATH /home/user/miniconda3/bin/:$PATH
</code>```

And remove the environment: PATH inside docker-compose.yml (Using this, you'll be passing your machine's PATH variable to the container)

Body:
I've created several docker images to each serve a simple flask app, I've tested that these run as expected when using the docker run command. Now I am trying to connect these services using docker-compose and when I run docker-compose up --build I get the following error:
Cannot start service lungs: OCI runtime create failed: container_linux.go:346: starting container process caused "exec: "python\": executable file not found in $PATH": unknown.

If I run the same container in interactive mode and check the PATH, I can see it pointing to the correct python executable. My dockerfile contains:

FROM base_private_image # sets up a user and miniconda on ubuntu
USER root
ADD ./ ./ . # copy flask code into image
RUN pip install flask requests
USER user # setup in the base_private_image, we need our containers not to run as root
CMD ["python", "app.py"] # I've tried many variations of this CMD, all with the same result

example of docker-compose.yml contents

version: '3'
services:
  central_service:
      build: ./central_service
      restart: always
      environment:
         - PATH=/home/user/miniconda3/bin/:$PATH
      ports:
        - '5010:5010'
      expose:
        - 5010

can anyone point out what functional difference between docker-compose and docker run might be causing this? I can't find any issue with the miniconda or python install or the PATH, so I'm thinking it must be something under the hood in docker-compose?

editing to add:
dockerfile that works, docker-compose can find python:

FROM python:3.7.6-slim

RUN mkdir /trigger_app
WORKDIR /trigger_app

COPY requirements.txt ./
RUN pip install -r requirements.txt

ADD . ./

EXPOSE 6000

CMD flask run --host=0.0.0.0 --port=6000

Body:
Try to set your PATH environment variable inside the Dockerfile

ENV PATH /home/user/miniconda3/bin/:$PATH

And remove the environment: PATH inside docker-compose.yml (Using this, you'll be passing your machine's PATH variable to the container)


问:
NOT HAVING (inverse HAVING) clause with aggregation in Oracle
I am trying to filter the results of a GROUP BY CUBE using the HAVING clause. However I need to keep rows that do not meet a combination of conditions.

I intuitively tried:

```<code>SELECT [...]
FROM [...]
NOT HAVING (flag_1 = 1 AND flag_2 = 1 AND flag_3 = 1)
GROUP BY CUBE [...]
</code>```

Sadly Oracle doesn't recognize NOT HAVING as valid syntax.

From a mathematical standpoint, inversing each individual condition does not yield the same result :

HAVING (flag_1 != 1 AND flag_2 != 1 AND flag_3 != 1)

How can I achieve the logical equivalent of NOT HAVING ?

Note: I found an existing question that was somewhat related, but it was specific to Microsoft Access and the goal was not the same, hence this new question.

答:
Well, I thought about adapting a similar method based on CASE that I sometimes use inside a WHERE.
It seems that CASE works inside HAVING as well !

Solution:

```<code>SELECT [...]
FROM [...]

HAVING
    CASE
        WHEN flag_1 = 1 AND flag_2 = 1 AND flag_3 = 1
        THEN 0
        ELSE 1
    END = 1

GROUP BY CUBE [...]
</code>```

Body:
I am trying to filter the results of a GROUP BY CUBE using the HAVING clause. However I need to keep rows that do not meet a combination of conditions.

I intuitively tried:

SELECT [...]
FROM [...]
NOT HAVING (flag_1 = 1 AND flag_2 = 1 AND flag_3 = 1)
GROUP BY CUBE [...]

Sadly Oracle doesn't recognize NOT HAVING as valid syntax.

From a mathematical standpoint, inversing each individual condition does not yield the same result :

HAVING (flag_1 != 1 AND flag_2 != 1 AND flag_3 != 1)

How can I achieve the logical equivalent of NOT HAVING ?

Note: I found an existing question that was somewhat related, but it was specific to Microsoft Access and the goal was not the same, hence this new question.

Body:
Well, I thought about adapting a similar method based on CASE that I sometimes use inside a WHERE.
It seems that CASE works inside HAVING as well !

Solution:

SELECT [...]
FROM [...]

HAVING
    CASE
        WHEN flag_1 = 1 AND flag_2 = 1 AND flag_3 = 1
        THEN 0
        ELSE 1
    END = 1

GROUP BY CUBE [...]


问:
Oracle ODT for VS2017 and VS2019
I have Visual Studio 2017 with ODT installed and Visual Studio 2019 installed. I'm about to attempt to install ODT for VS2019 and I see on Oracle's site it says to uninstall any ODT. However, the download for ODT seems to be specific for VS2017 and VS2019. </p>

<p>Do I need to uninstall ODT for VS2017 and then installed ODT for VS2019 or just install ODT for VS2019 and not remove the ODT for VS2017? If I have to uninstall ODT for VS2017 will the install of ODT for VS2019 work on both VS2017 and VS2019? </p>

答: I didn't remove ODT for VS2017 and just installed ODT for VS2019. Seemed to install without any problems which is unusual for me and Oracle products. I was able to open up VS2019 and use the Server Explorer to connect to the database. Now I'm going to look into getting Entity Framework to work with VS2019. </p>

Title: Oracle ODT for VS2017 and VS2019

Body:
I have Visual Studio 2017 with ODT installed and Visual Studio 2019 installed. I'm about to attempt to install ODT for VS2019 and I see on Oracle's site it says to uninstall any ODT. However, the download for ODT seems to be specific for VS2017 and VS2019.

Do I need to uninstall ODT for VS2017 and then installed ODT for VS2019 or just install ODT for VS2019 and not remove the ODT for VS2017? If I have to uninstall ODT for VS2017 will the install of ODT for VS2019 work on both VS2017 and VS2019?


问:
How to extend global properties in typescript?
src/window.d.ts

```<code>declare namespace NodeJS  {
    interface Global {
        window: {
            location: {};
        };
    }
}
</code>```

In my source code, I am trying to access global.window.location. I am getting an error Property 'window' does not exist on type Global.

I don't know if the typescript compiler is using my window.d.ts or not? How to tell the compiler to use my custom type?

答:
Add this file path to your files array of tsconfig.json, that way TS will be familiar with it, and extend the real Window object.

BTW, in order to add properties to the global Window object:

```<code>declare global {
  interface Window {
    location: {};
  }
}
</code>```

Body:
src/window.d.ts

declare namespace NodeJS  {
    interface Global {
        window: {
            location: {};
        };
    }
}

In my source code, I am trying to access global.window.location. I am getting an error Property 'window' does not exist on type Global.

I don't know if the typescript compiler is using my window.d.ts or not? How to tell the compiler to use my custom type?

Body:
Add this file path to your files array of tsconfig.json, that way TS will be familiar with it, and extend the real Window object.

BTW, in order to add properties to the global Window object:

declare global {
  interface Window {
    location: {};
  }
}


问:
Pandas dataframe column with lists of lists of varying lengths to different columns
I have a following dataframe:

df = pd.DataFrame({'column': [[['a', 0], ['b', 1]], [['b', 2]], [['c', 1], ['b', 2]]]})
df
```

```    column
0   [[a, 0], [b, 1]]
1   [[b, 2]]
2   [[c, 1], [b, 2]]
```

<p>Where I don't know which letters exist and the amount of lists in each row varies. My goal is to get it looking like this:</p>

```     a    b    c
0    0    1    NaN
1    NaN  2    NaN
2    NaN  2    1
```

<p>A first step can be taken using:</p>

<pre class="lang-py prettyprint-override"><code>df['column'].apply(pd.Series)
</code>```

```<code>    0       1
0   [a, 0]  [b, 1]
1   [b, 2]
2   [c, 1]  [b, 2]
</code>```

However, a large part of this problem still stands.

答:
If you are on Pandas 0.25+, you can use explode:

```<code>s  = df['column'].explode()
(pd.DataFrame(list(s.values), index=s.index)
   .set_index(0, append=True)[1]
   .unstack()
)
</code>```

Output:

```<code>0    a    b    c
0  0.0  1.0  NaN
1  NaN  2.0  NaN
2  NaN  2.0  1.0
</code>```

Body:
I have a following dataframe:

df = pd.DataFrame({'column': [[['a', 0], ['b', 1]], [['b', 2]], [['c', 1], ['b', 2]]]})
df

    column
0   [[a, 0], [b, 1]]
1   [[b, 2]]
2   [[c, 1], [b, 2]]

Where I don't know which letters exist and the amount of lists in each row varies. My goal is to get it looking like this:

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

A first step can be taken using:

df['column'].apply(pd.Series)

    0       1
0   [a, 0]  [b, 1]
1   [b, 2]
2   [c, 1]  [b, 2]

However, a large part of this problem still stands.

Body:
If you are on Pandas 0.25+, you can use explode:

s  = df['column'].explode()
(pd.DataFrame(list(s.values), index=s.index)
   .set_index(0, append=True)[1]
   .unstack()
)

Output:

0    a    b    c
0  0.0  1.0  NaN
1  NaN  2.0  NaN
2  NaN  2.0  1.0


问:
Default, value and zero initialization mess
I am very confused about value- & default- & zero-initialization.
and especially when they kick in for the different standards C++03 and C++11 (and C++14).

I am quoting and trying to extend a really good answer Value-/Default-/Zero- Init C++98 and C++03 here to make it more general as it would help a lot of users if somebody could help fill out the needed gaps to have a good overview about what happens when?

The full insight by examples in a nutshell:

Sometimes the memory returned by the new operator will be initialized, and sometimes it won't depending on whether the type you're newing up is a POD (plain old data), or if it's a class that contains POD members and is using a compiler-generated default constructor.

In C++1998 there are 2 types of initialization: zero- and default-initialization

In C++2003 a 3rd type of initialization, value-initialization was added.

In C++2011/C++2014 only list-initialization was added and the rules for value-/default-/zero-initialization changed a bit.

Assume:

```<code>struct A { int m; };
struct B { ~B(); int m; };
struct C { C() : m(){}; ~C(); int m; };
struct D { D(){}; int m; };
struct E { E() = default; int m;}; /** only possible in c++11/14 */
struct F {F(); int m;};  F::F() = default; /** only possible in c++11/14 */
</code>```

In a C++98 compiler, the following should occur:

new A   - indeterminate value (A is POD)

new A()- zero-initialize

new B   - default construct (B::m is uninitialized, B is non-POD)

new B() - default construct (B::m is uninitialized)

new C   - default construct (C::m is zero-initialized, C is non-POD)

new C() - default construct (C::m is zero-initialized)

new D   - default construct (D::m is uninitialized, D is non-POD)

new D() - default construct? (D::m is uninitialized)

In a C++03 conformant compiler, things should work like so:

new A    - indeterminate value (A is POD)

new A()  - value-initialize A, which is zero-initialization since it's a POD.

new B    - default-initializes (leaves B::m uninitialized, B is non-POD)

new B()  - value-initializes B which zero-initializes all fields since its default ctor is compiler generated as opposed to user-defined.

new C    - default-initializes C, which calls the default ctor. (C::m is zero-initialized, C is non-POD)

new C()  - value-initializes C, which calls the default ctor.  (C::m is zero-initialized)

new D    - default construct (D::m is uninitialized, D is non-POD)

new D()  - value-initializes D?, which calls the default ctor (D::m is uninitialized)

Italic values and ? are uncertainties, please help to correct this :-)

In a C++11 conformant compiler, things should work like so:

??? (please help if I start here it will anyway go wrong)

In a C++14 conformant compiler, things should work like so:
??? (please help if I start here it will anyway go wrong)
(Draft based on answer)

new A    - default-initializes A, compiler gen. ctor, (leavs A::m uninitialized) (A is POD)

new A()  - value-initializes A, which is zero-initialization since 2. point in [dcl.init]/8

new B   - default-initializes B, compiler gen. ctor, (leavs B::m uninitialized) (B is non-POD)

new B()  - value-initializes B which zero-initializes all fields since its default ctor is compiler generated as opposed to user-defined.

new C    - default-initializes C, which calls the default ctor. (C::m is zero-initialized, C is non-POD)

new C()  - value-initializes C, which calls the default ctor. (C::m is zero-initialized)

new D    - default-initializes D (D::m is uninitialized, D is non-POD)

new D()  - value-initializes D, which calls the default ctor (D::m is uninitialized)

new E    - default-initializes E, which calls the comp. gen. ctor. (E::m is uninitialized, E is non-POD)

new E()  - value-initializes E, which zero-initializes E since 2 point in [dcl.init]/8 )

new F    - default-initializes F, which calls the comp. gen. ctor. (F::m is uninitialized, F is non-POD)

new F()  - value-initializes F, which default-initializes F since 1. point in [dcl.init]/8 (F ctor function is user-provided if it is user-declared and not explicitly defaulted or deleted on its first declaration. Link)

答:
I can confirm that in C++11, everything mentioned in the question under C++14 is correct, at least as per compiler implementations.

In order to verify this, I added the following code to my test suite. I tested with -std=c++11 -O3 in GCC 7.4.0, GCC 5.4.0, Clang 10.0.1, and VS 2017, and all the tests below pass.

```<code>#include <gtest/gtest.h>
#include <memory>

struct A { int m;                    };
struct B { int m;            ~B(){}; };
struct C { int m; C():m(){}; ~C(){}; };
struct D { int m; D(){};             };
struct E { int m; E() = default;     };
struct F { int m; F();               }; F::F() = default;

// We use this macro to fill stack memory with something else than 0.
// Subsequent calls to EXPECT_NE(a.m, 0) are undefined behavior in theory, but
// pass in practice, and help illustrate that `a.m` is indeed not initialized
// to zero. Note that we initially tried the more aggressive test
// EXPECT_EQ(a.m, 42), but it didn't pass on all compilers (a.m wasn't equal to
// 42, but was still equal to some garbage value, not zero).
//
// Update 2020-12-14: Even the less aggressive EXPECT_NE(a.m, 0) fails in some
// machines, so we comment them out. But this change in behavior does illustrate
// that, in fact, the behavior was undefined.
//
#define FILL { int m = 42; EXPECT_EQ(m, 42); }

// We use this macro to fill heap memory with something else than 0, before
// doing a placement new at that same exact location. Subsequent calls to
// EXPECT_EQ(a->m, 42) are undefined behavior in theory, but pass in practice,
// and help illustrate that `a->m` is indeed not initialized to zero.
//
#define FILLH(b) std::unique_ptr<int> bp(new int(42)); int* b = bp.get(); EXPECT_EQ(*b, 42)

TEST(TestZero, StackDefaultInitialization)
{
    //{ FILL; A a; EXPECT_NE(a.m, 0); } // UB!
    //{ FILL; B a; EXPECT_NE(a.m, 0); } // UB!
    { FILL; C a; EXPECT_EQ(a.m, 0); }
    //{ FILL; D a; EXPECT_NE(a.m, 0); } // UB!
    //{ FILL; E a; EXPECT_NE(a.m, 0); } // UB!
    //{ FILL; F a; EXPECT_NE(a.m, 0); } // UB!
}

TEST(TestZero, StackValueInitialization)
{
    { FILL; A a = A(); EXPECT_EQ(a.m, 0); }
    { FILL; B a = B(); EXPECT_EQ(a.m, 0); }
    { FILL; C a = C(); EXPECT_EQ(a.m, 0); }
    //{ FILL; D a = D(); EXPECT_NE(a.m, 0); } // UB!
    { FILL; E a = E(); EXPECT_EQ(a.m, 0); }
    //{ FILL; F a = F(); EXPECT_NE(a.m, 0); } // UB!
}

TEST(TestZero, StackListInitialization)
{
    { FILL; A a{}; EXPECT_EQ(a.m, 0); }
    { FILL; B a{}; EXPECT_EQ(a.m, 0); }
    { FILL; C a{}; EXPECT_EQ(a.m, 0); }
    //{ FILL; D a{}; EXPECT_NE(a.m, 0); } // UB!
    { FILL; E a{}; EXPECT_EQ(a.m, 0); }
    //{ FILL; F a{}; EXPECT_NE(a.m, 0); } // UB!
}

TEST(TestZero, HeapDefaultInitialization)
{
    { FILLH(b); A* a = new (b) A; EXPECT_EQ(a->m, 42); } // ~UB
    { FILLH(b); B* a = new (b) B; EXPECT_EQ(a->m, 42); } // ~UB
    { FILLH(b); C* a = new (b) C; EXPECT_EQ(a->m, 0);  }
    { FILLH(b); D* a = new (b) D; EXPECT_EQ(a->m, 42); } // ~UB
    { FILLH(b); E* a = new (b) E; EXPECT_EQ(a->m, 42); } // ~UB
    { FILLH(b); F* a = new (b) F; EXPECT_EQ(a->m, 42); } // ~UB
}

TEST(TestZero, HeapValueInitialization)
{
    { FILLH(b); A* a = new (b) A(); EXPECT_EQ(a->m, 0);  }
    { FILLH(b); B* a = new (b) B(); EXPECT_EQ(a->m, 0);  }
    { FILLH(b); C* a = new (b) C(); EXPECT_EQ(a->m, 0);  }
    { FILLH(b); D* a = new (b) D(); EXPECT_EQ(a->m, 42); } // ~UB
    { FILLH(b); E* a = new (b) E(); EXPECT_EQ(a->m, 0);  }
    { FILLH(b); F* a = new (b) F(); EXPECT_EQ(a->m, 42); } // ~UB
}

TEST(TestZero, HeapListInitialization)
{
    { FILLH(b); A* a = new (b) A{}; EXPECT_EQ(a->m, 0);  }
    { FILLH(b); B* a = new (b) B{}; EXPECT_EQ(a->m, 0);  }
    { FILLH(b); C* a = new (b) C{}; EXPECT_EQ(a->m, 0);  }
    { FILLH(b); D* a = new (b) D{}; EXPECT_EQ(a->m, 42); } // ~UB
    { FILLH(b); E* a = new (b) E{}; EXPECT_EQ(a->m, 0);  }
    { FILLH(b); F* a = new (b) F{}; EXPECT_EQ(a->m, 42); } // ~UB
}

int main(int argc, char **argv)
{
    ::testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}
</code>```

The places where UB! is mentioned are undefined behavior, and the actual behavior is likely to depend on many factors (a.m might be equal to 42, 0, or some other garbage). The places where ~UB is mentioned are also undefined behavior in theory, but in practice, due the use of a placement new, it's very unlikely than a->m will be equal to anything else than 42.

Body:
I am very confused about value- & default- & zero-initialization.
and especially when they kick in for the different standards C++03 and C++11 (and C++14).

I am quoting and trying to extend a really good answer Value-/Default-/Zero- Init C++98 and C++03 here to make it more general as it would help a lot of users if somebody could help fill out the needed gaps to have a good overview about what happens when?

The full insight by examples in a nutshell:

Sometimes the memory returned by the new operator will be initialized, and sometimes it won't depending on whether the type you're newing up is a POD (plain old data), or if it's a class that contains POD members and is using a compiler-generated default constructor.

In C++1998 there are 2 types of initialization: zero- and default-initialization

In C++2003 a 3rd type of initialization, value-initialization was added.

In C++2011/C++2014 only list-initialization was added and the rules for value-/default-/zero-initialization changed a bit.

Assume:

struct A { int m; };
struct B { ~B(); int m; };
struct C { C() : m(){}; ~C(); int m; };
struct D { D(){}; int m; };
struct E { E() = default; int m;}; /** only possible in c++11/14 */
struct F {F(); int m;};  F::F() = default; /** only possible in c++11/14 */

In a C++98 compiler, the following should occur:

new A   - indeterminate value (A is POD)

new A()- zero-initialize

new B   - default construct (B::m is uninitialized, B is non-POD)

new B() - default construct (B::m is uninitialized)

new C   - default construct (C::m is zero-initialized, C is non-POD)

new C() - default construct (C::m is zero-initialized)

new D   - default construct (D::m is uninitialized, D is non-POD)

new D() - default construct? (D::m is uninitialized)

In a C++03 conformant compiler, things should work like so:

new A    - indeterminate value (A is POD)

new A()  - value-initialize A, which is zero-initialization since it's a POD.

new B    - default-initializes (leaves B::m uninitialized, B is non-POD)

new B()  - value-initializes B which zero-initializes all fields since its default ctor is compiler generated as opposed to user-defined.

new C    - default-initializes C, which calls the default ctor. (C::m is zero-initialized, C is non-POD)

new C()  - value-initializes C, which calls the default ctor.  (C::m is zero-initialized)

new D    - default construct (D::m is uninitialized, D is non-POD)

new D()  - value-initializes D?, which calls the default ctor (D::m is uninitialized)

Italic values and ? are uncertainties, please help to correct this :-)

In a C++11 conformant compiler, things should work like so:

??? (please help if I start here it will anyway go wrong)

In a C++14 conformant compiler, things should work like so:
??? (please help if I start here it will anyway go wrong)
(Draft based on answer)

new A    - default-initializes A, compiler gen. ctor, (leavs A::m uninitialized) (A is POD)

new A()  - value-initializes A, which is zero-initialization since 2. point in [dcl.init]/8

new B   - default-initializes B, compiler gen. ctor, (leavs B::m uninitialized) (B is non-POD)

new B()  - value-initializes B which zero-initializes all fields since its default ctor is compiler generated as opposed to user-defined.

new C    - default-initializes C, which calls the default ctor. (C::m is zero-initialized, C is non-POD)

new C()  - value-initializes C, which calls the default ctor. (C::m is zero-initialized)

new D    - default-initializes D (D::m is uninitialized, D is non-POD)

new D()  - value-initializes D, which calls the default ctor (D::m is uninitialized)

new E    - default-initializes E, which calls the comp. gen. ctor. (E::m is uninitialized, E is non-POD)

new E()  - value-initializes E, which zero-initializes E since 2 point in [dcl.init]/8 )

new F    - default-initializes F, which calls the comp. gen. ctor. (F::m is uninitialized, F is non-POD)

new F()  - value-initializes F, which default-initializes F since 1. point in [dcl.init]/8 (F ctor function is user-provided if it is user-declared and not explicitly defaulted or deleted on its first declaration. Link)

Body:
I can confirm that in C++11, everything mentioned in the question under C++14 is correct, at least as per compiler implementations.

In order to verify this, I added the following code to my test suite. I tested with -std=c++11 -O3 in GCC 7.4.0, GCC 5.4.0, Clang 10.0.1, and VS 2017, and all the tests below pass.

#include <gtest/gtest.h>
#include <memory>

struct A { int m;                    };
struct B { int m;            ~B(){}; };
struct C { int m; C():m(){}; ~C(){}; };
struct D { int m; D(){};             };
struct E { int m; E() = default;     };
struct F { int m; F();               }; F::F() = default;

// We use this macro to fill stack memory with something else than 0.
// Subsequent calls to EXPECT_NE(a.m, 0) are undefined behavior in theory, but
// pass in practice, and help illustrate that `a.m` is indeed not initialized
// to zero. Note that we initially tried the more aggressive test
// EXPECT_EQ(a.m, 42), but it didn't pass on all compilers (a.m wasn't equal to
// 42, but was still equal to some garbage value, not zero).
//
// Update 2020-12-14: Even the less aggressive EXPECT_NE(a.m, 0) fails in some
// machines, so we comment them out. But this change in behavior does illustrate
// that, in fact, the behavior was undefined.
//
#define FILL { int m = 42; EXPECT_EQ(m, 42); }

// We use this macro to fill heap memory with something else than 0, before
// doing a placement new at that same exact location. Subsequent calls to
// EXPECT_EQ(a->m, 42) are undefined behavior in theory, but pass in practice,
// and help illustrate that `a->m` is indeed not initialized to zero.
//
#define FILLH(b) std::unique_ptr<int> bp(new int(42)); int* b = bp.get(); EXPECT_EQ(*b, 42)

TEST(TestZero, StackDefaultInitialization)
{
    //{ FILL; A a; EXPECT_NE(a.m, 0); } // UB!
    //{ FILL; B a; EXPECT_NE(a.m, 0); } // UB!
    { FILL; C a; EXPECT_EQ(a.m, 0); }
    //{ FILL; D a; EXPECT_NE(a.m, 0); } // UB!
    //{ FILL; E a; EXPECT_NE(a.m, 0); } // UB!
    //{ FILL; F a; EXPECT_NE(a.m, 0); } // UB!
}

TEST(TestZero, StackValueInitialization)
{
    { FILL; A a = A(); EXPECT_EQ(a.m, 0); }
    { FILL; B a = B(); EXPECT_EQ(a.m, 0); }
    { FILL; C a = C(); EXPECT_EQ(a.m, 0); }
    //{ FILL; D a = D(); EXPECT_NE(a.m, 0); } // UB!
    { FILL; E a = E(); EXPECT_EQ(a.m, 0); }
    //{ FILL; F a = F(); EXPECT_NE(a.m, 0); } // UB!
}

TEST(TestZero, StackListInitialization)
{
    { FILL; A a{}; EXPECT_EQ(a.m, 0); }
    { FILL; B a{}; EXPECT_EQ(a.m, 0); }
    { FILL; C a{}; EXPECT_EQ(a.m, 0); }
    //{ FILL; D a{}; EXPECT_NE(a.m, 0); } // UB!
    { FILL; E a{}; EXPECT_EQ(a.m, 0); }
    //{ FILL; F a{}; EXPECT_NE(a.m, 0); } // UB!
}

TEST(TestZero, HeapDefaultInitialization)
{
    { FILLH(b); A* a = new (b) A; EXPECT_EQ(a->m, 42); } // ~UB
    { FILLH(b); B* a = new (b) B; EXPECT_EQ(a->m, 42); } // ~UB
    { FILLH(b); C* a = new (b) C; EXPECT_EQ(a->m, 0);  }
    { FILLH(b); D* a = new (b) D; EXPECT_EQ(a->m, 42); } // ~UB
    { FILLH(b); E* a = new (b) E; EXPECT_EQ(a->m, 42); } // ~UB
    { FILLH(b); F* a = new (b) F; EXPECT_EQ(a->m, 42); } // ~UB
}

TEST(TestZero, HeapValueInitialization)
{
    { FILLH(b); A* a = new (b) A(); EXPECT_EQ(a->m, 0);  }
    { FILLH(b); B* a = new (b) B(); EXPECT_EQ(a->m, 0);  }
    { FILLH(b); C* a = new (b) C(); EXPECT_EQ(a->m, 0);  }
    { FILLH(b); D* a = new (b) D(); EXPECT_EQ(a->m, 42); } // ~UB
    { FILLH(b); E* a = new (b) E(); EXPECT_EQ(a->m, 0);  }
    { FILLH(b); F* a = new (b) F(); EXPECT_EQ(a->m, 42); } // ~UB
}

TEST(TestZero, HeapListInitialization)
{
    { FILLH(b); A* a = new (b) A{}; EXPECT_EQ(a->m, 0);  }
    { FILLH(b); B* a = new (b) B{}; EXPECT_EQ(a->m, 0);  }
    { FILLH(b); C* a = new (b) C{}; EXPECT_EQ(a->m, 0);  }
    { FILLH(b); D* a = new (b) D{}; EXPECT_EQ(a->m, 42); } // ~UB
    { FILLH(b); E* a = new (b) E{}; EXPECT_EQ(a->m, 0);  }
    { FILLH(b); F* a = new (b) F{}; EXPECT_EQ(a->m, 42); } // ~UB
}

int main(int argc, char **argv)
{
    ::testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}

The places where UB! is mentioned are undefined behavior, and the actual behavior is likely to depend on many factors (a.m might be equal to 42, 0, or some other garbage). The places where ~UB is mentioned are also undefined behavior in theory, but in practice, due the use of a placement new, it's very unlikely than a->m will be equal to anything else than 42.


问:
Why does string concatenation create extra parameters using Access and PYODBC?

I created this procedure that I call with the cursor.execute method. The problem that I'm having is that PYODBC sees extra parameters than what I've given.
In this example query, the "-" and "-" are being read as extra parameters by PYODBC. Does anyone know why this is the case? This is happening any time I do any string concatenation in Access.

```<code>def GetAccessResults(self):

    with pyodbc.connect(SQL.DBPath) as con:
        cursor = con.cursor()

        if self.parameters == None:
            cursor.execute('{{Call {}}}'.format(self.storedProc))
        else:
            callString = self.__CreateStoredProcString()
            cursor.execute(callString, self.parameters)

        returnValue = cursor.fetchall()

    return returnValue

def __CreateStoredProcString(self):

    questionMarks = ('?,' * len(self.parameters))[:-1]

    return '{{Call {} ({})}}'.format(self.storedProc, questionMarks)
</code>```

答:
As OP found out, MS Access being both a frontend GUI application and backend database operates differently in running SQL. Usually, the backend mode tends to be closer to standard SQL, namely:

Quotes: In backend, single quotes are reserved for literals and double quotes for identifiers as opposed to being interchangeable inside MSAccess.exe.

Wildcards: In backend, by default wildcards for LIKE uses % and GUI uses * unless running Access database in SQL Server compatible syntax (ANSI 92) that uses the standard %. For this reason, consider Access' ALIKE (ANSI-Like) with % to be compatible in both Access modes. Interestingly, this is not the case with stored queries as OP uses but will if writing queries in code.

Parameter: In backend, any unquoted object not recognized in query is considered a named parameter and errs out. Meanwhile the GUI launches a pop-up Enter Parameter box (which beginners do not know is actually a runtime error) allowing typed answers to then be evaluated on fly.

GUI Objects: While in GUI, Access queries can reference controls in open forms and reports, even user-defined functions defined in standalone VBA modules, these same references will error out in backend which essentially runs Access in headless mode and only recognizes other tables and queries.

Optimization: See Allen Browne's differences in optimizations that can occur when creating queries in GUI vs backend especially referencing Access object library functions.

By the way, using LIKE on subquery evaluates one scalar to another scalar. In fact, Access will err out if subquery returns more than one row which potentially can occur with current setup.

Error 3354: At most one record can be returned by this subquery

In other databases, the evaluation runs on first row of subquery (which without ORDER BY can be a random row) and not all records of subquery. Instead, consider re-factoring SQL to use EXISTS clause:

PARAMETERS prmServiceName Tex(255);
SELECT c.*
FROM Charts c
WHERE EXISTS
  (SELECT 1
   FROM Services s
   WHERE s.ServiceName = prmService_Name
     AND c.FileName ALIKE '%-' & s.Service_Abbreviation & '-%');
```

Body:
I created this procedure that I call with the cursor.execute method. The problem that I'm having is that PYODBC sees extra parameters than what I've given.
In this example query, the "-" and "-" are being read as extra parameters by PYODBC. Does anyone know why this is the case? This is happening any time I do any string concatenation in Access.

def GetAccessResults(self):

    with pyodbc.connect(SQL.DBPath) as con:
        cursor = con.cursor()

        if self.parameters == None:
            cursor.execute('{{Call {}}}'.format(self.storedProc))
        else:
            callString = self.__CreateStoredProcString()
            cursor.execute(callString, self.parameters)

        returnValue = cursor.fetchall()

    return returnValue

def __CreateStoredProcString(self):

    questionMarks = ('?,' * len(self.parameters))[:-1]

    return '{{Call {} ({})}}'.format(self.storedProc, questionMarks)


问:
Qt SQlite cannot create table
I am trying to have a button click create a table:

```<code>void summary::on_pushButton_saveSummary_clicked()
{
if(db.open())
    {
        query.exec("create table parrot (total int, defects int, rust int)");
        if (!query.exec())
        {
        qDebug() << query.lastError();
        }
else
{
   qDebug() << db.lastError();
}
}
</code>```

The above produces: QSqlError("1", "Unable to fetch row", "table parrot already exists")
if I make these changes:

```<code>query.prepare("create table parrot (total int, defects int, rust int)");
query.exec();
</code>```

I get the new error: QSqlError("", "Unable to fetch row", "No query")

```<code>db.setDatabaseName("/home/igraves/Databases/testdb");
db.open();
</code>```

The above is in the constructor.

```<code>QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
QSqlQuery query;
</code>```

and the above is in my .h

I have tried every solution to OTHER peoples similar issues, but to no avail. I am hoping someone else has a new idea.

答:
@ellanesc was correct, I had tried that solution earlier but had no success, apparently in my frantic rearranging of code, it works now. Thank you!

```<code>CREATE TABLE IF NOT EXISTS parrot (total int, defects int, rust int)
</code>```

The above fixed the problem

Title: Qt SQlite cannot create table

Body:
I am trying to have a button click create a table:

void summary::on_pushButton_saveSummary_clicked()
{
if(db.open())
    {
        query.exec("create table parrot (total int, defects int, rust int)");
        if (!query.exec())
        {
        qDebug() << query.lastError();
        }
else
{
   qDebug() << db.lastError();
}
}

The above produces: QSqlError("1", "Unable to fetch row", "table parrot already exists")
if I make these changes:

query.prepare("create table parrot (total int, defects int, rust int)");
query.exec();

I get the new error: QSqlError("", "Unable to fetch row", "No query")

db.setDatabaseName("/home/igraves/Databases/testdb");
db.open();

The above is in the constructor.

QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
QSqlQuery query;

and the above is in my .h

I have tried every solution to OTHER peoples similar issues, but to no avail. I am hoping someone else has a new idea.

Body:
@ellanesc was correct, I had tried that solution earlier but had no success, apparently in my frantic rearranging of code, it works now. Thank you!

CREATE TABLE IF NOT EXISTS parrot (total int, defects int, rust int)

The above fixed the problem


问:
Why do i still get warnings when using @SuppressWarnings("unchecked")?
```<code>class Lenkeliste<T> implements Liste<T>{
  @SuppressWarnings({"unchecked"})
  private int iBruk = 0;
  private T[] liste = (T[]) new Object[10];

  public int stoerrelse(){
    return iBruk;
  }
  public void leggTil(int pos, T x) {
    if (pos < 0 || pos >= iBruk) {
      throw new UgyldigListeIndeks(pos);
    }
    if (iBruk == liste.lenght) {
      @SuppressWarnings({"unchecked"})
      T[] ny = (T[]) new Object[2*iBruk];
      for (int i = pos; i < iBruk; i++) {
        ny[i] = liste[i];
        liste = ny;
        liste[i+1] = liste[i];
      }
      liste[pos] = x;
      iBruk++;
    }
  }
  public void leggTil(T x) {
    if (iBruk == liste.lenght) {
      @SuppressWarnings({"unchecked"})
      T[] ny = (T[]) new Object[2*iBruk];
      for (int i = 0; i < iBruk; i++) {
        ny[i] = liste[i];
        liste = ny;
      }
      liste[iBruk] = x;
      iBruk++;
    }
  }
  public void sett(int pos, T x) {
    if (pos < 0 || pos >= iBruk) {
      throw new UgyldigListeIndeks(pos);
    }
    liste[pos] = x;
  }
  public T hent(int pos) {
    if (pos < 0 || pos >= iBruk) {
      throw new UgyldigListeIndeks(pos);
    }
    return liste[pos];
  }
  public T fjern(int pos) {
    if (pos < 0 || pos >= iBruk) {
      throw new UgyldigListeIndeks(pos);
    }
    T bort = liste[pos];
    for (int i = pos+1; i < iBruk; i++) {
      liste[i-1] = liste[i];
    }
    iBruk--;
    return bort;
  }
  public T fjern() {
    T ut = liste[0];
    for (int i = 1; i < iBruk; i++) {
      liste[i-1] = liste[i];
    }
    iBruk--;
    return ut;
  }
}
</code>```

This is the code i have. The teacher used similar code and got it to work, but I still get warnings.
Here are the errors i get:

```<code>Lenkeliste.java:15: error: cannot find symbol
    if (iBruk == liste.lenght) {
                      ^
  symbol:   variable lenght
  location: variable liste of type T[]
  where T is a type-variable:
    T extends Object declared in class Lenkeliste
Lenkeliste.java:28: error: cannot find symbol
    if (iBruk == liste.lenght) {
                      ^
  symbol:   variable lenght
  location: variable liste of type T[]
  where T is a type-variable:
    T extends Object declared in class Lenkeliste
Note: Lenkeliste.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
</code>```

答:
Consider the following minimal example:

public class Test<T> {
    public Test() {
        Object[] arr = new Object[10];
        T[] new_arr = (T[])arr;
    }
}
```

<p>This yields the following warning:</p>

```Note: Test.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
```

<p>I can recompile and see details about what unchecked operations I am doing:</p>

```Test.java:5: warning: [unchecked] unchecked cast
        T[] new_arr = (T[])arr;
                           ^
  required: T[]
  found:    Object[]
  where T is a type-variable:
    T extends Object declared in class Test
1 warning
```

<p>I can suppress all unchecked warnings for the whole class:</p>

<pre class="lang-java prettyprint-override"><code>@SuppressWarnings({"unchecked"})// @SuppressWarnings("unchecked") would also work here
public class Test<T> {
    public Test() {
        Object[] arr = new Object[10];
        T[] new_arr = (T[])arr;
    }
}
</code>```

Or I can suppress warnings for a specific method, in this case the constructor:

public class Test<T> {
    @SuppressWarnings("unchecked")//@SuppressWarnings({"unchecked"}) would also work here
    public Test() {
        Object[] arr = new Object[10];
        T[] new_arr = (T[])arr;
    }
}
```

<p>In your case you also have a variable declaration, so you need to do:</p>

<pre class="lang-java prettyprint-override"><code>public class Test<T> {

    @SuppressWarnings("unchecked")
    T[] other_arr = (T[])new Object[10];

    @SuppressWarnings("unchecked")
    public Test() {
        Object[] arr = new Object[10];
        T[] new_arr = (T[])arr;
    }
}

</code>```

It is worth pointing out that your original code has compilation errors, and those should be resolved first.

Lastly these warnings exist for a reason. You should endeavor to write code that doesn't cause them(though how to do that is perhaps a separate stackoverflow question).

Body:
class Lenkeliste<T> implements Liste<T>{
  @SuppressWarnings({"unchecked"})
  private int iBruk = 0;
  private T[] liste = (T[]) new Object[10];

  public int stoerrelse(){
    return iBruk;
  }
  public void leggTil(int pos, T x) {
    if (pos < 0 || pos >= iBruk) {
      throw new UgyldigListeIndeks(pos);
    }
    if (iBruk == liste.lenght) {
      @SuppressWarnings({"unchecked"})
      T[] ny = (T[]) new Object[2*iBruk];
      for (int i = pos; i < iBruk; i++) {
        ny[i] = liste[i];
        liste = ny;
        liste[i+1] = liste[i];
      }
      liste[pos] = x;
      iBruk++;
    }
  }
  public void leggTil(T x) {
    if (iBruk == liste.lenght) {
      @SuppressWarnings({"unchecked"})
      T[] ny = (T[]) new Object[2*iBruk];
      for (int i = 0; i < iBruk; i++) {
        ny[i] = liste[i];
        liste = ny;
      }
      liste[iBruk] = x;
      iBruk++;
    }
  }
  public void sett(int pos, T x) {
    if (pos < 0 || pos >= iBruk) {
      throw new UgyldigListeIndeks(pos);
    }
    liste[pos] = x;
  }
  public T hent(int pos) {
    if (pos < 0 || pos >= iBruk) {
      throw new UgyldigListeIndeks(pos);
    }
    return liste[pos];
  }
  public T fjern(int pos) {
    if (pos < 0 || pos >= iBruk) {
      throw new UgyldigListeIndeks(pos);
    }
    T bort = liste[pos];
    for (int i = pos+1; i < iBruk; i++) {
      liste[i-1] = liste[i];
    }
    iBruk--;
    return bort;
  }
  public T fjern() {
    T ut = liste[0];
    for (int i = 1; i < iBruk; i++) {
      liste[i-1] = liste[i];
    }
    iBruk--;
    return ut;
  }
}

This is the code i have. The teacher used similar code and got it to work, but I still get warnings.
Here are the errors i get:

Lenkeliste.java:15: error: cannot find symbol
    if (iBruk == liste.lenght) {
                      ^
  symbol:   variable lenght
  location: variable liste of type T[]
  where T is a type-variable:
    T extends Object declared in class Lenkeliste
Lenkeliste.java:28: error: cannot find symbol
    if (iBruk == liste.lenght) {
                      ^
  symbol:   variable lenght
  location: variable liste of type T[]
  where T is a type-variable:
    T extends Object declared in class Lenkeliste
Note: Lenkeliste.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.

Body:
Consider the following minimal example:

public class Test<T> {
    public Test() {
        Object[] arr = new Object[10];
        T[] new_arr = (T[])arr;
    }
}

This yields the following warning:

Note: Test.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.

I can recompile and see details about what unchecked operations I am doing:

Test.java:5: warning: [unchecked] unchecked cast
        T[] new_arr = (T[])arr;
                           ^
  required: T[]
  found:    Object[]
  where T is a type-variable:
    T extends Object declared in class Test
1 warning

I can suppress all unchecked warnings for the whole class:

@SuppressWarnings({"unchecked"})// @SuppressWarnings("unchecked") would also work here
public class Test<T> {
    public Test() {
        Object[] arr = new Object[10];
        T[] new_arr = (T[])arr;
    }
}

Or I can suppress warnings for a specific method, in this case the constructor:

public class Test<T> {
    @SuppressWarnings("unchecked")//@SuppressWarnings({"unchecked"}) would also work here
    public Test() {
        Object[] arr = new Object[10];
        T[] new_arr = (T[])arr;
    }
}

In your case you also have a variable declaration, so you need to do:

public class Test<T> {

    @SuppressWarnings("unchecked")
    T[] other_arr = (T[])new Object[10];

    @SuppressWarnings("unchecked")
    public Test() {
        Object[] arr = new Object[10];
        T[] new_arr = (T[])arr;
    }
}

It is worth pointing out that your original code has compilation errors, and those should be resolved first.

Lastly these warnings exist for a reason. You should endeavor to write code that doesn't cause them(though how to do that is perhaps a separate stackoverflow question).