问:
Id is added but not removed
When I click on the code button <> a second id is correctly added, but when I click on the code button again <> the new added id is not removed, so how can I remove the added id, since I have tried some alternatives and They don't work for me.

What I try to do is delete the following id newID

```<code>if (codeMode) {
    var formattedHtml = formatHtmlCode(htmlDiv.html());
    htmlDiv.css("white-space", "normal"); //pre
    htmlDiv.text(formattedHtml);
    var editor = $("#editor");
    editor.addClass("black-bg-colr codeMode");
    editor.attr('id', 'editor newID');
} else {
    htmlDiv.css("white-space", "normal");
    htmlDiv.html(htmlDiv.text().replace(/\r?\n|\r/g, ""));
    var editor = $("#editor");
    editor.removeClass("black-bg-colr codeMode");
    //editor.attr('id', 'editor');
    //$('div#newID').removeAttr('id');
    //editor.removeAttr( "newID" )
}
</code>```

Snippet:

 $(function() {
  function formatHtmlCode(str) {
   var div = document.createElement('div');
   div.innerHTML = str.trim();
   return format(div, 0).innerHTML;
  }
  function format(node, level) {
   var indentBefore = new Array(level++ + 1).join('  '),
   indentAfter = new Array(level - 1).join('  '),
   textNode;
   for (var i = 0; i < node.children.length; i++) {
    textNode = document.createTextNode('\n' + indentBefore);
    node.insertBefore(textNode, node.children[i]);
    format(node.children[i], level);
    if (node.lastElementChild == node.children[i]) {
     textNode = document.createTextNode('\n' + indentAfter);
     node.appendChild(textNode);
    }
   }
   return node;
  }
  $('#editControls a').click(function(e) {
   switch ($(this).data('role')) {
    case 'p':
     document.execCommand('formatBlock', false, $(this).data('role'));
     break;
    case 'code':
     codeMode = !codeMode;
     if (codeMode) {
      var formattedHtml = formatHtmlCode(htmlDiv.html());
      htmlDiv.css("white-space", "normal"); //pre
      htmlDiv.text(formattedHtml);
      var editor = $("#editor");
      editor.addClass("black-bg-colr codeMode");
      editor.attr('id', 'editor newID');
     } else {
      htmlDiv.css("white-space", "normal");
      htmlDiv.html(htmlDiv.text().replace(/\r?\n|\r/g, ""));
      var editor = $("#editor");
      editor.removeClass("black-bg-colr codeMode");
      //editor.attr('id', 'editor');
            //$('div#newID').removeAttr('id');
            //editor.removeAttr( "newID" )
     }
     break;
    default:
     document.execCommand($(this).data('role'), false, null);
     break;
   }
  });

  let codeMode = false;
  let htmlDiv = $("#editor");
  htmlDiv.on('keyup', function(e) {
   if (!e.shiftKey && e.keyCode === 13) {
    document.execCommand('formatBlock', false, 'p');
   } else if (e.shiftKey) {
    document.execCommand('formatBlock', false, 'div');
   }
  });

  htmlDiv.on("paste", function(e) {
   e.preventDefault();
   var text = (e.originalEvent || e).clipboardData.getData('text/plain');
   document.execCommand('formatBlock', false, 'div');
   document.execCommand('insertText', false, text);
  });

  htmlDiv.on("input", function(e) {
   $(".editor-preview").val(htmlDiv.html());
   $(".editor-preview").keyup();
  });

  $('.editor-preview').keyup(function() {
   var contentAttr = $(this).attr('class');
   if (!codeMode) {
    var value = $(this).val();
    $('.' + contentAttr).html(value);
   } else {
    $('.' + contentAttr).html(htmlDiv.text());
   }
  });

 });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#editControls {
    overflow: auto;
    border-top: 1px solid transparent;
    border-left: 1px solid transparent;
    border-right: 1px solid transparent;
    border-color: silver;
    border-top-left-radius: 5px;
    border-top-right-radius: 5px;
    padding: .5em 1em .5em 1em;
    background-color: #fbfbfb;
    margin: 0 auto;
    width: 100%; /*90*/
}
#editor {
    resize: vertical;
    overflow: auto;
    border: 1px solid silver;
    border-bottom-right-radius: 5px;
    border-bottom-left-radius: 5px;
    min-height: 100px;
    padding: 1em;
    background: white;
    margin: 0 auto;
    width: 100%;/*90*/
}
#editor:focus {
    outline: none !important;
    box-shadow: inset 0 0 2px silver;
}
.codeMode {
    font-family:Courier New,Source Code Pro Light,Medium,Source Code Pro ExtraLight,Menlo,Consola,Monaco Linux,Consola Regular,Fira Code Regular,DejaVu Sans Mono;
    /*font-family: inherit;*/
    /*font-family: 'Courier New';*/
    border: 0px;
    font-style: inherit;
    font-variant: inherit;
    font-weight: inherit;
    font-stretch: inherit;
    line-height: inherit;
    vertical-align: baseline;
    box-sizing: inherit;
    color: #fff;
}
.black-bg-colr {
  background-color: #000 !important;
}
.btn-group {
    position: relative;
    display: inline-block;
    font-size: 0;
    vertical-align: middle;
    white-space: nowrap;
}
.btn-group+.btn-group {
    margin-left: 5px;
}
.btn-group a {
    text-decoration: none;
}
.btn-editor {
    height: 30px;
    display: inline-block;
    padding: 6px 12px;
    margin-bottom: 0;
    font-size: 11px;
    font-weight: normal;
    line-height: 1.42857143;
    text-align: center;
    white-space: nowrap;
    vertical-align: middle;
    -ms-touch-action: manipulation;
    touch-action: manipulation;
    cursor: pointer;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
    background-image: none;
    border-radius: 4px;
    border: 1px solid transparent;
    color: #333;
    background-color: #fff;
    border-color: #ccc;
}
.btn-group>.btn-editor:first-child {
    margin-left: 0;
    -webkit-border-top-left-radius: 4px;
    -moz-border-radius-topleft: 4px;
    border-top-left-radius: 4px;
    -webkit-border-bottom-left-radius: 4px;
    -moz-border-radius-bottomleft: 4px;
    border-bottom-left-radius: 4px;
}
.btn-group>.btn-editor+.btn-editor {
    margin-left: -1px !important;
    border-top-right-radius: 4px;
    border-bottom-right-radius: 4px;
}
.btn-not-space{
    position: relative;
    float: left;
    margin-left: 0 !important;
    border-radius: inherit;
    border: 1px solid transparent;
    border-color: #ccc;
}
.btn-editor.btn-not-space:hover {
    background-color: rgba(230, 230, 230, 0.32);
}
#preview {
    padding: 1em;
    margin: 0 auto;
    width: 97%;
    border-top: 1px dotted #c8ccd0;
    border-bottom: 1px dotted #c8ccd0;
    clear: both;
}</code>```

   Bold
   Italic
   U
   abc

   </>

  <textarea id="textarea" name="detail" class="editor-preview" style="display: none;"></textarea>

```

Fiddle: https://jsfiddle.net/n4ctd795/

答:
I now understand what you attempt to do. When hitting <>, you want to edit the text in a "code view"...

So here is how I changed your project (without the ace.js instance, which is about color coding the code):

I use a "sub div" to show the code (with the black background style), declared as the codeDiv variable.

I squarely replace the #editor (main editor) content with the formatHtmlCode result, wrapped by the codeDiv.

When going out of the "code edition mode", I get the codeDiv content to turn it back into HTML and put it back in the main editor. Then I remove the codeDiv.

Now this does not use ace.js...

I will edit this solution when I'll find how to use it this way. It is an interesting question ;)

$(function() {

  let codeMode = false;
  let htmlDiv = $("#editor");
  htmlDiv.css("white-space", "normal"); // This could be set via CSS rule

  // Use a "sub div" to show the code
  let codeDiv = $("
")

  function formatHtmlCode(str) {
    var div = document.createElement('div');
    div.innerHTML = str.trim();
    return format(div, 0).innerHTML;
  }

  function format(node, level) {
    var indentBefore = new Array(level++ + 1).join('  '),
      indentAfter = new Array(level - 1).join('  '),
      textNode;
    for (var i = 0; i < node.children.length; i++) {
      textNode = document.createTextNode('\n' + indentBefore);
      node.insertBefore(textNode, node.children[i]);
      format(node.children[i], level);
      if (node.lastElementChild == node.children[i]) {
        textNode = document.createTextNode('\n' + indentAfter);
        node.appendChild(textNode);
      }
    }
    return node;
  }

  // HTML editor's buttons
  $('#editControls a').click(function(e) {
    switch ($(this).data('role')) {

      case 'p':
        document.execCommand('formatBlock', false, $(this).data('role'));
        break;

        // The <> code button
      case 'code':
        codeMode = !codeMode;
        if (codeMode) {

          // Format the text with the HTML tags in a "code sub div"
          var formattedHtml = formatHtmlCode(htmlDiv.html());
          codeDiv.text(formattedHtml);
          htmlDiv.html(codeDiv);
        } else {

          // Retrieve the modified HTML from the "code sub div" and overwrite the content... So the "codeDiv" is removed de facto. Simple!
          htmlDiv.html($("#codeDiv").text())
        }
        break;

      default:
        document.execCommand($(this).data('role'), false, null);
        break;
    }
  });

  htmlDiv.on('keyup', function(e) {
    if (!e.shiftKey && e.keyCode === 13) {
      document.execCommand('formatBlock', false, 'p');
    } else if (e.shiftKey) {
      document.execCommand('formatBlock', false, 'div');
    }
  });

  htmlDiv.on("paste", function(e) {
    e.preventDefault();
    var text = (e.originalEvent || e).clipboardData.getData('text/plain');
    document.execCommand('formatBlock', false, 'div');
    document.execCommand('insertText', false, text);
  });

  htmlDiv.on("input", function(e) {
    $(".editor-preview").val(htmlDiv.html());
  });

  $('.editor-preview').keyup(function() {
    var contentAttr = $(this).attr('class');
    if (!codeMode) {
      var value = $(this).val();
      $('.' + contentAttr).html(value);
    } else {
      $('.' + contentAttr).html(htmlDiv.text());
    }
  });

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#editControls {
  overflow: auto;
  border-top: 1px solid transparent;
  border-left: 1px solid transparent;
  border-right: 1px solid transparent;
  border-color: silver;
  border-top-left-radius: 5px;
  border-top-right-radius: 5px;
  padding: .5em 1em .5em 1em;
  background-color: #fbfbfb;
  margin: 0 auto;
  width: 100%;
  /*90*/
}

#editor {
  resize: vertical;
  overflow: auto;
  border: 1px solid silver;
  border-bottom-right-radius: 5px;
  border-bottom-left-radius: 5px;
  min-height: 100px;
  padding: 1em;
  background: white;
  margin: 0 auto;
  width: 100%;
  /*90*/
}

#editor:focus {
  outline: none !important;
  box-shadow: inset 0 0 2px silver;
}

.codeMode {
  font-family: Courier New, Source Code Pro Light, Medium, Source Code Pro ExtraLight, Menlo, Consola, Monaco Linux, Consola Regular, Fira Code Regular, DejaVu Sans Mono;
  /*font-family: inherit;*/
  /*font-family: 'Courier New';*/
  border: 0px;
  font-style: inherit;
  font-variant: inherit;
  font-weight: inherit;
  font-stretch: inherit;
  line-height: inherit;
  vertical-align: baseline;
  box-sizing: inherit;
  color: #fff;
}

.black-bg-colr {
  background-color: #000 !important;
}

.btn-group {
  position: relative;
  display: inline-block;
  font-size: 0;
  vertical-align: middle;
  white-space: nowrap;
}

.btn-group+.btn-group {
  margin-left: 5px;
}

.btn-group a {
  text-decoration: none;
}

.btn-editor {
  height: 30px;
  display: inline-block;
  padding: 6px 12px;
  margin-bottom: 0;
  font-size: 11px;
  font-weight: normal;
  line-height: 1.42857143;
  text-align: center;
  white-space: nowrap;
  vertical-align: middle;
  -ms-touch-action: manipulation;
  touch-action: manipulation;
  cursor: pointer;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
  background-image: none;
  border-radius: 4px;
  border: 1px solid transparent;
  color: #333;
  background-color: #fff;
  border-color: #ccc;
}

.btn-group>.btn-editor:first-child {
  margin-left: 0;
  -webkit-border-top-left-radius: 4px;
  -moz-border-radius-topleft: 4px;
  border-top-left-radius: 4px;
  -webkit-border-bottom-left-radius: 4px;
  -moz-border-radius-bottomleft: 4px;
  border-bottom-left-radius: 4px;
}

.btn-group>.btn-editor+.btn-editor {
  margin-left: -1px !important;
  border-top-right-radius: 4px;
  border-bottom-right-radius: 4px;
}

.btn-not-space {
  position: relative;
  float: left;
  margin-left: 0 !important;
  border-radius: inherit;
  border: 1px solid transparent;
  border-color: #ccc;
}

.btn-editor.btn-not-space:hover {
  background-color: rgba(230, 230, 230, 0.32);
}

#preview {
  padding: 1em;
  margin: 0 auto;
  width: 97%;
  border-top: 1px dotted #c8ccd0;
  border-bottom: 1px dotted #c8ccd0;
  clear: both;
}</code>```

      Bold
      Italic
      U
      abc

      </>

    Hello! Use the </> button to modify me.

  <textarea id="textarea" name="detail" class="editor-preview" style="display: none;"></textarea>

```

Title: Id is added but not removed

Body:
When I click on the code button <> a second id is correctly added, but when I click on the code button again <> the new added id is not removed, so how can I remove the added id, since I have tried some alternatives and They don't work for me.

What I try to do is delete the following id newID

if (codeMode) {
    var formattedHtml = formatHtmlCode(htmlDiv.html());
    htmlDiv.css("white-space", "normal"); //pre
    htmlDiv.text(formattedHtml);
    var editor = $("#editor");
    editor.addClass("black-bg-colr codeMode");
    editor.attr('id', 'editor newID');
} else {
    htmlDiv.css("white-space", "normal");
    htmlDiv.html(htmlDiv.text().replace(/\r?\n|\r/g, ""));
    var editor = $("#editor");
    editor.removeClass("black-bg-colr codeMode");
    //editor.attr('id', 'editor');
    //$('div#newID').removeAttr('id');
    //editor.removeAttr( "newID" )
}

Snippet:

 $(function() {
  function formatHtmlCode(str) {
   var div = document.createElement('div');
   div.innerHTML = str.trim();
   return format(div, 0).innerHTML;
  }
  function format(node, level) {
   var indentBefore = new Array(level++ + 1).join('  '),
   indentAfter = new Array(level - 1).join('  '),
   textNode;
   for (var i = 0; i < node.children.length; i++) {
    textNode = document.createTextNode('\n' + indentBefore);
    node.insertBefore(textNode, node.children[i]);
    format(node.children[i], level);
    if (node.lastElementChild == node.children[i]) {
     textNode = document.createTextNode('\n' + indentAfter);
     node.appendChild(textNode);
    }
   }
   return node;
  }
  $('#editControls a').click(function(e) {
   switch ($(this).data('role')) {
    case 'p':
     document.execCommand('formatBlock', false, $(this).data('role'));
     break;
    case 'code':
     codeMode = !codeMode;
     if (codeMode) {
      var formattedHtml = formatHtmlCode(htmlDiv.html());
      htmlDiv.css("white-space", "normal"); //pre
      htmlDiv.text(formattedHtml);
      var editor = $("#editor");
      editor.addClass("black-bg-colr codeMode");
      editor.attr('id', 'editor newID');
     } else {
      htmlDiv.css("white-space", "normal");
      htmlDiv.html(htmlDiv.text().replace(/\r?\n|\r/g, ""));
      var editor = $("#editor");
      editor.removeClass("black-bg-colr codeMode");
      //editor.attr('id', 'editor');
            //$('div#newID').removeAttr('id');
            //editor.removeAttr( "newID" )
     }
     break;
    default:
     document.execCommand($(this).data('role'), false, null);
     break;
   }
  });

  let codeMode = false;
  let htmlDiv = $("#editor");
  htmlDiv.on('keyup', function(e) {
   if (!e.shiftKey && e.keyCode === 13) {
    document.execCommand('formatBlock', false, 'p');
   } else if (e.shiftKey) {
    document.execCommand('formatBlock', false, 'div');
   }
  });

  htmlDiv.on("paste", function(e) {
   e.preventDefault();
   var text = (e.originalEvent || e).clipboardData.getData('text/plain');
   document.execCommand('formatBlock', false, 'div');
   document.execCommand('insertText', false, text);
  });

  htmlDiv.on("input", function(e) {
   $(".editor-preview").val(htmlDiv.html());
   $(".editor-preview").keyup();
  });

  $('.editor-preview').keyup(function() {
   var contentAttr = $(this).attr('class');
   if (!codeMode) {
    var value = $(this).val();
    $('.' + contentAttr).html(value);
   } else {
    $('.' + contentAttr).html(htmlDiv.text());
   }
  });

 });

#editControls {
    overflow: auto;
    border-top: 1px solid transparent;
    border-left: 1px solid transparent;
    border-right: 1px solid transparent;
    border-color: silver;
    border-top-left-radius: 5px;
    border-top-right-radius: 5px;
    padding: .5em 1em .5em 1em;
    background-color: #fbfbfb;
    margin: 0 auto;
    width: 100%; /*90*/
}
#editor {
    resize: vertical;
    overflow: auto;
    border: 1px solid silver;
    border-bottom-right-radius: 5px;
    border-bottom-left-radius: 5px;
    min-height: 100px;
    padding: 1em;
    background: white;
    margin: 0 auto;
    width: 100%;/*90*/
}
#editor:focus {
    outline: none !important;
    box-shadow: inset 0 0 2px silver;
}
.codeMode {
    font-family:Courier New,Source Code Pro Light,Medium,Source Code Pro ExtraLight,Menlo,Consola,Monaco Linux,Consola Regular,Fira Code Regular,DejaVu Sans Mono;
    /*font-family: inherit;*/
    /*font-family: 'Courier New';*/
    border: 0px;
    font-style: inherit;
    font-variant: inherit;
    font-weight: inherit;
    font-stretch: inherit;
    line-height: inherit;
    vertical-align: baseline;
    box-sizing: inherit;
    color: #fff;
}
.black-bg-colr {
  background-color: #000 !important;
}
.btn-group {
    position: relative;
    display: inline-block;
    font-size: 0;
    vertical-align: middle;
    white-space: nowrap;
}
.btn-group+.btn-group {
    margin-left: 5px;
}
.btn-group a {
    text-decoration: none;
}
.btn-editor {
    height: 30px;
    display: inline-block;
    padding: 6px 12px;
    margin-bottom: 0;
    font-size: 11px;
    font-weight: normal;
    line-height: 1.42857143;
    text-align: center;
    white-space: nowrap;
    vertical-align: middle;
    -ms-touch-action: manipulation;
    touch-action: manipulation;
    cursor: pointer;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
    background-image: none;
    border-radius: 4px;
    border: 1px solid transparent;
    color: #333;
    background-color: #fff;
    border-color: #ccc;
}
.btn-group>.btn-editor:first-child {
    margin-left: 0;
    -webkit-border-top-left-radius: 4px;
    -moz-border-radius-topleft: 4px;
    border-top-left-radius: 4px;
    -webkit-border-bottom-left-radius: 4px;
    -moz-border-radius-bottomleft: 4px;
    border-bottom-left-radius: 4px;
}
.btn-group>.btn-editor+.btn-editor {
    margin-left: -1px !important;
    border-top-right-radius: 4px;
    border-bottom-right-radius: 4px;
}
.btn-not-space{
    position: relative;
    float: left;
    margin-left: 0 !important;
    border-radius: inherit;
    border: 1px solid transparent;
    border-color: #ccc;
}
.btn-editor.btn-not-space:hover {
    background-color: rgba(230, 230, 230, 0.32);
}
#preview {
    padding: 1em;
    margin: 0 auto;
    width: 97%;
    border-top: 1px dotted #c8ccd0;
    border-bottom: 1px dotted #c8ccd0;
    clear: both;
}

   Bold
   Italic
   U
   abc

   </>

  <textarea id="textarea" name="detail" class="editor-preview" style="display: none;"></textarea>

Fiddle: https://jsfiddle.net/n4ctd795/

Body:
I now understand what you attempt to do. When hitting <>, you want to edit the text in a "code view"...

So here is how I changed your project (without the ace.js instance, which is about color coding the code):

I use a "sub div" to show the code (with the black background style), declared as the codeDiv variable.

I squarely replace the #editor (main editor) content with the formatHtmlCode result, wrapped by the codeDiv.

When going out of the "code edition mode", I get the codeDiv content to turn it back into HTML and put it back in the main editor. Then I remove the codeDiv.

Now this does not use ace.js...

I will edit this solution when I'll find how to use it this way. It is an interesting question ;)

$(function() {

  let codeMode = false;
  let htmlDiv = $("#editor");
  htmlDiv.css("white-space", "normal"); // This could be set via CSS rule

  // Use a "sub div" to show the code
  let codeDiv = $("<div id='codeDiv' class='black-bg-colr codeMode'>")

  function formatHtmlCode(str) {
    var div = document.createElement('div');
    div.innerHTML = str.trim();
    return format(div, 0).innerHTML;
  }

  function format(node, level) {
    var indentBefore = new Array(level++ + 1).join('  '),
      indentAfter = new Array(level - 1).join('  '),
      textNode;
    for (var i = 0; i < node.children.length; i++) {
      textNode = document.createTextNode('\n' + indentBefore);
      node.insertBefore(textNode, node.children[i]);
      format(node.children[i], level);
      if (node.lastElementChild == node.children[i]) {
        textNode = document.createTextNode('\n' + indentAfter);
        node.appendChild(textNode);
      }
    }
    return node;
  }

  // HTML editor's buttons
  $('#editControls a').click(function(e) {
    switch ($(this).data('role')) {

      case 'p':
        document.execCommand('formatBlock', false, $(this).data('role'));
        break;

        // The <> code button
      case 'code':
        codeMode = !codeMode;
        if (codeMode) {

          // Format the text with the HTML tags in a "code sub div"
          var formattedHtml = formatHtmlCode(htmlDiv.html());
          codeDiv.text(formattedHtml);
          htmlDiv.html(codeDiv);
        } else {

          // Retrieve the modified HTML from the "code sub div" and overwrite the content... So the "codeDiv" is removed de facto. Simple!
          htmlDiv.html($("#codeDiv").text())
        }
        break;

      default:
        document.execCommand($(this).data('role'), false, null);
        break;
    }
  });

  htmlDiv.on('keyup', function(e) {
    if (!e.shiftKey && e.keyCode === 13) {
      document.execCommand('formatBlock', false, 'p');
    } else if (e.shiftKey) {
      document.execCommand('formatBlock', false, 'div');
    }
  });

  htmlDiv.on("paste", function(e) {
    e.preventDefault();
    var text = (e.originalEvent || e).clipboardData.getData('text/plain');
    document.execCommand('formatBlock', false, 'div');
    document.execCommand('insertText', false, text);
  });

  htmlDiv.on("input", function(e) {
    $(".editor-preview").val(htmlDiv.html());
  });

  $('.editor-preview').keyup(function() {
    var contentAttr = $(this).attr('class');
    if (!codeMode) {
      var value = $(this).val();
      $('.' + contentAttr).html(value);
    } else {
      $('.' + contentAttr).html(htmlDiv.text());
    }
  });

});

#editControls {
  overflow: auto;
  border-top: 1px solid transparent;
  border-left: 1px solid transparent;
  border-right: 1px solid transparent;
  border-color: silver;
  border-top-left-radius: 5px;
  border-top-right-radius: 5px;
  padding: .5em 1em .5em 1em;
  background-color: #fbfbfb;
  margin: 0 auto;
  width: 100%;
  /*90*/
}

#editor {
  resize: vertical;
  overflow: auto;
  border: 1px solid silver;
  border-bottom-right-radius: 5px;
  border-bottom-left-radius: 5px;
  min-height: 100px;
  padding: 1em;
  background: white;
  margin: 0 auto;
  width: 100%;
  /*90*/
}

#editor:focus {
  outline: none !important;
  box-shadow: inset 0 0 2px silver;
}

.codeMode {
  font-family: Courier New, Source Code Pro Light, Medium, Source Code Pro ExtraLight, Menlo, Consola, Monaco Linux, Consola Regular, Fira Code Regular, DejaVu Sans Mono;
  /*font-family: inherit;*/
  /*font-family: 'Courier New';*/
  border: 0px;
  font-style: inherit;
  font-variant: inherit;
  font-weight: inherit;
  font-stretch: inherit;
  line-height: inherit;
  vertical-align: baseline;
  box-sizing: inherit;
  color: #fff;
}

.black-bg-colr {
  background-color: #000 !important;
}

.btn-group {
  position: relative;
  display: inline-block;
  font-size: 0;
  vertical-align: middle;
  white-space: nowrap;
}

.btn-group+.btn-group {
  margin-left: 5px;
}

.btn-group a {
  text-decoration: none;
}

.btn-editor {
  height: 30px;
  display: inline-block;
  padding: 6px 12px;
  margin-bottom: 0;
  font-size: 11px;
  font-weight: normal;
  line-height: 1.42857143;
  text-align: center;
  white-space: nowrap;
  vertical-align: middle;
  -ms-touch-action: manipulation;
  touch-action: manipulation;
  cursor: pointer;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
  background-image: none;
  border-radius: 4px;
  border: 1px solid transparent;
  color: #333;
  background-color: #fff;
  border-color: #ccc;
}

.btn-group>.btn-editor:first-child {
  margin-left: 0;
  -webkit-border-top-left-radius: 4px;
  -moz-border-radius-topleft: 4px;
  border-top-left-radius: 4px;
  -webkit-border-bottom-left-radius: 4px;
  -moz-border-radius-bottomleft: 4px;
  border-bottom-left-radius: 4px;
}

.btn-group>.btn-editor+.btn-editor {
  margin-left: -1px !important;
  border-top-right-radius: 4px;
  border-bottom-right-radius: 4px;
}

.btn-not-space {
  position: relative;
  float: left;
  margin-left: 0 !important;
  border-radius: inherit;
  border: 1px solid transparent;
  border-color: #ccc;
}

.btn-editor.btn-not-space:hover {
  background-color: rgba(230, 230, 230, 0.32);
}

#preview {
  padding: 1em;
  margin: 0 auto;
  width: 97%;
  border-top: 1px dotted #c8ccd0;
  border-bottom: 1px dotted #c8ccd0;
  clear: both;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="editor-wrapper">
  <div id="editControls">
    <div class="btn-group">
      <a class="btn-editor btn-not-space" data-role="bold" data-ref="#"><b>Bold</b></a>
      <a class="btn-editor btn-not-space" data-role="italic" data-ref="#"><em>Italic</em></a>
      <a class="btn-editor btn-not-space" data-role="underline" data-ref="#"><u><b>U</b></u></a>
      <a class="btn-editor btn-not-space" data-role="strikeThrough" data-ref="#"><strike>abc</strike></a>
    </div>
    <div class="btn-group">
      <a class="btn-editor btn-not-space" data-role="code" data-ref="#"><code>&lt;/&gt;</code></a>
    </div>
  </div>
  <div id="editor" contenteditable>
    <b>Hello! Use the &lt;/&gt; button to modify me.</b>
  </div>
  <textarea id="textarea" name="detail" class="editor-preview" style="display: none;"></textarea>
  <div id="preview" class="editor-preview"></div>
</div>


来源: stackexchange

问:
GKE cluster egress setup
I am running GKE cluster with single node. I have set up ingress for managing & forwarding rules inside Kubernetes cluster.

however by default pod use instance (Node) IP for external connection. I have not set up NAT gateway here. I have shared node external IP with the third party but changed IP from ephemeral to static to keep it.

What is the best way possible now to manage a single IP for egress even if we do auto-scaling from single node to multi-node but egress IP will be the same.

答:
The default behaviour for GKE when pods send traffic outside of the cluster, SNAT occurs and the node IP is used to replace the pod IP. The destination will only see the node IP. If you have more than 1 node, you will end up with more than 1 source IP.

Your best option to ensure you have a single IP for egress traffic is to use Cloud NAT with GKE

ContentLicense: CC BY-SA 4.0

Title: GKE cluster egress setup


问:
Referencing Text Content Controls
I am trying to reference and paste a specified string into a specific Text Content Controls and have been unable to do this properly.

Basically I have gone through and tried a few different things,  first being this;

```<code>Private Sub Document_ContentControlOnExit(ByVal ContentControl As ContentControl, Cancel As Boolean)

Dim ccs As ContentControls, cc As ContentControl
Set ccs = ActiveDocument.ContentControls
For Each cc In ccs
  If cc.Title = "ComboBox1" And cc.Range.Text = "Choose an item." Then
  SelectContentControlsByTitle("TextBox1").Add.SetPlaceholderText , , "Please make a drop down selection or manually fill out if not applicable"
</code>```

The above does not work, as every time I exit my content controller combo box it actually recreates the "placeholdertext" multiple times. I need this to only fill the "TextBox1" Content control.

I have also tried doing something like this,

```<code>Dim ccs As ContentControls, cc As ContentControl
Set ccs = ActiveDocument.ContentControls
Set CB1 = SelectContentControlsByTitle("TextBox1")
For Each cc In ccs
  If cc.Title = "ComboBox1" And cc.Range.Text = "Choose an item." Then
  CB1.Value = "Please make a drop down selection or manually fill out if not applicable"
</code>```

Due to the type, value is not able to be used like this. This does not work either.

Below is the original way I was doing what I wanted with the Active-X TextBox which does work;

```<code>Private Sub Document_ContentControlOnExit(ByVal ContentControl As ContentControl, Cancel As Boolean)

Dim ccs As ContentControls, cc As ContentControl
Set ccs = ActiveDocument.ContentControls
For Each cc In ccs
  If cc.Title = "ComboBox2" And cc.Range.Text = "Choose an item." Then
  TextBox2.Value = "Please make a drop down selection or manually fill out if not applicable"

  ElseIf cc.Title = "ComboBox2" And cc.Range.Text = "TMS backup" Then
  TextBox2.Value = "The TMS installation directory, settings directory and the database was backed up before the update was performed"

  ElseIf cc.Title = "ComboBox2" And cc.Range.Text = "TMS installation" Then
  TextBox2.Value = "Installation of version 1.17.X.19XXX performed"

  ElseIf cc.Title = "ComboBox2" And cc.Range.Text = "TMS update" Then
  TextBox2.Value = "Update from version 1.16.X.XXXXX to version 1.17.X.19XXX performed"

  ElseIf cc.Title = "ComboBox2" And cc.Range.Text = "Tool presetter update" Then
  TextBox2.Value = "Update from version 1.16.X.XXXXX to version 1.17.X.19XXX performed"

  ElseIf cc.Title = "ComboBox2" And cc.Range.Text = "Database generated" Then
  TextBox2.Value = "Database structure created with version 1.17.0"
</code>```

How can I do the above, while using the Text Content Controls?

答:
A better approach would be:

```<code>Private Sub Document_ContentControlOnExit(ByVal Ctrl As ContentControl, Cancel As Boolean)
Dim i As Long, StrDetails As String
With Ctrl
  If .Title = "ComboBox1" Then
  If ShowingPlaceholderText = True Then
    StrDetails = ""
  Else
    For i = 1 To .DropdownListEntries.Count
      If .DropdownListEntries(i).Text = .Range.Text Then
        StrDetails = .DropdownListEntries(i).Value
        Exit For
      End If
    Next
  End If
  ActiveDocument.SelectContentControlsByTitle("TextBox1")(1).Range.Text = StrDetails
  End If
End With
End Sub
</code>```

To make this work, simply add your 'conditional' text to each entry's 'Value' property, and make the "TextBox1" content control's placeholder text whatever you want its prompt to be. This way, you don't have to hard-code either the dropdown option or the 'conditional' text in your VBA code. For a practical demonstration, see: https://www.msofficeforums.com/word-vba/16498-multiple-entries-dropdown-lists.html#post46903

PS: You really should get away from the default ActiveX naming conventions and give your content controls meaningful titles.

Title: Referencing Text Content Controls

Body:
I am trying to reference and paste a specified string into a specific Text Content Controls and have been unable to do this properly.

Basically I have gone through and tried a few different things,  first being this;

Private Sub Document_ContentControlOnExit(ByVal ContentControl As ContentControl, Cancel As Boolean)

Dim ccs As ContentControls, cc As ContentControl
Set ccs = ActiveDocument.ContentControls
For Each cc In ccs
  If cc.Title = "ComboBox1" And cc.Range.Text = "Choose an item." Then
  SelectContentControlsByTitle("TextBox1").Add.SetPlaceholderText , , "Please make a drop down selection or manually fill out if not applicable"

The above does not work, as every time I exit my content controller combo box it actually recreates the "placeholdertext" multiple times. I need this to only fill the "TextBox1" Content control.

I have also tried doing something like this,

Dim ccs As ContentControls, cc As ContentControl
Set ccs = ActiveDocument.ContentControls
Set CB1 = SelectContentControlsByTitle("TextBox1")
For Each cc In ccs
  If cc.Title = "ComboBox1" And cc.Range.Text = "Choose an item." Then
  CB1.Value = "Please make a drop down selection or manually fill out if not applicable"

Due to the type, value is not able to be used like this. This does not work either.

Below is the original way I was doing what I wanted with the Active-X TextBox which does work;

Private Sub Document_ContentControlOnExit(ByVal ContentControl As ContentControl, Cancel As Boolean)

Dim ccs As ContentControls, cc As ContentControl
Set ccs = ActiveDocument.ContentControls
For Each cc In ccs
  If cc.Title = "ComboBox2" And cc.Range.Text = "Choose an item." Then
  TextBox2.Value = "Please make a drop down selection or manually fill out if not applicable"

  ElseIf cc.Title = "ComboBox2" And cc.Range.Text = "TMS backup" Then
  TextBox2.Value = "The TMS installation directory, settings directory and the database was backed up before the update was performed"

  ElseIf cc.Title = "ComboBox2" And cc.Range.Text = "TMS installation" Then
  TextBox2.Value = "Installation of version 1.17.X.19XXX performed"

  ElseIf cc.Title = "ComboBox2" And cc.Range.Text = "TMS update" Then
  TextBox2.Value = "Update from version 1.16.X.XXXXX to version 1.17.X.19XXX performed"

  ElseIf cc.Title = "ComboBox2" And cc.Range.Text = "Tool presetter update" Then
  TextBox2.Value = "Update from version 1.16.X.XXXXX to version 1.17.X.19XXX performed"

  ElseIf cc.Title = "ComboBox2" And cc.Range.Text = "Database generated" Then
  TextBox2.Value = "Database structure created with version 1.17.0"

How can I do the above, while using the Text Content Controls?

Body:
A better approach would be:

Private Sub Document_ContentControlOnExit(ByVal Ctrl As ContentControl, Cancel As Boolean)
Dim i As Long, StrDetails As String
With Ctrl
  If .Title = "ComboBox1" Then
  If ShowingPlaceholderText = True Then
    StrDetails = ""
  Else
    For i = 1 To .DropdownListEntries.Count
      If .DropdownListEntries(i).Text = .Range.Text Then
        StrDetails = .DropdownListEntries(i).Value
        Exit For
      End If
    Next
  End If
  ActiveDocument.SelectContentControlsByTitle("TextBox1")(1).Range.Text = StrDetails
  End If
End With
End Sub

To make this work, simply add your 'conditional' text to each entry's 'Value' property, and make the "TextBox1" content control's placeholder text whatever you want its prompt to be. This way, you don't have to hard-code either the dropdown option or the 'conditional' text in your VBA code. For a practical demonstration, see: https://www.msofficeforums.com/word-vba/16498-multiple-entries-dropdown-lists.html#post46903

PS: You really should get away from the default ActiveX naming conventions and give your content controls meaningful titles.


问:
How to display data coming from API in React buttons
I am trying to display the array of data coming from each API call. Let's say I have a /fruits API and /pizza API. I want to display in a table format that's separated by each element in the json array. How would I do this in react, given the API code is working as expected:

```<code>function getFood() {
    const fruitResult = API.get("fruits", "/fruits", params, {
    });
    const pizzaResult = API.get('pizza", "/pizza", params, {

  });
}
</code>```

The json let's say is:

```<code>data: {
  "food": [
    "fruits": [{
       "name":"apple",
       "price":"2.5",
       "weight":"1"
     },
      ...
     ]
  ]

}
</code>```

Ideally, I would want the price/weight to be clickable buttons and it would look something like this:

答:
Since you're not showing how your component looks like.. I'll make you a functional component from scratch.</p>

```<code>import React, { useEffect, useState } from 'react';
function CustomComponent() {
  const [fruits, setFruits] = useState([]);
  const [pizza, setPizzas] = useState([]);
  useEffect(() => {
    function getOdds() {
      const fruitResult = API.get("fruits", "/fruits", params, {
      });
      const pizzaResult = API.get("pizza", "/pizza", params, {
      });
      return Promise.all([fruitResult, pizzaResult])
    }
    getOdds().then(([fruitsRes, pizzasRes]) => {
      setFruits(fruitsRes);
      setPizzas(pizzasRes);
    });
  }
  return (
    <div>
      {fruits.map(fruit => <button>{fruit}</button>)}
    </div>
  )
}
</code>```

Body:
I am trying to display the array of data coming from each API call. Let's say I have a /fruits API and /pizza API. I want to display in a table format that's separated by each element in the json array. How would I do this in react, given the API code is working as expected:

function getFood() {
    const fruitResult = API.get("fruits", "/fruits", params, {
    });
    const pizzaResult = API.get('pizza", "/pizza", params, {

  });
}

The json let's say is:

data: {
  "food": [
    "fruits": [{
       "name":"apple",
       "price":"2.5",
       "weight":"1"
     },
      ...
     ]
  ]

}

Ideally, I would want the price/weight to be clickable buttons and it would look something like this:

Body:
Since you're not showing how your component looks like.. I'll make you a functional component from scratch.

import React, { useEffect, useState } from 'react';
function CustomComponent() {
  const [fruits, setFruits] = useState([]);
  const [pizza, setPizzas] = useState([]);
  useEffect(() => {
    function getOdds() {
      const fruitResult = API.get("fruits", "/fruits", params, {
      });
      const pizzaResult = API.get("pizza", "/pizza", params, {
      });
      return Promise.all([fruitResult, pizzaResult])
    }
    getOdds().then(([fruitsRes, pizzasRes]) => {
      setFruits(fruitsRes);
      setPizzas(pizzasRes);
    });
  }
  return (
    <div>
      {fruits.map(fruit => <button>{fruit}</button>)}
    </div>
  )
}


问:
Why text has underline with yellow color with big font size?
Screenshot of the code and it's result:

Hi, I have StatelessWidget which has Container returning in its build method and the Text widget as a child widget. But it's look and feel is not as expected. Why is the yellow underline and how can I remove it?

I tried replacing the Container with Stack, Column and Row nothing change.

答:
Because of you havent wrap your Text widget with a material widget. You can wrap with a Scaffold or with Material widget with color property as you want.

Example:

```<code>Scaffold(body: Center(child: Text("Here is the text")))
</code>```

or:

```<code>Material(color: Colors.white, child: Center(child: Text("Here is the text")))
</code>```

Body:
Because of you havent wrap your Text widget with a material widget. You can wrap with a Scaffold or with Material widget with color property as you want.

Example:

Scaffold(body: Center(child: Text("Here is the text")))

or:

Material(color: Colors.white, child: Center(child: Text("Here is the text")))


问:
Variables within app.config/web.config
Is it is possible to do something like the following in the app.config or web.config files?

```<code><appSettings>
 <add key="MyBaseDir" value="C:\MyBase" />
 <add key="Dir1" value="[MyBaseDir]\Dir1"/>
 <add key="Dir2" value="[MyBaseDir]\Dir2"/>
</appSettings>
</code>```

I then want to access Dir2 in my code by simply saying:

```<code> ConfigurationManager.AppSettings["Dir2"]
</code>```

This will help me when I install my application in different servers and locations wherein I will only have to change ONE entry in my entire app.config.
(I know I can manage all the concatenation in code, but I prefer it this way).

答:
Good question.

I don't think there is. I believe it would have been quite well known if there was an easy way, and I see that Microsoft is creating a mechanism in Visual Studio 2010 for deploying different configuration files for deployment and test.

With that said, however; I have found that you in the ConnectionStrings section have a kind of placeholder called "|DataDirectory|". Maybe you could have a look at what's at work there...

Here's a piece from machine.config showing it:

```<code> <connectionStrings>
    <add
        name="LocalSqlServer"
        connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true"
        providerName="System.Data.SqlClient"
    />
 </connectionStrings>
</code>```

OwnerDisplayName: DeeStackOverflow

ContentLicense: CC BY-SA 2.5

Title: Variables within app.config/web.config

Body:
Is it is possible to do something like the following in the app.config or web.config files?

<appSettings>
 <add key="MyBaseDir" value="C:\MyBase" />
 <add key="Dir1" value="[MyBaseDir]\Dir1"/>
 <add key="Dir2" value="[MyBaseDir]\Dir2"/>
</appSettings>

I then want to access Dir2 in my code by simply saying:

 ConfigurationManager.AppSettings["Dir2"]

This will help me when I install my application in different servers and locations wherein I will only have to change ONE entry in my entire app.config.
(I know I can manage all the concatenation in code, but I prefer it this way).

LastEditorDisplayName: LFSR Consulting

Body:
Good question.

I don't think there is. I believe it would have been quite well known if there was an easy way, and I see that Microsoft is creating a mechanism in Visual Studio 2010 for deploying different configuration files for deployment and test.

With that said, however; I have found that you in the ConnectionStrings section have a kind of placeholder called "|DataDirectory|". Maybe you could have a look at what's at work there...

Here's a piece from machine.config showing it:

 <connectionStrings>
    <add
        name="LocalSqlServer"
        connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true"
        providerName="System.Data.SqlClient"
    />
 </connectionStrings>

OwnerDisplayName: Arjan Einbu


问:
Flutter Pub: Expected a key while parsing a block mapping. path:
I'm using JSON file and register in Pubspec.ymal but showing error and also when I use an image and register it, the same error also occurs. Maybe there is a formatting mistake in it, but don't know what the problem is.this is the doc I followed.

Error on line 29, column 5 of pubspec.yaml: Expected a key while parsing a block mapping.
  assets:
      ^

This is my pubspec.yaml file

```<code>name: jsondata description: A new Flutter application.

  dependencies:

  flutter:

  sdk: flutter

  cupertino_icons: ^0.1.0

  dev_dependencies:

 flutter_test:

      sdk: flutter

    flutter:

    uses-material-design: true

      assets:

       - loadjson/person.json
</code>```

答: As @Baftek mentioned , just indent before uses-material-design:true and press Ctrl+Alt+l (Intellij or Android Studio) to reformat file.

Body:
I'm using JSON file and register in Pubspec.ymal but showing error and also when I use an image and register it, the same error also occurs. Maybe there is a formatting mistake in it, but don't know what the problem is.this is the doc I followed.

Error on line 29, column 5 of pubspec.yaml: Expected a key while parsing a block mapping.
  assets:
      ^

This is my pubspec.yaml file

name: jsondata description: A new Flutter application.

  dependencies:

  flutter:

  sdk: flutter

  cupertino_icons: ^0.1.0

  dev_dependencies:

 flutter_test:

      sdk: flutter

    flutter:

    uses-material-design: true

      assets:

       - loadjson/person.json


问:
Is there any way for Pandas' read_csv C engine to ignore or replace Unicode parsing errors?
Most questions around reading strings from disk in Python involve codec issues. In contrast, I have a CSV file that just flat out has garbage data in it. Here's how to create an example:

```<code>b = bytearray(b'a,b,c\n1,2,qwe\n10,-20,asdf')
b[10] = 0xff
b[11] = 0xff
with open('foo.csv', 'wb') as fid:
    fid.write(b)
</code>```

Note that the second row, third column has two bytes, 0xFF, which don't represent any encoding, just a small amount of garbage data.

When I try to read this with pandas.read_csv:

```<code>import pandas as pd
df = pd.read_csv('foo.csv') # fails
</code>```

I get an error, naturally:

```<code>  File "pandas/_libs/parsers.pyx", line 881, in pandas._libs.parsers.TextReader.read
  ...
  File "pandas/_libs/parsers.pyx", line 1520, in pandas._libs.parsers._string_box_utf8
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte
</code>```

I can however successfully read this file if I use Pandas' Python CSV engine:

```<code>df2 = pd.read_csv('foo.csv', engine='python') # success
</code>```

In this case, the invalid characters are replaced with U+EFBF characters that Unicode uses to represent "Invalid Character"s.

Question: is there any way for Pandas' C CSV engine to do the same thing as Python's here?

答:
The replacement of invalid characters you see with the python engine corresponds to the errors='replace' mode when encoding a bytes-like object.

You may read the csv using an arbitrary single-byte encoding and transcode columns with this error mode (passing a converter to read_csv or using series.str.encode/decode methods) but it's quite cumbersome since you have to identify a specific set of columns.

For a global effect, since read_csv does not support (yet) the errors parameter, you can pre-open the file with the python built-in open, which does support it.

```<code>df = pd.read_csv(open('foo.csv', errors='replace'))
</code>```

Body:
Most questions around reading strings from disk in Python involve codec issues. In contrast, I have a CSV file that just flat out has garbage data in it. Here's how to create an example:

b = bytearray(b'a,b,c\n1,2,qwe\n10,-20,asdf')
b[10] = 0xff
b[11] = 0xff
with open('foo.csv', 'wb') as fid:
    fid.write(b)

Note that the second row, third column has two bytes, 0xFF, which don't represent any encoding, just a small amount of garbage data.

When I try to read this with pandas.read_csv:

import pandas as pd
df = pd.read_csv('foo.csv') # fails

I get an error, naturally:

  File "pandas/_libs/parsers.pyx", line 881, in pandas._libs.parsers.TextReader.read
  ...
  File "pandas/_libs/parsers.pyx", line 1520, in pandas._libs.parsers._string_box_utf8
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte

I can however successfully read this file if I use Pandas' Python CSV engine:

df2 = pd.read_csv('foo.csv', engine='python') # success

In this case, the invalid characters are replaced with U+EFBF characters that Unicode uses to represent "Invalid Character"s.

Question: is there any way for Pandas' C CSV engine to do the same thing as Python's here?

Body:
The replacement of invalid characters you see with the python engine corresponds to the errors='replace' mode when encoding a bytes-like object.

You may read the csv using an arbitrary single-byte encoding and transcode columns with this error mode (passing a converter to read_csv or using series.str.encode/decode methods) but it's quite cumbersome since you have to identify a specific set of columns.

For a global effect, since read_csv does not support (yet) the errors parameter, you can pre-open the file with the python built-in open, which does support it.

df = pd.read_csv(open('foo.csv', errors='replace'))


问:
how to change part of argument passed to a function in C?
I have function

Oled_logo(const unsigned char *image)

so if i pass

unsigned char giphy_0 [] = {  0x80, 0x81, 0x03, 0x07,
  0x0f, 0x1f, 0x1f, 0x3f, 0x7f, 0xff, 0 };

e.g. -

Oled_logo(giphy_0);

it works

but i got 14 such images naming giphy_0 ,giphy_1 ... giphy_14

so i want to run these one by one to get an animation

i just want to pass arguments to Oled_logo like Oled_logo(giphy_0)  or Oled_log(giphy_1) or Oleg_logo(giphy_2) ,so instead of doing it for 14 times ,i want to call Oled_logo function in loop and change part of argument giphy_imagenumber in loop.

So instead of writing code to call Oled_logo function for 14 times ,i want a loop where i pass giphy_imagenumber to function Oled_logo and this imagenumber is replaced by loop variable ,so i have to write only few lines in a loop.
following i tried

```<code>unsigned char x[] = "giphy_0";
    volatile unsigned char y ;
    while(1)
    {
        for(int image_gif = 0 ; image_gif<=14;image_gif++)
        {

            x[6] = image_gif + 0x30;

        Oled_logo(x);

        ssd1306_UpdateScreen();
        HAL_Delay(4000);
        }
}
</code>```

No error came ,but output is some garbage

I tried with strcat ,converted loop variable to string and concatanate with giphy_ and passed to Oled_logo function
Same problem

What i am doing wrong ?

答:
What you're attempting to do is pass in a string with the name of the variable in question an expecting the program to automatically replace this string with the contents of the variable of that name.  That's not how C works.

The real problem here is how you've defined the arrays.  Rather than having a set of arrays with names containing the array number:

```<code>unsigned char giphy_0 [] = { 0x80, 0x81, 0x03, 0x07, 0x0f, 0x1f, 0x1f, 0x3f, 0x7f, 0xff, 0 };
unsigned char giphy_1 [] = { 0x80, 0x81, 0x03, 0x07, 0x0f, 0x1f, 0x1f, 0x3f, 0x7f, 0xff, 0 };
unsigned char giphy_2 [] = { 0x80, 0x81, 0x03, 0x07, 0x0f, 0x1f, 0x1f, 0x3f, 0x7f, 0xff, 0 };
...
unsigned char giphy_14 [] = { 0x80, 0x81, 0x03, 0x07, 0x0f, 0x1f, 0x1f, 0x3f, 0x7f, 0xff, 0 };
</code>```

Create an array of arrays:

```<code>unsigned char giphy[][11] = {
    { 0x80, 0x81, 0x03, 0x07, 0x0f, 0x1f, 0x1f, 0x3f, 0x7f, 0xff, 0 },
    { 0x80, 0x81, 0x03, 0x07, 0x0f, 0x1f, 0x1f, 0x3f, 0x7f, 0xff, 0 },
    { 0x80, 0x81, 0x03, 0x07, 0x0f, 0x1f, 0x1f, 0x3f, 0x7f, 0xff, 0 },
    ...
    { 0x80, 0x81, 0x03, 0x07, 0x0f, 0x1f, 0x1f, 0x3f, 0x7f, 0xff, 0 },
};
</code>```

And pass loop through the outer dimension:

```<code>    for(int image_gif = 0 ; image_gif<=14; image_gif++)
    {
        Oled_logo(giphy[image_gif]);

        ssd1306_UpdateScreen();
        HAL_Delay(4000);
    }
</code>```

Body:
I have function

Oled_logo(const unsigned char *image)

so if i pass

unsigned char giphy_0 [] = {  0x80, 0x81, 0x03, 0x07,
  0x0f, 0x1f, 0x1f, 0x3f, 0x7f, 0xff, 0 };

e.g. -

Oled_logo(giphy_0);

it works

but i got 14 such images naming giphy_0 ,giphy_1 ... giphy_14

so i want to run these one by one to get an animation

i just want to pass arguments to Oled_logo like Oled_logo(giphy_0)  or Oled_log(giphy_1) or Oleg_logo(giphy_2) ,so instead of doing it for 14 times ,i want to call Oled_logo function in loop and change part of argument giphy_imagenumber in loop.

So instead of writing code to call Oled_logo function for 14 times ,i want a loop where i pass giphy_imagenumber to function Oled_logo and this imagenumber is replaced by loop variable ,so i have to write only few lines in a loop.
following i tried

unsigned char x[] = "giphy_0";
    volatile unsigned char y ;
    while(1)
    {
        for(int image_gif = 0 ; image_gif<=14;image_gif++)
        {

            x[6] = image_gif + 0x30;

        Oled_logo(x);

        ssd1306_UpdateScreen();
        HAL_Delay(4000);
        }
}

No error came ,but output is some garbage

I tried with strcat ,converted loop variable to string and concatanate with giphy_ and passed to Oled_logo function
Same problem

What i am doing wrong ?

Body:
What you're attempting to do is pass in a string with the name of the variable in question an expecting the program to automatically replace this string with the contents of the variable of that name.  That's not how C works.

The real problem here is how you've defined the arrays.  Rather than having a set of arrays with names containing the array number:

unsigned char giphy_0 [] = { 0x80, 0x81, 0x03, 0x07, 0x0f, 0x1f, 0x1f, 0x3f, 0x7f, 0xff, 0 };
unsigned char giphy_1 [] = { 0x80, 0x81, 0x03, 0x07, 0x0f, 0x1f, 0x1f, 0x3f, 0x7f, 0xff, 0 };
unsigned char giphy_2 [] = { 0x80, 0x81, 0x03, 0x07, 0x0f, 0x1f, 0x1f, 0x3f, 0x7f, 0xff, 0 };
...
unsigned char giphy_14 [] = { 0x80, 0x81, 0x03, 0x07, 0x0f, 0x1f, 0x1f, 0x3f, 0x7f, 0xff, 0 };

Create an array of arrays:

unsigned char giphy[][11] = {
    { 0x80, 0x81, 0x03, 0x07, 0x0f, 0x1f, 0x1f, 0x3f, 0x7f, 0xff, 0 },
    { 0x80, 0x81, 0x03, 0x07, 0x0f, 0x1f, 0x1f, 0x3f, 0x7f, 0xff, 0 },
    { 0x80, 0x81, 0x03, 0x07, 0x0f, 0x1f, 0x1f, 0x3f, 0x7f, 0xff, 0 },
    ...
    { 0x80, 0x81, 0x03, 0x07, 0x0f, 0x1f, 0x1f, 0x3f, 0x7f, 0xff, 0 },
};

And pass loop through the outer dimension:

    for(int image_gif = 0 ; image_gif<=14; image_gif++)
    {
        Oled_logo(giphy[image_gif]);

        ssd1306_UpdateScreen();
        HAL_Delay(4000);
    }


问:
React hooks - Remove multi items from array and update state
How to delete multiple items of array and set state? I have selected multiple items from checkbox. This is the selected item [5, 4, 3] I want to remove all items in array based on id and update the state. This is my code.

```<code>const [products, setProducts] = useState();

 const DeleteProducts = () => {
  const selectedItems = [5, 4, 3];

    selectedItems.forEach(function(p) {
      setProducts(products.filter(prd => prd.id !== p));
    });
}
</code>```

Its removing only one item at time, but I selected 3 items. How to remove 3 selected items and  products state?
Thanks

答:
You're calling setProducts ever iteration of the loop. You have to call setProducts after you filter them so that it only triggers state change once

```<code>const [products, setProducts] = useState();

 const DeleteProducts = () => {
  const selectedItems = [5, 4, 3];
  let newProducts;
    selectedItems.forEach(function(p) {
      newProducts = products.filter(prd => prd.id !== p);
    });
  setProducts(newProducts);
}
</code>```

better yet you can filter it faster like this without looping

```<code>
const DeleteProducts = () => {
  const selectedItems = [5, 4, 3];
  const newProducts = products.filter(prd => selectedItems.indexOf(prd.id) >= 0);
  setProducts(newProducts);
}

</code>```

Body:
How to delete multiple items of array and set state? I have selected multiple items from checkbox. This is the selected item [5, 4, 3] I want to remove all items in array based on id and update the state. This is my code.

const [products, setProducts] = useState();

 const DeleteProducts = () => {
  const selectedItems = [5, 4, 3];

    selectedItems.forEach(function(p) {
      setProducts(products.filter(prd => prd.id !== p));
    });
}

Its removing only one item at time, but I selected 3 items. How to remove 3 selected items and  products state?
Thanks

Body:
You're calling setProducts ever iteration of the loop. You have to call setProducts after you filter them so that it only triggers state change once

const [products, setProducts] = useState();

 const DeleteProducts = () => {
  const selectedItems = [5, 4, 3];
  let newProducts;
    selectedItems.forEach(function(p) {
      newProducts = products.filter(prd => prd.id !== p);
    });
  setProducts(newProducts);
}

better yet you can filter it faster like this without looping

const DeleteProducts = () => {
  const selectedItems = [5, 4, 3];
  const newProducts = products.filter(prd => selectedItems.indexOf(prd.id) >= 0);
  setProducts(newProducts);
}


问:
Randomly grab 3 items from an array, where the 3rd item can be a “restaurant" but does not have to be
I apologize for the poorly written title. I was not sure how exactly to write it. I have an array. I need to randomly grab three items from the array. Only one item can be a "restaurant" and the restaurant can ONLY ever go in the third position.

Let me explain with an example. here is a sample array

```<code>el 1 - restaurant = false
el 2 - restaurant = true
el 3 - restaurant = true
el 4 - restaurant = false
el 5 - restaurant = false
el 6 - restaurant = false
el 7 - restaurant = true
el 8 - restaurant = false
el 9 - restaurant = false
</code>```

My current code loops through this array and randomly grabs three items. Positions 1 and 2 can NEVER have a restaurant in them so they have to be taken from the items with the restaurant property set to false. The 3rd position can have a restaurant but I don't want it to always be a restaurant.

Here is my current code:

```<code>const amountOfLocations = 3

// have list of locations
// shuffle it
for (let i = locations.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [locations[i], locations[j]] = [locations[j], locations[i]];
}

let selectedLocations = locations.slice(0, amountOfLocations)
</code>```

My initial thought is I need to grab only 2 items from this current loop instead of 3, then using the original array remove these two items and shuffle the array up again to randomly grab one more item which will then be placed in the 3rd position.

答:
You can try something like this.

```<code>    var array1 = [
     {'restaurant': true},
     {'restaurant': false},
     {'restaurant': false},
     {'restaurant': true},
     {'restaurant': false},
     {'restaurant': true},
     {'restaurant': false},
     {'restaurant': false},
     {'restaurant': false},
     {'restaurant': false},
     {'restaurant': true}
    ];

    var array2 = array1.filter((v) => {
      return v.restaurant === false;
    }).slice(0, 2);
    array2.push(array1[Math.floor(Math.random() * array1.length)]);

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

Here's a link to fiddle. https://jsfiddle.net/90gda2sb/

Body:
I apologize for the poorly written title. I was not sure how exactly to write it. I have an array. I need to randomly grab three items from the array. Only one item can be a "restaurant" and the restaurant can ONLY ever go in the third position.

Let me explain with an example. here is a sample array

el 1 - restaurant = false
el 2 - restaurant = true
el 3 - restaurant = true
el 4 - restaurant = false
el 5 - restaurant = false
el 6 - restaurant = false
el 7 - restaurant = true
el 8 - restaurant = false
el 9 - restaurant = false

My current code loops through this array and randomly grabs three items. Positions 1 and 2 can NEVER have a restaurant in them so they have to be taken from the items with the restaurant property set to false. The 3rd position can have a restaurant but I don't want it to always be a restaurant.

Here is my current code:

const amountOfLocations = 3

// have list of locations
// shuffle it
for (let i = locations.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [locations[i], locations[j]] = [locations[j], locations[i]];
}

let selectedLocations = locations.slice(0, amountOfLocations)

My initial thought is I need to grab only 2 items from this current loop instead of 3, then using the original array remove these two items and shuffle the array up again to randomly grab one more item which will then be placed in the 3rd position.

Body:
You can try something like this.

    var array1 = [
     {'restaurant': true},
     {'restaurant': false},
     {'restaurant': false},
     {'restaurant': true},
     {'restaurant': false},
     {'restaurant': true},
     {'restaurant': false},
     {'restaurant': false},
     {'restaurant': false},
     {'restaurant': false},
     {'restaurant': true}
    ];

    var array2 = array1.filter((v) => {
      return v.restaurant === false;
    }).slice(0, 2);
    array2.push(array1[Math.floor(Math.random() * array1.length)]);

console.log(array2);

Here's a link to fiddle. https://jsfiddle.net/90gda2sb/


问:
Extracting data from a pdf, turning into a QR code and inserting the pdf and QR codes into a word.doc
In a nutshell - i want to take an existing PDF and read just the tool numbers and add barcodes for the tool number to the PDF/Word doc. since word will convert pdf's.

I need some ideas to get data from a PDF which is a printout of an access database.
So we pull up the doc after filling out a few things on the form (access) then we print it. well this database is not available for me to play around with so i wanted to print to a PDF and then read the "TOOL NUMBERS"using TABULA or something similar then export to excel. turn them into either 39extended barcode or QR code. then import into word the original PDF and insert the BAR CODE under the tool number and print.  yes crazy as it sounds this is the only work around i can come up with.
i wrote the excel column with tool numbers to QR code (.png's) "toolnumber.png". or is there a way for me to find the MDB file and extract data from that? the column in that datafile should be "ToolNumber".

答: Since you ultimately want the output in Excel, there's no need to involve Word or PDFs in the process at all - simply query the Access DB directly from Excel and format the output as required.</p>


问:
Align a div to the bottom of its parent div while maintaining the parent height of 100VH and not using fixed positioning
Here is my fiddle: https://jsfiddle.net/cwverdkt/.

I am trying to keep "hello" in the center and the photo of the dog on the bottom left. I need the main div to be 100vh and not relative because I am going to implement parallax scrolling and I can't have the dog always be on the bottom.

I have tried:

```<code>#photo{
  bottom: 0;
}
</code>```

and

```<code>#photo{
  display: inline-block;
  align-self: flex-end;
}
</code>```

and

.bottom-aligner {
  display: inline-block;
  height: 100%;
  vertical-align: bottom;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="bottom-aligner">
  <div id="dog">
    <img src="http://i.imgur.com/FleWUfc.png" />
  </div>
</div></code>```

The last one sort of worked except it cropped the photo of the dog.

Here's a screenshot of what I want to make it look like:

答:
Just added CSS below mentioned. Demo try this</p>

```<code>#slide3{display:table}
#photo {
    width: 100%;
    bottom: 0;
    height: 100vh;
    vertical-align: bottom;
    display: table-cell;
}
</code>```

Body:
Here is my fiddle: https://jsfiddle.net/cwverdkt/.

I am trying to keep "hello" in the center and the photo of the dog on the bottom left. I need the main div to be 100vh and not relative because I am going to implement parallax scrolling and I can't have the dog always be on the bottom.

I have tried:

#photo{
  bottom: 0;
}

and

#photo{
  display: inline-block;
  align-self: flex-end;
}

and

.bottom-aligner {
  display: inline-block;
  height: 100%;
  vertical-align: bottom;
}

The last one sort of worked except it cropped the photo of the dog.

Here's a screenshot of what I want to make it look like:

Body:
Just added CSS below mentioned. Demo try this

#slide3{display:table}
#photo {
    width: 100%;
    bottom: 0;
    height: 100vh;
    vertical-align: bottom;
    display: table-cell;
}


问:
gunicorn + flask (connexion/swagger_server) time out/not responding to API requests
swagger_server connexion/flask running fine when I do:

```<code>python3 -m swagger_server
</code>```

It's running on port 8080.

When I try to put it on gunicorn (reference: how to use gunicorn with swagger_server on flask), gunicorn runs fine but requests to port 8080 fail.

First, when I use the same port 8080, it complains of bind/already in use (expected, I believe, as they're both on port 8080):

```<code>gunicorn "swagger_server.__main__:main" -b 0.0.0.0:8080 -w 4
...
OSError: [Errno 48] Address already in use
</code>```

But when I move to port 4000, for example, requests time out:

```<code>gunicorn "swagger_server.__main__:main" -b 0.0.0.0:4000 -w 4
...
 * Running on http://0.0.0.0:8080/ (Press CTRL+C to quit)
[2020-02-16 17:21:18 -0500] [34798] [CRITICAL] WORKER TIMEOUT (pid:34802)
</code>```

When I enable debug, I see it's trying to connect to port 4000, instead of 8080.

```<code>[2020-02-16 17:28:13 -0500] [34866] [INFO] Starting gunicorn 20.0.4
[2020-02-16 17:28:13 -0500] [34866] [ERROR] Connection in use: ('0.0.0.0', 4000)
[2020-02-16 17:28:13 -0500] [34866] [ERROR] Retrying in 1 second.
[2020-02-16 17:28:14 -0500] [34866] [ERROR] Connection in use: ('0.0.0.0', 4000)
...
</code>```

Here's my main.py

```<code>def main(arg1, arg2):
    app = connexion.App(__name__, specification_dir='./swagger_server/', debug=False)
    app.app.json_encoder = encoder.JSONEncoder
    app.add_api('api-v2.yaml', arguments={'title': 'API'})
    app.run(host='0.0.0.0', port=8080)

if __name__ == '__main__':
    main(None, None)
</code>```

Please advise what I'm missing here.  Thank you.

答:
Swagger generates __main__.py in wrong way, you need to make a modifition base on it.

```<code>#!/usr/bin/env python3

import connexion

from swagger_server import encoder

app = connexion.App(__name__, specification_dir='./swagger/')
app.app.json_encoder = encoder.JSONEncoder
app.add_api('swagger.yaml', arguments={'title': 'My API'}, pythonic_params=True)
</code>```

Then try it again

```<code>gunicorn swagger_server.__main__:app
</code>```

Gunicorn wraps netowrk request in WSGI and forward to flask(werkzeug), the varible app in __main__.py is werkzeug WSGI entry point.

Body:
swagger_server connexion/flask running fine when I do:

python3 -m swagger_server

It's running on port 8080.

When I try to put it on gunicorn (reference: how to use gunicorn with swagger_server on flask), gunicorn runs fine but requests to port 8080 fail.

First, when I use the same port 8080, it complains of bind/already in use (expected, I believe, as they're both on port 8080):

gunicorn "swagger_server.__main__:main" -b 0.0.0.0:8080 -w 4
...
OSError: [Errno 48] Address already in use

But when I move to port 4000, for example, requests time out:

gunicorn "swagger_server.__main__:main" -b 0.0.0.0:4000 -w 4
...
 * Running on http://0.0.0.0:8080/ (Press CTRL+C to quit)
[2020-02-16 17:21:18 -0500] [34798] [CRITICAL] WORKER TIMEOUT (pid:34802)

When I enable debug, I see it's trying to connect to port 4000, instead of 8080.

[2020-02-16 17:28:13 -0500] [34866] [INFO] Starting gunicorn 20.0.4
[2020-02-16 17:28:13 -0500] [34866] [ERROR] Connection in use: ('0.0.0.0', 4000)
[2020-02-16 17:28:13 -0500] [34866] [ERROR] Retrying in 1 second.
[2020-02-16 17:28:14 -0500] [34866] [ERROR] Connection in use: ('0.0.0.0', 4000)
...

Here's my main.py

def main(arg1, arg2):
    app = connexion.App(__name__, specification_dir='./swagger_server/', debug=False)
    app.app.json_encoder = encoder.JSONEncoder
    app.add_api('api-v2.yaml', arguments={'title': 'API'})
    app.run(host='0.0.0.0', port=8080)

if __name__ == '__main__':
    main(None, None)

Please advise what I'm missing here.  Thank you.

Body:
Swagger generates __main__.py in wrong way, you need to make a modifition base on it.

#!/usr/bin/env python3

import connexion

from swagger_server import encoder

app = connexion.App(__name__, specification_dir='./swagger/')
app.app.json_encoder = encoder.JSONEncoder
app.add_api('swagger.yaml', arguments={'title': 'My API'}, pythonic_params=True)

Then try it again

gunicorn swagger_server.__main__:app

Gunicorn wraps netowrk request in WSGI and forward to flask(werkzeug), the varible app in __main__.py is werkzeug WSGI entry point.


问:
How to check checkbox array values exist from database PHP Laravel?
I want to check either the countries exist in countries and the checkbox will be displayed. The values is directly from the database. I can't set the value at the input since it is array/multiple values. So, I want to check every array so that it will be a checkbox.

Controller :

```<code>public function edit($id)
{
    $region = Region::find($id);
    $countries = Country::all();
    $country_region = DB::table('regions')
        ->select('countries.id', 'countries.name')
        ->join('country_region', 'regions.id', '=', 'country_region.region_id')
        ->join('countries', 'country_region.country_id', '=', 'countries.id')
        ->where('regions.id', '=', $id)
        ->get();

    $items = array(
        'region' => $region,
        'countries' => $countries,
        'country_region' => $country_region,
    );

    return view('admin.region.edit')->with($items);
}
</code>```

blade

```<code><div class="form-group">
    <label>Choose Country</label>
    <select id="test" type="checkbox" name="country_id[]">
        @foreach ($countries as $item)
        <option value="{{$item->id}}" selected @if (in_array($item->id, array_keys($country_region))) checked="checked"
            @endif>{{$item->name}}
        </option>
        @endforeach
    </select>
</div>
</code>```

As you can see, I put php statement inside the blade to check either $country_region is exist in the countries or not. I got errors that related to the array such below :

```<code>array_keys() expects parameter 1 to be array, object given
</code>```

Database :

Country Region Table :

Region Table :

Country Table :

答:
I don't think you need array function there like in_array since you are already looping each country, simple if should work, also please show the content of tables you are trying to compare.

```<code><div class="form-group">
    <label>Choose Country</label>
    <select id="test" type="checkbox" name="country_id[]">
        @foreach ($countries as $item)
        <option value="{{$item->id}}" selected @if ($item->id == $country_region.country.id) checked="checked"
            @endif>{{$item->name}}
        </option>
        @endforeach
    </select>
</div>
</code>```

Body:
I want to check either the countries exist in countries and the checkbox will be displayed. The values is directly from the database. I can't set the value at the input since it is array/multiple values. So, I want to check every array so that it will be a checkbox.

Controller :

public function edit($id)
{
    $region = Region::find($id);
    $countries = Country::all();
    $country_region = DB::table('regions')
        ->select('countries.id', 'countries.name')
        ->join('country_region', 'regions.id', '=', 'country_region.region_id')
        ->join('countries', 'country_region.country_id', '=', 'countries.id')
        ->where('regions.id', '=', $id)
        ->get();

    $items = array(
        'region' => $region,
        'countries' => $countries,
        'country_region' => $country_region,
    );

    return view('admin.region.edit')->with($items);
}

blade

    Choose Country
    <select id="test" type="checkbox" name="country_id[]">
        @foreach ($countries as $item)
        <option value="{{$item->id}}" selected @if (in_array($item->id, array_keys($country_region))) checked="checked"
            @endif>{{$item->name}}
        </option>
        @endforeach
    </select>

As you can see, I put php statement inside the blade to check either $country_region is exist in the countries or not. I got errors that related to the array such below :

array_keys() expects parameter 1 to be array, object given

Database :

Country Region Table :

Region Table :

Country Table :

Body:
I don't think you need array function there like in_array since you are already looping each country, simple if should work, also please show the content of tables you are trying to compare.

<div class="form-group">
    <label>Choose Country</label>
    <select id="test" type="checkbox" name="country_id[]">
        @foreach ($countries as $item)
        <option value="{{$item->id}}" selected @if ($item->id == $country_region.country.id) checked="checked"
            @endif>{{$item->name}}
        </option>
        @endforeach
    </select>
</div>


问:
What is the algorithm used in sort method in dart?
I found out that dart language has a built-in sort method in List class and I would like to know what is the algorithm they used in this method and what is the Big O notation of it?</p>

答:
At https://dartpad.dartlang.org/, try the following code.  I can't answer your question about what the implementation is under the covers, but you can bet it's O(n log n).

I'm using an answer because I can't supply code in a comment easily.

```<code>void main() {
  Map<String, int> map = {'a': 1, 'b': 2};

  List<String> list = ['banana', 'apple', 'age', 'bob'];

  list.sort((String a, String b) => a.compareTo(b));
  print(list);
}
</code>```

BTW list.sort(); would give the same results since that custom comparitor is the same as the default.

Body:
At https://dartpad.dartlang.org/, try the following code.  I can't answer your question about what the implementation is under the covers, but you can bet it's O(n log n).

I'm using an answer because I can't supply code in a comment easily.

void main() {
  Map<String, int> map = {'a': 1, 'b': 2};

  List<String> list = ['banana', 'apple', 'age', 'bob'];

  list.sort((String a, String b) => a.compareTo(b));
  print(list);
}

BTW list.sort(); would give the same results since that custom comparitor is the same as the default.


问:
Hooks useCallback keeps using old values when refreshing list
What is wrong with the useCallback below that I do not get the values below every time the function onRefresh is called ?
How can I make it return the expected values using Hooks?

Example when I call onRefresh 2x

values expected:

```<code>true
0
20
false

true
0
20
false
</code>```

values: received

```<code>false
0
0
false

false
20
20
false
</code>```

initialization of the state variables

```<code>const [refreshing, setRefreshing] = useState(false)
const [offsetQuestions, setOffsetQuestions] = useState(0)
</code>```

Function call with useCallback:

```<code>const fetchSomeData = async () => {
  await new Promise(resolve => setTimeout(resolve, 3000)) // 3 sec
}

const onRefresh = useCallback( async () => {
  setRefreshing(true)
  setOffsetQuestions(0)
  console.log(refreshing)
  console.log(offsetQuestions)

  await fetchSomeData()

  setOffsetQuestions(20)
  setRefreshing(false)
  console.log(offsetQuestions)
  console.log(refreshing)
}, [refreshing, offsetQuestions])
</code>```

Where the function is called:

```<code><FlatList
   data={questionsLocal}
   refreshing={refreshing}
   onRefresh={onRefresh}
   ...
/>
</code>```

答: What you are getting is the expected behaviour in hooks. It's all about closures. Each render in react has its own props, state, functions and event handlers and they forever stay the same for that particular render. So whats happening here is that the useCallback is closing over the state variables for that particular render, So the console.log even after a setState will always give you the value of the state for that particular render because of closure.

Body:
What is wrong with the useCallback below that I do not get the values below every time the function onRefresh is called ?
How can I make it return the expected values using Hooks?

Example when I call onRefresh 2x

values expected:

true
0
20
false

true
0
20
false

values: received

false
0
0
false

false
20
20
false

initialization of the state variables

const [refreshing, setRefreshing] = useState(false)
const [offsetQuestions, setOffsetQuestions] = useState(0)

Function call with useCallback:

const fetchSomeData = async () => {
  await new Promise(resolve => setTimeout(resolve, 3000)) // 3 sec
}

const onRefresh = useCallback( async () => {
  setRefreshing(true)
  setOffsetQuestions(0)
  console.log(refreshing)
  console.log(offsetQuestions)

  await fetchSomeData()

  setOffsetQuestions(20)
  setRefreshing(false)
  console.log(offsetQuestions)
  console.log(refreshing)
}, [refreshing, offsetQuestions])

Where the function is called:

<FlatList
   data={questionsLocal}
   refreshing={refreshing}
   onRefresh={onRefresh}
   ...
/>


问:
How to make the history logs store in the spreadsheet?
I've created a simple counter which has a single textbox, disabled box and a history to record all previous value in the disabled box.

It works perfectly, but somehow when the page is accidentally refreshed all the logs are deleted.

Is there a way to keep that record even if the page reload? Or maybe store it in a spreadsheet?

CODE :

```<code>let box1 = document.getElementById("box1");
let box2 = document.getElementById("box2");
let resetBtn = document.getElementById("reset");
let historyContainer = document.getElementById("history");
let history = [];

//listen key enter press on the input
box1.addEventListener("keyup", e => {
  if (e.key === "Enter" && e.target.value !== "") {
  const summedValue = (box2.value && box2.value.trim() === "")  ? Number(box2.value) : Number(box2.value) + Number(e.target.value)
  box2.value = summedValue;
  historyContainer.innerHTML += `<p>${box2.value}</p>`;
  box1.value = "";
  }
});
//reset the second box and
resetBtn.addEventListener("click", () => {
  box2.value = "";
  historyContainer.innerHTML = ""
});
<input type="number" id="box1" />
<input type="number" id="box2" disabled />
<div id="history">
</div>

<button type="button" id="reset">
Reset
</button>
</code>```

答:
You can use storage api to achieve your ideas, here I use localStorage as an example

Stores array data named history, and updates the storage location every time it is added

```<code>//listen key enter press on the input
box1.addEventListener("keyup", e => {
  if (e.key === "Enter" && e.target.value !== "") {
    const summedValue = (box2.value && box2.value.trim() === "") ? Number(box2.value) : Number(box2.value) + Number(e.target.value)
    box2.value = summedValue;

    history.push(summedValue);

    // Store data
    localStorage.setItem("history", history);

    historyContainer.innerHTML += `<p>${box2.value}</p>`;
    box1.value = "";
  }
});
</code>```

Remove the storage array data when pressing the reset button

```<code>//reset the second box and
resetBtn.addEventListener("click", () => {
  box2.value = "";
  historyContainer.innerHTML = "";
  // Remove data
  localStorage.removeItem('history');
});
</code>```

When the page is refreshed, read the storage location. If it is not undefined and the length is greater than 0, then take out the data and put it on the screen

```<code>document.addEventListener("DOMContentLoaded", function() {
  // Get data
  const local_history = localStorage.getItem("history");
  if (typeof local_history !== "undefined" && local_history.length > 0) {
    let html_str = "";
    local_history.forEach(element => {
      html_str += `<p>${element}</p>`;
    });
    historyContainer.innerHTML = html_str;
  }
});
</code>```

Body:
I've created a simple counter which has a single textbox, disabled box and a history to record all previous value in the disabled box.

It works perfectly, but somehow when the page is accidentally refreshed all the logs are deleted.

Is there a way to keep that record even if the page reload? Or maybe store it in a spreadsheet?

CODE :

let box1 = document.getElementById("box1");
let box2 = document.getElementById("box2");
let resetBtn = document.getElementById("reset");
let historyContainer = document.getElementById("history");
let history = [];

//listen key enter press on the input
box1.addEventListener("keyup", e => {
  if (e.key === "Enter" && e.target.value !== "") {
  const summedValue = (box2.value && box2.value.trim() === "")  ? Number(box2.value) : Number(box2.value) + Number(e.target.value)
  box2.value = summedValue;
  historyContainer.innerHTML += `<p>${box2.value}</p>`;
  box1.value = "";
  }
});
//reset the second box and
resetBtn.addEventListener("click", () => {
  box2.value = "";
  historyContainer.innerHTML = ""
});
<input type="number" id="box1" />
<input type="number" id="box2" disabled />

<button type="button" id="reset">
Reset
</button>

Body:
You can use storage api to achieve your ideas, here I use localStorage as an example

Stores array data named history, and updates the storage location every time it is added

//listen key enter press on the input
box1.addEventListener("keyup", e => {
  if (e.key === "Enter" && e.target.value !== "") {
    const summedValue = (box2.value && box2.value.trim() === "") ? Number(box2.value) : Number(box2.value) + Number(e.target.value)
    box2.value = summedValue;

    history.push(summedValue);

    // Store data
    localStorage.setItem("history", history);

    historyContainer.innerHTML += `<p>${box2.value}</p>`;
    box1.value = "";
  }
});

Remove the storage array data when pressing the reset button

//reset the second box and
resetBtn.addEventListener("click", () => {
  box2.value = "";
  historyContainer.innerHTML = "";
  // Remove data
  localStorage.removeItem('history');
});

When the page is refreshed, read the storage location. If it is not undefined and the length is greater than 0, then take out the data and put it on the screen

document.addEventListener("DOMContentLoaded", function() {
  // Get data
  const local_history = localStorage.getItem("history");
  if (typeof local_history !== "undefined" && local_history.length > 0) {
    let html_str = "";
    local_history.forEach(element => {
      html_str += `<p>${element}</p>`;
    });
    historyContainer.innerHTML = html_str;
  }
});


问:
Invoke one stored procedure from another stored procedure by passing array values in postgresql
I'm unable to pass the array values as input to another stored procedure. However when I try to insert(table kvstore populated without issues) the array values, the table get loaded. Please advice me on how to pass array values dynamically from one stored procedure to another.

The raise notice prints values like below
NOTICE:  Value 1:
NOTICE:  Value 2:

```<code>
CREATE OR REPLACE FUNCTION test_schema.test_insert_choice(
    p_member_crn  character varying,
    p_preferencearray text[][],
    p_created timestamp without time zone,
    p_modified timestamp without time zone,
    p_created_system smallint,
    p_created_by character varying,
    p_modified_by character varying,
    p_modified_system smallint
    )
  RETURNS text AS
$BODY$
DECLARE

    lv_n_rtn                INTEGER ;
    lv_t_err_msg            TEXT ;
    lv_t_err_dtl            TEXT ;

BEGIN

    /*FOR i IN 1 .. array_upper(p_preferencearray, 1) LOOP
        INSERT INTO lcdm_main.kvstore (key, value)
        VALUES (p_preferencearray[i][1], p_preferencearray[i][2]);
    END LOOP;*/

    FOR i IN 1 .. array_upper(p_preferencearray, 1) LOOP
    raise notice 'Value 1: %', p_preferencearray[i][1];
    raise notice 'Value 2: %', p_preferencearray[i][2];
        perform  test_schema.test_insert_master(p_member_crn,
                                                         p_preferencearray[i][1],
                                                         p_preferencearray[i][2],
                                                         p_created,
                                                         p_modified,
                                                         p_created_system,
                                                         p_created_by,
                                                         p_modified_by,
                                                         p_modified_system);
    END LOOP;

    RETURN 0;

END;

$BODY$
  LANGUAGE plpgsql VOLATILE SECURITY DEFINER
  COST 100;```
```

答:
Found the solution and replacing FOR with FOREACH helped to resolve the issue

```<code>CREATE OR REPLACE FUNCTION test_schema.test_insert_choice(
    p_member_crn  character varying,
    p_preferencearray text[][],
    p_created timestamp without time zone,
    p_modified timestamp without time zone,
    p_created_system smallint,
    p_created_by character varying,
    p_modified_by character varying,
    p_modified_system smallint
    )
  RETURNS text AS
$BODY$
DECLARE

    lv_n_rtn                INTEGER ;
    lv_t_err_msg            TEXT ;
    lv_t_err_dtl            TEXT ;

       m   text[];
       arr text[] := p_preferencearray;

BEGIN

   FOREACH m SLICE 1 IN ARRAY arr
   LOOP
       perform  test_schema.test_insert_master(p_member_crn,
                                                         m[1],  --Preference Id
                                                         m[2],  --Preference Value
                                                         p_created,
                                                         p_modified,
                                                         p_created_system,
                                                         p_created_by,
                                                         p_modified_by,
                                                         p_modified_system);
   END LOOP;

    RETURN 0;

END;

$BODY$
  LANGUAGE plpgsql VOLATILE SECURITY DEFINER
  COST 100;
</code>```

Thanks for everyone

Body:
I'm unable to pass the array values as input to another stored procedure. However when I try to insert(table kvstore populated without issues) the array values, the table get loaded. Please advice me on how to pass array values dynamically from one stored procedure to another.

The raise notice prints values like below
NOTICE:  Value 1:
NOTICE:  Value 2:

CREATE OR REPLACE FUNCTION test_schema.test_insert_choice(
    p_member_crn  character varying,
    p_preferencearray text[][],
    p_created timestamp without time zone,
    p_modified timestamp without time zone,
    p_created_system smallint,
    p_created_by character varying,
    p_modified_by character varying,
    p_modified_system smallint
    )
  RETURNS text AS
$BODY$
DECLARE

    lv_n_rtn                INTEGER ;
    lv_t_err_msg            TEXT ;
    lv_t_err_dtl            TEXT ;

BEGIN

    /*FOR i IN 1 .. array_upper(p_preferencearray, 1) LOOP
        INSERT INTO lcdm_main.kvstore (key, value)
        VALUES (p_preferencearray[i][1], p_preferencearray[i][2]);
    END LOOP;*/

    FOR i IN 1 .. array_upper(p_preferencearray, 1) LOOP
    raise notice 'Value 1: %', p_preferencearray[i][1];
    raise notice 'Value 2: %', p_preferencearray[i][2];
        perform  test_schema.test_insert_master(p_member_crn,
                                                         p_preferencearray[i][1],
                                                         p_preferencearray[i][2],
                                                         p_created,
                                                         p_modified,
                                                         p_created_system,
                                                         p_created_by,
                                                         p_modified_by,
                                                         p_modified_system);
    END LOOP;

    RETURN 0;

END;

$BODY$
  LANGUAGE plpgsql VOLATILE SECURITY DEFINER
  COST 100;```

Body:
Found the solution and replacing FOR with FOREACH helped to resolve the issue

CREATE OR REPLACE FUNCTION test_schema.test_insert_choice(
    p_member_crn  character varying,
    p_preferencearray text[][],
    p_created timestamp without time zone,
    p_modified timestamp without time zone,
    p_created_system smallint,
    p_created_by character varying,
    p_modified_by character varying,
    p_modified_system smallint
    )
  RETURNS text AS
$BODY$
DECLARE

    lv_n_rtn                INTEGER ;
    lv_t_err_msg            TEXT ;
    lv_t_err_dtl            TEXT ;

       m   text[];
       arr text[] := p_preferencearray;

BEGIN

   FOREACH m SLICE 1 IN ARRAY arr
   LOOP
       perform  test_schema.test_insert_master(p_member_crn,
                                                         m[1],  --Preference Id
                                                         m[2],  --Preference Value
                                                         p_created,
                                                         p_modified,
                                                         p_created_system,
                                                         p_created_by,
                                                         p_modified_by,
                                                         p_modified_system);
   END LOOP;

    RETURN 0;

END;

$BODY$
  LANGUAGE plpgsql VOLATILE SECURITY DEFINER
  COST 100;

Thanks for everyone


问:
How to make a UIView transparent while presenting it from UITableViewCell with UITapGestureRecognizer?
I presented a UINib (custom AlertView) from UITableviewCell by tapping on UILabel. UINib is having two views, one is for custom alert and the background view is to show an alert view effect by making it transparent.

```<code>@objc func taptakeYourMedsDescriptionLabel(tapGestureRecognizer: UITapGestureRecognizer) {
    let undectableVC = UndetectableAlertVC(nibName: "UndetectableAlertVC", bundle: nil)
    undectableVC.view.backgroundColor = UIColor.black.withAlphaComponent(0.1)
    UIApplication.shared.keyWindow?.rootViewController?.present(undectableVC, animated: true, completion: nil)
 }
</code>```

I also gave undectableVC.view.backgroundColor = UIColor.black.withAlphaComponent(0.1) in viewWillAppear of UndetectableAlertVC

Problem: The view is transparent while presenting it but soon after the view is presented it is changing to black color.

Requirement:

Can anyone help me with this?

答:
Try This   </p>

```<code>let undectableVC = UndetectableAlertVC(nibName: "UndetectableAlertVC", bundle: nil)
undectableVC.view.backgroundColor = UIColor.black.withAlphaComponent(0.5)

undectableVC.modalPresentationStyle = .custom
undectableVC.modalTransitionStyle = .crossDissolve
self.navigationController?.present(undectableVC, animated: true, completion: nil)
</code>```

Body:
I presented a UINib (custom AlertView) from UITableviewCell by tapping on UILabel. UINib is having two views, one is for custom alert and the background view is to show an alert view effect by making it transparent.

@objc func taptakeYourMedsDescriptionLabel(tapGestureRecognizer: UITapGestureRecognizer) {
    let undectableVC = UndetectableAlertVC(nibName: "UndetectableAlertVC", bundle: nil)
    undectableVC.view.backgroundColor = UIColor.black.withAlphaComponent(0.1)
    UIApplication.shared.keyWindow?.rootViewController?.present(undectableVC, animated: true, completion: nil)
 }

I also gave undectableVC.view.backgroundColor = UIColor.black.withAlphaComponent(0.1) in viewWillAppear of UndetectableAlertVC

Problem: The view is transparent while presenting it but soon after the view is presented it is changing to black color.

Requirement:

Can anyone help me with this?

Body:
Try This

let undectableVC = UndetectableAlertVC(nibName: "UndetectableAlertVC", bundle: nil)
undectableVC.view.backgroundColor = UIColor.black.withAlphaComponent(0.5)

undectableVC.modalPresentationStyle = .custom
undectableVC.modalTransitionStyle = .crossDissolve
self.navigationController?.present(undectableVC, animated: true, completion: nil)


答: make sure that $country_region is an array</p>

Title: How to check checkbox array values exist from database PHP Laravel?


问:
VBA- Is it possible to code an If/Then statement based on if a trimmed text changes color from black to white
Current code below doesn't work because it finds the RsnChng is always = "Reason".

Initially where I thought the term "Reason" was popping up, I figured I could just code for that, but in actuality it's always there just not visible because it's colored black same as the background so you don't see it, - the text color for it turns white when it needs an action done.

So is there a way I could toss into the code below to determine the text color is white and then execute the code?

```<code>RsnChng = Trim(HE.CurrentHost.TextRC(20, 2, 6))
If RsnChng = "Reason" Then
    HE.CurrentHost.PutText "Finished by MPT055", 20, 20
    Utilities.PressKey "ENTER", False, UseIBM1, "6", , "YES", "BUTTONS"
End If
</code>```

Thanks in advance,
Mike

答:
You can use the following code to get Font Color:

```<code>Function GetFontColor(Target As Range) As Integer
    GetFontColor = Target.Font.ColorIndex
End Function
</code>```

Then use the same in IF condition.

```<code>If GetFontColor(Range("A1"))=2 then
...
End If
</code>```

And if you want to check Cell color then use the following

```<code>If Range("A1").Interior.Color = RGB(255, 255, 255) Then
...
End If
</code>```

Body:
Current code below doesn't work because it finds the RsnChng is always = "Reason".

Initially where I thought the term "Reason" was popping up, I figured I could just code for that, but in actuality it's always there just not visible because it's colored black same as the background so you don't see it, - the text color for it turns white when it needs an action done.

So is there a way I could toss into the code below to determine the text color is white and then execute the code?

RsnChng = Trim(HE.CurrentHost.TextRC(20, 2, 6))
If RsnChng = "Reason" Then
    HE.CurrentHost.PutText "Finished by MPT055", 20, 20
    Utilities.PressKey "ENTER", False, UseIBM1, "6", , "YES", "BUTTONS"
End If

Thanks in advance,
Mike

Body:
You can use the following code to get Font Color:

Function GetFontColor(Target As Range) As Integer
    GetFontColor = Target.Font.ColorIndex
End Function

Then use the same in IF condition.

If GetFontColor(Range("A1"))=2 then
...
End If

And if you want to check Cell color then use the following

If Range("A1").Interior.Color = RGB(255, 255, 255) Then
...
End If


答:
You could continue using the shuffle method so you don't end up selecting duplicates like with plain random indexing, then you just extract the first element from the shuffled array and call it "third". Then you filter out non-restaurants (and slice the first index before because we've already selected it) and select any 2 elements:</p>

```<code>for (let i = locations.length - 1; i > 0; i--) {
  const j = Math.floor(Math.random() * (i + 1));
  [locations[i], locations[j]] = [locations[j], locations[i]];
}

let third = locations[0];
let [first, second] = locations.slice(1).filter(l => !l.restaurant);
let selectedLocations = [first, second, third];
</code>```

Title: Randomly grab 3 items from an array, where the 3rd item can be a “restaurant" but does not have to be

Body:
I apologize for the poorly written title. I was not sure how exactly to write it. I have an array. I need to randomly grab three items from the array. Only one item can be a "restaurant" and the restaurant can ONLY ever go in the third position.

Let me explain with an example. here is a sample array

el 1 - restaurant = false
el 2 - restaurant = true
el 3 - restaurant = true
el 4 - restaurant = false
el 5 - restaurant = false
el 6 - restaurant = false
el 7 - restaurant = true
el 8 - restaurant = false
el 9 - restaurant = false

My current code loops through this array and randomly grabs three items. Positions 1 and 2 can NEVER have a restaurant in them so they have to be taken from the items with the restaurant property set to false. The 3rd position can have a restaurant but I don't want it to always be a restaurant.

Here is my current code:

const amountOfLocations = 3

// have list of locations
// shuffle it
for (let i = locations.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [locations[i], locations[j]] = [locations[j], locations[i]];
}

let selectedLocations = locations.slice(0, amountOfLocations)

My initial thought is I need to grab only 2 items from this current loop instead of 3, then using the original array remove these two items and shuffle the array up again to randomly grab one more item which will then be placed in the 3rd position.

Body:
You could continue using the shuffle method so you don't end up selecting duplicates like with plain random indexing, then you just extract the first element from the shuffled array and call it "third". Then you filter out non-restaurants (and slice the first index before because we've already selected it) and select any 2 elements:

for (let i = locations.length - 1; i > 0; i--) {
  const j = Math.floor(Math.random() * (i + 1));
  [locations[i], locations[j]] = [locations[j], locations[i]];
}

let third = locations[0];
let [first, second] = locations.slice(1).filter(l => !l.restaurant);
let selectedLocations = [first, second, third];


问:
Expanding variable scope
Within a for loop (i.e. .each()), I need to set the variable of openvalue to 1 if a condition is met. I then need to access the value of this variable at the end of the loop. Regardless of the situation, when I print the variable to the console, the result is always 0. I know why (variable scope), but I'm wondering how I can modify my code so that if openvalue is set to 1 within the forloop, that value will have permanence outside of the forloop.

```<code>var openvalue = 0; //sets default value
textinputs.each(function () {
    var attr = $(this).attr('disabled');
    if (attr == undefined || attr == false) {
        var openvalue = 1; // if there is an input that is not disabled, set this value to 1
    }
});
console.log(openvalue);
</code>```

Thanks for your help!

答:
In your loop, you declare a new variable with the same name.  Instead, you want to assign a value to the already declared variable.  So, "openvalue = 1" instead of "var openvalue = 1":</p>

```<code>var openvalue = 0; //sets default value
textinputs.each(function () {
var attr = $(this).attr('disabled');
if (attr == undefined || attr == false) {
    openvalue = 1; // if there is an input that is not disabled, set this value to 1
}
});

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

Title: Expanding variable scope

Body:
Within a for loop (i.e. .each()), I need to set the variable of openvalue to 1 if a condition is met. I then need to access the value of this variable at the end of the loop. Regardless of the situation, when I print the variable to the console, the result is always 0. I know why (variable scope), but I'm wondering how I can modify my code so that if openvalue is set to 1 within the forloop, that value will have permanence outside of the forloop.

var openvalue = 0; //sets default value
textinputs.each(function () {
    var attr = $(this).attr('disabled');
    if (attr == undefined || attr == false) {
        var openvalue = 1; // if there is an input that is not disabled, set this value to 1
    }
});
console.log(openvalue);

Thanks for your help!

Body:
In your loop, you declare a new variable with the same name.  Instead, you want to assign a value to the already declared variable.  So, "openvalue = 1" instead of "var openvalue = 1":

var openvalue = 0; //sets default value
textinputs.each(function () {
var attr = $(this).attr('disabled');
if (attr == undefined || attr == false) {
    openvalue = 1; // if there is an input that is not disabled, set this value to 1
}
});

console.log(openvalue);


问:
How to test ECS autoscaling properly?
I have a ECS service that I have set up auto-scaling for. It is a service that has 2 Fargate tasks. The problem is the Docker containers' CPU utilization is usually very low, generally around 0.1%. I would like to test my auto-scaling set up, especially auto-scaling down which should happen when CPU utilization drops below a threshold. What is the best approach to test it?</p>

答: I've been also thought about that before, then I was adjusting the threshold from 50% to 0.1% to trigger the auto-scaling, as well as adjusted the scale-in threshold.</p>

Title: How to test ECS autoscaling properly?