问:
CSS not loading since adding new id element to div class
First off what changed is I added two new divs and assigned it an id class of "order" and one "menuOutput".  Ever since then my CSS within the div id="menuOutput" has disappeared.  How do I get my CSS styles back whilst not changing how my js code works?  I know the new additions of the div are the problem but please tell me how to keep my styles with the new code?  </p>

```<code><body>
<div id="order"></div>
<div id="menuOutput">
<h1 class="menu">Menu</h1>
  <div class="grid">
    <div class="two">
      <h2>Pizza by the slice ($2)</h2>
      <input type="number" id="qty_slice of pizza">
      <h2>Toppings</h2>
      <p class="titles">Per Pepperoni($0.25):</p> <input type="number" id="qty_pepperoni">
      <p class="titles">Per Meatball($0.35):</p> <input type="number" id="qty_meatballs">
      <p class="titles">Per Mushhroom($0.40):</p> <input type="number" id="qty_mushrooms">
      <p class="titles">Per Olive($0.20):</p> <input type="number" id="qty_olives">
    </div>

    <div class="one">
      <h2>Sides</h2>
      <p class="titles">Potato Salad($1.25):</p> <input type="number" id="qty_potato salad">
      <p class="titles">Humus($2.50):</p> <input type="number" id="qty_hummus">
      <p class="titles">Caesar Salad($3.50):</p> <input type="number" id="qty_caesar salad">
      <p class="titles">Garden Salad($2.25):</p> <input type="number" id="qty_garden salad">
    </div>

    <div class="three">
        <h2>Drinks</h2>
        <div>

          <p class="titles">Small Soda($1.95):</p> <input type="number" id="qty_small">
          <p class="titles">Medium Soda($2.20):</p> <input type="number" id="qty_medium">
          <p class="titles">Large Soda($2.50):</p> <input type="number" id="qty_large">
        </div><hr>
      <p class="titles">Juice($2.00):</p> <input type="number" id="qty_juice">
      <p class="titles">Water($1.25):</p> <input type="number" id="qty_water">

    </div>
 </div><br>
 </div>
<div class="button">
  <button type class="button" id="submitOrder">Review Order</button>
</div>
<div id="order"></div>
<script src="./run.js"></script>
</body>

 ------------------------------------JS---------------------------
 //get menu from api
 var getJSON = function(url, callback) {
var xhr = new XMLHttpRequest();
xhr.open('get', url, true);
xhr.responseType = 'json';
xhr.onload = function() {
  var status = xhr.status;
  if (status == 200) {
    callback(null, xhr.response);
  } else {
    callback(status);
  }
};
xhr.send();
};

/*
{
"menu": {
"slice of pizza": "2.00",
qty_slice of pizza
"toppings": {
  "pepperoni": ".25",
  "meatballs": ".35",
  "mushrooms": ".40",
  "olives": ".20"
 },
 "sides": {
  "potato salad": "1.25",
  "hummus": "2.50",
  "caesar salad": "3.50",
  "garden salad": "2.25"
  },
  "drinks": {
  "soda": {
    "small": "1.95",
    "medium": "2.20",
    "large": "2.50"
   },
  "juice": "2.00",
  "water": "1.25"
  }
 }
 }
*/

 getJSON('https://mm214.com/menu.php', function(err, data) {
 if (err != null) {
 alert('Something went wrong: ' + err);
 } else {

 var content = '';

 for (x in data.menu){
 if (typeof(data.menu[x]) == 'object'){
    for (y in data.menu[x]) {
        if (typeof(data.menu[x][y]) == 'object'){
            for (z in data.menu[x][y]) {
      content +=  z + ':' + data.menu[x][y][z] + '<input type="number" id = "qty_' + z + '"><br>';
            }
          }
            else {
      content += y + ':' + data.menu[x][y] + '<input type="number" id = "qty_' + y + '"><br>';
            }
        }//closes y in data

  }
  else
  {
  content += x + ':' + data.menu[x] + '<input type="number" id = "qty_' + x + '"><br>';

  }//else for data.menu[x] if not an object
  }
  }//closes outer for loop

  //localStorage only stores strings! Stringify turns objects into strings!
  //parse converts JSON strings to objects that can be looped around

  document.getElementById("menuOutput").innerHTML = content;
  localStorage.setItem('order',JSON.stringify(data));
  console.log(a + ':' + order[a]);

  var order = JSON.parse(localStorage.getItem('order'));
  console.log(typeof(order));
  for (a in order){
  }

  });

  function storeOrder(){
   var pizzaqty = document.getElementById('qty_slice of pizza').value;
   localStorage.setItem('pizza',pizzaqty);
   var price  = pizzaqty * 2;

  }

  function retrieveOrder(){
    var pizzaordered = localStorage.getItem('pizza');

  }

  //output html
  //
  //document.getElementById("menuOutput").innerHTML = "Here is the menu: <br>" + data.menu;
  //why in't this working?

  //style menu for ordering
  //save order as json string
  //save in local storage
  //your order button

  //onclick: show order
  document.getElementById('order').innerHTML = localStorage.getItem('order1');

------------------CSS------------------------------

 @import url('https://fonts.googleapis.com/css2?
 family=Bangers&family=Bree+Serif&family=Chelsea+Market&family=Oswald:wght@300&display=swap');

 .grid {
 display: grid;
 grid-template-areas:
    "one two three"
    "one two three"
    "one two three";
grid-template-columns: 1fr 2fr 1fr;
grid-template-rows: repeat(3, 165px);
 }

.title {
font-family: 'Chelsea Market', cursive;
font-size: 30px;
text-align: center;
color: teal;
}

input[type="number"] {
width: 40px;
}

.menu {
text-align: center;
}

.button {
text-align: center;
font-family: 'Bangers', cursive;
font-size: 25px;
 }

.titles {
font-family: 'Bree Serif', serif;
}

.pizza {
text-align: center;
color: tomato;
background-color: teal;
}

.one {
grid-area: one;
background-color: #008c45;
text-align: center;
}

.two {
text-align: center;
grid-area: two;
background-color: #f4f5f0;
color: black;
}

.three {
grid-area: three;
text-align: center;
background-color: #cd212a;
}

h2 {
font-size: 30px;
font-family: 'Oswald', sans-serif;
text-align: center;
}
</code>```

答:
The root cause of the problem is due to the div tags getting mixed up.

Here are the steps to resolve the problem:

Move the div tag meant for menu-output to the bottom of the page and add closure to it immediately.

Remove the duplicate div tags with same ID (menuOutput, order).

Here is the working example with the div tags adjusted and duplicate divs removed:

```<code><html>
    <head>
        <title>Menu - demo</title>
        <style>
            @import url('https://fonts.googleapis.com/css2?family=Bangers&family=Bree+Serif&family=Chelsea+Market&family=Oswald:wght@300&display=swap');
            .grid {
                display: grid;
                grid-template-areas:
                "one two three"
                "one two three"
                "one two three";
                grid-template-columns: 1fr 2fr 1fr;
                grid-template-rows: repeat(3, 165px);
            }

            .title {
                font-family: 'Chelsea Market', cursive;
                font-size: 30px;
                text-align: center;
                color: teal;
            }

            input[type="number"] {
                width: 40px;
            }

            .menu {
                text-align: center;
            }

            .button {
                text-align: center;
                font-family: 'Bangers', cursive;
                font-size: 25px;
            }

            .titles {
                font-family: 'Bree Serif', serif;
            }

            .pizza {
                text-align: center;
                color: tomato;
                background-color: teal;
            }

            .one {
                grid-area: one;
                background-color: #008c45;
                text-align: center;
            }

            .two {
                text-align: center;
                grid-area: two;
                background-color: #f4f5f0;
                color: black;
            }

            .three {
                grid-area: three;
                text-align: center;
                background-color: #cd212a;
            }

            h2 {
                font-size: 30px;
                font-family: 'Oswald', sans-serif;
                text-align: center;
            }
        </style>
    </head>
    <body>
        <div id="order">
            <h1 class="menu">Menu</h1>
            <div class="grid">
                <div class="two">
                    <h2>Pizza by the slice ($2)</h2>
                    <input type="number" id="qty_slice_of_pizza" />
                    <h2>Toppings</h2>
                    <p class="titles">Per Pepperoni($0.25):</p>
                    <input type="number" id="qty_pepperoni">
                    <p class="titles">Per Meatball($0.35):</p>
                    <input type="number" id="qty_meatballs">
                    <p class="titles">Per Mushroom($0.40):</p>
                    <input type="number" id="qty_mushrooms">
                    <p class="titles">Per Olive($0.20):</p>
                    <input type="number" id="qty_olives">
                </div>

                <div class="one">
                    <h2>Sides</h2>
                    <p class="titles">Potato Salad($1.25):</p>
                    <input type="number" id="qty_potato_salad">
                    <p class="titles">Humus($2.50):</p>
                    <input type="number" id="qty_hummus">
                    <p class="titles">Caesar Salad($3.50):</p>
                    <input type="number" id="qty_caesar_salad">
                    <p class="titles">Garden Salad($2.25):</p>
                    <input type="number" id="qty_garden_salad">
                </div>

                <div class="three">
                    <h2>Drinks</h2>
                    <p class="titles">Small Soda($1.95):</p>
                    <input type="number" id="qty_small">
                    <p class="titles">Medium Soda($2.20):</p>
                    <input type="number" id="qty_medium">
                    <p class="titles">Large Soda($2.50):</p>
                    <input type="number" id="qty_large">
                    <p class="titles">Juice($2.00):</p>
                    <input type="number" id="qty_juice">
                    <p class="titles">Water($1.25):</p>
                    <input type="number" id="qty_water">
                </div>
            </div>
            <br>
        </div>
        <div class="button">
            <button type="button" id="submitOrder">Review Order</button>
        </div>
        <div id="menuOutput"></div>
        <script>
            //get menu from api
             var getJSON = function(url, callback) {
            var xhr = new XMLHttpRequest();
            xhr.open('get', url, true);
            xhr.responseType = 'json';
            xhr.onload = function() {
              var status = xhr.status;
              if (status == 200) {
                callback(null, xhr.response);
              } else {
                callback(status);
              }
            };
            xhr.send();
            };

            getJSON('https://mm214.com/menu.php', function(err, data) {
                if (err != null) {
                    alert('Something went wrong: ' + err);
                } else {

                var content = '';

                for (x in data.menu){
                    if (typeof(data.menu[x]) == 'object'){
                        for (y in data.menu[x]) {
                            if (typeof(data.menu[x][y]) == 'object'){
                                for (z in data.menu[x][y]) {
                                    content +=  z + ':' + data.menu[x][y][z] + '<input type="number" id = "qty_' + z + '"><br>';
                        }
                      }
                else {
                  content += y + ':' + data.menu[x][y] + '<input type="number" id = "qty_' + y + '"><br>';
                        }
                    }//closes y in data

              }
              else
              {
              content += x + ':' + data.menu[x] + '<input type="number" id = "qty_' + x + '"><br>';

              }//else for data.menu[x] if not an object
              }
              }//closes outer for loop

              //localStorage only stores strings! Stringify turns objects into strings!
              //parse converts JSON strings to objects that can be looped around

              document.getElementById("menuOutput").innerHTML = content;
              localStorage.setItem('order',JSON.stringify(data));
              console.log(a + ':' + order[a]);

              var order = JSON.parse(localStorage.getItem('order'));
              console.log(typeof(order));
              for (a in order){
              }

              });

              function storeOrder(){
               var pizzaqty = document.getElementById('qty_slice of pizza').value;
               localStorage.setItem('pizza',pizzaqty);
               var price  = pizzaqty * 2;

              }
              function retrieveOrder(){
                var pizzaordered = localStorage.getItem('pizza');

              }
        </script>
    </body>
</html>
</code>```

Output:

Body:
First off what changed is I added two new divs and assigned it an id class of "order" and one "menuOutput".  Ever since then my CSS within the div id="menuOutput" has disappeared.  How do I get my CSS styles back whilst not changing how my js code works?  I know the new additions of the div are the problem but please tell me how to keep my styles with the new code?

Menu

Pizza by the slice ($2)

      <input type="number" id="qty_slice of pizza">

Toppings

Per Pepperoni($0.25):
 <input type="number" id="qty_pepperoni">

Per Meatball($0.35):
 <input type="number" id="qty_meatballs">

Per Mushhroom($0.40):
 <input type="number" id="qty_mushrooms">

Per Olive($0.20):
 <input type="number" id="qty_olives">

Sides

Potato Salad($1.25):
 <input type="number" id="qty_potato salad">

Humus($2.50):
 <input type="number" id="qty_hummus">

Caesar Salad($3.50):
 <input type="number" id="qty_caesar salad">

Garden Salad($2.25):
 <input type="number" id="qty_garden salad">

Drinks

Small Soda($1.95):
 <input type="number" id="qty_small">

Medium Soda($2.20):
 <input type="number" id="qty_medium">

Large Soda($2.50):
 <input type="number" id="qty_large">

Juice($2.00):
 <input type="number" id="qty_juice">

Water($1.25):
 <input type="number" id="qty_water">

  <button type class="button" id="submitOrder">Review Order</button>

 ------------------------------------JS---------------------------
 //get menu from api
 var getJSON = function(url, callback) {
var xhr = new XMLHttpRequest();
xhr.open('get', url, true);
xhr.responseType = 'json';
xhr.onload = function() {
  var status = xhr.status;
  if (status == 200) {
    callback(null, xhr.response);
  } else {
    callback(status);
  }
};
xhr.send();
};

/*
{
"menu": {
"slice of pizza": "2.00",
qty_slice of pizza
"toppings": {
  "pepperoni": ".25",
  "meatballs": ".35",
  "mushrooms": ".40",
  "olives": ".20"
 },
 "sides": {
  "potato salad": "1.25",
  "hummus": "2.50",
  "caesar salad": "3.50",
  "garden salad": "2.25"
  },
  "drinks": {
  "soda": {
    "small": "1.95",
    "medium": "2.20",
    "large": "2.50"
   },
  "juice": "2.00",
  "water": "1.25"
  }
 }
 }
*/

 getJSON('https://mm214.com/menu.php', function(err, data) {
 if (err != null) {
 alert('Something went wrong: ' + err);
 } else {

 var content = '';

 for (x in data.menu){
 if (typeof(data.menu[x]) == 'object'){
    for (y in data.menu[x]) {
        if (typeof(data.menu[x][y]) == 'object'){
            for (z in data.menu[x][y]) {
      content +=  z + ':' + data.menu[x][y][z] + '<input type="number" id = "qty_' + z + '">
';
            }
          }
            else {
      content += y + ':' + data.menu[x][y] + '<input type="number" id = "qty_' + y + '">
';
            }
        }//closes y in data

  }
  else
  {
  content += x + ':' + data.menu[x] + '<input type="number" id = "qty_' + x + '">
';

  }//else for data.menu[x] if not an object
  }
  }//closes outer for loop

  //localStorage only stores strings! Stringify turns objects into strings!
  //parse converts JSON strings to objects that can be looped around

  document.getElementById("menuOutput").innerHTML = content;
  localStorage.setItem('order',JSON.stringify(data));
  console.log(a + ':' + order[a]);

  var order = JSON.parse(localStorage.getItem('order'));
  console.log(typeof(order));
  for (a in order){
  }

  });

  function storeOrder(){
   var pizzaqty = document.getElementById('qty_slice of pizza').value;
   localStorage.setItem('pizza',pizzaqty);
   var price  = pizzaqty * 2;

  }

  function retrieveOrder(){
    var pizzaordered = localStorage.getItem('pizza');

  }

  //output html
  //
  //document.getElementById("menuOutput").innerHTML = "Here is the menu:
" + data.menu;
  //why in't this working?

  //style menu for ordering
  //save order as json string
  //save in local storage
  //your order button

  //onclick: show order
  document.getElementById('order').innerHTML = localStorage.getItem('order1');

------------------CSS------------------------------

 @import url('https://fonts.googleapis.com/css2?
 family=Bangers&family=Bree+Serif&family=Chelsea+Market&family=Oswald:wght@300&display=swap');

 .grid {
 display: grid;
 grid-template-areas:
    "one two three"
    "one two three"
    "one two three";
grid-template-columns: 1fr 2fr 1fr;
grid-template-rows: repeat(3, 165px);
 }

.title {
font-family: 'Chelsea Market', cursive;
font-size: 30px;
text-align: center;
color: teal;
}

input[type="number"] {
width: 40px;
}

.menu {
text-align: center;
}

.button {
text-align: center;
font-family: 'Bangers', cursive;
font-size: 25px;
 }

.titles {
font-family: 'Bree Serif', serif;
}

.pizza {
text-align: center;
color: tomato;
background-color: teal;
}

.one {
grid-area: one;
background-color: #008c45;
text-align: center;
}

.two {
text-align: center;
grid-area: two;
background-color: #f4f5f0;
color: black;
}

.three {
grid-area: three;
text-align: center;
background-color: #cd212a;
}

h2 {
font-size: 30px;
font-family: 'Oswald', sans-serif;
text-align: center;
}

Body:
The root cause of the problem is due to the div tags getting mixed up.

Here are the steps to resolve the problem:

Move the div tag meant for menu-output to the bottom of the page and add closure to it immediately.

Remove the duplicate div tags with same ID (menuOutput, order).

Here is the working example with the div tags adjusted and duplicate divs removed:

<html>
    <head>
        <title>Menu - demo</title>
        <style>
            @import url('https://fonts.googleapis.com/css2?family=Bangers&family=Bree+Serif&family=Chelsea+Market&family=Oswald:wght@300&display=swap');
            .grid {
                display: grid;
                grid-template-areas:
                "one two three"
                "one two three"
                "one two three";
                grid-template-columns: 1fr 2fr 1fr;
                grid-template-rows: repeat(3, 165px);
            }

            .title {
                font-family: 'Chelsea Market', cursive;
                font-size: 30px;
                text-align: center;
                color: teal;
            }

            input[type="number"] {
                width: 40px;
            }

            .menu {
                text-align: center;
            }

            .button {
                text-align: center;
                font-family: 'Bangers', cursive;
                font-size: 25px;
            }

            .titles {
                font-family: 'Bree Serif', serif;
            }

            .pizza {
                text-align: center;
                color: tomato;
                background-color: teal;
            }

            .one {
                grid-area: one;
                background-color: #008c45;
                text-align: center;
            }

            .two {
                text-align: center;
                grid-area: two;
                background-color: #f4f5f0;
                color: black;
            }

            .three {
                grid-area: three;
                text-align: center;
                background-color: #cd212a;
            }

            h2 {
                font-size: 30px;
                font-family: 'Oswald', sans-serif;
                text-align: center;
            }
        </style>
    </head>
    <body>
        <div id="order">
            <h1 class="menu">Menu</h1>
            <div class="grid">
                <div class="two">
                    <h2>Pizza by the slice ($2)</h2>
                    <input type="number" id="qty_slice_of_pizza" />
                    <h2>Toppings</h2>
                    <p class="titles">Per Pepperoni($0.25):</p>
                    <input type="number" id="qty_pepperoni">
                    <p class="titles">Per Meatball($0.35):</p>
                    <input type="number" id="qty_meatballs">
                    <p class="titles">Per Mushroom($0.40):</p>
                    <input type="number" id="qty_mushrooms">
                    <p class="titles">Per Olive($0.20):</p>
                    <input type="number" id="qty_olives">
                </div>

                <div class="one">
                    <h2>Sides</h2>
                    <p class="titles">Potato Salad($1.25):</p>
                    <input type="number" id="qty_potato_salad">
                    <p class="titles">Humus($2.50):</p>
                    <input type="number" id="qty_hummus">
                    <p class="titles">Caesar Salad($3.50):</p>
                    <input type="number" id="qty_caesar_salad">
                    <p class="titles">Garden Salad($2.25):</p>
                    <input type="number" id="qty_garden_salad">
                </div>

                <div class="three">
                    <h2>Drinks</h2>
                    <p class="titles">Small Soda($1.95):</p>
                    <input type="number" id="qty_small">
                    <p class="titles">Medium Soda($2.20):</p>
                    <input type="number" id="qty_medium">
                    <p class="titles">Large Soda($2.50):</p>
                    <input type="number" id="qty_large">
                    <p class="titles">Juice($2.00):</p>
                    <input type="number" id="qty_juice">
                    <p class="titles">Water($1.25):</p>
                    <input type="number" id="qty_water">
                </div>
            </div>
            <br>
        </div>
        <div class="button">
            <button type="button" id="submitOrder">Review Order</button>
        </div>
        <div id="menuOutput"></div>
        <script>
            //get menu from api
             var getJSON = function(url, callback) {
            var xhr = new XMLHttpRequest();
            xhr.open('get', url, true);
            xhr.responseType = 'json';
            xhr.onload = function() {
              var status = xhr.status;
              if (status == 200) {
                callback(null, xhr.response);
              } else {
                callback(status);
              }
            };
            xhr.send();
            };

            getJSON('https://mm214.com/menu.php', function(err, data) {
                if (err != null) {
                    alert('Something went wrong: ' + err);
                } else {

                var content = '';

                for (x in data.menu){
                    if (typeof(data.menu[x]) == 'object'){
                        for (y in data.menu[x]) {
                            if (typeof(data.menu[x][y]) == 'object'){
                                for (z in data.menu[x][y]) {
                                    content +=  z + ':' + data.menu[x][y][z] + '<input type="number" id = "qty_' + z + '"><br>';
                        }
                      }
                else {
                  content += y + ':' + data.menu[x][y] + '<input type="number" id = "qty_' + y + '"><br>';
                        }
                    }//closes y in data

              }
              else
              {
              content += x + ':' + data.menu[x] + '<input type="number" id = "qty_' + x + '"><br>';

              }//else for data.menu[x] if not an object
              }
              }//closes outer for loop

              //localStorage only stores strings! Stringify turns objects into strings!
              //parse converts JSON strings to objects that can be looped around

              document.getElementById("menuOutput").innerHTML = content;
              localStorage.setItem('order',JSON.stringify(data));
              console.log(a + ':' + order[a]);

              var order = JSON.parse(localStorage.getItem('order'));
              console.log(typeof(order));
              for (a in order){
              }

              });

              function storeOrder(){
               var pizzaqty = document.getElementById('qty_slice of pizza').value;
               localStorage.setItem('pizza',pizzaqty);
               var price  = pizzaqty * 2;

              }
              function retrieveOrder(){
                var pizzaordered = localStorage.getItem('pizza');

              }
        </script>
    </body>
</html>

Output:


来源: stackexchange

问:
Replace characters in all tables in Database Postgres
I'm using PostgreSQL with pgadmin.
I need to replace multiple characters in all fields of type string, and in all tables in my database.</p>

答:
Use the below with caution - adjust as necessary, and make sure you review each and every resultant query (yes - this generates a resultset of queries) before copying the results and executing - as this may include queries that would attempt to modify views, calculated fields, system tables etc. etc.

I'm a T-SQL'er - but I believe the below should be valid in PostgresSQL.

```<code>SELECT 'UPDATE ' || TABLE_SCHEMA || '.' || TABLE_NAME ||
       ' SET ' || COLUMN_NAME || ' = REPLACE(' ||
       COLUMN_NAME || ', ''FROM'', ''TO'')'
FROM INFORMATION_SCHEMA.COLUMNS
WHERE DATA_TYPE LIKE '%char%'
</code>```

For additional information, which may provide ideas on how to adjust this query, check out INFORMATION_SCHEMA.COLUMNS.

ContentLicense: CC BY-SA 4.0

Body:
Use the below with caution - adjust as necessary, and make sure you review each and every resultant query (yes - this generates a resultset of queries) before copying the results and executing - as this may include queries that would attempt to modify views, calculated fields, system tables etc. etc.

I'm a T-SQL'er - but I believe the below should be valid in PostgresSQL.

SELECT 'UPDATE ' || TABLE_SCHEMA || '.' || TABLE_NAME ||
       ' SET ' || COLUMN_NAME || ' = REPLACE(' ||
       COLUMN_NAME || ', ''FROM'', ''TO'')'
FROM INFORMATION_SCHEMA.COLUMNS
WHERE DATA_TYPE LIKE '%char%'

For additional information, which may provide ideas on how to adjust this query, check out INFORMATION_SCHEMA.COLUMNS.

ContentLicense: CC BY-SA 3.0


问:
How to remove ANSI escape character in C#
I am trying to export the console output from Linux machine after running sh command through UiPath using C# nuget package.

When I write it into notepad I am getting below

```<code>]0;sqsuser@primedbdmc:~[sqsuser@primedbdmc ~]$
</code>```

The same is coming like below when i store the value in a runtime variable

```<code>\u001b]0;sqsuser@primedbdmc:~\a\u001b[?1034h[sqsuser@primedbdmc ~]$
</code>```

I would like to remove this using code or regex in UiPath but I couldnt done via regex. Please help

答:
After a long search, the solution is below

Regex.Replace(Regex.Replace(str_Response,""\x1B(?:[@-Z\-_]|[[0-?][ -/][@-~])"",""),"\a","")

Body:
I am trying to export the console output from Linux machine after running sh command through UiPath using C# nuget package.

When I write it into notepad I am getting below

]0;sqsuser@primedbdmc:~[sqsuser@primedbdmc ~]$

The same is coming like below when i store the value in a runtime variable

\u001b]0;sqsuser@primedbdmc:~\a\u001b[?1034h[sqsuser@primedbdmc ~]$

I would like to remove this using code or regex in UiPath but I couldnt done via regex. Please help


问:
Why am I getting a compilation error in a C++ factorial function?
I am trying to write a simple factorial function in C++ by using the ternary operator. It gives a compilation error.

```<code>int factorial(int n) {
    (n == 0) ? return 1 : return n * factorial(n-1);
}
</code>```

It says Expected ':' to match this '?'
I am new to C++.

答:
?: is an ternary operator that takes three expressions and evaluates them in some way to produce a result. return 0 in your case is not an expression but it's a statement, so your syntax doesn't work and gives error. It cannot be used where a value is expected.

The correct code and it's syntax should be as follows :

```<code>int factorial(int n) {
    return ((n <= 1) ? 1 : n * factorial(n-1) );
}
</code>```

Your code would have worked in case you used if-else like this -

```<code>int factorial(int n) {
    if(n == 0) return 1; else return n * factorial(n-1);
}
</code>```

if-else is semantically different than ternary operator ?:. You can  use statements inside if-else, while on the other hand, you have to use expression which evaluate to some value in case of ternary operator.

So, when you use the statement - return ((n <= 1) ? 1 : n * factorial(n-1) );, the ternary operator will get evaluated first and it will give out a value (which is why the expression inside ternary operator need to evaluate to a value)according to the satisfied condition and that value is eventually returned by the return.

Hope you understand the difference and this solves your doubt !

Body:
I am trying to write a simple factorial function in C++ by using the ternary operator. It gives a compilation error.

int factorial(int n) {
    (n == 0) ? return 1 : return n * factorial(n-1);
}

It says Expected ':' to match this '?'
I am new to C++.

Body:
?: is an ternary operator that takes three expressions and evaluates them in some way to produce a result. return 0 in your case is not an expression but it's a statement, so your syntax doesn't work and gives error. It cannot be used where a value is expected.

The correct code and it's syntax should be as follows :

int factorial(int n) {
    return ((n <= 1) ? 1 : n * factorial(n-1) );
}

Your code would have worked in case you used if-else like this -

int factorial(int n) {
    if(n == 0) return 1; else return n * factorial(n-1);
}

if-else is semantically different than ternary operator ?:. You can  use statements inside if-else, while on the other hand, you have to use expression which evaluate to some value in case of ternary operator.

So, when you use the statement - return ((n <= 1) ? 1 : n * factorial(n-1) );, the ternary operator will get evaluated first and it will give out a value (which is why the expression inside ternary operator need to evaluate to a value)according to the satisfied condition and that value is eventually returned by the return.

Hope you understand the difference and this solves your doubt !


问:
How to make TFLite model Inference on video input
I am trying to test my exported Mobilenet v2 SSDLitemodel(https://drive.google.com/open?id=1htyBE6R62yVCV8v-9muEJ_lGmoPxQMmJ) with video. Then i found an answer here, i modify somewhere to adapt my model :

```<code>import cv2
from PIL import Image
import numpy as np
import tensorflow as tf

def read_tensor_from_readed_frame(frame, input_height=300, input_width=300,
        input_mean=128, input_std=128):
  output_name = "normalized"
  # float_caster = tf.cast(frame, tf.float32)
  float_caster = tf.cast(frame, tf.uint8)
  dims_expander = tf.expand_dims(float_caster, 0);
  resized = tf.image.resize_bilinear(dims_expander, [input_height, input_width])
  normalized = tf.divide(tf.subtract(resized, [input_mean]), [input_std])
  sess = tf.Session()
  result = sess.run(normalized)
  return result

def load_labels(label_file):
  label = []
  proto_as_ascii_lines = tf.gfile.GFile(label_file).readlines()
  for l in proto_as_ascii_lines:
    label.append(l.rstrip())
  return label

def VideoSrcInit(paath):
    cap = cv2.VideoCapture(paath)
    flag, image = cap.read()
    if flag:
        print("Valid Video Path. Lets move to detection!")
    else:
        raise ValueError("Video Initialization Failed. Please make sure video path is valid.")
    return cap

def main():
  Labels_Path = "C:/MachineLearning/CV/coco-labelmap.txt"
  Model_Path = "C:/MachineLearning/CV/previous_float_model_converted_from_ssd_mobilenet_v2_quantized_300x300_coco_2019_01_03.tflite"
  input_path = "C:/MachineLearning/CV/Object_Tracking/video2.mp4"

  ##Loading labels
  labels = load_labels(Labels_Path)

  ##Load tflite model and allocate tensors
  interpreter = tf.lite.Interpreter(model_path=Model_Path)
  interpreter.allocate_tensors()
  # Get input and output tensors.
  input_details = interpreter.get_input_details()
  output_details = interpreter.get_output_details()

  input_shape = input_details[0]['shape']

  ##Read video
  cap = VideoSrcInit(input_path)

  while True:
    ok, cv_image = cap.read()
    if not ok:
      break

    ##Converting the readed frame to RGB as opencv reads frame in BGR
    image = Image.fromarray(cv_image).convert('RGB')

    ##Converting image into tensor
    image_tensor = read_tensor_from_readed_frame(image ,300, 300)

    ##Test model
    interpreter.set_tensor(input_details[0]['index'], image_tensor)
    interpreter.invoke()
    output_data = interpreter.get_tensor(output_details[0]['index'])

    ## You need to check the output of the output_data variable and
    ## map it on the frame in order to draw the bounding boxes.

    cv2.namedWindow("cv_image", cv2.WINDOW_NORMAL)
    cv2.imshow("cv_image",cv_image)

    ##Use p to pause the video and use q to termiate the program
    key = cv2.waitKey(10) & 0xFF
    if key == ord("q"):
      break
    elif key == ord("p"):
      cv2.waitKey(0)
      continue
  cap.release()

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

When i run this scrpit on my tflite modle, the FPS is very very slow almost still, so what is wrong with the script ?

答:
I solve it myself，this is the sript:

```<code>import numpy as np
import tensorflow as tf
import cv2
import time
print(tf.__version__)

Model_Path = "C:/MachineLearning/CV/uint8_dequantized_model_converted_from_exported_model.tflite"
Video_path = "C:/MachineLearning/CV/Object_Tracking/video2.mp4"

interpreter = tf.lite.Interpreter(model_path=Model_Path)
interpreter.allocate_tensors()

input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()

class_names = ['person', 'bicycle', 'car', 'motorcycle', 'airplane','bus', 'train', 'truck', 'boat', 'traffic light',
'fire hydrant ', 'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow', 'elephant', 'bear',
'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie', 'suitcase', 'frisbee', 'skis', 'snowboard', 'sports ball',
'kite', 'baseball bat', 'baseball glove', 'skateboard', 'surfboard', 'tennis racket', 'bottle', 'wine glass', ' cup',
'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple', 'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza',
'donut', 'cake', 'chair', 'couch', 'potted plant', 'bed', 'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote',
'keyboard', ' cell phone', 'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors',
'teddy bear', 'hair drier', 'toothbrush']

cap = cv2.VideoCapture(Video_path)
ok, frame_image = cap.read()
original_image_height, original_image_width, _ = frame_image.shape
thickness = original_image_height // 500
fontsize = original_image_height / 1500
print(thickness)
print(fontsize)

while True:
    ok, frame_image = cap.read()
    if not ok:
        break

    model_interpreter_start_time = time.time()
    resize_img = cv2.resize(frame_image, (300, 300), interpolation=cv2.INTER_CUBIC)
    reshape_image = resize_img.reshape(300, 300, 3)
    image_np_expanded = np.expand_dims(reshape_image, axis=0)
    image_np_expanded = image_np_expanded.astype('uint8')  # float32

    interpreter.set_tensor(input_details[0]['index'], image_np_expanded)
    interpreter.invoke()

    output_data = interpreter.get_tensor(output_details[0]['index'])
    output_data_1 = interpreter.get_tensor(output_details[1]['index'])
    output_data_2 = interpreter.get_tensor(output_details[2]['index'])
    output_data_3 = interpreter.get_tensor(output_details[3]['index'])
    each_interpreter_time = time.time() - model_interpreter_start_time

    for i in range(len(output_data_1[0])):
        confidence_threshold = output_data_2[0][i]
        if confidence_threshold > 0.3:
            label = "{}: {:.2f}% ".format(class_names[int(output_data_1[0][i])], output_data_2[0][i] * 100)
            label2 = "inference time : {:.3f}s" .format(each_interpreter_time)
            left_up_corner = (int(output_data[0][i][1]*original_image_width), int(output_data[0][i][0]*original_image_height))
            left_up_corner_higher = (int(output_data[0][i][1]*original_image_width), int(output_data[0][i][0]*original_image_height)-20)
            right_down_corner = (int(output_data[0][i][3]*original_image_width), int(output_data[0][i][2]*original_image_height))
            cv2.rectangle(frame_image, left_up_corner_higher, right_down_corner, (0, 255, 0), thickness)
            cv2.putText(frame_image, label, left_up_corner_higher, cv2.FONT_HERSHEY_DUPLEX, fontsize, (255, 255, 255), thickness=thickness)
            cv2.putText(frame_image, label2, (30, 30), cv2.FONT_HERSHEY_DUPLEX, fontsize, (255, 255, 255), thickness=thickness)
    cv2.namedWindow('detect_result', cv2.WINDOW_NORMAL)
    # cv2.resizeWindow('detect_result', 800, 600)
    cv2.imshow("detect_result", frame_image)

    key = cv2.waitKey(10) & 0xFF
    if key == ord("q"):
        break
    elif key == 32:
        cv2.waitKey(0)
        continue
cap.release()
cv2.destroyAllWindows()
</code>```

but the inference spped is still slow, because tflite's operations are optimized for mobile devide, not for Desktop.

Body:
I am trying to test my exported Mobilenet v2 SSDLitemodel(https://drive.google.com/open?id=1htyBE6R62yVCV8v-9muEJ_lGmoPxQMmJ) with video. Then i found an answer here, i modify somewhere to adapt my model :

import cv2
from PIL import Image
import numpy as np
import tensorflow as tf

def read_tensor_from_readed_frame(frame, input_height=300, input_width=300,
        input_mean=128, input_std=128):
  output_name = "normalized"
  # float_caster = tf.cast(frame, tf.float32)
  float_caster = tf.cast(frame, tf.uint8)
  dims_expander = tf.expand_dims(float_caster, 0);
  resized = tf.image.resize_bilinear(dims_expander, [input_height, input_width])
  normalized = tf.divide(tf.subtract(resized, [input_mean]), [input_std])
  sess = tf.Session()
  result = sess.run(normalized)
  return result

def load_labels(label_file):
  label = []
  proto_as_ascii_lines = tf.gfile.GFile(label_file).readlines()
  for l in proto_as_ascii_lines:
    label.append(l.rstrip())
  return label

def VideoSrcInit(paath):
    cap = cv2.VideoCapture(paath)
    flag, image = cap.read()
    if flag:
        print("Valid Video Path. Lets move to detection!")
    else:
        raise ValueError("Video Initialization Failed. Please make sure video path is valid.")
    return cap

def main():
  Labels_Path = "C:/MachineLearning/CV/coco-labelmap.txt"
  Model_Path = "C:/MachineLearning/CV/previous_float_model_converted_from_ssd_mobilenet_v2_quantized_300x300_coco_2019_01_03.tflite"
  input_path = "C:/MachineLearning/CV/Object_Tracking/video2.mp4"

  ##Loading labels
  labels = load_labels(Labels_Path)

  ##Load tflite model and allocate tensors
  interpreter = tf.lite.Interpreter(model_path=Model_Path)
  interpreter.allocate_tensors()
  # Get input and output tensors.
  input_details = interpreter.get_input_details()
  output_details = interpreter.get_output_details()

  input_shape = input_details[0]['shape']

  ##Read video
  cap = VideoSrcInit(input_path)

  while True:
    ok, cv_image = cap.read()
    if not ok:
      break

    ##Converting the readed frame to RGB as opencv reads frame in BGR
    image = Image.fromarray(cv_image).convert('RGB')

    ##Converting image into tensor
    image_tensor = read_tensor_from_readed_frame(image ,300, 300)

    ##Test model
    interpreter.set_tensor(input_details[0]['index'], image_tensor)
    interpreter.invoke()
    output_data = interpreter.get_tensor(output_details[0]['index'])

    ## You need to check the output of the output_data variable and
    ## map it on the frame in order to draw the bounding boxes.

    cv2.namedWindow("cv_image", cv2.WINDOW_NORMAL)
    cv2.imshow("cv_image",cv_image)

    ##Use p to pause the video and use q to termiate the program
    key = cv2.waitKey(10) & 0xFF
    if key == ord("q"):
      break
    elif key == ord("p"):
      cv2.waitKey(0)
      continue
  cap.release()

if __name__ == '__main__':
  main()

When i run this scrpit on my tflite modle, the FPS is very very slow almost still, so what is wrong with the script ?

Body:
I solve it myself，this is the sript:

import numpy as np
import tensorflow as tf
import cv2
import time
print(tf.__version__)

Model_Path = "C:/MachineLearning/CV/uint8_dequantized_model_converted_from_exported_model.tflite"
Video_path = "C:/MachineLearning/CV/Object_Tracking/video2.mp4"

interpreter = tf.lite.Interpreter(model_path=Model_Path)
interpreter.allocate_tensors()

input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()

class_names = ['person', 'bicycle', 'car', 'motorcycle', 'airplane','bus', 'train', 'truck', 'boat', 'traffic light',
'fire hydrant ', 'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow', 'elephant', 'bear',
'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie', 'suitcase', 'frisbee', 'skis', 'snowboard', 'sports ball',
'kite', 'baseball bat', 'baseball glove', 'skateboard', 'surfboard', 'tennis racket', 'bottle', 'wine glass', ' cup',
'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple', 'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza',
'donut', 'cake', 'chair', 'couch', 'potted plant', 'bed', 'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote',
'keyboard', ' cell phone', 'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors',
'teddy bear', 'hair drier', 'toothbrush']

cap = cv2.VideoCapture(Video_path)
ok, frame_image = cap.read()
original_image_height, original_image_width, _ = frame_image.shape
thickness = original_image_height // 500
fontsize = original_image_height / 1500
print(thickness)
print(fontsize)

while True:
    ok, frame_image = cap.read()
    if not ok:
        break

    model_interpreter_start_time = time.time()
    resize_img = cv2.resize(frame_image, (300, 300), interpolation=cv2.INTER_CUBIC)
    reshape_image = resize_img.reshape(300, 300, 3)
    image_np_expanded = np.expand_dims(reshape_image, axis=0)
    image_np_expanded = image_np_expanded.astype('uint8')  # float32

    interpreter.set_tensor(input_details[0]['index'], image_np_expanded)
    interpreter.invoke()

    output_data = interpreter.get_tensor(output_details[0]['index'])
    output_data_1 = interpreter.get_tensor(output_details[1]['index'])
    output_data_2 = interpreter.get_tensor(output_details[2]['index'])
    output_data_3 = interpreter.get_tensor(output_details[3]['index'])
    each_interpreter_time = time.time() - model_interpreter_start_time

    for i in range(len(output_data_1[0])):
        confidence_threshold = output_data_2[0][i]
        if confidence_threshold > 0.3:
            label = "{}: {:.2f}% ".format(class_names[int(output_data_1[0][i])], output_data_2[0][i] * 100)
            label2 = "inference time : {:.3f}s" .format(each_interpreter_time)
            left_up_corner = (int(output_data[0][i][1]*original_image_width), int(output_data[0][i][0]*original_image_height))
            left_up_corner_higher = (int(output_data[0][i][1]*original_image_width), int(output_data[0][i][0]*original_image_height)-20)
            right_down_corner = (int(output_data[0][i][3]*original_image_width), int(output_data[0][i][2]*original_image_height))
            cv2.rectangle(frame_image, left_up_corner_higher, right_down_corner, (0, 255, 0), thickness)
            cv2.putText(frame_image, label, left_up_corner_higher, cv2.FONT_HERSHEY_DUPLEX, fontsize, (255, 255, 255), thickness=thickness)
            cv2.putText(frame_image, label2, (30, 30), cv2.FONT_HERSHEY_DUPLEX, fontsize, (255, 255, 255), thickness=thickness)
    cv2.namedWindow('detect_result', cv2.WINDOW_NORMAL)
    # cv2.resizeWindow('detect_result', 800, 600)
    cv2.imshow("detect_result", frame_image)

    key = cv2.waitKey(10) & 0xFF
    if key == ord("q"):
        break
    elif key == 32:
        cv2.waitKey(0)
        continue
cap.release()
cv2.destroyAllWindows()

but the inference spped is still slow, because tflite's operations are optimized for mobile devide, not for Desktop.


问:
Best practices to store credentials in your Python script
My setup is: the code is in the private repository in Github which I run from AWS EC2.
I have this doubt where should I store the API and database credentials. My feeling at the moment is that no credentials should be stored in the code, instead, I should use the AWS Secret Manager to access them but then, you also connect to AWS. What is your view on it?  A disclosure, I am starting with Python, so, please, be gentle.</p>

答:
Never store your secrets in code. In your case I  would  recommend AWS Secret Manager (Or secret parameters in AWS System Manager Parameter Store) and store your secrets there.
I would recommend to create an IAM role for your EC2 which has a policy which allows the role to read the correct secrets from AWS Secret Manager. Connect the role with an instance profile and the instance profile with the EC2. This is done automatically in the AWS console but not when your using CloudFormation. An instance profile is kind of a wrapper around a role that allows the role to be attached to an instance.

In this flow your EC2 instance will be allowed to read the secrets from system manager by using the instance profile and role. Roles are the recommended way to make AWS resources interact with each other because it uses temporary credentials and restricts access.

With the above setup you should be able to read the secrets from within your code like explained here. You can use boto3 (AWS SDK for Python) to interact from within the EC2 to the secrets manager.


问:
Logcat not showing anything android api level 22
I have problem with Logcat.
 Logcat not showing anything only if I use some device with Android API level 22.
I use Android Studio.I did: change ADB location on device,kill adb server, restart Logcat, Invalidies caches/restart, reinstal Device, reset Android Studio /Computer. nothing solved problem. </p>

答:
Have you tried setting the correct device in the Logcat?

I've faced the same problem once and it was just that...


问:
cmd.executenonquery is returning -1 in vb.net windows application
I am just inserting a record in sqlserver database using stored procedure.
In this code Binddata() is the method where i have binbed the gridview with records.

here is the code:

```<code>Private Sub btnadd_Click(ByVal sender As System.Object, _
    ByVal e As System.EventArgs) Handles btnadd.Click

    sqlSP = "INSERT_E_CLIENTMASTER_REC"
    strConnection = _
        ConfigurationManager.ConnectionStrings("connectstring").ConnectionString
    Dim conn As New SqlConnection(strConnection)

    conn.Open()

    Dim cmd As New SqlCommand(sqlSP, conn)

    cmd.CommandType = CommandType.StoredProcedure

    cmd.Parameters.Add(
        New SqlParameter("@CLIENTCODE", SqlDbType.VarChar, 100, _
            ParameterDirection.Input, False, 0, 0, "", _
            DataRowVersion.Proposed, txtclientcode.Text))
    'cmd.Parameters.Add( _
    '    New SqlParameter("@CLIENT_WEBXID", SqlDbType.NVarChar, _
    '        Convert.ToString(txtwebxid.Text))) _
    cmd.Parameters.Add( _
        New SqlParameter("@CLIENT_WEBXID", SqlDbType.VarChar, 100, _
            ParameterDirection.Input, False, 0, 0, "", _
            DataRowVersion.Proposed, txtwebxid.Text))

    cmd.Parameters.Add( _
        New SqlParameter("@ToEmail", SqlDbType.VarChar, 100, _
            ParameterDirection.Input, False, 0, 0, "", _
            DataRowVersion.Proposed, txttoemail.Text))

    cmd.Parameters.Add( _
        New SqlParameter("@ClientName", SqlDbType.VarChar, 100, _
        ParameterDirection.Input, _
        False, 0, 0, "", DataRowVersion.Proposed, txtclientname.Text))

    cmd.Parameters.Add(_
        New SqlParameter("@CcEmail", SqlDbType.VarChar, 100, _
        ParameterDirection.Input, False, 0, 0, "", _
        DataRowVersion.Proposed, txtccname.Text))

    Dim i As Int32 = cmd.ExecuteNonQuery()
    If (i < 0) Then
        BindData()
        MsgBox("Record Inserted successfully ", MsgBoxStyle.OkOnly)
        txtclientcode.Text = ""
        txtwebxid.Text = ""
        txttoemail.Text = ""
        txtclientname.Text = ""
        txtccname.Text = ""

    Else
        MsgBox("Record Not Inserted successfully ", MsgBoxStyle.OkOnly)
    End If
</code>```

End Sub

In this code cmd.ExecuteNonQuery() is returning -1 so i have given (i<0) condition actually it should be positive value when rows are affected.

Thanks in advance.

答:
Is the record saved to the database? If so, then that's because the stored procedure is not returning a value.

ExecuteNonQuery()

For UPDATE, INSERT, and DELETE
  statements, the return value is the
  number of rows affected by the
  command. When a trigger exists on a
  table being inserted or updated, the
  return value includes the number of
  rows affected by both the insert or
  update operation and the number of
  rows affected by the trigger or
  triggers. For all other types of
  statements, the return value is -1. If
  a rollback occurs, the return value is
  also -1.

If you need to return a value from the stored procedure, look at this StackOverFlow Question

On a side note - Look into using the "USING Block" for your connections

Body:
I am just inserting a record in sqlserver database using stored procedure.
In this code Binddata() is the method where i have binbed the gridview with records.

here is the code:

Private Sub btnadd_Click(ByVal sender As System.Object, _
    ByVal e As System.EventArgs) Handles btnadd.Click

    sqlSP = "INSERT_E_CLIENTMASTER_REC"
    strConnection = _
        ConfigurationManager.ConnectionStrings("connectstring").ConnectionString
    Dim conn As New SqlConnection(strConnection)

    conn.Open()

    Dim cmd As New SqlCommand(sqlSP, conn)

    cmd.CommandType = CommandType.StoredProcedure

    cmd.Parameters.Add(
        New SqlParameter("@CLIENTCODE", SqlDbType.VarChar, 100, _
            ParameterDirection.Input, False, 0, 0, "", _
            DataRowVersion.Proposed, txtclientcode.Text))
    'cmd.Parameters.Add( _
    '    New SqlParameter("@CLIENT_WEBXID", SqlDbType.NVarChar, _
    '        Convert.ToString(txtwebxid.Text))) _
    cmd.Parameters.Add( _
        New SqlParameter("@CLIENT_WEBXID", SqlDbType.VarChar, 100, _
            ParameterDirection.Input, False, 0, 0, "", _
            DataRowVersion.Proposed, txtwebxid.Text))

    cmd.Parameters.Add( _
        New SqlParameter("@ToEmail", SqlDbType.VarChar, 100, _
            ParameterDirection.Input, False, 0, 0, "", _
            DataRowVersion.Proposed, txttoemail.Text))

    cmd.Parameters.Add( _
        New SqlParameter("@ClientName", SqlDbType.VarChar, 100, _
        ParameterDirection.Input, _
        False, 0, 0, "", DataRowVersion.Proposed, txtclientname.Text))

    cmd.Parameters.Add(_
        New SqlParameter("@CcEmail", SqlDbType.VarChar, 100, _
        ParameterDirection.Input, False, 0, 0, "", _
        DataRowVersion.Proposed, txtccname.Text))

    Dim i As Int32 = cmd.ExecuteNonQuery()
    If (i < 0) Then
        BindData()
        MsgBox("Record Inserted successfully ", MsgBoxStyle.OkOnly)
        txtclientcode.Text = ""
        txtwebxid.Text = ""
        txttoemail.Text = ""
        txtclientname.Text = ""
        txtccname.Text = ""

    Else
        MsgBox("Record Not Inserted successfully ", MsgBoxStyle.OkOnly)
    End If

End Sub

In this code cmd.ExecuteNonQuery() is returning -1 so i have given (i<0) condition actually it should be positive value when rows are affected.

Thanks in advance.


问:
Jquery Focus Repeatedly Called
I have a form to collect data entry from the user with button clicks that inserts a value into a
 cell. A global counter variable is used on the page. As the button's are pressed, it finds the relevant -	 (there are 9 of these) and matches to the current global counter value. When updated, the global counter is incremented.

I would like to add in the ability to tap / click a  cell to reset the global counter back to this tabindex number, to allow data entry corrections.

Currently, I have this code which is picking up the first click on the  cell. However, it just endlessly re-runs the alert() call... The only thing I can do is reload the page, then click the final alert() away.

```<code><script>
   $( "td" ).focus(function() {
      alert($(this).attr('tabindex'));
   });
</script>
</code>```

Note, I put in the tabindex value through researching & testing how to implement my desired behaviour, with a description on jquery.com's documentation for the .focus() function that modern browsers can accept this. I reverted to the  element and have progressed this far in getting it to detect a click.

Is it still needed?

Is this a better way to track which element was clicked?

If so, what would the equivalent code be?

答:
This is probably happening because when you click the td it gets "focus" and triggers your code and the focus goes to the alert box, then when you close the alert, the focus goes back to the last element which was the td which again triggers your code.

It sounds like you could use the "click" event for you needs instead, something like:

```<code><script>
   $("#someTableId").on('click', 'td', function() {
      alert($(this).attr('tabindex'));
   });
</script>
</code>```

Note the use of $("#someTableId").on('click', 'td' instead of simply $("td").click(  Either would work but using .on like I did would ensure that:

a) any dynamically added td elements still work with the code

b) we only attach the listener to td elements in the target table, and not ALL td elements on the page

Title: Jquery Focus Repeatedly Called

Body:
I have a form to collect data entry from the user with button clicks that inserts a value into a
 cell. A global counter variable is used on the page. As the button's are pressed, it finds the relevant -	 (there are 9 of these) and matches to the current global counter value. When updated, the global counter is incremented.

I would like to add in the ability to tap / click a  cell to reset the global counter back to this tabindex number, to allow data entry corrections.

Currently, I have this code which is picking up the first click on the  cell. However, it just endlessly re-runs the alert() call... The only thing I can do is reload the page, then click the final alert() away.

Note, I put in the tabindex value through researching & testing how to implement my desired behaviour, with a description on jquery.com's documentation for the .focus() function that modern browsers can accept this. I reverted to the  element and have progressed this far in getting it to detect a click.

Is it still needed?

Is this a better way to track which element was clicked?

If so, what would the equivalent code be?

Body:
This is probably happening because when you click the td it gets "focus" and triggers your code and the focus goes to the alert box, then when you close the alert, the focus goes back to the last element which was the td which again triggers your code.

It sounds like you could use the "click" event for you needs instead, something like:

<script>
   $("#someTableId").on('click', 'td', function() {
      alert($(this).attr('tabindex'));
   });
</script>

Note the use of $("#someTableId").on('click', 'td' instead of simply $("td").click(  Either would work but using .on like I did would ensure that:

a) any dynamically added td elements still work with the code

b) we only attach the listener to td elements in the target table, and not ALL td elements on the page


问:
Understanding View.drawableStateChanged
Can anyone explain when exactly View.drawableStateChanged is called? I want to use it in conjunction with ViewGroup.setAddStatesFromChildren to make a complete ViewGroup "optically" focused, meaning e.g. change background color when e.g. an EditText of this ViewGroup gets focus.

When I implement View.drawableStateChanged it's called very often, how do I know that the current call is the one I care about? What's the advantage over settings focus listeners on the child Views?

答:
From reading through the documentation which states:

```<code>This function is called whenever the state of the view changes in
such a way that it impacts the state of drawables being shown.
</code>```

It seems that this function will be called by the framework whenever the component needs to be redrawn and you can override it to (for example) perform so application specific logic which you need to do when the component is redrawn, like manually drawing something over the top of the component, or changing the font or doing something which is not possible using the stock attributes.

This question has an example of how you might implement it.

Title: Understanding View.drawableStateChanged

Body:
From reading through the documentation which states:

This function is called whenever the state of the view changes in
such a way that it impacts the state of drawables being shown.

It seems that this function will be called by the framework whenever the component needs to be redrawn and you can override it to (for example) perform so application specific logic which you need to do when the component is redrawn, like manually drawing something over the top of the component, or changing the font or doing something which is not possible using the stock attributes.

This question has an example of how you might implement it.


问:
How to configure a conditional type based on value of a property?
I have a number of Item objects and a method that processes them. The issue is that some Items could potentially have certain properties that others don't.

type ItemType = 'ApiGateway' | 'ApiGatewayEndpoint' | 'ApiGatewayMethod';

export default interface Item {
    ref?: string;
    position: Position;
    type: ItemType;
    children?: Item[];
}

function process(item: Item) {...}
```

<p>Now, let's say I want to create a separate interface <code>ApiGatewayMethodItem</code> (that extends <code>Item</code>) that has an additional string property called 'method' representing whether it's a GET or POST or something else. Is there a way I can type it in such a way that as soon as I type <code>process({type: 'ApiGatewayMethod'})</code> tsc will start complaining about the missing property <code>method</code> ? I understand that TS has a pretty good support for the "conditional types", but I haven't used them before and I'm having a hard time wrapping my head around them...</p>

<p>So let's say I have the interface </p>

```interface ApiGatewayMethodItem extends Omit<Item, 'type'> {
    type: 'ApiGatewayMethod';
    method: string;
}
```

now when I call the process function, I need the compiler to complain that the method property is missing when I don't specify it, but specify the type ApiGatewayMethod

答:
You could define your item type with only the 2 ItemTypes that doesn't have the property 'method'. Then add the property 'method' only to the type 'ApiGatewayMethodItem' </p>

```<code>type ItemType = 'ApiGateway' | 'ApiGatewayEndpoint';

export default interface DefaultItem {
    ref?: string;
    position: Position;
    type: ItemType;
    children?: DefaultItem[];
}

interface ApiGatewayMethodItem extends Omit<DefaultItem, 'type'> {
    type: 'ApiGatewayMethod';
    method: string;
}

type Item = DefaultItem | ApiGatewayMethodItem;

function process(item: Item) {

}

process ({
    type: 'ApiGatewayMethod',
    position: null
})
</code>```

Body:
I have a number of Item objects and a method that processes them. The issue is that some Items could potentially have certain properties that others don't.

type ItemType = 'ApiGateway' | 'ApiGatewayEndpoint' | 'ApiGatewayMethod';

export default interface Item {
    ref?: string;
    position: Position;
    type: ItemType;
    children?: Item[];
}

function process(item: Item) {...}

Now, let's say I want to create a separate interface ApiGatewayMethodItem (that extends Item) that has an additional string property called 'method' representing whether it's a GET or POST or something else. Is there a way I can type it in such a way that as soon as I type process({type: 'ApiGatewayMethod'}) tsc will start complaining about the missing property method ? I understand that TS has a pretty good support for the "conditional types", but I haven't used them before and I'm having a hard time wrapping my head around them...

So let's say I have the interface

interface ApiGatewayMethodItem extends Omit<Item, 'type'> {
    type: 'ApiGatewayMethod';
    method: string;
}

now when I call the process function, I need the compiler to complain that the method property is missing when I don't specify it, but specify the type ApiGatewayMethod

Body:
You could define your item type with only the 2 ItemTypes that doesn't have the property 'method'. Then add the property 'method' only to the type 'ApiGatewayMethodItem'

type ItemType = 'ApiGateway' | 'ApiGatewayEndpoint';

export default interface DefaultItem {
    ref?: string;
    position: Position;
    type: ItemType;
    children?: DefaultItem[];
}

interface ApiGatewayMethodItem extends Omit<DefaultItem, 'type'> {
    type: 'ApiGatewayMethod';
    method: string;
}

type Item = DefaultItem | ApiGatewayMethodItem;

function process(item: Item) {

}

process ({
    type: 'ApiGatewayMethod',
    position: null
})


问:
How to DROP a table or stream in KSQL when topic was dropped first
Using KSQL (Confluent: Version: 5.0.1) I'm able to drop a table / stream normally (using DROP [TABLE|STREAM]) <NAME> when the linked topic exist and when it is registered (Registered=true).

However, if the topic is dropped first (Registered=false) then the associated stream or table can't be dropped with KSQL pointing out that "No topic with name Foo was registered".

The problem is that the stream / table still shows in the list and no new stream / table can be added using the same name.

Is there any way to delete them after the topic was dropped?

答:
From the official documentation, I would do it like this:

```<code>SHOW QUERIES;
</code>```

Write down the QueryID;

```<code>TERMINATE <QueryID>;

DROP TABLE <tablename>;
</code>```

[See documentation...]

https://docs.ksqldb.io/en/latest/developer-guide/create-a-table/#delete-a-ksqldb-table

https://docs.ksqldb.io/en/latest/developer-guide/ksqldb-reference/terminate/

Body:
From the official documentation, I would do it like this:

SHOW QUERIES;

Write down the QueryID;

TERMINATE <QueryID>;

DROP TABLE <tablename>;

[See documentation...]

https://docs.ksqldb.io/en/latest/developer-guide/create-a-table/#delete-a-ksqldb-table

https://docs.ksqldb.io/en/latest/developer-guide/ksqldb-reference/terminate/


问:
How to filter within a subgroup (Pandas)
here is my problem:

You will find below a Pandas DataFrame, I would like to groupby Date and then filtering within the subgroups, but I have a lot of difficulties in doing it (spent 3 hours on this and I haven't find any solution).

This is what I am looking for :
I first have to group everything by date, then sort each score from the max to the lower (in each subgroup) and then select the two best scores but they have to be from different countries.
(For example, if the two best are from the same country then we select the higher score with a country different from the first).

This is the DataFrame :

```<code>Date  Name     Score  Country
2012  Paul      65     France
2012  Silvia    81     Italy
2012  David     80     UK
2012  Alphonse  46     France
2012  Giovanni  82     Italy
2012  Britney   53     UK
2013  Paul      32     France
2013  Silvia    59     Italy
2013  David     92     UK
2013  Alphonse  68     France
2013  Giovanni  23     Italy
2013  Britney   78     UK
2014  Paul      46     France
2014  Silvia    87     Italy
2014  David     89     UK
2014  Alphonse  76     France
2014  Giovanni  53     Italy
2014  Britney   90     UK
</code>```

The Result I am looking for is something like this :

```<code>Date  Name     Score  Country
2012  Giovanni  82     Italy
2012  David     80     UK
2013  David     92     UK
2013  Alphonse  68     France
2014  Britney   90     UK
2014  Silvia    87     Italy
</code>```

Here is the code that I started :

```<code>df = pd.DataFrame(
    {'Date':["2012","2012","2012","2012","2012","2012","2013","2013","2013","2013","2013","2013","2014","2014","2014","2014","2014","2014"],
     'Name': ["Paul", "Silvia","David","Alphone", "Giovanni", "Britney","Paul", "Silvia","David","Alphone", "Giovanni", "Britney","Paul", "Silvia","David","Alphone", "Giovanni", "Britney"],
     'Score': [65, 81, 80, 46, 82, 53,32,59,92,68,23,78,46,87,89,76,53,90],
     "Country":["France","Italy","UK","France","Italy","UK","France","Italy","UK","France","Italy","UK","France","Italy","UK","France","Italy","UK"]})

df = df.set_index('Name').groupby('Date')["Score","Country"].apply(lambda _df: _df.sort_values(["Score"],ascending=False))
</code>```

And this is what I have :

But as you can see for example in 2012, the two best scores are from the same country (Italy), so what I still have to do is :
1. Select the max per country for each year
2. Select only two best scores (and the countries have to be different).

I will be really thankful for that because I really don't know how to do it.
If somebody has some ideas on that, please share it :)

PS : please don't hesitate to tell me if it wasn't clear enough

答:
Use DataFrame.sort_values first by 2 columns, then remove duplicates by 2 columns by DataFrame.drop_duplicates and last select top values per groups by GroupBy.head:

```<code>df1 = (df.sort_values(['Date','Score'], ascending=[True, False])
         .drop_duplicates(['Date','Country'])
         .groupby('Date')
         .head(2))
print (df1)
    Date      Name  Score Country
4   2012  Giovanni     82   Italy
2   2012     David     80      UK
8   2013     David     92      UK
9   2013  Alphonse     68  France
17  2014   Britney     90      UK
13  2014    Silvia     87   Italy
</code>```

Body:
here is my problem:

You will find below a Pandas DataFrame, I would like to groupby Date and then filtering within the subgroups, but I have a lot of difficulties in doing it (spent 3 hours on this and I haven't find any solution).

This is what I am looking for :
I first have to group everything by date, then sort each score from the max to the lower (in each subgroup) and then select the two best scores but they have to be from different countries.
(For example, if the two best are from the same country then we select the higher score with a country different from the first).

This is the DataFrame :

Date  Name     Score  Country
2012  Paul      65     France
2012  Silvia    81     Italy
2012  David     80     UK
2012  Alphonse  46     France
2012  Giovanni  82     Italy
2012  Britney   53     UK
2013  Paul      32     France
2013  Silvia    59     Italy
2013  David     92     UK
2013  Alphonse  68     France
2013  Giovanni  23     Italy
2013  Britney   78     UK
2014  Paul      46     France
2014  Silvia    87     Italy
2014  David     89     UK
2014  Alphonse  76     France
2014  Giovanni  53     Italy
2014  Britney   90     UK

The Result I am looking for is something like this :

Date  Name     Score  Country
2012  Giovanni  82     Italy
2012  David     80     UK
2013  David     92     UK
2013  Alphonse  68     France
2014  Britney   90     UK
2014  Silvia    87     Italy

Here is the code that I started :

df = pd.DataFrame(
    {'Date':["2012","2012","2012","2012","2012","2012","2013","2013","2013","2013","2013","2013","2014","2014","2014","2014","2014","2014"],
     'Name': ["Paul", "Silvia","David","Alphone", "Giovanni", "Britney","Paul", "Silvia","David","Alphone", "Giovanni", "Britney","Paul", "Silvia","David","Alphone", "Giovanni", "Britney"],
     'Score': [65, 81, 80, 46, 82, 53,32,59,92,68,23,78,46,87,89,76,53,90],
     "Country":["France","Italy","UK","France","Italy","UK","France","Italy","UK","France","Italy","UK","France","Italy","UK","France","Italy","UK"]})

df = df.set_index('Name').groupby('Date')["Score","Country"].apply(lambda _df: _df.sort_values(["Score"],ascending=False))

And this is what I have :

But as you can see for example in 2012, the two best scores are from the same country (Italy), so what I still have to do is :
1. Select the max per country for each year
2. Select only two best scores (and the countries have to be different).

I will be really thankful for that because I really don't know how to do it.
If somebody has some ideas on that, please share it :)

PS : please don't hesitate to tell me if it wasn't clear enough

Body:
Use DataFrame.sort_values first by 2 columns, then remove duplicates by 2 columns by DataFrame.drop_duplicates and last select top values per groups by GroupBy.head:

df1 = (df.sort_values(['Date','Score'], ascending=[True, False])
         .drop_duplicates(['Date','Country'])
         .groupby('Date')
         .head(2))
print (df1)
    Date      Name  Score Country
4   2012  Giovanni     82   Italy
2   2012     David     80      UK
8   2013     David     92      UK
9   2013  Alphonse     68  France
17  2014   Britney     90      UK
13  2014    Silvia     87   Italy


问:
How to Update data and Add new rows
I have the Invoice form so sometime I want to update the data of the same Invoice number and add now rows.

I want to update the data  and new rows on the same Invoice No, on my code below is update and add one row instead of add more than one rows which i have selected.

supposed the invoice has one row and i want to update by add 10 rows on that Invoice number, so the code below is works but it update one row and add 1 new row instead of 10(news rows).

My controller of update

```<code>public function update(Request $request, $inv_no)
{

$data = $request->all();

$date = date ("Y-m-d",  strtotime($request->Indate));

$stocks = Stock::where('inv_no', $inv_no)->get();
$i = 0;

foreach ($stocks as $stock) {
    Stock::where('inv_no', $inv_no)
        ->where('id', $stock->id)
        ->update([
            'pid' => $request->pid[$i],
            'qty' => $request->qty[$i],
            'user_id' => Auth::user()->id,
            'Indate'=>$date ,
            'supplierName' => $request->supplierName,
            'receiptNumber' => $request->receiptNumber,
            'truckNumber' => $request->truckNumber[$i],
            'driverName' => $request->driverName,
            'remark' => $request->remark,
        ]);

             $i++;
    }

    $totalPid = count($data['pid']);
    $totalQty = count($data['qty']);
    $totalTruckNumber = count($data['truckNumber']);
 // dd($stocks);

    if (count($stocks) < $totalPid) {
        Stock::create([
            'pid' => $request->pid[$totalPid-1],
            'qty' => $request->qty[$totalQty-1],
            'inv_no' => $request->inv_no,
            'user_id' => Auth::user()->id,
            'Indate'=>$date,
            'supplierName' => $request->supplierName,
            'receiptNumber' => $request->receiptNumber,
            'truckNumber' => $request->truckNumber[$totalTruckNumber-1],
            'driverName' => $request->driverName,
            'remark' => $request->remark,
        ]);
    }

return  $this->show($inv_no)->with('success', 'GRN  Edited Successfully ');
</code>```

}

below is the Invoice form which i want to Update and Add new rows.

So I need the help what can i Add there to update and able to add more rows.

答:
I got the answer this it works as well</p>

```<code>$stockcount= count($stocks);
    $totalPid = count($data['pid']);
    $totalQty = count($data['qty']);
    $totalTruckNumber = count($data['truckNumber']);

    $remain=$totalPid-$stockcount;

    for($i=$stockcount; $i<$totalPid; $i++){
        Stock::create([
            'pid' => $request->pid[$i],
            'qty' => $request->qty[$i],
            'inv_no' => $request->inv_no,
            'user_id' => Auth::user()->id,
            'Indate'=>$date,
            'supplierName' => $request->supplierName,
            'receiptNumber' => $request->receiptNumber,
            'truckNumber' => $request->truckNumber[$i],
            'driverName' => $request->driverName,
            'remark' => $request->remark,
        ]);
    }
</code>```

Title: How to Update data and Add new rows

Body:
I have the Invoice form so sometime I want to update the data of the same Invoice number and add now rows.

I want to update the data  and new rows on the same Invoice No, on my code below is update and add one row instead of add more than one rows which i have selected.

supposed the invoice has one row and i want to update by add 10 rows on that Invoice number, so the code below is works but it update one row and add 1 new row instead of 10(news rows).

My controller of update

public function update(Request $request, $inv_no)
{

$data = $request->all();

$date = date ("Y-m-d",  strtotime($request->Indate));

$stocks = Stock::where('inv_no', $inv_no)->get();
$i = 0;

foreach ($stocks as $stock) {
    Stock::where('inv_no', $inv_no)
        ->where('id', $stock->id)
        ->update([
            'pid' => $request->pid[$i],
            'qty' => $request->qty[$i],
            'user_id' => Auth::user()->id,
            'Indate'=>$date ,
            'supplierName' => $request->supplierName,
            'receiptNumber' => $request->receiptNumber,
            'truckNumber' => $request->truckNumber[$i],
            'driverName' => $request->driverName,
            'remark' => $request->remark,
        ]);

             $i++;
    }

    $totalPid = count($data['pid']);
    $totalQty = count($data['qty']);
    $totalTruckNumber = count($data['truckNumber']);
 // dd($stocks);

    if (count($stocks) < $totalPid) {
        Stock::create([
            'pid' => $request->pid[$totalPid-1],
            'qty' => $request->qty[$totalQty-1],
            'inv_no' => $request->inv_no,
            'user_id' => Auth::user()->id,
            'Indate'=>$date,
            'supplierName' => $request->supplierName,
            'receiptNumber' => $request->receiptNumber,
            'truckNumber' => $request->truckNumber[$totalTruckNumber-1],
            'driverName' => $request->driverName,
            'remark' => $request->remark,
        ]);
    }

return  $this->show($inv_no)->with('success', 'GRN  Edited Successfully ');

}

below is the Invoice form which i want to Update and Add new rows.

So I need the help what can i Add there to update and able to add more rows.

Body:
I got the answer this it works as well

$stockcount= count($stocks);
    $totalPid = count($data['pid']);
    $totalQty = count($data['qty']);
    $totalTruckNumber = count($data['truckNumber']);

    $remain=$totalPid-$stockcount;

    for($i=$stockcount; $i<$totalPid; $i++){
        Stock::create([
            'pid' => $request->pid[$i],
            'qty' => $request->qty[$i],
            'inv_no' => $request->inv_no,
            'user_id' => Auth::user()->id,
            'Indate'=>$date,
            'supplierName' => $request->supplierName,
            'receiptNumber' => $request->receiptNumber,
            'truckNumber' => $request->truckNumber[$i],
            'driverName' => $request->driverName,
            'remark' => $request->remark,
        ]);
    }


问:
How to let iphone connect json server API for debug?
I have try to use json server to call my API sample.

In simulator, I use this code to call API successfully.

```<code>//json-server -w db.json

var request = try self.buildRequestNew(requestHeader: requestHeader, from: route)

let testUrl = route.baseURL.appendingPathComponent("\(route.path)")

if testUrl == URL(string: "https://xxxxxxxxxxx.com.tw/xxxxxxx/rest/test1") {
       request = URLRequest(url: URL(string: "http://localhost:3000/test1")!) //my request change this URL.
       request.httpMethod = "GET"
}

</code>```

But when I connect iphone, it's fail.

I need to do what and change what ip address to let my API call successfully.

Thanks

答: When running in the simulator, localhost is the address of your development machine. Running on the phone, localhost refers to the phone, so you need to replace that with the hostname or IP address of your Mac. We can't tell you what that is exactly, you'll have to figue that out e.g. from System Preferences > Network.

Body:
I have try to use json server to call my API sample.

In simulator, I use this code to call API successfully.

//json-server -w db.json

var request = try self.buildRequestNew(requestHeader: requestHeader, from: route)

let testUrl = route.baseURL.appendingPathComponent("\(route.path)")

if testUrl == URL(string: "https://xxxxxxxxxxx.com.tw/xxxxxxx/rest/test1") {
       request = URLRequest(url: URL(string: "http://localhost:3000/test1")!) //my request change this URL.
       request.httpMethod = "GET"
}

But when I connect iphone, it's fail.

I need to do what and change what ip address to let my API call successfully.

Thanks


问:
Simple SwiftUI transition that doesn't seem to be working
I've been trying to get a comprehensive understanding of how Animations and Transitions work in SwiftUI.

I've been experimenting with different transitions and animations all day but one transition I want isn't working. I'll first show the code and then explain what sort of transition I want.

```<code>struct Test: View {
    @State private var pressed = false // Controls whether the tower is shown or not.

    var body: some View {
        VStack {
            Button(pressed ? "Press me to hide tower" : "Press me to show tower") {  // Controls truth value of the "pressed" variable above.
                withAnimation(.easeInOut(duration: 5)) {  // I've set the duration to 5 because I want to see the animation in slow-motion.
                    self.pressed.toggle()  // Toggles truth value of "pressed" from true to false or vice-versa.
                }
            }

            if pressed {  // Displays the Tower when "pressed" is true.
                Tower()  // Tower struct is provided below.
            }
        }
    }
}
</code>```

And this is the Tower struct:

```<code>struct Tower: View {
    var body: some View {
        VStack {
            Text("Level 3").transition(.move(edge: .leading))
            Text("Level 2")
            Text("Level 1").transition(.move(edge: .trailing))
        }
    }
}
</code>```

The transition I want to achieve is pretty straightforward - I want Level 3 to fly in from the left, Level 1 to fly in from the right, and Level 2 to just fade in and out. With this code however, Levels 1, 2 and 3, all just fade in and out together. The .move(edge: .trailing) transition seems to not work for some reason.

The catch is that I definitely want the Tower struct and the Test struct to be separate at all times.
(I don't want to copy-paste any of the code that's within the Tower struct inside of the Test struct)

If you can show me how I can make the upper and lower levels fly in from different sides please let me know (if you can provide a code sample as well it'll help a ton).

答:
Transition is an engine to present/remove a view in/from view hierarchy (with animation if animation is specified). It is applied to view as a whole, directly, and is not passed-into view's subviews. So if you try to add view into view hierarchy that does not have own transition it just appears, immediately, if there is animation then by default fade-in/out transition is applied (again, to view as a whole).

But you want to transition view's internals from outside. So here is possible solution.

Tested with Xcode 11.4 / iOS 13.4 (you can play with animations by yourself)

```<code>struct Test: View {
    @State private var pressed = false

    var body: some View {
        VStack {
            Button(pressed ? "Press me to hide tower" : "Press me to show tower") {
                self.pressed.toggle()
            }

            Tower(show: $pressed)
        }.animation(.easeInOut)
    }
}

struct Tower: View {
    @Binding var show: Bool
    var body: some View {
        VStack {
            if show {
                Text("Level 3").transition(.move(edge: .leading))
                Text("Level 2")
                Text("Level 1").transition(.move(edge: .trailing))
            }
        }
        .animation(.easeInOut)
    }
}
</code>```

Body:
I've been trying to get a comprehensive understanding of how Animations and Transitions work in SwiftUI.

I've been experimenting with different transitions and animations all day but one transition I want isn't working. I'll first show the code and then explain what sort of transition I want.

struct Test: View {
    @State private var pressed = false // Controls whether the tower is shown or not.

    var body: some View {
        VStack {
            Button(pressed ? "Press me to hide tower" : "Press me to show tower") {  // Controls truth value of the "pressed" variable above.
                withAnimation(.easeInOut(duration: 5)) {  // I've set the duration to 5 because I want to see the animation in slow-motion.
                    self.pressed.toggle()  // Toggles truth value of "pressed" from true to false or vice-versa.
                }
            }

            if pressed {  // Displays the Tower when "pressed" is true.
                Tower()  // Tower struct is provided below.
            }
        }
    }
}

And this is the Tower struct:

struct Tower: View {
    var body: some View {
        VStack {
            Text("Level 3").transition(.move(edge: .leading))
            Text("Level 2")
            Text("Level 1").transition(.move(edge: .trailing))
        }
    }
}

The transition I want to achieve is pretty straightforward - I want Level 3 to fly in from the left, Level 1 to fly in from the right, and Level 2 to just fade in and out. With this code however, Levels 1, 2 and 3, all just fade in and out together. The .move(edge: .trailing) transition seems to not work for some reason.

The catch is that I definitely want the Tower struct and the Test struct to be separate at all times.
(I don't want to copy-paste any of the code that's within the Tower struct inside of the Test struct)

If you can show me how I can make the upper and lower levels fly in from different sides please let me know (if you can provide a code sample as well it'll help a ton).

Body:
Transition is an engine to present/remove a view in/from view hierarchy (with animation if animation is specified). It is applied to view as a whole, directly, and is not passed-into view's subviews. So if you try to add view into view hierarchy that does not have own transition it just appears, immediately, if there is animation then by default fade-in/out transition is applied (again, to view as a whole).

But you want to transition view's internals from outside. So here is possible solution.

Tested with Xcode 11.4 / iOS 13.4 (you can play with animations by yourself)

struct Test: View {
    @State private var pressed = false

    var body: some View {
        VStack {
            Button(pressed ? "Press me to hide tower" : "Press me to show tower") {
                self.pressed.toggle()
            }

            Tower(show: $pressed)
        }.animation(.easeInOut)
    }
}

struct Tower: View {
    @Binding var show: Bool
    var body: some View {
        VStack {
            if show {
                Text("Level 3").transition(.move(edge: .leading))
                Text("Level 2")
                Text("Level 1").transition(.move(edge: .trailing))
            }
        }
        .animation(.easeInOut)
    }
}


问:
using passportjs passport.authenticate() in Sapper route or sapper middleware
I used passportjs in the past with expressjs and currently I'm trying to incorporate it with Sapper app but I'm unable to figure out how to inlcude the passport.authenticate() in my route because it's a sapper route not an express route. Also if I try to run everything in my server.js file I run into the issue of how to integrate it with the sapper middleware.
How do you use passport.authenticate() in/with Sapper middleware or sapper routes js files (which is the front not server routes)?

My server.js is typical:

```<code>const sirv = require('sirv');
import express from 'express';
var cookieParser = require('cookie-parser');
import * as sapper from '@sapper/server';
const session = require('express-session');
var passport = require('passport');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/passport', {
 useNewUrlParser: true });
const MongoStore = require('connect-mongo')(session);
const bodyParser = require('body-parser');

const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());

app.use(session({
    secret: 'keyboard cat',
    resave: false,
    saveUninitialized: true,
    store: new MongoStore({ url: 'mongodb://localhost/passport' }),
    cookie: { secure: false, maxAge: 1000 * 60 * 60 * 24 * 7 }
}));
app.use(passport.initialize());
app.use(passport.session());

const { PORT, NODE_ENV } = process.env;
const dev = NODE_ENV === 'development';

const assets = sirv('static', {
    maxAge: 31536000, // 1Y
    immutable: true
});

 app.use(assets, sapper.middleware({
    session: req => ({
        user: req.session && req.session.user
    })})).listen(process.env.PORT, err => { if (err) console.log('error', err); });
</code>```

As you can see, Sapper is just a middleware so if I want to authenticate a user and send it to the front/sapper, I need to figure out how to run passport.authenticate() inside the middleware function, right?

If I want to use passport in the route JS file which is sapper front route:

```<code>//How to import passport.js here to make passport.authenticate() middleware available?
import passport from './passport';
import User from './mongoso';

export async function post(req, res, next) {

    res.setHeader('Content-Type', 'application/json');
    /* Retrieve the data */
    var data = req.body;

    req.session.user = data.email;
    console.log("Here's the posted data:", data);
    console.log("information in the session is:", req.session);

    /* Returns the result */
    return res.end(JSON.stringify({ Email: req.session.user }));
    //return res.json({ data: data });

}
</code>```

Any ideas?  Greatly appreciated if someone out there could help.

答:
I used the answer from DioXine to implement Google Auth.

The cookie is now also http only.

import sirv from "sirv";
import express from "express";
import bodyParser from "body-parser";
import session from "express-session";
import sessionFileStore from "session-file-store";
import compression from "compression";
import * as sapper from "@sapper/server";
import passport from "passport";
import { Strategy as GoogleStrategy } from "passport-google-oauth20";

const { PORT, NODE_ENV } = process.env;
const dev = NODE_ENV === "development";

passport.use(
  new GoogleStrategy(
    {
      clientID: GOOGLE_CLIENT_ID,
      clientSecret: GOOGLE_CLIENT_SECRET,
      callbackURL: "http://localhost:3000/auth/google/callback",
    },
    function (accessToken, refreshToken, profile, cb) {
      // User.findOrCreate({ googleId: profile.id }, function (err, user) {
      //   return cb(err, user);
      // });
      return cb(null, profile);
    }
  )
);

passport.serializeUser(function (user, cb) {
  cb(null, user);
});

passport.deserializeUser(function (obj, cb) {
  cb(null, obj);
});

const FileStore = sessionFileStore(session);

const sessionConfig = {
  secret: "sefmvks4Fgblolf4sdJHBd",
  resave: false,
  saveUninitialized: true,
  cookie: {
    httpOnly: true,
    maxAge: 31536000,
  },
  //TODO: redis
  store: new FileStore({
    path: `.sessions`,
  }),
};

express()
  .use(passport.initialize())
  .use(bodyParser.json())
  .use(session(sessionConfig))

  .get("/auth/google", passport.authenticate("google", { scope: ["profile"] }))
  .get(
    "/auth/google/callback",
    passport.authenticate("google", { failureRedirect: "/auth/login" }),
    (req, res) => {
      res.redirect("/");
    }
  )
  .get("/auth/logout", (req, res) => {
    req.logout();
    req.session.destroy(function (err) {
      res.redirect("/");
    });
  })
  .use(
    compression({ threshold: 0 }),
    sirv("static", { dev }),
    sapper.middleware({
      session: (req) => {
        const user = req.session.passport ? req.session.passport.user.id : null;
        return { user };
      },
    })
  )
  .listen(PORT, (err) => {
    if (err) console.log("error", err);
  });
```

<p>This is not changed:</p>

<pre class="lang-html prettyprint-override"><code><script context="module">
  export function preload(page, { user }) {
    return { user };
  }
</script>

<script>
  import { stores } from "@sapper/app";
  import { onMount } from "svelte";

  const { session } = stores();
  export let user;

  onMount(() => {
    console.log($session);
  });

</script>

<div>
  {#if !user}
    <p>Not logged in</p>
  {:else}
    <p>Logged in!</p>
  {/if}
</div>
</code>```

If it only works after refresh check this:
https://github.com/sveltejs/sapper/issues/567#issuecomment-542788270

Body:
I used passportjs in the past with expressjs and currently I'm trying to incorporate it with Sapper app but I'm unable to figure out how to inlcude the passport.authenticate() in my route because it's a sapper route not an express route. Also if I try to run everything in my server.js file I run into the issue of how to integrate it with the sapper middleware.
How do you use passport.authenticate() in/with Sapper middleware or sapper routes js files (which is the front not server routes)?

My server.js is typical:

const sirv = require('sirv');
import express from 'express';
var cookieParser = require('cookie-parser');
import * as sapper from '@sapper/server';
const session = require('express-session');
var passport = require('passport');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/passport', {
 useNewUrlParser: true });
const MongoStore = require('connect-mongo')(session);
const bodyParser = require('body-parser');

const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());

app.use(session({
    secret: 'keyboard cat',
    resave: false,
    saveUninitialized: true,
    store: new MongoStore({ url: 'mongodb://localhost/passport' }),
    cookie: { secure: false, maxAge: 1000 * 60 * 60 * 24 * 7 }
}));
app.use(passport.initialize());
app.use(passport.session());

const { PORT, NODE_ENV } = process.env;
const dev = NODE_ENV === 'development';

const assets = sirv('static', {
    maxAge: 31536000, // 1Y
    immutable: true
});

 app.use(assets, sapper.middleware({
    session: req => ({
        user: req.session && req.session.user
    })})).listen(process.env.PORT, err => { if (err) console.log('error', err); });

As you can see, Sapper is just a middleware so if I want to authenticate a user and send it to the front/sapper, I need to figure out how to run passport.authenticate() inside the middleware function, right?

If I want to use passport in the route JS file which is sapper front route:

//How to import passport.js here to make passport.authenticate() middleware available?
import passport from './passport';
import User from './mongoso';

export async function post(req, res, next) {

    res.setHeader('Content-Type', 'application/json');
    /* Retrieve the data */
    var data = req.body;

    req.session.user = data.email;
    console.log("Here's the posted data:", data);
    console.log("information in the session is:", req.session);

    /* Returns the result */
    return res.end(JSON.stringify({ Email: req.session.user }));
    //return res.json({ data: data });

}

Any ideas?  Greatly appreciated if someone out there could help.

Body:
I used the answer from DioXine to implement Google Auth.

The cookie is now also http only.

import sirv from "sirv";
import express from "express";
import bodyParser from "body-parser";
import session from "express-session";
import sessionFileStore from "session-file-store";
import compression from "compression";
import * as sapper from "@sapper/server";
import passport from "passport";
import { Strategy as GoogleStrategy } from "passport-google-oauth20";

const { PORT, NODE_ENV } = process.env;
const dev = NODE_ENV === "development";

passport.use(
  new GoogleStrategy(
    {
      clientID: GOOGLE_CLIENT_ID,
      clientSecret: GOOGLE_CLIENT_SECRET,
      callbackURL: "http://localhost:3000/auth/google/callback",
    },
    function (accessToken, refreshToken, profile, cb) {
      // User.findOrCreate({ googleId: profile.id }, function (err, user) {
      //   return cb(err, user);
      // });
      return cb(null, profile);
    }
  )
);

passport.serializeUser(function (user, cb) {
  cb(null, user);
});

passport.deserializeUser(function (obj, cb) {
  cb(null, obj);
});

const FileStore = sessionFileStore(session);

const sessionConfig = {
  secret: "sefmvks4Fgblolf4sdJHBd",
  resave: false,
  saveUninitialized: true,
  cookie: {
    httpOnly: true,
    maxAge: 31536000,
  },
  //TODO: redis
  store: new FileStore({
    path: `.sessions`,
  }),
};

express()
  .use(passport.initialize())
  .use(bodyParser.json())
  .use(session(sessionConfig))

  .get("/auth/google", passport.authenticate("google", { scope: ["profile"] }))
  .get(
    "/auth/google/callback",
    passport.authenticate("google", { failureRedirect: "/auth/login" }),
    (req, res) => {
      res.redirect("/");
    }
  )
  .get("/auth/logout", (req, res) => {
    req.logout();
    req.session.destroy(function (err) {
      res.redirect("/");
    });
  })
  .use(
    compression({ threshold: 0 }),
    sirv("static", { dev }),
    sapper.middleware({
      session: (req) => {
        const user = req.session.passport ? req.session.passport.user.id : null;
        return { user };
      },
    })
  )
  .listen(PORT, (err) => {
    if (err) console.log("error", err);
  });

This is not changed:

<script context="module">
  export function preload(page, { user }) {
    return { user };
  }
</script>

<script>
  import { stores } from "@sapper/app";
  import { onMount } from "svelte";

  const { session } = stores();
  export let user;

  onMount(() => {
    console.log($session);
  });

</script>

<div>
  {#if !user}
    <p>Not logged in</p>
  {:else}
    <p>Logged in!</p>
  {/if}
</div>

If it only works after refresh check this:
https://github.com/sveltejs/sapper/issues/567#issuecomment-542788270


问:
Angular 9 prodution build sub-directory crash on reload, fix this for both apache and nginx servers
Angular apps on production build crash on reload from a sub-directory. Say, https://example.com/contact and it works as expected but whenever refreshed the page, the page crashes. However, this phenomenon doesn't happen with the homepage.
To avoid this, there is HashLocationStrategy available. But this has its own demerit. This adds an # in the URL, so the URL becomes https://example.com/#/contact and apparently the URL looks ugly.

Some answers on forums say that this happens because angular serves routes from root URL and it could be fixed by serving requests from root URL however I have no idea how to do that.

What would be a good approach to fix the crash on reload issue without including # in URl? If this could be solved by serving rules, then please mention configurations for both Apache and Nginx.

Edit: this is the error:
Object not found! The requested URL was not found on this server. If you entered the URL manually please check your spelling and try again. If you think this is a server error, please contact the webmaster.

答:
try this configuration</p>

```<code>location / {
  root /usr/share/nginx/html; #set your root
  index index.html index.htm;
  try_files $uri $uri/ /index.html =404;
}
</code>```

Body:
try this configuration

location / {
  root /usr/share/nginx/html; #set your root
  index index.html index.htm;
  try_files $uri $uri/ /index.html =404;
}


问:
INST:07545:Unexpected error.java.lang.NullPointerException
while installing (oracle fusion middleware 12c infrastructure installation) getting INST:07545:Unexpected error.java.lang.NullPointerException  fail to create
folder in C:\Oracle\Middleware\Oracle_Home

答:
You can set up new temp dir and restart installation process.

```<code>**1.** Create a new Temp directory.

eg:
E:\Temp
**2.** Set temp environment variable as

set TEMP=E:\Temp
set TMP=E:\Temp
**3.** Start the installer from the same prompt as

java -jar fmw_12.2.1.4.0_wls.jar
OR

Installer can be started using the command

java -Djava.io.tmpdir=E:\Temp -jar fmw_12.2.1.4.0_wls.jar
</code>```

Body:
You can set up new temp dir and restart installation process.

**1.** Create a new Temp directory.

eg:
E:\Temp
**2.** Set temp environment variable as

set TEMP=E:\Temp
set TMP=E:\Temp
**3.** Start the installer from the same prompt as

java -jar fmw_12.2.1.4.0_wls.jar
OR

Installer can be started using the command

java -Djava.io.tmpdir=E:\Temp -jar fmw_12.2.1.4.0_wls.jar