问:
How to multiply a number until it reaches a specific number in Python?
I want this code to multiply this list until all numbers exceeds 100, but I am struggling in the loop part.

import numpy as np

a = np.array([230, 10, 284, 39, 76])

def all_30_or_up(ls):
    for i in ls:
        if i < 100:
            return False
    return True

while True:
    if all_30_or_up(a) == False:
        print(a*2)
    else:
        break
```
<p>This exercise is from the book "How to Think Like a Computer Scientist: Learning with Python 3". That's the actual question in the book:</p>
<p>"Use a mask to multiply all values below 100 in the following list by 2:</p>
<pre class="lang-py prettyprint-override"><code>a = np.array([230, 10, 284, 39, 76])
</code>```

Repeat this until all values are above 100. (Not manually, but by looping)
Then, select all values between 150 < a < 200."

答:
As the question states, you need to use a mask here to select the indices where the value is below 100. Let's use the dataset given by the exercise.

import numpy as np
a = np.array([230, 10, 284, 39, 76])
```
<p>First we need to be able to efficiently check if all values are above 100 or not. We can do so by performing comparison over the whole array, which returns an array of boolean, and check their values:</p>
<pre class="lang-py prettyprint-override"><code># To check if all values are above 100:
np.all(a>100) # or alternatively: np.any(a<100)
</code>```

Now we need a way to select only indices where the value is below 100. Fortunately, we can use complex indexing with numpy, and actually use a comparison over the whole array, which gives an array of boolean, and use it inside the [] to select indices where the result of the comparison is True. We then multiply those by two, and update them.

a[a<100] = a[a<100]*2
# or inplace multiplication:
a[a<100] *= 2
```
<p>Now we need to put all that into a loop:</p>
<pre class="lang-py prettyprint-override"><code>while not np.all(a>100):
    a[a<100] *= 2
</code>```

And here you have it!

Body:
I want this code to multiply this list until all numbers exceeds 100, but I am struggling in the loop part.

import numpy as np

a = np.array([230, 10, 284, 39, 76])

def all_30_or_up(ls):
    for i in ls:
        if i < 100:
            return False
    return True

while True:
    if all_30_or_up(a) == False:
        print(a*2)
    else:
        break

This exercise is from the book "How to Think Like a Computer Scientist: Learning with Python 3". That's the actual question in the book:

"Use a mask to multiply all values below 100 in the following list by 2:

a = np.array([230, 10, 284, 39, 76])

Repeat this until all values are above 100. (Not manually, but by looping)
Then, select all values between 150 < a < 200."

Body:
As the question states, you need to use a mask here to select the indices where the value is below 100. Let's use the dataset given by the exercise.

import numpy as np
a = np.array([230, 10, 284, 39, 76])

First we need to be able to efficiently check if all values are above 100 or not. We can do so by performing comparison over the whole array, which returns an array of boolean, and check their values:

# To check if all values are above 100:
np.all(a>100) # or alternatively: np.any(a<100)

Now we need a way to select only indices where the value is below 100. Fortunately, we can use complex indexing with numpy, and actually use a comparison over the whole array, which gives an array of boolean, and use it inside the [] to select indices where the result of the comparison is True. We then multiply those by two, and update them.

a[a<100] = a[a<100]*2
# or inplace multiplication:
a[a<100] *= 2

Now we need to put all that into a loop:

while not np.all(a>100):
    a[a<100] *= 2

And here you have it!


来源: stackexchange

问:
React addEventListener handler function called TWICE
Having such simple React main App file:

```<code>import React from 'react';
import './App.css';

import { BrowserRouter as Router, Routes, Route, Link } from 'react-router-dom';

import {Header} from "./Components/header"
import {Footer} from "./Components/footer"
import {Sidebar} from "./Components/sidebar"
import {About} from "./Components/about"
import {User} from "./Components/user"

const listener = () => {
    console.log("Main listener")
};

function App() {

    const media = window.matchMedia('(min-width: 700px)');
    media.addEventListener("change", listener);

    return (
        <Router>
            <div className="App">

                <Header />
                <Sidebar />
                <Footer />

                <Routes>
                    <Route path="/"></Route>
                    <Route path="/about" element={<About/>}></Route>
                    <Route path="/user" element={<User/>}></Route>
                </Routes>

                <div className="App">
                    <ul>
                    <li>
                        <Link to="/">Home</Link>
                    </li>
                    <li>
                        <Link to="/about">About</Link>
                    </li>
                    <li>
                        <Link to="/user">User</Link>
                    </li>
                    </ul>
                </div>

            </div>
        </Router>
    );
}

export default App;
</code>```

The thing that makes me wonder is that the change event handler function (listener) is called TWICE! when I resize the browser window. Why isn't the handler function called just once as expected?

答:
You cannot expect App to be called only once. It will be called in every rerender (by React renderer when it wants to).

Normally, event listers are added when the component is mounted and they are removed when the component is getting unmounted to avoid possible memory leaks.

It can be done using a useEffect as below.

```<code>import React, { useEffect } from "react";
...
...

const listener = () => {
    console.log("Main listener");
};

function App() {
    useEffect(() => {
        const media = window.matchMedia("(min-width: 700px)");

        // add the event listener
        media.addEventListener("change", listener);

        return () => {
            // remove the event listener
            media.removeEventListener("change", listener);
        };
    }, []);

    return (
        ...
        ...
    );
}

export default App;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Having such simple React main App file:

import React from 'react';
import './App.css';

import { BrowserRouter as Router, Routes, Route, Link } from 'react-router-dom';

import {Header} from "./Components/header"
import {Footer} from "./Components/footer"
import {Sidebar} from "./Components/sidebar"
import {About} from "./Components/about"
import {User} from "./Components/user"

const listener = () => {
    console.log("Main listener")
};

function App() {

    const media = window.matchMedia('(min-width: 700px)');
    media.addEventListener("change", listener);

    return (
        <Router>

                <Sidebar />

                <Routes>
                    <Route path="/"></Route>
                    <Route path="/about" element={<About/>}></Route>
                    <Route path="/user" element={<User/>}></Route>
                </Routes>

                        <Link to="/">Home</Link>

                        <Link to="/about">About</Link>

                        <Link to="/user">User</Link>

        </Router>
    );
}

export default App;

The thing that makes me wonder is that the change event handler function (listener) is called TWICE! when I resize the browser window. Why isn't the handler function called just once as expected?

Body:
You cannot expect App to be called only once. It will be called in every rerender (by React renderer when it wants to).

Normally, event listers are added when the component is mounted and they are removed when the component is getting unmounted to avoid possible memory leaks.

It can be done using a useEffect as below.

import React, { useEffect } from "react";
...
...

const listener = () => {
    console.log("Main listener");
};

function App() {
    useEffect(() => {
        const media = window.matchMedia("(min-width: 700px)");

        // add the event listener
        media.addEventListener("change", listener);

        return () => {
            // remove the event listener
            media.removeEventListener("change", listener);
        };
    }, []);

    return (
        ...
        ...
    );
}

export default App;


问:
I am new to spring boot.While I am running my Spring Boot Application I am getting below error
I am getting this error:
org.springframework.beans.factory.UnsatisfiedDependencyException</p>

答:
Spring is a Dependency Injection framework. Among other things, this means it provides objects to constructors (and not only) at runtime. If it searches for an object which is required and it cannot find it, an UnsatisfiedDependencyException is thrown.

For example, if you have class A which requires instances of classes B and C in its constructor, Spring searches for instances of B and C (also known as Beans) which may be used to instantiate A. If it cannot find at least one dependency, let’s say an instance of C, it throws the exception you’re receiving.


问:
Change Pin Color when user tapped
I would change the color from red to green of an annotation when the user pin tapped addition to changing its title and subtitle.

I am truly lost. I searched how to make a custom annotation pin, ok. I found the implementation of the method when the user touches the pin didSelectAnnotationView and it works when I tap the annotation NSLog(@"Tap") ; , but now I can not change the pin that was touched.

Thank you very much everyone for your contributions.

Ciao

答:
In your method set the pinColor property of your MKAnnotationView as follows:

```<code>annotationView.pinColor = MKPinAnnotationColorRed; // Green or Purple
</code>```

ContentLicense: CC BY-SA 3.0

Title: Change Pin Color when user tapped

Body:
In your method set the pinColor property of your MKAnnotationView as follows:

annotationView.pinColor = MKPinAnnotationColorRed; // Green or Purple


问:
webpack 5 Error "Can't resolve 'uglify-js', '@swc/core', 'esbuild'
I have some errors with webpack 5, express, github actions.
I use the github actions because want to use github secrets.
also, I use webpack because of using the secrets in the code.

anyway, I got errors below,

```<code>ERROR in ./node_modules/terser-webpack-plugin/dist/utils.js 479:6-26
Module not found: Error: Can't resolve 'uglify-js' in '/Users/luna/workspace/express_api/node_modules/terser-webpack-plugin/dist'
@ ./node_modules/terser-webpack-plugin/dist/index.js 27:4-22
@ ./webpack.config.js 2:21-53
@ ./app.js 13:15-45

ERROR in ./node_modules/terser-webpack-plugin/dist/utils.js 557:14-34
Module not found: Error: Can't resolve '@swc/core' in '/Users/luna/workspace/express_api/node_modules/terser-webpack-plugin/dist'
@ ./node_modules/terser-webpack-plugin/dist/index.js 27:4-22
@ ./webpack.config.js 2:21-53
@ ./app.js 13:15-45

ERROR in ./node_modules/terser-webpack-plugin/dist/utils.js 635:18-36
Module not found: Error: Can't resolve 'esbuild' in '/Users/luna/workspace/express_api/node_modules/terser-webpack-plugin/dist'
@ ./node_modules/terser-webpack-plugin/dist/index.js 27:4-22
@ ./webpack.config.js 2:21-53
@ ./app.js 13:15-45
</code>```

Also, got 15 warnings. if you want to the warnings, let me know.

what is the problem?

Below is the webpack.config.js

const webpack = require("webpack");

module.exports = {
  target: "async-node",
  mode: "production",
  entry: "./app.js",
  output: {
    path: "/dist",
    filename: "main.js",
  },
  plugins: [
    new webpack.DefinePlugin({
      "process.env.PA_URL": JSON.stringify(process.env.PA_URL),
      "process.env.PA5_EMAIL": JSON.stringify(process.env.PA5_EMAIL),
      "process.env.PA5_PASSWORD": JSON.stringify(process.env.PA5_PASSWORD),
    }),
  ],
};

```

the webpack version is wrong?

答:
You are bundling your entry file, but also any node_modules your ./app.js requires, which in turn tries to require a bunch of third-party stuff, which is not available - hence the errors on missing modules.

Exclude those node_modules by extending your webpack config:
yarn add -D webpack-node-externals
(see: https://www.npmjs.com/package/webpack-node-externals)

```<code>const webpack = require("webpack");
const nodeExternals = require("webpack-node-externals");

module.exports = {
  target: "async-node",
  mode: "production",
  entry: "./app.js",
  externalsPresets: { node: true },   // <-- here
  externals: [nodeExternals()],       // <-- and here
  ...etc
</code>```

That should exclude them and you should be good to go.

Body:
I have some errors with webpack 5, express, github actions.
I use the github actions because want to use github secrets.
also, I use webpack because of using the secrets in the code.

anyway, I got errors below,

ERROR in ./node_modules/terser-webpack-plugin/dist/utils.js 479:6-26
Module not found: Error: Can't resolve 'uglify-js' in '/Users/luna/workspace/express_api/node_modules/terser-webpack-plugin/dist'
@ ./node_modules/terser-webpack-plugin/dist/index.js 27:4-22
@ ./webpack.config.js 2:21-53
@ ./app.js 13:15-45

ERROR in ./node_modules/terser-webpack-plugin/dist/utils.js 557:14-34
Module not found: Error: Can't resolve '@swc/core' in '/Users/luna/workspace/express_api/node_modules/terser-webpack-plugin/dist'
@ ./node_modules/terser-webpack-plugin/dist/index.js 27:4-22
@ ./webpack.config.js 2:21-53
@ ./app.js 13:15-45

ERROR in ./node_modules/terser-webpack-plugin/dist/utils.js 635:18-36
Module not found: Error: Can't resolve 'esbuild' in '/Users/luna/workspace/express_api/node_modules/terser-webpack-plugin/dist'
@ ./node_modules/terser-webpack-plugin/dist/index.js 27:4-22
@ ./webpack.config.js 2:21-53
@ ./app.js 13:15-45

Also, got 15 warnings. if you want to the warnings, let me know.

what is the problem?

Below is the webpack.config.js

const webpack = require("webpack");

module.exports = {
  target: "async-node",
  mode: "production",
  entry: "./app.js",
  output: {
    path: "/dist",
    filename: "main.js",
  },
  plugins: [
    new webpack.DefinePlugin({
      "process.env.PA_URL": JSON.stringify(process.env.PA_URL),
      "process.env.PA5_EMAIL": JSON.stringify(process.env.PA5_EMAIL),
      "process.env.PA5_PASSWORD": JSON.stringify(process.env.PA5_PASSWORD),
    }),
  ],
};

the webpack version is wrong?

Body:
You are bundling your entry file, but also any node_modules your ./app.js requires, which in turn tries to require a bunch of third-party stuff, which is not available - hence the errors on missing modules.

Exclude those node_modules by extending your webpack config:
yarn add -D webpack-node-externals
(see: https://www.npmjs.com/package/webpack-node-externals)

const webpack = require("webpack");
const nodeExternals = require("webpack-node-externals");

module.exports = {
  target: "async-node",
  mode: "production",
  entry: "./app.js",
  externalsPresets: { node: true },   // <-- here
  externals: [nodeExternals()],       // <-- and here
  ...etc

That should exclude them and you should be good to go.


问:
Show the content of the function in the div
How do I show myFunction content in myDiv div? So show "Example"?

function myFunction() {
  document.getElementById("demo").innerHTML = "Example!";
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.myDiv {
  border: 5px outset red;
  background-color: lightblue;
  text-align: center;
}</code>```

```

答:
You can solve this just by using the getElementById no need for a function.

document.getElementById("demo").innerHTML = "Example!";```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.myDiv {
  border: 5px outset red;
  background-color: lightblue;
  text-align: center;
}</code>```

```

Body:
How do I show myFunction content in myDiv div? So show "Example"?

function myFunction() {
  document.getElementById("demo").innerHTML = "Example!";
}

.myDiv {
  border: 5px outset red;
  background-color: lightblue;
  text-align: center;
}

Body:
You can solve this just by using the getElementById no need for a function.

document.getElementById("demo").innerHTML = "Example!";

.myDiv {
  border: 5px outset red;
  background-color: lightblue;
  text-align: center;
}

<div class="myDiv">
  <p id="demo"><p>
</div>


问:
How Can i show multiple php form field in one page without sql?
I'm new to development. Try to Learning php but I'm Having issue with php form. Here Is my Problem. I have Two Form In a page. So, When I submit data in first form then second form show > > Undefined index. Other hand,  When I submit data in second form then first form show > >  Undefined index. I'm try to receive data using >>> $_SERVER["PHP_SELF"]

Here Is my Enter Code

```<code><!DOCTYPE html>
<html>
    <head>
        <title> Hello world</title>
        <link rel= "stylesheet" href="style.css" />
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
    </head>
    <body class="container mt-5">
        <?php
            $name=$email="";
            if($_SERVER["REQUEST_METHOD"]=="POST"){
                $name = test_input($_POST["name"]);
                $email = test_input($_POST["email"]);
            }
            function test_input($data){
                $data = trim($data);
                $data = stripslashes($data);
                $data = htmlspecialchars($data);
                return $data;
            }
        ?>
        <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post" class="row">
            <div class="col-auto">
                <label class="visually-hidden" for="autoSizingInput"> Name</label>
                <input type="text" class="form-control" id="autoZizingInput" name="name" placeholder="User name"></input>
            </div>
            <div class="col-auto">
            <input type="email" class="form-control" id="autoZizingInput" name="email" placeholder="Enter Email"></input>

            </div>
            <div class="col-auto">
            <button type="submit" class="btn btn-primary">Submit</button>
            </div>

        </form>
        <div class="container">
            <div class="row mt-5">
               <?php
                if(!empty($name)&& !empty($email)):?>
                    <h1>Your Name Is <?php echo $name;?> & Email Address <?php echo $email;?></h1>
                    <?php
                endif;
               ?>
            </div>
        </div>

            <?php
                $color="";
                if($_SERVER["REQUEST_METHOD"]=="POST"):
                  $color = $_POST["color"];
                endif;
            ?>
            <form class="row mt-5" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
                <input type="text" class="form-control" placeholder="Enter colot name" name="color"></input>
                <button type="submit" class="btn btn-danger mt-5"> Submit</button>
            </form>
            <div class="row">
                <?php
                    if(!empty($color)):?>
                    <h1>Color Is <?php echo $color;?><h1>
                  <?php
                    endif;
                ?>
            </div>

    </body>
</html>
</code>```

答:
```<code>    <!DOCTYPE html>
<html>

<head>
  <title> Hello world</title>
  <link rel="stylesheet" href="style.css" />
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
</head>

<body class="container mt-5">
  <?php
  $name = "";
  $email = "";
  if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $name = test_input(isset($_POST["name"]) ? $_POST["name"] : '');
    $email = test_input(isset($_POST["email"]) ? $_POST["email"] : '');
  }
  function test_input($data)
  {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
  }
  ?>
  <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post" class="row">
    <div class="col-auto">
      <label class="visually-hidden" for="autoSizingInput"> Name</label>
      <input type="text" class="form-control" id="autoZizingInput" name="name" placeholder="User name"></input>
    </div>
    <div class="col-auto">
      <input type="email" class="form-control" id="autoZizingInput" name="email" placeholder="Enter Email"></input>

    </div>
    <div class="col-auto">
      <button type="submit" class="btn btn-primary">Submit</button>
    </div>

  </form>
  <div class="container">
    <div class="row mt-5">
      <?php
      if (!empty($name) && !empty($email)) : ?>
        <h1>Your Name Is <?php echo isset($name) ? $name : ''; ?> & Email Address <?php echo isset($email) ? $email : ''; ?></h1>
      <?php
      endif;
      ?>
    </div>
  </div>

  <?php
  $color = "";
  if ($_SERVER["REQUEST_METHOD"] == "POST") :
    $color =  isset($_POST["color"]) ? $_POST["color"] : '';
  endif;
  ?>
  <form class="row mt-5" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
    <input type="text" class="form-control" placeholder="Enter colot name" name="color"></input>
    <button type="submit" class="btn btn-danger mt-5"> Submit</button>
  </form>
  <div class="row">
    <?php
    if (!empty($color)) : ?>
      <h1>Color Is <?php echo $color; ?><h1>
        <?php
      endif;
        ?>
  </div>

</body>

</html>
</code>```

The isset() function checks whether a variable is set, which means that it has to be declared and is not NULL.

This function returns true if the variable exists and is not NULL, otherwise it returns false.

Body:
I'm new to development. Try to Learning php but I'm Having issue with php form. Here Is my Problem. I have Two Form In a page. So, When I submit data in first form then second form show > > Undefined index. Other hand,  When I submit data in second form then first form show > >  Undefined index. I'm try to receive data using >>> $_SERVER["PHP_SELF"]

Here Is my Enter Code

<!DOCTYPE html>

        <title> Hello world</title>
        <link rel= "stylesheet" href="style.css" />
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">

        <?php
            $name=$email="";
            if($_SERVER["REQUEST_METHOD"]=="POST"){
                $name = test_input($_POST["name"]);
                $email = test_input($_POST["email"]);
            }
            function test_input($data){
                $data = trim($data);
                $data = stripslashes($data);
                $data = htmlspecialchars($data);
                return $data;
            }
        ?>
        <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post" class="row">

                 Name
                <input type="text" class="form-control" id="autoZizingInput" name="name" placeholder="User name"></input>

            <input type="email" class="form-control" id="autoZizingInput" name="email" placeholder="Enter Email"></input>

            <button type="submit" class="btn btn-primary">Submit</button>

        </form>

               <?php
                if(!empty($name)&& !empty($email)):?>

Your Name Is <?php echo $name;?> & Email Address <?php echo $email;?>

                    <?php
                endif;
               ?>

            <?php
                $color="";
                if($_SERVER["REQUEST_METHOD"]=="POST"):
                  $color = $_POST["color"];
                endif;
            ?>
            <form class="row mt-5" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
                <input type="text" class="form-control" placeholder="Enter colot name" name="color"></input>
                <button type="submit" class="btn btn-danger mt-5"> Submit</button>
            </form>

                <?php
                    if(!empty($color)):?>

Color Is <?php echo $color;?>

                  <?php
                    endif;
                ?>

Body:
    <!DOCTYPE html>
<html>

<head>
  <title> Hello world</title>
  <link rel="stylesheet" href="style.css" />
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
</head>

<body class="container mt-5">
  <?php
  $name = "";
  $email = "";
  if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $name = test_input(isset($_POST["name"]) ? $_POST["name"] : '');
    $email = test_input(isset($_POST["email"]) ? $_POST["email"] : '');
  }
  function test_input($data)
  {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
  }
  ?>
  <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post" class="row">
    <div class="col-auto">
      <label class="visually-hidden" for="autoSizingInput"> Name</label>
      <input type="text" class="form-control" id="autoZizingInput" name="name" placeholder="User name"></input>
    </div>
    <div class="col-auto">
      <input type="email" class="form-control" id="autoZizingInput" name="email" placeholder="Enter Email"></input>

    </div>
    <div class="col-auto">
      <button type="submit" class="btn btn-primary">Submit</button>
    </div>

  </form>
  <div class="container">
    <div class="row mt-5">
      <?php
      if (!empty($name) && !empty($email)) : ?>
        <h1>Your Name Is <?php echo isset($name) ? $name : ''; ?> & Email Address <?php echo isset($email) ? $email : ''; ?></h1>
      <?php
      endif;
      ?>
    </div>
  </div>

  <?php
  $color = "";
  if ($_SERVER["REQUEST_METHOD"] == "POST") :
    $color =  isset($_POST["color"]) ? $_POST["color"] : '';
  endif;
  ?>
  <form class="row mt-5" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
    <input type="text" class="form-control" placeholder="Enter colot name" name="color"></input>
    <button type="submit" class="btn btn-danger mt-5"> Submit</button>
  </form>
  <div class="row">
    <?php
    if (!empty($color)) : ?>
      <h1>Color Is <?php echo $color; ?><h1>
        <?php
      endif;
        ?>
  </div>

</body>

</html>

The isset() function checks whether a variable is set, which means that it has to be declared and is not NULL.

This function returns true if the variable exists and is not NULL, otherwise it returns false.


问:
Overload typescript property from npm package
Problem: Using a 3rd party npm package that has a d.ts file with definitions that are wrong

Looking for: a solution how to overload/introduce the correct types

What is seen on the snapshot is wrong , in fact the function supports objects. How do I change the interface?

答:
you can make the typescript compiler consider the new type with as keyword.
for example, if you have an object say

```<code>obj= {prop1: 1, prop2: "str", otherProp: ["str"] }
</code>```

with predefined type

```<code>objType = {
 prop1: number;
 prop2: string;
 otherProp: string[];
}
</code>```

you can overwrite this type like this

```<code>obj= {prop1: 1, prop2: "str"} as newType

type newType = {
  prop1: number;
  prop2: number;
}
</code>```

off course, this is not the good approach you should follow, because you lose the importance of using type check, but it is considered a escape hitch in your case

Body:
you can make the typescript compiler consider the new type with as keyword.
for example, if you have an object say

obj= {prop1: 1, prop2: "str", otherProp: ["str"] }

with predefined type

objType = {
 prop1: number;
 prop2: string;
 otherProp: string[];
}

you can overwrite this type like this

obj= {prop1: 1, prop2: "str"} as newType

type newType = {
  prop1: number;
  prop2: number;
}

off course, this is not the good approach you should follow, because you lose the importance of using type check, but it is considered a escape hitch in your case


问:
How to upgrade exiting sqlite db?
i was published android apps using sqlite in local db.now i am add one more table in that db.how to upgrade existing db to user.i.e user data can't delete.only my update  will effect when user update previous apps version.how to handle this issue?how to republish my application?

Thanks in advance...

答:
You have to override onUpgrade method of SQLiteOpenHelper

```<code>    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
        db.execSQL(CREATE_NEW_TABLE);//create your new table
        //execute other sql statements if required
}
</code>```

Did in one of my project here is Link. Hope this help

Title: How to upgrade exiting sqlite db?

Body:
You have to override onUpgrade method of SQLiteOpenHelper

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
        db.execSQL(CREATE_NEW_TABLE);//create your new table
        //execute other sql statements if required
}

Did in one of my project here is Link. Hope this help


问:
Error when deploying the gatsby app with gatsby-source-buttercms on Zeit
My code: https://github.com/who-know-cg/main-gatsby

Every time I build my Gatsby app (on Zeit) I get this error message:

```<code>ERROR #11321  PLUGIN

"gatsby-transformer-json" threw an error while running the onCreateNode lifecycle:

Could not find function loadNodeContent for plugin gatsby-source-buttercms

Error: Could not find function loadNodeContent for plugin gatsby-source-butter  cms
</code>```

And I never meet this error when in developing using gatsby develop.

Here is a similar question on github https://github.com/ldd/gatsby-source-github-api/issues/10 .
But I don't know what the answer means, and I don't know if it's the same issue either.

Please help me find what part is going wrong, thanks you.

答:
this works for me

npm install Pearce-Ropion/gatsby-source-apiserver#6112115 -D
yarn add Pearce-Ropion/gatsby-source-apiserver#6112115 -D

Body:
My code: https://github.com/who-know-cg/main-gatsby

Every time I build my Gatsby app (on Zeit) I get this error message:

ERROR #11321  PLUGIN

"gatsby-transformer-json" threw an error while running the onCreateNode lifecycle:

Could not find function loadNodeContent for plugin gatsby-source-buttercms

Error: Could not find function loadNodeContent for plugin gatsby-source-butter  cms

And I never meet this error when in developing using gatsby develop.

Here is a similar question on github https://github.com/ldd/gatsby-source-github-api/issues/10 .
But I don't know what the answer means, and I don't know if it's the same issue either.

Please help me find what part is going wrong, thanks you.


问:
Show more rows across two HTML tables on click with jQuery
I am trying to display some historical data in 2 different tables (at one point in the history the data is slightly different). The older table only has 4 columns and the newer table has 6 columns. I'm trying to add a show more.. button to display more rows and its working fine, the problem is the button ceases to work after getting part of the way into the second table.

This code shows the headers and the first 10 rows of the table, then clicking the show more button displays the next 12 rows. This all works great until the 2nd table starts to show. Once it displays the first x number of rows in the 2nd table the button no longer does anything.

What am I missing?

jQuery(function($) {
  $('table tr:lt(11)').addClass('active');

  $('a.load_more').on('click', function(e) {
    e.preventDefault();
    var $rows = $('table tr');
    var lastActiveIndex = $rows.filter('.active:last').index();
    $rows.filter(':lt(' + (lastActiveIndex + 13) + ')').addClass('active');

    // hide the button when all elements visible
    $(this).toggle($rows.filter(':hidden').length !== 0);
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

<table>
  <thead>
    <tr>
      <th>A</th>
      <th>B</th>
      <th>C</th>
      <th>D</th>
      <th>E</th>
      <th>F</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
      <td>5</td>
      <td>6</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
      <td>5</td>
      <td>6</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
      <td>5</td>
      <td>6</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
      <td>5</td>
      <td>6</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
      <td>5</td>
      <td>6</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
      <td>5</td>
      <td>6</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
      <td>5</td>
      <td>6</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
      <td>5</td>
      <td>6</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
      <td>5</td>
      <td>6</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
      <td>5</td>
      <td>6</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
      <td>5</td>
      <td>6</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
      <td>5</td>
      <td>6</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
      <td>5</td>
      <td>6</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
      <td>5</td>
      <td>6</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
      <td>5</td>
      <td>6</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
      <td>5</td>
      <td>6</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
      <td>5</td>
      <td>6</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
      <td>5</td>
      <td>6</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
      <td>5</td>
      <td>6</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
      <td>5</td>
      <td>6</td>
    </tr>
  </tbody>
</table>
<table>
  <thead>
    <tr>
      <th>A</th>
      <th>B</th>
      <th>C</th>
      <th>D</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
    </tr>
  </tbody>
</table>

Load more</code>```

答:
These two lines are the cause:

```<code>var $rows = $('table tr');
var lastActiveIndex = $rows.filter('.active:last').index();
</code>```

.index() (no arguments) will give you: https://api.jquery.com/index/

an integer indicating the position of the first element within the jQuery object relative to its sibling elements.

So $rows.filter('.active:last').index(); will give you the index within each table, not within the collection of $rows - so the second time you click "load more" (with the data provided) the last row's index is 0 as the first row is shown at this point.

You need to use the other version of index:

```<code>$rows.index(element)
</code>```

If .index() is called on a collection of elements and a DOM element or jQuery object is passed in, .index() returns an integer indicating the position of the passed element relative to the original collection.

(added emphasis)

In your case, that will be:

```<code>var $rows = $('table tr');
var lastActiveIndex = $rows.index($rows.filter('.active').last());
</code>```

which will give you the index within the $rows collection

Updated snippet:

jQuery(function($) {
  $('table tr:lt(11)').addClass('active');

  $('a.load_more').on('click', function(e) {
    e.preventDefault();
    var $rows = $('table tr');

    var lastActiveIndex = $rows.index($rows.filter('.active').last());

    $rows.filter(':lt(' + (lastActiveIndex + 13) + ')').addClass('active');

    // hide the button when all elements visible
    $(this).toggle($rows.filter(':hidden').length !== 0);
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>table tr { display: none; }
table tr.active { display: table-row; }</code>```

      A
      B
      C
      D
      E
      F

      1
      2
      3
      4
      5
      6

      1
      2
      3
      4
      5
      6

      1
      2
      3
      4
      5
      6

      1
      2
      3
      4
      5
      6

      1
      2
      3
      4
      5
      6

      1
      2
      3
      4
      5
      6

      1
      2
      3
      4
      5
      6

      1
      2
      3
      4
      5
      6

      1
      2
      3
      4
      5
      6

      1
      2
      3
      4
      5
      6

      1
      2
      3
      4
      5
      6

      1
      2
      3
      4
      5
      6

      1
      2
      3
      4
      5
      6

      1
      2
      3
      4
      5
      6

      1
      2
      3
      4
      5
      6

      1
      2
      3
      4
      5
      6

      1
      2
      3
      4
      5
      6

      1
      2
      3
      4
      5
      6

      1
      2
      3
      4
      5
      6

      1
      2
      3
      4
      5
      6

      A
      B
      C
      D

      1
      2
      3
      4

      1
      2
      3
      4

      1
      2
      3
      4

      1
      2
      3
      4

      1
      2
      3
      4

      1
      2
      3
      4

      1
      2
      3
      4

      1
      2
      3
      4

      1
      2
      3
      4

      1
      2
      3
      4

      1
      2
      3
      4

      1
      2
      3
      4

      1
      2
      3
      4

      1
      2
      3
      4

Load more```

Body:
I am trying to display some historical data in 2 different tables (at one point in the history the data is slightly different). The older table only has 4 columns and the newer table has 6 columns. I'm trying to add a show more.. button to display more rows and its working fine, the problem is the button ceases to work after getting part of the way into the second table.

This code shows the headers and the first 10 rows of the table, then clicking the show more button displays the next 12 rows. This all works great until the 2nd table starts to show. Once it displays the first x number of rows in the 2nd table the button no longer does anything.

What am I missing?

jQuery(function($) {
  $('table tr:lt(11)').addClass('active');

  $('a.load_more').on('click', function(e) {
    e.preventDefault();
    var $rows = $('table tr');
    var lastActiveIndex = $rows.filter('.active:last').index();
    $rows.filter(':lt(' + (lastActiveIndex + 13) + ')').addClass('active');

    // hide the button when all elements visible
    $(this).toggle($rows.filter(':hidden').length !== 0);
  });
});

      A
      B
      C
      D
      E
      F

      1
      2
      3
      4
      5
      6

      1
      2
      3
      4
      5
      6

      1
      2
      3
      4
      5
      6

      1
      2
      3
      4
      5
      6

      1
      2
      3
      4
      5
      6

      1
      2
      3
      4
      5
      6

      1
      2
      3
      4
      5
      6

      1
      2
      3
      4
      5
      6

      1
      2
      3
      4
      5
      6

      1
      2
      3
      4
      5
      6

      1
      2
      3
      4
      5
      6

      1
      2
      3
      4
      5
      6

      1
      2
      3
      4
      5
      6

      1
      2
      3
      4
      5
      6

      1
      2
      3
      4
      5
      6

      1
      2
      3
      4
      5
      6

      1
      2
      3
      4
      5
      6

      1
      2
      3
      4
      5
      6

      1
      2
      3
      4
      5
      6

      1
      2
      3
      4
      5
      6

      A
      B
      C
      D

      1
      2
      3
      4

      1
      2
      3
      4

      1
      2
      3
      4

      1
      2
      3
      4

      1
      2
      3
      4

      1
      2
      3
      4

      1
      2
      3
      4

      1
      2
      3
      4

      1
      2
      3
      4

      1
      2
      3
      4

      1
      2
      3
      4

      1
      2
      3
      4

      1
      2
      3
      4

      1
      2
      3
      4

Load more

Body:
These two lines are the cause:

var $rows = $('table tr');
var lastActiveIndex = $rows.filter('.active:last').index();

.index() (no arguments) will give you: https://api.jquery.com/index/

an integer indicating the position of the first element within the jQuery object relative to its sibling elements.

So $rows.filter('.active:last').index(); will give you the index within each table, not within the collection of $rows - so the second time you click "load more" (with the data provided) the last row's index is 0 as the first row is shown at this point.

You need to use the other version of index:

$rows.index(element)

If .index() is called on a collection of elements and a DOM element or jQuery object is passed in, .index() returns an integer indicating the position of the passed element relative to the original collection.

(added emphasis)

In your case, that will be:

var $rows = $('table tr');
var lastActiveIndex = $rows.index($rows.filter('.active').last());

which will give you the index within the $rows collection

Updated snippet:

jQuery(function($) {
  $('table tr:lt(11)').addClass('active');

  $('a.load_more').on('click', function(e) {
    e.preventDefault();
    var $rows = $('table tr');

    var lastActiveIndex = $rows.index($rows.filter('.active').last());

    $rows.filter(':lt(' + (lastActiveIndex + 13) + ')').addClass('active');

    // hide the button when all elements visible
    $(this).toggle($rows.filter(':hidden').length !== 0);
  });
});

table tr { display: none; }
table tr.active { display: table-row; }

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <thead>
    <tr>
      <th>A</th>
      <th>B</th>
      <th>C</th>
      <th>D</th>
      <th>E</th>
      <th>F</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
      <td>5</td>
      <td>6</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
      <td>5</td>
      <td>6</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
      <td>5</td>
      <td>6</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
      <td>5</td>
      <td>6</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
      <td>5</td>
      <td>6</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
      <td>5</td>
      <td>6</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
      <td>5</td>
      <td>6</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
      <td>5</td>
      <td>6</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
      <td>5</td>
      <td>6</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
      <td>5</td>
      <td>6</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
      <td>5</td>
      <td>6</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
      <td>5</td>
      <td>6</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
      <td>5</td>
      <td>6</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
      <td>5</td>
      <td>6</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
      <td>5</td>
      <td>6</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
      <td>5</td>
      <td>6</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
      <td>5</td>
      <td>6</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
      <td>5</td>
      <td>6</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
      <td>5</td>
      <td>6</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
      <td>5</td>
      <td>6</td>
    </tr>
  </tbody>
</table>
<table>
  <thead>
    <tr>
      <th>A</th>
      <th>B</th>
      <th>C</th>
      <th>D</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
    </tr>
  </tbody>
</table>
<a class="load_more" href="#">Load more</a>


问:
I'm implementing hashtag recognizer in UITextView but it never highlights two words with the same begining
I found this question: How to make UITextView detect hashtags? and I copied the accepted answer into my code. I also set up a delegate to my textview and then put this code:

```<code>func textViewDidChange(textView: UITextView) {
    textView.resolveHashTags()
}
</code>```

By doing that I want to check the user's input on the textview and each time user types a #hashtag - I will automatically highlight it.

But there is a weird problem: it never highlights words that starts with the same letters.

It looks like this:

what might be the problem here?

答:
Here is Swift 5 solution as String extension:

```<code>extension String
{
    func withHashTags(color: UIColor) -> NSMutableAttributedString
    {
        let words = self.components(separatedBy: " ")

        let attributedString = NSMutableAttributedString(string: self)

        for word in words
        {
            if word.hasPrefix("#")
            {
                let range = (self as NSString).range(of: word)
                attributedString.addAttribute(.foregroundColor, value: color, range: range)
            }
        }

        return attributedString
    }
}
</code>```

Pass param color to set specific color for hashtags

Body:
I found this question: How to make UITextView detect hashtags? and I copied the accepted answer into my code. I also set up a delegate to my textview and then put this code:

func textViewDidChange(textView: UITextView) {
    textView.resolveHashTags()
}

By doing that I want to check the user's input on the textview and each time user types a #hashtag - I will automatically highlight it.

But there is a weird problem: it never highlights words that starts with the same letters.

It looks like this:

what might be the problem here?

Body:
Here is Swift 5 solution as String extension:

extension String
{
    func withHashTags(color: UIColor) -> NSMutableAttributedString
    {
        let words = self.components(separatedBy: " ")

        let attributedString = NSMutableAttributedString(string: self)

        for word in words
        {
            if word.hasPrefix("#")
            {
                let range = (self as NSString).range(of: word)
                attributedString.addAttribute(.foregroundColor, value: color, range: range)
            }
        }

        return attributedString
    }
}

Pass param color to set specific color for hashtags


问:
How do I turn string into datetime values and merge
I have a string of yearly data month 1-12, trying to convert it to datetime.month values and then converge it on the main df that already has dt.month values according to some date

```<code>usage_12month["MONTH"]= pd.to_datetime(usage_12month["MONTH"])
usage_12month['MONTH'] = usage_12month['MONTH'].dt.month
display(usage_12month)
merge = pd.merge(df,usage_12month, how='left',on='MONTH')
</code>```

ValueError: Given date string not likely a datetime.

get the error on the 1st line

答:
.dt.month on a datetime returns an int. So I'm assuming you want to convert usage_12month["MONTH"] from a string to an int to be able to merge it with the other df.

There is a simplier way than converting it to a datetime. You could replace the first two lines by usage_12month["MONTH"]= pd.to_numeric(usage_12month["MONTH"]) and it should work.

--

The error you get on the first line is because you don't specify to the to_datetime function how to interpet the string as a datetime (the number in the string could represent a day, an hour...).

To make your way work you have to give a 'format' parameter to the to_datetime function. In your case, your string contains only the month number, so the format string would be '%m' (see https://strftime.org/) : usage_12month["MONTH"]= pd.to_datetime(usage_12month["MONTH"], format = '%m')

When you're supplying the function with a "usual" date fromat like 'yyyy/mm/dd' it guesses how to interpret it, but it is alway better to provide a format to the function.

Body:
I have a string of yearly data month 1-12, trying to convert it to datetime.month values and then converge it on the main df that already has dt.month values according to some date

usage_12month["MONTH"]= pd.to_datetime(usage_12month["MONTH"])
usage_12month['MONTH'] = usage_12month['MONTH'].dt.month
display(usage_12month)
merge = pd.merge(df,usage_12month, how='left',on='MONTH')

ValueError: Given date string not likely a datetime.

get the error on the 1st line


问:
Report errors manually from Rails to Sentry
In my ApiController  I have:

```<code>rescue_from Exception, with: :render_exception_error

  def render_exception_error(exception)
    raise exception if Rails.env.test?

    logger.error(exception)
    render json: { error: 'An error occurred' }, status: 500 unless performed?
  end

</code>```

I want that method to also report the error to Sentry.
Do you know if by doing the line that does logger.error(...) it automatically logs it in Sentry too?

Or do I have to manually do Raven.capture_exception(exception) or something like that? Will this be done in the background?

答:
Edit 2022

Raven is deprecated since a few months now and you should use the new Sentry gem.

To answer the question, which is Report errors manually from Rails to Sentry, you can check the documentation here: https://docs.sentry.io/platforms/ruby/guides/rails/usage/

TL;DR you can capture exception with

Sentry.capture_exception(exception)
```
<p>Or you can capture a message with</p>
<pre class="lang-rb prettyprint-override"><code>Sentry.capture_message('Something went wrong')
</code>```

Body:
In my ApiController  I have:

rescue_from Exception, with: :render_exception_error

  def render_exception_error(exception)
    raise exception if Rails.env.test?

    logger.error(exception)
    render json: { error: 'An error occurred' }, status: 500 unless performed?
  end

I want that method to also report the error to Sentry.
Do you know if by doing the line that does logger.error(...) it automatically logs it in Sentry too?

Or do I have to manually do Raven.capture_exception(exception) or something like that? Will this be done in the background?

Body:
Edit 2022

Raven is deprecated since a few months now and you should use the new Sentry gem.

To answer the question, which is Report errors manually from Rails to Sentry, you can check the documentation here: https://docs.sentry.io/platforms/ruby/guides/rails/usage/

TL;DR you can capture exception with

Sentry.capture_exception(exception)

Or you can capture a message with

Sentry.capture_message('Something went wrong')


问:
How to identify dynamic text using column expressions
first, the title might not fit that well. I was not quite sure how to summarize it the best. I hope it is not misleading.

I have a datatable which includes a column with values from an http request.

ID
DynamicContent

1
{"DynamicProperties":{"Name":"John Doe","Birthday":"24.12.2021"}}

2
{"DynamicProperties":{"Name":"Jane Doe","Birthday":"21.12.2021"}}

I now want to dynamically add a new "calculated" column for each value in an Array {"Name", "Birthday"}.
Column name should be the string from the array and the value should be the value from the string in the DynamicContent column.
The final datatable should look like this.

ID
DynamicContent
Name
Birthday

1
{"DynamicProperties":{"Name":"John Doe","Birthday":"24.12.2021"}}
John Doe
24.12.2021

2
{"DynamicProperties":{"Name":"Jane Doe","Birthday":"21.12.2021"}}
Jane Doe
21.12.2021

Would this be able with some kind of column Expression in combination with regex? Or is there another aproach that could help me here? I did not work with column expressions before.

答:
Since you didn't provide more info I made it work with DataTable object, note that this may not work depending on what library are you using to communicate with the database.</p>
```<code>using System;
using System.Data;
using System.Text.Json;

public static void Main()
    {
        var myDataTable = new DataTable();
        myDataTable.Columns.Add("Name", typeof(string));
        myDataTable.Columns.Add("Birthday", typeof(DateTime));
        foreach(DataRow row in myDataTable.Rows)
        {
            using JsonDocument doc = JsonDocument.Parse(row["DynamicProperties"].ToString());
            var name = doc.RootElement.GetProperty("DynamicProperties")
                                      .GetProperty("Name").GetString();
            var birthday = DateTime.ParseExact(doc.RootElement.GetProperty("DynamicProperties")
                              .GetProperty("Birthday").GetString(), "dd.mm.yyyy", null);

        row["Name"] = name;
        row["Birthday"] = birthday;
    }
}
</code>```

Body:
Since you didn't provide more info I made it work with DataTable object, note that this may not work depending on what library are you using to communicate with the database.

using System;
using System.Data;
using System.Text.Json;

public static void Main()
    {
        var myDataTable = new DataTable();
        myDataTable.Columns.Add("Name", typeof(string));
        myDataTable.Columns.Add("Birthday", typeof(DateTime));
        foreach(DataRow row in myDataTable.Rows)
        {
            using JsonDocument doc = JsonDocument.Parse(row["DynamicProperties"].ToString());
            var name = doc.RootElement.GetProperty("DynamicProperties")
                                      .GetProperty("Name").GetString();
            var birthday = DateTime.ParseExact(doc.RootElement.GetProperty("DynamicProperties")
                              .GetProperty("Birthday").GetString(), "dd.mm.yyyy", null);

        row["Name"] = name;
        row["Birthday"] = birthday;
    }
}


问:
if statement php?
i don't know why but this is not working:

I am working on an Ajax send , i have send a value to a PHP script which parses the values and store the values in a php variable.
and now:

```<code>$id = $_GET['id'];
$url = $_GET['url'];
$check = $_GET['check'];
$filid = mysql_real_escape_string($id);
$filurl = mysql_real_escape_string($url);

if($check == 'true'){
    $insert  = "INSERT INTO tab (id,url) VALUES ('$filid','$filurl')";
    mysql_query($insert) or die(mysql_error());
}
</code>```

I am confirmed that my Ajax code is working , i'm not sure about php.When i remove the if statement and directly put the data into my database , it's working.

I'm new so please tolerate.
I hope someone can point me out my mistakes are.

Thanks!

答:
If $check is a boolean (or evaluates to a boolean value in comparisons):

```<code>if($check == true){
</code>```

or better, just:

```<code>if ($check) {
</code>```

Title: if statement php?

Body:
i don't know why but this is not working:

I am working on an Ajax send , i have send a value to a PHP script which parses the values and store the values in a php variable.
and now:

$id = $_GET['id'];
$url = $_GET['url'];
$check = $_GET['check'];
$filid = mysql_real_escape_string($id);
$filurl = mysql_real_escape_string($url);

if($check == 'true'){
    $insert  = "INSERT INTO tab (id,url) VALUES ('$filid','$filurl')";
    mysql_query($insert) or die(mysql_error());
}

I am confirmed that my Ajax code is working , i'm not sure about php.When i remove the if statement and directly put the data into my database , it's working.

I'm new so please tolerate.
I hope someone can point me out my mistakes are.

Thanks!

Body:
If $check is a boolean (or evaluates to a boolean value in comparisons):

if($check == true){

or better, just:

if ($check) {


问:
What exactly is container parameter in onCreateView method in Fragment
When I want to create a simple fragment, usually use following code:

```<code>public class TestFragment extends Fragment {
  @Nullable
  @Override
  public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    return inflater.inflate(R.layout.fragment_latout, container, false);
  }
}
</code>```

My questions are:
What exactly is container parameter? where it is defined?
Can we see this ViewGroup(container) in XML/Layout Designer?
In this method(onCreateView), what is this ViewGroup(container) id?
In R.id.x, to access this ViewGroup(container) What should we replace x with?
Thanks.

答:
You don't call that method, the system does, as part of the fragment lifecycle.

When a fragment is added to a layout, onCreateView will eventually get called, and container is the view that holds the fragment. That lets you do things like access the parent's layout parameters, the style/theme applied to it, etc. That's why you pass container when you call inflate, so it can apply any necessary attributes while inflating the fragment's layout.

Basically don't worry about it, and pass the parent/container when you inflate a layout. 99% of the time, that's all you need to know!

Body:
When I want to create a simple fragment, usually use following code:

public class TestFragment extends Fragment {
  @Nullable
  @Override
  public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    return inflater.inflate(R.layout.fragment_latout, container, false);
  }
}

My questions are:
What exactly is container parameter? where it is defined?
Can we see this ViewGroup(container) in XML/Layout Designer?
In this method(onCreateView), what is this ViewGroup(container) id?
In R.id.x, to access this ViewGroup(container) What should we replace x with?
Thanks.


问:
React-router <Route> tag not rendering component
I'm running into an issue where my route tag in specific is not rendering any components.

Steps I have tried:

Changed import of { Route } from "react-router-dom".

Changed paths to see if other paths render.

Rendered the component within  tags (this worked).

The issue seems to be coming down to something going on with the  tag.

Here is a copy of my code:

```<code>import { Component } from "react";
//import all components rendered
import NavBar from "./Nav";
import Orders from "./Orders";
import Cart from "./Cart";
import Menu from "./Menu";
import Login from "./Login.jsx";
import Home from "./Home.jsx";
// for routing
import { Route } from "react-router";
import { BrowserRouter } from "react-router-dom";

//main App to combine all components and be rendered
class App extends Component {
    render() {
        return (
            <BrowserRouter>
                <NavBar />
                <Route path="/" exact component={Login} />
            </BrowserRouter>
        )
    }
}

export default App;
</code>```

The versions are:

```<code>├─┬ react-router-dom@6.2.1
│ └── react-router@6.2.1 deduped
└── react-router@6.2.1
</code>```

I tried changing the tags to  as per a suggestion and it still didn't work, but I may have implemented it incorrectly. Here is what I tried:

```<code>import { Component } from "react";
//import all components rendered
import NavBar from "./Nav";
import Orders from "./Orders";
import Cart from "./Cart";
import Menu from "./Menu";
import Login from "./Login.jsx";
import Home from "./Home.jsx";
// for routing
import { Route } from "react-router";
import { BrowserRouter, Routes } from "react-router-dom";

//main App to combine all components and be rendered
class App extends Component {
    render() {
        return (
            <Routes>
                <NavBar />
                <Route path="/" exact component={Login} />
            </Routes>
        )
    }
}

export default App;
</code>```

The errors I am getting on the console are:

```<code>Uncaught Error: useRoutes() may be used only in the context of a <Router> component.
    Choo 3
    React 17
    Choo 2
    Webpack 3
</code>```
```<code>The above error occurred in the <Routes> component:

Routes@http://localhost:3000/static/js/bundle.js:54433:7
App@http://localhost:3000/static/js/bundle.js:42:1
</code>```

Any help would be greatly appreciated!

Solution:

Was resolved by switching the "component" tag to "element" tag and removing the  tag outside as follows:

```<code>            <>
                <NavBar />
                <Routes>
                    <Route path="/" exact element={<Login />} />
                </Routes>
            </>
</code>```

答: I ran into the same issue on react router v6, you need to wrap all your routes in the Routes component from react-router-dom.</p>

Body:
I'm running into an issue where my route tag in specific is not rendering any components.

Steps I have tried:

Changed import of { Route } from "react-router-dom".

Changed paths to see if other paths render.

Rendered the component within  tags (this worked).

The issue seems to be coming down to something going on with the  tag.

Here is a copy of my code:

import { Component } from "react";
//import all components rendered
import NavBar from "./Nav";
import Orders from "./Orders";
import Cart from "./Cart";
import Menu from "./Menu";
import Login from "./Login.jsx";
import Home from "./Home.jsx";
// for routing
import { Route } from "react-router";
import { BrowserRouter } from "react-router-dom";

//main App to combine all components and be rendered
class App extends Component {
    render() {
        return (
            <BrowserRouter>
                <NavBar />
                <Route path="/" exact component={Login} />
            </BrowserRouter>
        )
    }
}

export default App;

The versions are:

├─┬ react-router-dom@6.2.1
│ └── react-router@6.2.1 deduped
└── react-router@6.2.1

I tried changing the tags to  as per a suggestion and it still didn't work, but I may have implemented it incorrectly. Here is what I tried:

import { Component } from "react";
//import all components rendered
import NavBar from "./Nav";
import Orders from "./Orders";
import Cart from "./Cart";
import Menu from "./Menu";
import Login from "./Login.jsx";
import Home from "./Home.jsx";
// for routing
import { Route } from "react-router";
import { BrowserRouter, Routes } from "react-router-dom";

//main App to combine all components and be rendered
class App extends Component {
    render() {
        return (
            <Routes>
                <NavBar />
                <Route path="/" exact component={Login} />
            </Routes>
        )
    }
}

export default App;

The errors I am getting on the console are:

Uncaught Error: useRoutes() may be used only in the context of a <Router> component.
    Choo 3
    React 17
    Choo 2
    Webpack 3

The above error occurred in the <Routes> component:

Routes@http://localhost:3000/static/js/bundle.js:54433:7
App@http://localhost:3000/static/js/bundle.js:42:1

Any help would be greatly appreciated!

Solution:

Was resolved by switching the "component" tag to "element" tag and removing the  tag outside as follows:

            <>
                <NavBar />
                <Routes>
                    <Route path="/" exact element={<Login />} />
                </Routes>
            </>


问:
Compare two files with string and output required for specific format
Thank you for your answer at https://stackoverflow.com/questions/71080087
@RavinderSingh13

In questions/71080087, I compared two files by the field delimiter.

one more question...
I want to ask a more detailed question

This is a list of file systems provided by each of the two servers.

```<code>cat volume1.txt (by server1)
/         80G    xfs  /dev/mapper/rootvg-lv_root
/boot     1014M  xfs  /dev/sda2
/boot/efi 500M   vfat /dev/sda1
/swlogs   10G    xfs  /dev/mapper/datavg-lv_swlogs
</code>```
```<code># cat volume2.txt (by server2)
/         33G    xfs  /dev/mapper/rhel-root
/boot/efi 599M   vfat /dev/sda1
/boot     1014M  xfs  /dev/sda2

</code>```

Is it possible to output as below? (order of the lines doesn't matter)

```<code>volume1.txt                                                        volume2.txt
/       80G    xfs  /dev/mapper/rootvg-lv_root     : [ NotMatch ] : /       33G    xfs  /dev/mapper/rhel-root
/boot     1014M  xfs  /dev/sda2                    : [    OK    ] :
/boot/efi 500M   vfat /dev/sda1                    : [ NotMatch ] : /boot/efi 599M   vfat /dev/sda1
/swlogs   10G    xfs  /dev/mapper/datavg-lv_swlogs : [ NotExist ] :
</code>```

my work...

```<code>FOOD1=`cat ./food1.txt`
FOOD2=`cat ./food2.txt`

echo "$FOOD1" | while read ACCOUNT
do
grep -w $ACCOUNT ./food2.txt  >/dev/null 2>&1
if [ $? -eq 0 ] ; then
echo "-----[  OK  ] : $ACCOUNT"
else
echo "-----[ WARN ] : $ACCOUNT"
fi
done
</code>```

If you don't understand my question please tell me.

答:
With your shown samples, please try following awk code. Written and tested in GNU awk.

```<code>awk '
BEGIN{
  print ARGV[1]"                   "ARGV[2]
}
FNR==NR{
  arr1[$1]=$0
  next
}
($1 in arr1){
  if($0==arr1[$1]){
     print  $0 "           :[    OK     ] : "
  }
  else if($0!=arr1[$1]){
     print arr1[$1]"  :[ NotMatch  ] : "$0
  }
  arr2[$1]
  next
}
{
  print $0"  :[ NotExist  ] : "
}
END{
  for(i in arr1){
     if(!(i in arr2)){
        print arr1[i]"           :[ NotExist  ] : "
     }
  }
}
' volume1.txt  volume2.txt
</code>```

Explanation: Adding detailed explanation for above.

```<code>awk '                                                        ##Starting awk program from here.
BEGIN{                                                       ##Starting BEGIN section from here.
  print ARGV[1]"                   "ARGV[2]                  ##Printing passed Input_file names here.
}
FNR==NR{                                                     ##Checking condition FNR==NR which will be TRUE when food1.txt is being read.
  arr1[$1]=$0                                                ##Creating array named arr1 with index of 1st field and value is $0.
  next                                                       ##next will skip all further statements from here.
}
($1 in arr1){                                                ##Checking condition if $1 is present in arr1 then do following.
  if($0==arr1[$1]){                                          ##Checking condition if whole line is equal to arr1 value.
     print  "           :[    OK     ] : " $0                ##Printing ok message with current line of food2.txt here.
  }
  else if($0!=arr1[$1]){                                     ##Else(in case whole line is NOT equal to arr1 value) then do following.
     print arr1[$1]"  :[ NotMatch  ] : "$0             ##Printing first field FS value of arr1 followed by NotMatch followed by current line from food2.txt.
  }
  arr2[$1]                                                   ##Making an entry of current $1 for arr2 array here.
  next                                                       ##next will skip all further statements from here.
}
{
  print $0"  :[ NotExist  ] : "                              ##printing current line followed by NotExist statement.
}
END{                                                         ##Starting END block for this program from here.
  for(i in arr1){                                            ##Traversing through arr1 elements here.
     if(!(i in arr2)){                                       ##Checking condition if key i is NOT present in arr2 then do following.
        print "           :[ NotExist  ] : "i FS arr1[i]     ##printing NOtExist statements followed by i FS and arr1 value.
     }
  }
}
' volume1.txt  volume2.txt                                   ##Mentioning Input_file names here.
</code>```

Body:
Thank you for your answer at https://stackoverflow.com/questions/71080087
@RavinderSingh13

In questions/71080087, I compared two files by the field delimiter.

one more question...
I want to ask a more detailed question

This is a list of file systems provided by each of the two servers.

cat volume1.txt (by server1)
/         80G    xfs  /dev/mapper/rootvg-lv_root
/boot     1014M  xfs  /dev/sda2
/boot/efi 500M   vfat /dev/sda1
/swlogs   10G    xfs  /dev/mapper/datavg-lv_swlogs

# cat volume2.txt (by server2)
/         33G    xfs  /dev/mapper/rhel-root
/boot/efi 599M   vfat /dev/sda1
/boot     1014M  xfs  /dev/sda2

Is it possible to output as below? (order of the lines doesn't matter)

volume1.txt                                                        volume2.txt
/       80G    xfs  /dev/mapper/rootvg-lv_root     : [ NotMatch ] : /       33G    xfs  /dev/mapper/rhel-root
/boot     1014M  xfs  /dev/sda2                    : [    OK    ] :
/boot/efi 500M   vfat /dev/sda1                    : [ NotMatch ] : /boot/efi 599M   vfat /dev/sda1
/swlogs   10G    xfs  /dev/mapper/datavg-lv_swlogs : [ NotExist ] :

my work...

FOOD1=`cat ./food1.txt`
FOOD2=`cat ./food2.txt`

echo "$FOOD1" | while read ACCOUNT
do
grep -w $ACCOUNT ./food2.txt  >/dev/null 2>&1
if [ $? -eq 0 ] ; then
echo "-----[  OK  ] : $ACCOUNT"
else
echo "-----[ WARN ] : $ACCOUNT"
fi
done

If you don't understand my question please tell me.

Body:
With your shown samples, please try following awk code. Written and tested in GNU awk.

awk '
BEGIN{
  print ARGV[1]"                   "ARGV[2]
}
FNR==NR{
  arr1[$1]=$0
  next
}
($1 in arr1){
  if($0==arr1[$1]){
     print  $0 "           :[    OK     ] : "
  }
  else if($0!=arr1[$1]){
     print arr1[$1]"  :[ NotMatch  ] : "$0
  }
  arr2[$1]
  next
}
{
  print $0"  :[ NotExist  ] : "
}
END{
  for(i in arr1){
     if(!(i in arr2)){
        print arr1[i]"           :[ NotExist  ] : "
     }
  }
}
' volume1.txt  volume2.txt

Explanation: Adding detailed explanation for above.

awk '                                                        ##Starting awk program from here.
BEGIN{                                                       ##Starting BEGIN section from here.
  print ARGV[1]"                   "ARGV[2]                  ##Printing passed Input_file names here.
}
FNR==NR{                                                     ##Checking condition FNR==NR which will be TRUE when food1.txt is being read.
  arr1[$1]=$0                                                ##Creating array named arr1 with index of 1st field and value is $0.
  next                                                       ##next will skip all further statements from here.
}
($1 in arr1){                                                ##Checking condition if $1 is present in arr1 then do following.
  if($0==arr1[$1]){                                          ##Checking condition if whole line is equal to arr1 value.
     print  "           :[    OK     ] : " $0                ##Printing ok message with current line of food2.txt here.
  }
  else if($0!=arr1[$1]){                                     ##Else(in case whole line is NOT equal to arr1 value) then do following.
     print arr1[$1]"  :[ NotMatch  ] : "$0             ##Printing first field FS value of arr1 followed by NotMatch followed by current line from food2.txt.
  }
  arr2[$1]                                                   ##Making an entry of current $1 for arr2 array here.
  next                                                       ##next will skip all further statements from here.
}
{
  print $0"  :[ NotExist  ] : "                              ##printing current line followed by NotExist statement.
}
END{                                                         ##Starting END block for this program from here.
  for(i in arr1){                                            ##Traversing through arr1 elements here.
     if(!(i in arr2)){                                       ##Checking condition if key i is NOT present in arr2 then do following.
        print "           :[ NotExist  ] : "i FS arr1[i]     ##printing NOtExist statements followed by i FS and arr1 value.
     }
  }
}
' volume1.txt  volume2.txt                                   ##Mentioning Input_file names here.


问:
Comparing a int[] and a String to check if numbers are in the right sequence and if they have any same number in Java
I am trying to compare a method that creates random numbers and adds them to an int[], with the user input which is saved as a String.
The code for the random number generator is this

```<code>int[] x = {0, 0, 0, 0};
boolean isDuplicate = false;
for (int i = 0; i < x.length; i++) {
    int y = (int) (Math.random() * 9) + 1;
    for (int j = 0; j < x.length; j++) {
        if (x[j] == y) {
            isDuplicate = true;
            break;
        }
    }
    if (isDuplicate) {
        i--;
        isDuplicate = false;
    } else {
        x[i] = y;
    }
}
//Stores a representation of the int[] array to the String y and returns it.
String y = Arrays.toString(x);
return y;
</code>```

So my question is how do I compare the int[] and the user input String to see if they contain any same numbers and then check to see if any of the numbers are in the same order
i.e
Say that i have variable checkNumber and checkSequence
If I have

```<code>int[] = { 3, 5, 6, 1}
String userinput= "1,5,9,7"
</code>```

I would want to get checkNumber = 2; and checkSequence = 1;

I then want to add them in an ArrayList, so seeing as an ArrayList cannot contain primitive types like int but does accept Strings, how would I convert the int[] to a String and then compare it to my other String?

答:
You would want to split by a comma, and convert the resulting String array to an int array (createArr() is the code you provided for generating the array but changed to return an int array instead of a String):

```<code>public static void main(String[] args) {

        //Create the int array
        int [] arr1 = createArr();
        String userInput = "1,5,9,7";

        //Split the String by comma to create an array of String
        String [] strArr = userInput.split(",");

        int [] arr2 = new int[strArr.length];

        //Convert String array to int array
        for (int i = 0; i < strArr.length; i++) {
            arr2[i] = Integer.parseInt(strArr[i]);
        }

        compareArrays(arr1, arr2);
    }
</code>```

You can see in the above code a split(",") call on the userInput, which you then iterate over with a for loop filling in the values of the second int array.

Here is the createArr method you made slightly altered to return the int array:

```<code>public static int[] createArr() {
    int[] x = {0, 0, 0, 0};
    boolean isDuplicate = false;
        for (int i = 0; i < x.length; i++) {
         int y = (int) (Math.random() * 9) + 1;
           for (int j = 0; j < x.length; j++) {
             if (x[j] == y) {
                isDuplicate = true;
                 break;
              }
         }
         if (isDuplicate) {
        i--;
        isDuplicate = false;
         } else {
            x[i] = y;
        }
    }
    return x;
}
</code>```

Then you can make a method to compare them such as:

```<code>public static void compareArrays(int [] arr1, int [] arr2) {
    int checkNumber = 0, checkSequence = 0;

    //TODO: For loops to compare the arrays

    //Print out the results
    System.out.println("Array 1: " + Arrays.toString(arr1));
    System.out.println("Array 2: " + Arrays.toString(arr2));
    System.out.println("checkNumber: " + checkNumber);
    System.out.println("checkSequence: " + checkSequence);
}
</code>```

I left out the code for the compare loops so you could work that part yourself (hint you can use a nested for loop).

Test Run (with compare logic done):

```<code>Array 1: [3, 5, 7, 2]
Array 2: [1, 5, 9, 7]
checkNumber: 2
checkSequence: 1
</code>```

Note:  Splitting and converting to an int array is simpler with streams, but I thought that would be out of scope of this question.

Body:
I am trying to compare a method that creates random numbers and adds them to an int[], with the user input which is saved as a String.
The code for the random number generator is this

int[] x = {0, 0, 0, 0};
boolean isDuplicate = false;
for (int i = 0; i < x.length; i++) {
    int y = (int) (Math.random() * 9) + 1;
    for (int j = 0; j < x.length; j++) {
        if (x[j] == y) {
            isDuplicate = true;
            break;
        }
    }
    if (isDuplicate) {
        i--;
        isDuplicate = false;
    } else {
        x[i] = y;
    }
}
//Stores a representation of the int[] array to the String y and returns it.
String y = Arrays.toString(x);
return y;

So my question is how do I compare the int[] and the user input String to see if they contain any same numbers and then check to see if any of the numbers are in the same order
i.e
Say that i have variable checkNumber and checkSequence
If I have

int[] = { 3, 5, 6, 1}
String userinput= "1,5,9,7"

I would want to get checkNumber = 2; and checkSequence = 1;

I then want to add them in an ArrayList, so seeing as an ArrayList cannot contain primitive types like int but does accept Strings, how would I convert the int[] to a String and then compare it to my other String?

Body:
You would want to split by a comma, and convert the resulting String array to an int array (createArr() is the code you provided for generating the array but changed to return an int array instead of a String):

public static void main(String[] args) {

        //Create the int array
        int [] arr1 = createArr();
        String userInput = "1,5,9,7";

        //Split the String by comma to create an array of String
        String [] strArr = userInput.split(",");

        int [] arr2 = new int[strArr.length];

        //Convert String array to int array
        for (int i = 0; i < strArr.length; i++) {
            arr2[i] = Integer.parseInt(strArr[i]);
        }

        compareArrays(arr1, arr2);
    }

You can see in the above code a split(",") call on the userInput, which you then iterate over with a for loop filling in the values of the second int array.

Here is the createArr method you made slightly altered to return the int array:

public static int[] createArr() {
    int[] x = {0, 0, 0, 0};
    boolean isDuplicate = false;
        for (int i = 0; i < x.length; i++) {
         int y = (int) (Math.random() * 9) + 1;
           for (int j = 0; j < x.length; j++) {
             if (x[j] == y) {
                isDuplicate = true;
                 break;
              }
         }
         if (isDuplicate) {
        i--;
        isDuplicate = false;
         } else {
            x[i] = y;
        }
    }
    return x;
}

Then you can make a method to compare them such as:

public static void compareArrays(int [] arr1, int [] arr2) {
    int checkNumber = 0, checkSequence = 0;

    //TODO: For loops to compare the arrays

    //Print out the results
    System.out.println("Array 1: " + Arrays.toString(arr1));
    System.out.println("Array 2: " + Arrays.toString(arr2));
    System.out.println("checkNumber: " + checkNumber);
    System.out.println("checkSequence: " + checkSequence);
}

I left out the code for the compare loops so you could work that part yourself (hint you can use a nested for loop).

Test Run (with compare logic done):

Array 1: [3, 5, 7, 2]
Array 2: [1, 5, 9, 7]
checkNumber: 2
checkSequence: 1

Note:  Splitting and converting to an int array is simpler with streams, but I thought that would be out of scope of this question.


问:
Is there an "undefined behavior" problem with some APIs in "node-addon-api"?
In <napi.h>, there are some overloads declaration for the static method Accessor in the class PropertyDescriptor.

One of such overloads declaration is here:

```<code>template <typename Getter>
static PropertyDescriptor Accessor(Napi::Env env,
                                   Napi::Object object,
                                   const std::string& utf8name,
                                   Getter getter,
                                   napi_property_attributes attributes = napi_default,
                                   void* data = nullptr);
</code>```

That declaration wants a reference to a const std::string

The definition of that declaration is in <napi-inl.h>:

```<code>template <typename Getter>
inline PropertyDescriptor PropertyDescriptor::Accessor(Napi::Env env,
                                                       Napi::Object object,
                                                       const std::string& utf8name,
                                                       Getter getter,
                                                       napi_property_attributes attributes,
                                                       void* data) {
  return Accessor(env, object, utf8name.c_str(), getter, attributes, data);
}
</code>```

As you can see, the implementation takes the .c_str() of the passed std::string, as the implementation in fact uses another overload which wants a const char*.

The overload used is also in <napi-inl.h>:

```<code>template <typename Getter>
inline PropertyDescriptor
PropertyDescriptor::Accessor(Napi::Env env,
                             Napi::Object object,
                             const char* utf8name,
                             Getter getter,
                             napi_property_attributes attributes,
                             void* data) {
  using CbData = details::CallbackData<Getter, Napi::Value>;
  auto callbackData = new CbData({ getter, data });

  napi_status status = AttachData(env, object, callbackData);
  if (status != napi_ok) {
    delete callbackData;
    NAPI_THROW_IF_FAILED(env, status, napi_property_descriptor());
  }

  return PropertyDescriptor({
    utf8name,
    nullptr,
    nullptr,
    CbData::Wrapper,
    nullptr,
    nullptr,
    attributes,
    callbackData
  });
}
</code>```

That implementation uses Node-API, as node-addon-api is just a C++ wrapper arround Node-API. The fact is that the const char* utf8name obtained from .c_str() is passed as is to the constructor and is stored in the private member napi_property_descriptor _desc;

Conclusion: each time you use Napi::PropertyDescriptor::Accessor passing a std::string and then storing the PD in a vector, or just making the string goes out of scope with the PD still here, you trigger an undefined behavior!

Example:

```<code>Napi::Object TheNewObject = Napi::Object::New(env);
std::vector<Napi::PropertyDescriptor> vProps;
for (size_t index = 0; index < 2; ++index ) {
    std::string strName("MyName_");
    strName += std::to_string(index);
    auto PD = Napi::PropertyDescriptor::Accessor(env, TheNewObject, strName, Caller);
    vProps.push_back(PD);
}
</code>```

I opened an issue here, 12 days ago, with no avail.

EDIT: After reading comments, I should add that:

The napi_property_descriptor is a simple C structure.

Address of that struct will later be passed to the Node-API napi_define_properties

答:
There is indeed a problem with current implementations of PropertyDescriptor.
See https://github.com/nodejs/node-addon-api/issues/1127#issuecomment-1036394322

Glad I wasn't completely delirious.

Body:
In <napi.h>, there are some overloads declaration for the static method Accessor in the class PropertyDescriptor.

One of such overloads declaration is here:

template <typename Getter>
static PropertyDescriptor Accessor(Napi::Env env,
                                   Napi::Object object,
                                   const std::string& utf8name,
                                   Getter getter,
                                   napi_property_attributes attributes = napi_default,
                                   void* data = nullptr);

That declaration wants a reference to a const std::string

The definition of that declaration is in <napi-inl.h>:

template <typename Getter>
inline PropertyDescriptor PropertyDescriptor::Accessor(Napi::Env env,
                                                       Napi::Object object,
                                                       const std::string& utf8name,
                                                       Getter getter,
                                                       napi_property_attributes attributes,
                                                       void* data) {
  return Accessor(env, object, utf8name.c_str(), getter, attributes, data);
}

As you can see, the implementation takes the .c_str() of the passed std::string, as the implementation in fact uses another overload which wants a const char*.

The overload used is also in <napi-inl.h>:

template <typename Getter>
inline PropertyDescriptor
PropertyDescriptor::Accessor(Napi::Env env,
                             Napi::Object object,
                             const char* utf8name,
                             Getter getter,
                             napi_property_attributes attributes,
                             void* data) {
  using CbData = details::CallbackData<Getter, Napi::Value>;
  auto callbackData = new CbData({ getter, data });

  napi_status status = AttachData(env, object, callbackData);
  if (status != napi_ok) {
    delete callbackData;
    NAPI_THROW_IF_FAILED(env, status, napi_property_descriptor());
  }

  return PropertyDescriptor({
    utf8name,
    nullptr,
    nullptr,
    CbData::Wrapper,
    nullptr,
    nullptr,
    attributes,
    callbackData
  });
}

That implementation uses Node-API, as node-addon-api is just a C++ wrapper arround Node-API. The fact is that the const char* utf8name obtained from .c_str() is passed as is to the constructor and is stored in the private member napi_property_descriptor _desc;

Conclusion: each time you use Napi::PropertyDescriptor::Accessor passing a std::string and then storing the PD in a vector, or just making the string goes out of scope with the PD still here, you trigger an undefined behavior!

Example:

Napi::Object TheNewObject = Napi::Object::New(env);
std::vector<Napi::PropertyDescriptor> vProps;
for (size_t index = 0; index < 2; ++index ) {
    std::string strName("MyName_");
    strName += std::to_string(index);
    auto PD = Napi::PropertyDescriptor::Accessor(env, TheNewObject, strName, Caller);
    vProps.push_back(PD);
}

I opened an issue here, 12 days ago, with no avail.

EDIT: After reading comments, I should add that:

The napi_property_descriptor is a simple C structure.

Address of that struct will later be passed to the Node-API napi_define_properties


问:
How does the presence of routerLinkActive cause a mat-row to be focused
This is not really an issue, just trying to understand behavior better.

I have a mat-table which I had been handling click events from to highlight rows, and I'm switching now to make it work with a router instead.

When I add routerLinkActive to a mat-row and then click on the row it becomes highlighted. It turns out this is due to :focus being set for some reason which causes a blue outline.

```<code><mat-row
        matRipple

        routerLink="doesnt/exist"
        routerLinkActive="class-doesnt-even-exist"

        *matRowDef="let row; columns: displayedColumns;"
        (click)="alert('clicked')"></mat-row>
</code>```

It isn't even an active route that is being highlighted, just the row I click on.

The docs for mat-table even says the following:

mat-table does not manage any focus/keyboard interaction on its own.
  Users can add desired focus/keyboard interactions in their
  application.

I've looked in the source for the router directives and don't see anything there about focus.

The problem can easily be solved by setting my own :focus selector, but I'm trying to understand what is causing this out of curiosity.

Here's a sample:

https://stackblitz.com/edit/angular-5-generic-data-table-mzro7w?file=app/data-table/data-table.component.html

答:
When you use tabindex="-1" there are some downfalls.  You can no longer focus any child element inside there.  Taking a look at the sourcecode for RouterLink we can see that Angular is looking for the presence of any tabindex attribute and if one exists, it will not monkey with the tabindex.

My solution then was to use tabindex="ignore" -- an intentionally invalid value.  In practice, we get the best of both worlds: Angular does not add the tabindex attribute, and child elements can still be focused if they have tabindex, and the browser ignores the invalid value and doesn't consider it a tab stop.

Body:
This is not really an issue, just trying to understand behavior better.

I have a mat-table which I had been handling click events from to highlight rows, and I'm switching now to make it work with a router instead.

When I add routerLinkActive to a mat-row and then click on the row it becomes highlighted. It turns out this is due to :focus being set for some reason which causes a blue outline.

<mat-row
        matRipple

        routerLink="doesnt/exist"
        routerLinkActive="class-doesnt-even-exist"

        *matRowDef="let row; columns: displayedColumns;"
        (click)="alert('clicked')"></mat-row>

It isn't even an active route that is being highlighted, just the row I click on.

The docs for mat-table even says the following:

mat-table does not manage any focus/keyboard interaction on its own.
  Users can add desired focus/keyboard interactions in their
  application.

I've looked in the source for the router directives and don't see anything there about focus.

The problem can easily be solved by setting my own :focus selector, but I'm trying to understand what is causing this out of curiosity.

Here's a sample:

https://stackblitz.com/edit/angular-5-generic-data-table-mzro7w?file=app/data-table/data-table.component.html


问:
Prevent exploding loss function multi-step multi-variate/output forecast ConvLSTM
I have a plausible problem that currently fails to solve. During the training, my loss function explodes becomes inf or NaN, because the MSE of all errors becomes huge if the predictions (at the beginning of the training) are worse. And that is the normal intended behavior and correct. But, how do I train a ConvLSTM to which loss function to be able to learn a multi-step multi-variate output?

E.g. i try a (32, None, 200, 12) to predict (32, None, 30, 12). 32 is the batch size, None is the number of samples (>3000). 200 is the number of time steps, 12 features wide. 30 output time steps, 12 features wide.

My ConvLSTM model:

```<code>    input = Input(shape=(None, input_shape[1]))
    conv1d_1 = Conv1D(filters=64, kernel_size=3, activation=LeakyReLU())(input)
    conv1d_2 = Conv1D(filters=32, kernel_size=3, activation=LeakyReLU())(conv1d_1)
    dropout = Dropout(0.3)(conv1d_2)
    lstm_1 = LSTM(32, activation=LeakyReLU())(dropout)
    dense_1 = Dense(forecasting_horizon * input_shape[1], activation=LeakyReLU())(lstm_1)
    output = Reshape((forecasting_horizon, input_shape[1]))(dense_1)
    model = Model(inputs=input, outputs=output)
</code>```

My ds generation:

```<code>                ds_inputs = tf.keras.utils.timeseries_dataset_from_array(df[:-forecast_horizon], None, sequence_length=window_size, sequence_stride=1,
                                                                          shuffle=False, batch_size=None)
                ds_targets = tf.keras.utils.timeseries_dataset_from_array(df[forecast_horizon:], None, sequence_length=forecast_horizon, sequence_stride=1,
                                                                          shuffle=False, batch_size=None)
                ds_inputs = ds_inputs.batch(batch_size, drop_remainder=True)
                ds_targets = ds_targets.batch(batch_size, drop_remainder=True)
                ds = tf.data.Dataset.zip((ds_inputs, ds_targets))
                ds = ds.shuffle(buffer_size=(len(ds)))
</code>```

Besides MSE, I already tried MeanAbsoluteError, MeanSquaredLogarithmicError, MeanAbsolutePercentageError, CosineSimilarity. Where the last, produce non-sense. MSLE works best but does not favor large errors and therefore the MSE (used as metric has an incredible variation during training). Additionally, after a while, the Network becomes stale and gets no better loss (my explanation is that the difference in loss becomes too minor on the logarithmic scale and therefore the weights cannot be well adjusted).

答: I can partially answer my own question. One issue is that I used ReLu/LeakyReLu which will lead to exploding gradient problem because the RNN/LSTM Layer applies the same weights over time leading to exploding values as the values add up. Weights will not be reduced by any chance (ReLu min == 0). With Tanh as activation, it is possible to have negative values which also allow a reduction of the internal weights and really minimize the chance of exploding weights/predictions within the network. After some tests, the LSTM layer stays numerical stable.</p>

Body:
I have a plausible problem that currently fails to solve. During the training, my loss function explodes becomes inf or NaN, because the MSE of all errors becomes huge if the predictions (at the beginning of the training) are worse. And that is the normal intended behavior and correct. But, how do I train a ConvLSTM to which loss function to be able to learn a multi-step multi-variate output?

E.g. i try a (32, None, 200, 12) to predict (32, None, 30, 12). 32 is the batch size, None is the number of samples (>3000). 200 is the number of time steps, 12 features wide. 30 output time steps, 12 features wide.

My ConvLSTM model:

    input = Input(shape=(None, input_shape[1]))
    conv1d_1 = Conv1D(filters=64, kernel_size=3, activation=LeakyReLU())(input)
    conv1d_2 = Conv1D(filters=32, kernel_size=3, activation=LeakyReLU())(conv1d_1)
    dropout = Dropout(0.3)(conv1d_2)
    lstm_1 = LSTM(32, activation=LeakyReLU())(dropout)
    dense_1 = Dense(forecasting_horizon * input_shape[1], activation=LeakyReLU())(lstm_1)
    output = Reshape((forecasting_horizon, input_shape[1]))(dense_1)
    model = Model(inputs=input, outputs=output)

My ds generation:

                ds_inputs = tf.keras.utils.timeseries_dataset_from_array(df[:-forecast_horizon], None, sequence_length=window_size, sequence_stride=1,
                                                                          shuffle=False, batch_size=None)
                ds_targets = tf.keras.utils.timeseries_dataset_from_array(df[forecast_horizon:], None, sequence_length=forecast_horizon, sequence_stride=1,
                                                                          shuffle=False, batch_size=None)
                ds_inputs = ds_inputs.batch(batch_size, drop_remainder=True)
                ds_targets = ds_targets.batch(batch_size, drop_remainder=True)
                ds = tf.data.Dataset.zip((ds_inputs, ds_targets))
                ds = ds.shuffle(buffer_size=(len(ds)))

Besides MSE, I already tried MeanAbsoluteError, MeanSquaredLogarithmicError, MeanAbsolutePercentageError, CosineSimilarity. Where the last, produce non-sense. MSLE works best but does not favor large errors and therefore the MSE (used as metric has an incredible variation during training). Additionally, after a while, the Network becomes stale and gets no better loss (my explanation is that the difference in loss becomes too minor on the logarithmic scale and therefore the weights cannot be well adjusted).


问:
Simple question about Entity Framework
I have this very simple example:

This generates these straightforward classes:

However, when I access the property Cities of any of my User objects read from the database it is always set to null. I thought that the Entity Framework would fill that property. Am I right? What I'm doing wrong?

Thanks.

EDIT: Just as a note I'm using 3.5, not 4 (looks like there are some key differences)

答:
By default, EF uses Lazy Loading, in order to avoid mapping a whole referential integrity graph (imagine you've had more tables under Cities table - it would then make the underlying SQL query extremely huge and contain a lot of JOINs).

So you need to explicitly include subentities you want to be included and then a JOIN would occur behind the scenes. Call .Include("Cities") after you query for Users (or whatever queried subset of it like Users.Where(...)).

Title: Simple question about Entity Framework