问:
The Id cannot be computed, since the navigation source 'values' cannot be resolved to a known entity set from model
I am accessing my OData service with following metadata (simplified and obfuscated to the relevant part), this is generated by using Microsoft.AspNet.OData :

```<code><Edmx xmlns:edmx="http://docs.oasis-open.org/odata/ns/edmx" Version="4.0">
    <DataServices>
        <Schema xmlns="http://docs.oasis-open.org/odata/ns/edm" Namespace="MyProject.Api.Models">
            <EntityType Name="ValuesContainer">
                <Key>
                    <PropertyRef Name="id" />
                </Key>
                <Property Name="id" Type="Edm.Guid" Nullable="false" />
                <NavigationProperty Name="values" Type="Collection(MyProject.Api.Models.Value)"/>
            </EntityType>
            <EntityType Name="Value">
                <Key>
                    <PropertyRef Name="id"/>
                </Key>
                <Property Name="value" Type="Edm.String" />
                <Property Name="id" Type="Edm.Guid" Nullable="false" />
                <Property Name="valuesContainerId" Type="Edm.Guid"/>
                <NavigationProperty Name="valuesContainer" Type="MyProject.Api.Models.ValuesContainer">
                    <ReferentialConstraint Property="valuesContainerId" ReferencedProperty="id"/>
                </NavigationProperty>
            </EntityType>
        </Schema>
        </DataServices>
</Edmx>
</code>```

Some example the output it generates:

```<code>{
    "@odata.context": "https://localhost:5002/v1/odata/$metadata#ValuesContainer(values())",
    "value": [
        {
            "id": "2996e6ea-3e72-4b4c-8b3b-b076e34f6dac",
            "values": [
                {
                    "value": "Hello world",
                    "valuesContainerId": "2996e6ea-3e72-4b4c-8b3b-b076e34f6dac",
                    "id": "3d10fcfa-27a2-4c21-7e01-08d783bf6c40"
                }
            ]
        }
    ]
}
</code>```

When I try to get a ValuesContainer via using the Simple.Odata.Client I receive the following error:

Microsoft.OData.ODataException: 'The Id cannot be computed, since the navigation source 'values' cannot be resolved to a known entity set from model.'

Part where the exception is thrown:

```<code>namespace Simple.OData.Client.V4.Adapter
{
    public class ResponseReader : ResponseReaderBase
...
private ODataEntryAnnotations CreateAnnotations(ODataResource odataEntry)
        {
            string id = null;
            Uri readLink = null;
            Uri editLink = null;
            if (_session.Adapter.GetMetadata().IsTypeWithId(odataEntry.TypeName))
            {
                try
                {
// Over here my exception occurs, calculating the odataEntry.Id.AbsoluteUri
                    id = odataEntry.Id.AbsoluteUri;
                    readLink = odataEntry.ReadLink;
                    editLink = odataEntry.EditLink;
                }
                catch (ODataException)
                {
/// Yep, the library contains this typo
                    // Ingored
                }
            }

            return new ODataEntryAnnotations
            {
                Id = id,
                TypeName = odataEntry.TypeName,
                ReadLink = readLink,
                EditLink = editLink,
                ETag = odataEntry.ETag,
                MediaResource = CreateAnnotations(odataEntry.MediaResource),
                InstanceAnnotations = odataEntry.InstanceAnnotations,
            };
        }
...
}
</code>```

Is my metadata wrong and/or is there a workaround for this? It's not really required to solve it, but having that many exceptions thrown during runtime causes too much overhead as these are expensive operations.

答:
I was getting this error, I resolved it by setting:

```<code>MergeOption = MergeOption.NoTracking;
</code>```

on my Client, as I was only doing read-only operations at the time.

Found that answer here: https://github.com/OData/odata.net/issues/2211

Body:
I am accessing my OData service with following metadata (simplified and obfuscated to the relevant part), this is generated by using Microsoft.AspNet.OData :

<Edmx xmlns:edmx="http://docs.oasis-open.org/odata/ns/edmx" Version="4.0">
    <DataServices>
        <Schema xmlns="http://docs.oasis-open.org/odata/ns/edm" Namespace="MyProject.Api.Models">
            <EntityType Name="ValuesContainer">
                <Key>
                    <PropertyRef Name="id" />
                </Key>
                <Property Name="id" Type="Edm.Guid" Nullable="false" />
                <NavigationProperty Name="values" Type="Collection(MyProject.Api.Models.Value)"/>
            </EntityType>
            <EntityType Name="Value">
                <Key>
                    <PropertyRef Name="id"/>
                </Key>
                <Property Name="value" Type="Edm.String" />
                <Property Name="id" Type="Edm.Guid" Nullable="false" />
                <Property Name="valuesContainerId" Type="Edm.Guid"/>
                <NavigationProperty Name="valuesContainer" Type="MyProject.Api.Models.ValuesContainer">
                    <ReferentialConstraint Property="valuesContainerId" ReferencedProperty="id"/>
                </NavigationProperty>
            </EntityType>
        </Schema>
        </DataServices>
</Edmx>

Some example the output it generates:

{
    "@odata.context": "https://localhost:5002/v1/odata/$metadata#ValuesContainer(values())",
    "value": [
        {
            "id": "2996e6ea-3e72-4b4c-8b3b-b076e34f6dac",
            "values": [
                {
                    "value": "Hello world",
                    "valuesContainerId": "2996e6ea-3e72-4b4c-8b3b-b076e34f6dac",
                    "id": "3d10fcfa-27a2-4c21-7e01-08d783bf6c40"
                }
            ]
        }
    ]
}

When I try to get a ValuesContainer via using the Simple.Odata.Client I receive the following error:

Microsoft.OData.ODataException: 'The Id cannot be computed, since the navigation source 'values' cannot be resolved to a known entity set from model.'

Part where the exception is thrown:

namespace Simple.OData.Client.V4.Adapter
{
    public class ResponseReader : ResponseReaderBase
...
private ODataEntryAnnotations CreateAnnotations(ODataResource odataEntry)
        {
            string id = null;
            Uri readLink = null;
            Uri editLink = null;
            if (_session.Adapter.GetMetadata().IsTypeWithId(odataEntry.TypeName))
            {
                try
                {
// Over here my exception occurs, calculating the odataEntry.Id.AbsoluteUri
                    id = odataEntry.Id.AbsoluteUri;
                    readLink = odataEntry.ReadLink;
                    editLink = odataEntry.EditLink;
                }
                catch (ODataException)
                {
/// Yep, the library contains this typo
                    // Ingored
                }
            }

            return new ODataEntryAnnotations
            {
                Id = id,
                TypeName = odataEntry.TypeName,
                ReadLink = readLink,
                EditLink = editLink,
                ETag = odataEntry.ETag,
                MediaResource = CreateAnnotations(odataEntry.MediaResource),
                InstanceAnnotations = odataEntry.InstanceAnnotations,
            };
        }
...
}

Is my metadata wrong and/or is there a workaround for this? It's not really required to solve it, but having that many exceptions thrown during runtime causes too much overhead as these are expensive operations.

Body:
I was getting this error, I resolved it by setting:

MergeOption = MergeOption.NoTracking;

on my Client, as I was only doing read-only operations at the time.

Found that answer here: https://github.com/OData/odata.net/issues/2211


来源: stackexchange

问:
How to use setup.py and setup.cfg and pip-tools to obtain layered requirements.txt under different environment of a Django project?
I'm using https://github.com/jazzband/pip-tools to handle compiling the requirements.txt for a Django project.

Previously, I was using without a setup.py and so i was using base.in, local.in, and production.in.

When I needed a local requirements.txt after i finish pip-compile, I just run pip-sync base.txt local.txt and it will install the requirements for local environment.

When I needed a production requirements.txt after i finish pip-compile, I just run pip-sync base.txt production.txt and it will install the requirements for production environment.

So I switch away from using base.in is because I wanted to also lock the python version and i realized, setup.py and setup.cfg can help using python_requires

But now i become unsure of how to use setup.py and setup.cfg along with pip-tools to compile requirements.txt that can be environment-specific.

The only documentation for layered requirements is by using the different .in files as written in the README as https://github.com/jazzband/pip-tools#workflow-for-layered-requirements

So my question is:

Given:

pip-tools

setup.py and setup.cfg

how to still have layered requirements?

答:
pip-tools works smoothly with setup.py too. You just need to run it without providing it with an *.in file.

Mixed variant with setup.py and in files:

So assuming, that you have the following structure:

```<code># setup.py replacing the base.in file
from distutils.core import setup

setup(
    name="MyLibrary",
    version="1.0",
    install_requires=[
        "requests",
        "bcrypt",
    ]
)
</code>```

and a local.in file:

```<code>django
</code>```

you need to do the following to compile the dependencies:

```<code>$ pip-compile -o base.txt
$ pip-compile local.in
$ pip-sync base.txt local.txt
</code>```

$ pip-compile -o base.txt will generate dependencies from setup.py using base.txt as an output file. It defaults to requirements.txt.
$ pip-compile local.in is the same what you did before, as with the pip-sync part which doesn't change.

So the only magic here is to run pip-compile without providing it with an input file.

Setup.py only solution:

Setup.py supports extras_require which is a dictionary of named optional dependencies:

```<code>[...]
    extras_require={
        "local": ["pytest"],
    },
[...]
</code>```

pip-tools has an option extra:

```<code>$ pip-compile --help |grep extra
  --extra TEXT     Name of an extras_require group to install;
</code>```

So you could do the following:

```<code>pip-compile --extra local -o local.txt
pip-compile --extra production -o production.txt
</code>```

The output files contain all requiremenets in install_requires + the extra requirements specified.

Afterwards you just sync the local/production.txt:

```<code>$ pip-sync local.txt
$ pip-sync production.txt
</code>```

If I was you, I would grab the pure setup.py variant.

ContentLicense: CC BY-SA 4.0

Body:
pip-tools works smoothly with setup.py too. You just need to run it without providing it with an *.in file.

Mixed variant with setup.py and in files:

So assuming, that you have the following structure:

# setup.py replacing the base.in file
from distutils.core import setup

setup(
    name="MyLibrary",
    version="1.0",
    install_requires=[
        "requests",
        "bcrypt",
    ]
)

and a local.in file:

django

you need to do the following to compile the dependencies:

$ pip-compile -o base.txt
$ pip-compile local.in
$ pip-sync base.txt local.txt

$ pip-compile -o base.txt will generate dependencies from setup.py using base.txt as an output file. It defaults to requirements.txt.
$ pip-compile local.in is the same what you did before, as with the pip-sync part which doesn't change.

So the only magic here is to run pip-compile without providing it with an input file.

Setup.py only solution:

Setup.py supports extras_require which is a dictionary of named optional dependencies:

[...]
    extras_require={
        "local": ["pytest"],
    },
[...]

pip-tools has an option extra:

$ pip-compile --help |grep extra
  --extra TEXT     Name of an extras_require group to install;

So you could do the following:

pip-compile --extra local -o local.txt
pip-compile --extra production -o production.txt

The output files contain all requiremenets in install_requires + the extra requirements specified.

Afterwards you just sync the local/production.txt:

$ pip-sync local.txt
$ pip-sync production.txt

If I was you, I would grab the pure setup.py variant.


问:
React Environmental Variables are undefined with Dotenv
I am using dotenv to create an environment variable to insert a base url into my API call using react, dotenv, and webpack.

When I call the variables in the code, I don't get any error other than them printing as undefined. What am I doing wrong?

Here is my webpack file

```<code>const webpack = require("webpack");
const Dotenv = require("dotenv");

dotenv.config();

module.exports = (env) => {
  return {
    plugins: [
      new Dotenv(),
      new webpack.ProvidePlugin({
        process: "process/browser",
      }),
      new webpack.DefinePlugin({
        'process.env': JSON.stringify(process.env)
     })
    ],
  };
};
</code>```

Here are what the variables look like in the .env file in the root of my project

```<code>API_URL=http://localhost:8000
BASE_URL=https://my-url.com
</code>```

And here is how I am accessing it in the code (with axios for auth)

```<code>  axiosAuth: axios.create({
    baseURL: `${process.env.BASE_URL}`,
    timeout: 5000,
  })
</code>```

答:
Set the values explicitly to be defined instead of the whole process.env. Try:

```<code>new webpack.DefinePlugin({
   'process.env': {
       API_URL: JSON.stringify(process.env.API_URL),
       BASE_URL: JSON.stringify(process.env.BASE_URL),
    }
})
</code>```

And if you're using create-react-app, prefixing REACT_APP_ will also work and you could remove the define plugin and Dotenv.

example:

API_URL -> REACT_APP_API_URL // .env

usage: `process.env.REACT_APP_API_URL

Body:
I am using dotenv to create an environment variable to insert a base url into my API call using react, dotenv, and webpack.

When I call the variables in the code, I don't get any error other than them printing as undefined. What am I doing wrong?

Here is my webpack file

const webpack = require("webpack");
const Dotenv = require("dotenv");

dotenv.config();

module.exports = (env) => {
  return {
    plugins: [
      new Dotenv(),
      new webpack.ProvidePlugin({
        process: "process/browser",
      }),
      new webpack.DefinePlugin({
        'process.env': JSON.stringify(process.env)
     })
    ],
  };
};

Here are what the variables look like in the .env file in the root of my project

API_URL=http://localhost:8000
BASE_URL=https://my-url.com

And here is how I am accessing it in the code (with axios for auth)

  axiosAuth: axios.create({
    baseURL: `${process.env.BASE_URL}`,
    timeout: 5000,
  })

Body:
Set the values explicitly to be defined instead of the whole process.env. Try:

new webpack.DefinePlugin({
   'process.env': {
       API_URL: JSON.stringify(process.env.API_URL),
       BASE_URL: JSON.stringify(process.env.BASE_URL),
    }
})

And if you're using create-react-app, prefixing REACT_APP_ will also work and you could remove the define plugin and Dotenv.

example:

API_URL -> REACT_APP_API_URL // .env

usage: `process.env.REACT_APP_API_URL


问:
Angular JS Table Formatting
I have a AngularJS application in which I have a table as You can see in the image below,

as you can see the last column contains a delete and and a edit button for every row. How can I highlight row when the corresponding delete button is pressed?

Here is my code: https://plnkr.co/edit/ZNzgVO59eWJSVMH7?preview

var myApp = angular.module('myApp', []);

myApp.constant('Employees',

    [{ Name: "Ishan", Code: 1, Is_Intern: "Yes", DateOfJoining: "01/02/2022", Skills: "VB, DOT.NET, Angular", Status: "Working" },
    { Name: "Ashwin", Code: 2, Is_Intern: "No", DateOfJoining: "21/03/2021", Skills: "VB, Ruby, Angular", Status: "Inactive" },
    { Name: "Shailesh", Code: 3, Is_Intern: "Yes", DateOfJoining: "27/04/2021", Skills: "VB, Python, Angular", Status: "Working" },
    { Name: "Pawan", Code: 4, Is_Intern: "No", DateOfJoining: "14/01/2022", Skills: "VB, Sapphire, Angular", Status: "Inactive" }]);

myApp.component('employeeDetail', {

    bindings: {
        Name: '<',
        Code: '<',
        Is_Intern: '<',
        DateOfJoining: '<',
        Skills: '<',
    },

    controller: 'empCtrl',
});

myApp.controller('empCtrl', function empCtrl($scope, Employees) {

    $scope.EmployeeDetails = Employees;

    $scope.Name = Employees.Name;
    $scope.Code = Employees.Code;
    $scope.Is_Intern = Employees.Is_Intern;
    $scope.DateOfJoining = Employees.DateOfJoining;
    $scope.Skills = Employees.Skills;
    $scope.Status = Employees.Status;

    $scope.add = function () {

        $scope.EmployeeDetails.push({

            Name: $scope.Name,
            Code: $scope.Code,
            Is_Intern: $scope.Is_Intern,
            DateOfJoining: $scope.DateOfJoining,
            Skills: $scope.Skills,
            Status: $scope.Status,
        });
        $scope.id = '';
        $scope.Code = '';
        $scope.Is_Intern = '';
        $scope.DateOfJoining = '';
        $scope.Skills = '';
        $scope.Status = '';
    };

    function select(Name) {

        for (let i = 0; i < $scope.EmployeeDetails.length; i++) {
            if ($scope.EmployeeDetails[i].Name == Name) {
                return i;
            }
        }
        return -1;
    };

    $scope.edit = function (Name) {

        let index = select(Name);
        let emp = $scope.EmployeeDetails[index];
        $scope.Name = emp.Name;
        $scope.Code = emp.Code;
        $scope.Is_Intern = emp.Is_Intern;
        $scope.DateOfJoining = emp.DateOfJoining;
        $scope.Skills = emp.Skills;
        $scope.Status = emp.Status;
    }

    $scope.save = function () {

        let index = select($scope.Name);
        $scope.EmployeeDetails[index].Name = $scope.Name;
        $scope.EmployeeDetails[index].Code = $scope.Code;
        $scope.EmployeeDetails[index].Is_Intern = $scope.Is_Intern;
        $scope.EmployeeDetails[index].DateOfJoining = $scope.DateOfJoining;
        $scope.EmployeeDetails[index].Skills = $scope.Skills;
        $scope.EmployeeDetails[index].Status = $scope.Status;

        $scope.Name = '';
        $scope.Code = '';
        $scope.Is_Intern = '';
        $scope.DateOfJoining = '';
        $scope.Skills = '';
        $scope.Status = '';
    }

    $scope.delete = function (emp) {
        if (confirm("Are You Sure You want to delete this record ?")) {
            $scope.EmployeeDetails.splice(emp, 1)
            alert("Deleted")
        }
    }

    $scope.selectedRow = null;
    $scope.setClickedRow = function (index) {
        $scope.selectedRow = index;
    }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>table {
    border-collapse: collapse;
    font-family: Arial;
}

td {
    border: 1px solid black;
    padding: 5px;
}

th {
    border: 1px solid black;
    padding: 5px;
    text-align: center;
}

label,
input {
    display: block;
}

label {
    margin-bottom: 5px;
}</code>```

            Names of Employees

                Name
                Code
                Is_Intern
                Skills
                Status
                DateOfJoining
                Action

                {{emp.Name}}
                {{emp.Code}}
                {{emp.Is_Intern}}
                {{emp.Skills}}
                {{emp.Status}}
                {{emp.DateOfJoining}}
                <button ng-click="edit(emp.Name)">Edit</button>
                <button ng-click="delete($index)">Delete</button>

            Name
            <input ng-model="Name" type="text" />

            Code
            <input ng-model="Code" type="number" />

            Is_Intern
            <input ng-model="Is_Intern" type="text" />

            Skills
            <input ng-model="Skills" type="text" />

            Status
            <input ng-model="Status" type="text" />

            Date Of Joining
            <input ng-model="DateOfJoining" type="text" />

            <button ng-click="add()">Add</button>

        <button ng-click="save()">Update</button>

```

答:
This can be achieved by using ng-class in angular js.

Logic.

On delete button click set some flag on the row to indicate that the row is active I used an isActive class.

Then use a ng-class condition, ng-class="{'highlight': emp.isActive == true}".

Since you are making use of a JavaScript confirm method, you have to use a setTimeout function to trigger the confirm dialog. Or else the changes will not be visible in the DOM.

Since you have used setTimeout, you have to use $scope.$apply() to get your changes reflected in the UI.

Working Fiddle.

var myApp = angular.module('myApp', []);

myApp.constant('Employees',

    [{ Name: "Ishan", Code: 1, Is_Intern: "Yes", DateOfJoining: "01/02/2022", Skills: "VB, DOT.NET, Angular", Status: "Working" },
    { Name: "Ashwin", Code: 2, Is_Intern: "No", DateOfJoining: "21/03/2021", Skills: "VB, Ruby, Angular", Status: "Inactive" },
    { Name: "Shailesh", Code: 3, Is_Intern: "Yes", DateOfJoining: "27/04/2021", Skills: "VB, Python, Angular", Status: "Working" },
    { Name: "Pawan", Code: 4, Is_Intern: "No", DateOfJoining: "14/01/2022", Skills: "VB, Sapphire, Angular", Status: "Inactive" }]);

myApp.component('employeeDetail', {

    bindings: {
        Name: '<',
        Code: '<',
        Is_Intern: '<',
        DateOfJoining: '<',
        Skills: '<',
    },

    controller: 'empCtrl',
});

myApp.controller('empCtrl', function empCtrl($scope, Employees) {

    $scope.EmployeeDetails = Employees;

    $scope.Name = Employees.Name;
    $scope.Code = Employees.Code;
    $scope.Is_Intern = Employees.Is_Intern;
    $scope.DateOfJoining = Employees.DateOfJoining;
    $scope.Skills = Employees.Skills;
    $scope.Status = Employees.Status;

    $scope.add = function () {

        $scope.EmployeeDetails.push({

            Name: $scope.Name,
            Code: $scope.Code,
            Is_Intern: $scope.Is_Intern,
            DateOfJoining: $scope.DateOfJoining,
            Skills: $scope.Skills,
            Status: $scope.Status,
        });
        $scope.id = '';
        $scope.Code = '';
        $scope.Is_Intern = '';
        $scope.DateOfJoining = '';
        $scope.Skills = '';
        $scope.Status = '';
    };

    function select(Name) {

        for (let i = 0; i < $scope.EmployeeDetails.length; i++) {
            if ($scope.EmployeeDetails[i].Name == Name) {
                return i;
            }
        }
        return -1;
    };

    $scope.edit = function (Name) {

        let index = select(Name);
        let emp = $scope.EmployeeDetails[index];
        $scope.Name = emp.Name;
        $scope.Code = emp.Code;
        $scope.Is_Intern = emp.Is_Intern;
        $scope.DateOfJoining = emp.DateOfJoining;
        $scope.Skills = emp.Skills;
        $scope.Status = emp.Status;
    }

    $scope.save = function () {

        let index = select($scope.Name);
        $scope.EmployeeDetails[index].Name = $scope.Name;
        $scope.EmployeeDetails[index].Code = $scope.Code;
        $scope.EmployeeDetails[index].Is_Intern = $scope.Is_Intern;
        $scope.EmployeeDetails[index].DateOfJoining = $scope.DateOfJoining;
        $scope.EmployeeDetails[index].Skills = $scope.Skills;
        $scope.EmployeeDetails[index].Status = $scope.Status;

        $scope.Name = '';
        $scope.Code = '';
        $scope.Is_Intern = '';
        $scope.DateOfJoining = '';
        $scope.Skills = '';
        $scope.Status = '';
    }

    $scope.deleteRow = function (emp, row) {
        row.isActive = true;
        setTimeout(function () {
            $scope.delete(emp, row);
        });
    }

    $scope.delete = function (emp, row) {
        if (confirm("Are You Sure You want to delete this record ?")) {
            $scope.EmployeeDetails.splice(emp, 1)
            $scope.$apply();
            alert("Deleted");
        }
        row.isActive = false;
    }

    $scope.selectedRow = null;
    $scope.setClickedRow = function (index) {
        $scope.selectedRow = index;
    }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>table {
    border-collapse: collapse;
    font-family: Arial;
}

td {
    border: 1px solid black;
    padding: 5px;
}

th {
    border: 1px solid black;
    padding: 5px;
    text-align: center;
}

label,
input {
    display: block;
}

label {
    margin-bottom: 5px;
}

.highlight {
    background: gray;
}</code>```

            Names of Employees

                Name
                Code
                Is_Intern
                Skills
                Status
                DateOfJoining
                Action

                {{emp.Name}} - {{ emp.isActive }}
                {{emp.Code}}
                {{emp.Is_Intern}}
                {{emp.Skills}}
                {{emp.Status}}
                {{emp.DateOfJoining}}
                <button ng-click="edit(emp.Nam, emp)">Edit</button>
                <button ng-click="deleteRow($index, emp)">Delete</button>

            Name
            <input ng-model="Name" type="text" />

            Code
            <input ng-model="Code" type="number" />

            Is_Intern
            <input ng-model="Is_Intern" type="text" />

            Skills
            <input ng-model="Skills" type="text" />

            Status
            <input ng-model="Status" type="text" />

            Date Of Joining
            <input ng-model="DateOfJoining" type="text" />

            <button ng-click="add()">Add</button>

        <button ng-click="save()">Update</button>

```

Title: Angular JS Table Formatting

Body:
I have a AngularJS application in which I have a table as You can see in the image below,

as you can see the last column contains a delete and and a edit button for every row. How can I highlight row when the corresponding delete button is pressed?

Here is my code: https://plnkr.co/edit/ZNzgVO59eWJSVMH7?preview

var myApp = angular.module('myApp', []);

myApp.constant('Employees',

    [{ Name: "Ishan", Code: 1, Is_Intern: "Yes", DateOfJoining: "01/02/2022", Skills: "VB, DOT.NET, Angular", Status: "Working" },
    { Name: "Ashwin", Code: 2, Is_Intern: "No", DateOfJoining: "21/03/2021", Skills: "VB, Ruby, Angular", Status: "Inactive" },
    { Name: "Shailesh", Code: 3, Is_Intern: "Yes", DateOfJoining: "27/04/2021", Skills: "VB, Python, Angular", Status: "Working" },
    { Name: "Pawan", Code: 4, Is_Intern: "No", DateOfJoining: "14/01/2022", Skills: "VB, Sapphire, Angular", Status: "Inactive" }]);

myApp.component('employeeDetail', {

    bindings: {
        Name: '<',
        Code: '<',
        Is_Intern: '<',
        DateOfJoining: '<',
        Skills: '<',
    },

    controller: 'empCtrl',
});

myApp.controller('empCtrl', function empCtrl($scope, Employees) {

    $scope.EmployeeDetails = Employees;

    $scope.Name = Employees.Name;
    $scope.Code = Employees.Code;
    $scope.Is_Intern = Employees.Is_Intern;
    $scope.DateOfJoining = Employees.DateOfJoining;
    $scope.Skills = Employees.Skills;
    $scope.Status = Employees.Status;

    $scope.add = function () {

        $scope.EmployeeDetails.push({

            Name: $scope.Name,
            Code: $scope.Code,
            Is_Intern: $scope.Is_Intern,
            DateOfJoining: $scope.DateOfJoining,
            Skills: $scope.Skills,
            Status: $scope.Status,
        });
        $scope.id = '';
        $scope.Code = '';
        $scope.Is_Intern = '';
        $scope.DateOfJoining = '';
        $scope.Skills = '';
        $scope.Status = '';
    };

    function select(Name) {

        for (let i = 0; i < $scope.EmployeeDetails.length; i++) {
            if ($scope.EmployeeDetails[i].Name == Name) {
                return i;
            }
        }
        return -1;
    };

    $scope.edit = function (Name) {

        let index = select(Name);
        let emp = $scope.EmployeeDetails[index];
        $scope.Name = emp.Name;
        $scope.Code = emp.Code;
        $scope.Is_Intern = emp.Is_Intern;
        $scope.DateOfJoining = emp.DateOfJoining;
        $scope.Skills = emp.Skills;
        $scope.Status = emp.Status;
    }

    $scope.save = function () {

        let index = select($scope.Name);
        $scope.EmployeeDetails[index].Name = $scope.Name;
        $scope.EmployeeDetails[index].Code = $scope.Code;
        $scope.EmployeeDetails[index].Is_Intern = $scope.Is_Intern;
        $scope.EmployeeDetails[index].DateOfJoining = $scope.DateOfJoining;
        $scope.EmployeeDetails[index].Skills = $scope.Skills;
        $scope.EmployeeDetails[index].Status = $scope.Status;

        $scope.Name = '';
        $scope.Code = '';
        $scope.Is_Intern = '';
        $scope.DateOfJoining = '';
        $scope.Skills = '';
        $scope.Status = '';
    }

    $scope.delete = function (emp) {
        if (confirm("Are You Sure You want to delete this record ?")) {
            $scope.EmployeeDetails.splice(emp, 1)
            alert("Deleted")
        }
    }

    $scope.selectedRow = null;
    $scope.setClickedRow = function (index) {
        $scope.selectedRow = index;
    }
});

table {
    border-collapse: collapse;
    font-family: Arial;
}

td {
    border: 1px solid black;
    padding: 5px;
}

th {
    border: 1px solid black;
    padding: 5px;
    text-align: center;
}

label,
input {
    display: block;
}

label {
    margin-bottom: 5px;
}

            Names of Employees

                Name
                Code
                Is_Intern
                Skills
                Status
                DateOfJoining
                Action

                {{emp.Name}}
                {{emp.Code}}
                {{emp.Is_Intern}}
                {{emp.Skills}}
                {{emp.Status}}
                {{emp.DateOfJoining}}
                <button ng-click="edit(emp.Name)">Edit</button>
                <button ng-click="delete($index)">Delete</button>

            Name
            <input ng-model="Name" type="text" />

            Code
            <input ng-model="Code" type="number" />

            Is_Intern
            <input ng-model="Is_Intern" type="text" />

            Skills
            <input ng-model="Skills" type="text" />

            Status
            <input ng-model="Status" type="text" />

            Date Of Joining
            <input ng-model="DateOfJoining" type="text" />

            <button ng-click="add()">Add</button>

        <button ng-click="save()">Update</button>

Body:
This can be achieved by using ng-class in angular js.

Logic.

On delete button click set some flag on the row to indicate that the row is active I used an isActive class.

Then use a ng-class condition, ng-class="{'highlight': emp.isActive == true}".

Since you are making use of a JavaScript confirm method, you have to use a setTimeout function to trigger the confirm dialog. Or else the changes will not be visible in the DOM.

Since you have used setTimeout, you have to use $scope.$apply() to get your changes reflected in the UI.

Working Fiddle.

var myApp = angular.module('myApp', []);

myApp.constant('Employees',

    [{ Name: "Ishan", Code: 1, Is_Intern: "Yes", DateOfJoining: "01/02/2022", Skills: "VB, DOT.NET, Angular", Status: "Working" },
    { Name: "Ashwin", Code: 2, Is_Intern: "No", DateOfJoining: "21/03/2021", Skills: "VB, Ruby, Angular", Status: "Inactive" },
    { Name: "Shailesh", Code: 3, Is_Intern: "Yes", DateOfJoining: "27/04/2021", Skills: "VB, Python, Angular", Status: "Working" },
    { Name: "Pawan", Code: 4, Is_Intern: "No", DateOfJoining: "14/01/2022", Skills: "VB, Sapphire, Angular", Status: "Inactive" }]);

myApp.component('employeeDetail', {

    bindings: {
        Name: '<',
        Code: '<',
        Is_Intern: '<',
        DateOfJoining: '<',
        Skills: '<',
    },

    controller: 'empCtrl',
});

myApp.controller('empCtrl', function empCtrl($scope, Employees) {

    $scope.EmployeeDetails = Employees;

    $scope.Name = Employees.Name;
    $scope.Code = Employees.Code;
    $scope.Is_Intern = Employees.Is_Intern;
    $scope.DateOfJoining = Employees.DateOfJoining;
    $scope.Skills = Employees.Skills;
    $scope.Status = Employees.Status;

    $scope.add = function () {

        $scope.EmployeeDetails.push({

            Name: $scope.Name,
            Code: $scope.Code,
            Is_Intern: $scope.Is_Intern,
            DateOfJoining: $scope.DateOfJoining,
            Skills: $scope.Skills,
            Status: $scope.Status,
        });
        $scope.id = '';
        $scope.Code = '';
        $scope.Is_Intern = '';
        $scope.DateOfJoining = '';
        $scope.Skills = '';
        $scope.Status = '';
    };

    function select(Name) {

        for (let i = 0; i < $scope.EmployeeDetails.length; i++) {
            if ($scope.EmployeeDetails[i].Name == Name) {
                return i;
            }
        }
        return -1;
    };

    $scope.edit = function (Name) {

        let index = select(Name);
        let emp = $scope.EmployeeDetails[index];
        $scope.Name = emp.Name;
        $scope.Code = emp.Code;
        $scope.Is_Intern = emp.Is_Intern;
        $scope.DateOfJoining = emp.DateOfJoining;
        $scope.Skills = emp.Skills;
        $scope.Status = emp.Status;
    }

    $scope.save = function () {

        let index = select($scope.Name);
        $scope.EmployeeDetails[index].Name = $scope.Name;
        $scope.EmployeeDetails[index].Code = $scope.Code;
        $scope.EmployeeDetails[index].Is_Intern = $scope.Is_Intern;
        $scope.EmployeeDetails[index].DateOfJoining = $scope.DateOfJoining;
        $scope.EmployeeDetails[index].Skills = $scope.Skills;
        $scope.EmployeeDetails[index].Status = $scope.Status;

        $scope.Name = '';
        $scope.Code = '';
        $scope.Is_Intern = '';
        $scope.DateOfJoining = '';
        $scope.Skills = '';
        $scope.Status = '';
    }

    $scope.deleteRow = function (emp, row) {
        row.isActive = true;
        setTimeout(function () {
            $scope.delete(emp, row);
        });
    }

    $scope.delete = function (emp, row) {
        if (confirm("Are You Sure You want to delete this record ?")) {
            $scope.EmployeeDetails.splice(emp, 1)
            $scope.$apply();
            alert("Deleted");
        }
        row.isActive = false;
    }

    $scope.selectedRow = null;
    $scope.setClickedRow = function (index) {
        $scope.selectedRow = index;
    }
});

table {
    border-collapse: collapse;
    font-family: Arial;
}

td {
    border: 1px solid black;
    padding: 5px;
}

th {
    border: 1px solid black;
    padding: 5px;
    text-align: center;
}

label,
input {
    display: block;
}

label {
    margin-bottom: 5px;
}

.highlight {
    background: gray;
}

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
<body ng-app="myApp" ng-controller="empCtrl">
    <table>
        <thead>
            <th colspan="8">Names of Employees</th>

        </thead>
        <tbody>
            <tr>
                <th>Name</th>
                <th>Code</th>
                <th>Is_Intern</th>
                <th>Skills</th>
                <th>Status</th>
                <th>DateOfJoining</th>
                <th colspan="2" style="text-align: center;">Action</th>

            </tr>
            <tr ng-repeat="emp in EmployeeDetails" ng-class="{'highlight': emp.isActive == true}">
                <td>{{emp.Name}} - {{ emp.isActive }}</td>
                <td>{{emp.Code}}</td>
                <td>{{emp.Is_Intern}}</td>
                <td>{{emp.Skills}}</td>
                <td>{{emp.Status}}</td>
                <td>{{emp.DateOfJoining}}</td>
                <td><button ng-click="edit(emp.Nam, emp)">Edit</button></td>
                <td><button ng-click="deleteRow($index, emp)">Delete</button></td>
            </tr>

        </tbody>
        <label>
            Name
            <input ng-model="Name" type="text" />
        </label>
        <label>
            Code
            <input ng-model="Code" type="number" />
        </label>
        <label>
            Is_Intern
            <input ng-model="Is_Intern" type="text" />
        </label>
        <label>
            Skills
            <input ng-model="Skills" type="text" />
        </label>
        <label>
            Status
            <input ng-model="Status" type="text" />
        </label>
        <label>
            Date Of Joining
            <input ng-model="DateOfJoining" type="text" />
        </label>
        <label>
            <button ng-click="add()">Add</button>&nbsp;&nbsp;&nbsp;
        </label>
        <button ng-click="save()">Update</button><br><br>
    </table>
    <br>
</body>


问:
Is there a way to check for @Output wire up from within a component in Angular?
In the ngOnInit method of a component the @Input values will have been bound so you can check those properties on the component, but there doesn't seem to be a way to check @Output event bindings. I want to be able to know if the @Output was wired up on the component or not.

(using Angular and TypeScript)

```<code>import {Component, Output, EventEmitter} from '@angular/core';

@Component({
    selector: 'sample',
    template: `<p>a sample</p>`
})
export class SampleComponent {
    @Output() cancel = new EventEmitter();

    ngOnInit() {
        // would like to check and see if cancel was used
        // on the element <sample (cancel)="doSomething()"></sample>
        // or not <sample></sample>
    }
}
</code>```

答:
as of now current version Angular 13 to check if is there any observer/callback is provided you can use this.cancel.observed which will return boolean

```<code>import {Component, Output, EventEmitter} from '@angular/core';

@Component({
    selector: 'sample',
    template: `<p>a sample</p>`
})
export class SampleComponent {
    @Output() cancel = new EventEmitter();
    private isCancelUsed = false;

    ngOnInit() {
        this.isCancelUsed = this.cancel.observed;
    }
}
</code>```

Body:
In the ngOnInit method of a component the @Input values will have been bound so you can check those properties on the component, but there doesn't seem to be a way to check @Output event bindings. I want to be able to know if the @Output was wired up on the component or not.

(using Angular and TypeScript)

import {Component, Output, EventEmitter} from '@angular/core';

@Component({
    selector: 'sample',
    template: `<p>a sample</p>`
})
export class SampleComponent {
    @Output() cancel = new EventEmitter();

    ngOnInit() {
        // would like to check and see if cancel was used
        // on the element <sample (cancel)="doSomething()"></sample>
        // or not <sample></sample>
    }
}

Body:
as of now current version Angular 13 to check if is there any observer/callback is provided you can use this.cancel.observed which will return boolean

import {Component, Output, EventEmitter} from '@angular/core';

@Component({
    selector: 'sample',
    template: `<p>a sample</p>`
})
export class SampleComponent {
    @Output() cancel = new EventEmitter();
    private isCancelUsed = false;

    ngOnInit() {
        this.isCancelUsed = this.cancel.observed;
    }
}


问:
What is "ejecting"
The vue cli documentaion mention it in:

At the same time, it still offers the flexibility to tweak the config
of each tool without the need for ejecting

What does it mean?

答:
"ejecting", popularized by Create-React-App, means to stop using a tool that automatically creates and maintains your code or configuration, so you can instead maintain this by hand.

The typical scenario is that you start using a tool to simplify the creation and development of a small project. However, as the project becomes more complex, the tool no longer supports everything you need to do.

When the tool supports automatic ejecting, it will hard-code its currently generated files into the project, and remove any hooks that would regenerate them. The project should still work the same way, but you can now make advanced customizations to the code/config without them being overwritten, at the cost of losing the convenience of the tool.

Title: What is "ejecting"


问:
Can I Use Task.CompletedTask to Detect if Virtual Method was Overridden?
I have an asp.net core web application with an abstract class with a virtual method that child classes may or may not override. I want to execute different logic based on whether it was overridden or not and was wondering if the below check is a good idea or not:

```<code>public abstract class BaseClass
{
    public async Task DoSomethingAsync()
    {
        var task = OverrideMe();
        bool wasOverridden = task != Task.CompletedTask;
        await task;

        if (wasOverridden)
        {
            //Virtual method was overridden
        }
        else
        {
            //Virtual method was not overridden
        }
    }

    protected virtual Task OverrideMe()
    {
        return Task.CompletedTask;
    }
}
</code>```

I realize that if the child class returns Task.CompletedTask it would still look like it wasn't overridden. But if we ignore that fact, would this check work? What I'm most concerned about is the Id field of the task. Would that change and maybe cause the equality comparison to fail? When I test my code above it works but what if there are other async tasks running in parallel etc?

答:
What if you set a private field when the method has no overwrite like this:

```<code>public abstract class BaseClass
{
    private bool _notOverwritten;
    public async Task DoSomethingAsync()
    {
        var task = OverrideMe();

        await task;

        if (!_notOverwritten)
        {
            //Virtual method was overridden
        }
        else
        {
            //Virtual method was not overridden
        }
    }

    protected virtual Task OverrideMe()
    {
        _notOVerwritten = true;

        return Task.CompletedTask;
    }
}
</code>```

EDIT: This solution does not work completely as a derived class can still call base.OverrideMe() like @Theodor Zoulias mentioned.

You could throw an exception when the base.OverrideMe() is called and catch it in the DoSomethingAsync but again the derived class can also catch this exception.

Body:
I have an asp.net core web application with an abstract class with a virtual method that child classes may or may not override. I want to execute different logic based on whether it was overridden or not and was wondering if the below check is a good idea or not:

public abstract class BaseClass
{
    public async Task DoSomethingAsync()
    {
        var task = OverrideMe();
        bool wasOverridden = task != Task.CompletedTask;
        await task;

        if (wasOverridden)
        {
            //Virtual method was overridden
        }
        else
        {
            //Virtual method was not overridden
        }
    }

    protected virtual Task OverrideMe()
    {
        return Task.CompletedTask;
    }
}

I realize that if the child class returns Task.CompletedTask it would still look like it wasn't overridden. But if we ignore that fact, would this check work? What I'm most concerned about is the Id field of the task. Would that change and maybe cause the equality comparison to fail? When I test my code above it works but what if there are other async tasks running in parallel etc?

Body:
What if you set a private field when the method has no overwrite like this:

public abstract class BaseClass
{
    private bool _notOverwritten;
    public async Task DoSomethingAsync()
    {
        var task = OverrideMe();

        await task;

        if (!_notOverwritten)
        {
            //Virtual method was overridden
        }
        else
        {
            //Virtual method was not overridden
        }
    }

    protected virtual Task OverrideMe()
    {
        _notOVerwritten = true;

        return Task.CompletedTask;
    }
}

EDIT: This solution does not work completely as a derived class can still call base.OverrideMe() like @Theodor Zoulias mentioned.

You could throw an exception when the base.OverrideMe() is called and catch it in the DoSomethingAsync but again the derived class can also catch this exception.


问:
SharePoint Designer Site Configuration error while creating forms
I have configure SharePoint site in my local system, While I am going to create forms I am getting error

答:
You could try to follow some advice mentioned below:

Step 1: Create a new list item on your list. If it works, go to step 2. If doesn't, check our list columns (or content types of that list) - specially calculated fields and lookup fields.
Step 2: Create new custom form by SharePoint Designer 2013. If it doesn't work, try to clear SPD cache in location:
c:/Users/[your current user]/Appdata/Local/Microsoft/WebsiteCache

Reference:
Could not save the List Changes to Server in Sharepoint 2013

Here are another similar thread you could have a look:
"could not save the list changes to the server" in designer


问:
Is it valid to delete a lambda while executing it?
Is it allowed to delete a lambda object while executing the associated lambda function, as long as precautions are taken not to access any of the captured state after the deletion?

Consider the following example:

int main() {
    int x = 1;

    std::function<void()> d;

    auto l = new auto([x, &d]() {
        fmt::print("x is {}\n", x);
        d();
        fmt::print("I'm deleted\n");
    });

    d = [l](){ delete l; };

    (*l)();
}
```

Here, the lambda pointed to by l deletes itself using a Rube Goldberg-like approach through the d function1. After the deletion it prints a fixed message which doesn't access any captured state.

Is it defined behavior?

1 I couldn't figure out a better way to break the circular dependency between the lambda code which needs to see something that points to itself: I'm open to better options.

答:
There might not be an explicit specification for this in the standard.

Although not specified to be so, lambda types are "essentially" like special classes. Staying with this analogy, the question would be same as "Is it well defined to delete this;". The typical answer to that question is:

As long as you’re careful, it’s okay (not evil) for an object to commit suicide (delete this).

Here’s how I define “careful”:

You must be absolutely 100% positively sure that this object was allocated via new (not by new[], nor by placement new, nor a local object on the stack, nor a namespace-scope / global, nor a member of another object; but by plain ordinary new).

You must be absolutely 100% positively sure that your member function will be the last member function invoked on this object.

You must be absolutely 100% positively sure that the rest of your member function (after the delete this line) doesn’t touch any piece of this object (including calling any other member functions or touching any data members). This includes code that will run in destructors for any objects allocated on the stack that are still alive.

You must be absolutely 100% positively sure that no one even touches the this pointer itself after the delete this line. In other words, you must not examine it, compare it with another pointer, compare it with nullptr, print it, cast it, do anything with it.

To translate these points to lambdas, "call a member function" becomes "call the lambda", "any data members" becomes "any capture". Your example satisfies all of the points.

Body:
Is it allowed to delete a lambda object while executing the associated lambda function, as long as precautions are taken not to access any of the captured state after the deletion?

Consider the following example:

int main() {
    int x = 1;

    std::function<void()> d;

    auto l = new auto([x, &d]() {
        fmt::print("x is {}\n", x);
        d();
        fmt::print("I'm deleted\n");
    });

    d = [l](){ delete l; };

    (*l)();
}

Here, the lambda pointed to by l deletes itself using a Rube Goldberg-like approach through the d function1. After the deletion it prints a fixed message which doesn't access any captured state.

Is it defined behavior?

1 I couldn't figure out a better way to break the circular dependency between the lambda code which needs to see something that points to itself: I'm open to better options.


问:
How to add red asterisk in label of TextFormField In Flutter
As we are not able to make widget like RichText/Text Span For styling TextFormField,

Can anyone help me out regarding this...

Now Getting:-

Expected Result:-

How we can achieve a result like this?

答:
Place this code in TextFormField or TextField

this label works as an hint property

```<code>label: RichText(
  text: TextSpan(
    text: 'Full Name',
    style: const TextStyle(
      color: Colors.grey),
      children: [
        TextSpan(
          text: ' *',
          style: TextStyle(
          color: Colors.red,
        )
      )
    ]
  ),
  floatingLabelBehavior:FloatingLabelBehavior.never,

</code>```

look at above screenshot of label parameter holding a Widget not a String without any error

Body:
Place this code in TextFormField or TextField

this label works as an hint property

label: RichText(
  text: TextSpan(
    text: 'Full Name',
    style: const TextStyle(
      color: Colors.grey),
      children: [
        TextSpan(
          text: ' *',
          style: TextStyle(
          color: Colors.red,
        )
      )
    ]
  ),
  floatingLabelBehavior:FloatingLabelBehavior.never,

look at above screenshot of label parameter holding a Widget not a String without any error


问:
Faster ExtJs 4 learning methodology
How can a JQuery Ninja cross over to ExtJS as fast as possible? Given that ExtJS 3.x is now obsolete, how can one quickly grip concepts in Ext JS 4. Hardly can one find a book on Ext JS 4 online. The documentation is quite forward but complex. Ext Js has many components, and each component has several APIs e.g. a Grid has very many ways of manipulating its view e.t.c. What learning flow may work for me to quickly not skip anything on components, views, controllers e.t.c. I would want to write good Ext JS code in a period of 2 months from now.
please suggest methods of learning Ext JS 4

NOTE: the writer has never used Ext Js wether in older versions of it or the new

答:
you may wish to refer to this thread

Also not that a few books are available now like this one  and another one which is in a review phase but the most comprehensive guide will always be the documentation which you can get here. Otherwise you are not supposed to find any hardship because its all javascript.

ContentLicense: CC BY-SA 3.0

Title: Faster ExtJs 4 learning methodology


问:
To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config
I running jest test file and getting the following error:

```<code> ● Test suite failed to run

    Jest encountered an unexpected token

    Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.

    Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.

    By default "node_modules" folder is ignored by transformers.

    Here's what you can do:
     • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
     • If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
     • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
     • If you need a custom transformation specify a "transform" option in your config.
     • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

    You'll find more details and examples of these config options in the docs:
    https://jestjs.io/docs/configuration
    For information about custom transformations, see:
    https://jestjs.io/docs/code-transformation

    Details:

    /Users/test/dev/pm/client/node_modules/spacetime/src/index.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import Spacetime from './spacetime.js'
                                                                                ^^^^^^

    SyntaxError: Cannot use import statement outside a module

       6 | import search from '../../assets/images/search.svg';
       7 | import Dropdown from 'react-bootstrap/Dropdown';
    >  8 | import spacetime from "spacetime";
         | ^
       9 | import languages from "../../libraries/languages/language-list";
      10 | import { Rating } from 'react-simple-star-rating';
      11 |

      at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1728:14)
      at Object.<anonymous> (src/components/Mentor/MentorList.js:8:1)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        2.097 s
</code>```

I tried to fix it by adding the following to package.json, but that didn't work:

```<code>  "jest": {
    "transformIgnorePatterns": [
      "node_modules/(?!spacetime)"
    ]
  },
</code>```

Can someone please help?

答:
spacetime package main file is ES6 module. See node_modules/spacetime/src/index.js, this is the main file the package exports.The package.json of spacetime include "main": "src/index.js".

By default "node_modules" folder is ignored by transformers.

You don't need to add transformIgnorePatterns configuration for jest config, the node_modules folder is ignored by transformers.

But this is not the issue.

The issue is jest does not parse es6 import/export statement by default, even though it uses babel.

Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.

We need to transform the es6 import and export syntax.

option 1. Add babel config

option 2. Use ts-jest preset for jest.

jest.config.js:

module.exports = {
  preset: 'ts-jest/presets/js-with-ts',
  testEnvironment: 'jsdom'
};
```
<p>option 3. Use esbuild-jest</p>
<p><code>jest.config.js</code>:</p>
<pre class="lang-js prettyprint-override"><code>module.exports = {
  testEnvironment: 'jsdom',
  transform: {
    '\\.[jt]sx?$': 'esbuild-jest',
  },
};
</code>```

Body:
I running jest test file and getting the following error:

 ● Test suite failed to run

    Jest encountered an unexpected token

    Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.

    Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.

    By default "node_modules" folder is ignored by transformers.

    Here's what you can do:
     • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
     • If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
     • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
     • If you need a custom transformation specify a "transform" option in your config.
     • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

    You'll find more details and examples of these config options in the docs:
    https://jestjs.io/docs/configuration
    For information about custom transformations, see:
    https://jestjs.io/docs/code-transformation

    Details:

    /Users/test/dev/pm/client/node_modules/spacetime/src/index.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import Spacetime from './spacetime.js'
                                                                                ^^^^^^

    SyntaxError: Cannot use import statement outside a module

       6 | import search from '../../assets/images/search.svg';
       7 | import Dropdown from 'react-bootstrap/Dropdown';
    >  8 | import spacetime from "spacetime";
         | ^
       9 | import languages from "../../libraries/languages/language-list";
      10 | import { Rating } from 'react-simple-star-rating';
      11 |

      at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1728:14)
      at Object.<anonymous> (src/components/Mentor/MentorList.js:8:1)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        2.097 s

I tried to fix it by adding the following to package.json, but that didn't work:

  "jest": {
    "transformIgnorePatterns": [
      "node_modules/(?!spacetime)"
    ]
  },

Can someone please help?

Body:
spacetime package main file is ES6 module. See node_modules/spacetime/src/index.js, this is the main file the package exports.The package.json of spacetime include "main": "src/index.js".

By default "node_modules" folder is ignored by transformers.

You don't need to add transformIgnorePatterns configuration for jest config, the node_modules folder is ignored by transformers.

But this is not the issue.

The issue is jest does not parse es6 import/export statement by default, even though it uses babel.

Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.

We need to transform the es6 import and export syntax.

option 1. Add babel config

option 2. Use ts-jest preset for jest.

jest.config.js:

module.exports = {
  preset: 'ts-jest/presets/js-with-ts',
  testEnvironment: 'jsdom'
};

option 3. Use esbuild-jest

jest.config.js:

module.exports = {
  testEnvironment: 'jsdom',
  transform: {
    '\\.[jt]sx?$': 'esbuild-jest',
  },
};


问:
Tomcat and Tomcat dbcp issue after upgrade to v9.0.58
I'm getting this issue when upgrading Tomcat and Tomcat DBCP from v9.0.54 to v.9.0.58 with Java 11.</p>
```<code>Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2022-02-08T08:24:15,900Z ERROR [tartedMain] SpringApplication [SpringApplication.java:854] Application run failed
org.springframework.jmx.export.UnableToRegisterMBeanException: Unable to register MBean [org.apache.tomcat.dbcp.dbcp2.BasicDataSource@3b60547f] with key 'datasource'; nested exception is javax.management.NotCompliantMBeanException: org.apache.tomcat.dbcp.dbcp2.BasicDataSourceMXBean: Method org.apache.tomcat.dbcp.dbcp2.DataSourceMXBean.getSoftMinEvictableIdleDuration has parameter or return type that cannot be translated into an open type
    at org.springframework.jmx.export.MBeanExporter.registerBeanNameOrInstance(MBeanExporter.java:626)
    at org.springframework.jmx.export.MBeanExporter.lambda$registerBeans$2(MBeanExporter.java:552)
    at java.base/java.util.HashMap.forEach(HashMap.java:1336)
    at org.springframework.jmx.export.MBeanExporter.registerBeans(MBeanExporter.java:552)
    at org.springframework.jmx.export.MBeanExporter.afterSingletonsInstantiated(MBeanExporter.java:435)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:972)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:918)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:583)
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:145)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:765)
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:445)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:338)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1354)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1343)
    at com.wk.gbs.intakeportal.IntakePortalWarApplication.main(IntakePortalWarApplication.java:30)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49)
Caused by: javax.management.NotCompliantMBeanException: org.apache.tomcat.dbcp.dbcp2.BasicDataSourceMXBean: Method org.apache.tomcat.dbcp.dbcp2.DataSourceMXBean.getSoftMinEvictableIdleDuration has parameter or return type that cannot be translated into an open type
    at java.management/com.sun.jmx.mbeanserver.Introspector.throwException(Introspector.java:467)
    at java.management/com.sun.jmx.mbeanserver.MBeanAnalyzer.<init>(MBeanAnalyzer.java:120)
    at java.management/com.sun.jmx.mbeanserver.MBeanAnalyzer.analyzer(MBeanAnalyzer.java:102)
    at java.management/com.sun.jmx.mbeanserver.MXBeanIntrospector.getAnalyzer(MXBeanIntrospector.java:74)
    at java.management/com.sun.jmx.mbeanserver.MBeanIntrospector.getPerInterface(MBeanIntrospector.java:192)
    at java.management/com.sun.jmx.mbeanserver.MBeanSupport.<init>(MBeanSupport.java:138)
    at java.management/com.sun.jmx.mbeanserver.MXBeanSupport.<init>(MXBeanSupport.java:66)
    at java.management/com.sun.jmx.mbeanserver.Introspector.makeDynamicMBean(Introspector.java:203)
    at java.management/com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.registerObject(DefaultMBeanServerInterceptor.java:888)
    at java.management/com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.registerMBean(DefaultMBeanServerInterceptor.java:320)
    at java.management/com.sun.jmx.mbeanserver.JmxMBeanServer.registerMBean(JmxMBeanServer.java:522)
    at org.springframework.jmx.support.MBeanRegistrationSupport.doRegister(MBeanRegistrationSupport.java:138)
    at org.springframework.jmx.export.MBeanExporter.registerBeanInstance(MBeanExporter.java:672)
    at org.springframework.jmx.export.MBeanExporter.registerBeanNameOrInstance(MBeanExporter.java:616)
    ... 19 common frames omitted
Caused by: java.lang.IllegalArgumentException: Method org.apache.tomcat.dbcp.dbcp2.DataSourceMXBean.getSoftMinEvictableIdleDuration has parameter or return type that cannot be translated into an open type
    at java.management/com.sun.jmx.mbeanserver.ConvertingMethod.from(ConvertingMethod.java:46)
    at java.management/com.sun.jmx.mbeanserver.MXBeanIntrospector.mFrom(MXBeanIntrospector.java:84)
    at java.management/com.sun.jmx.mbeanserver.MXBeanIntrospector.mFrom(MXBeanIntrospector.java:54)
    at java.management/com.sun.jmx.mbeanserver.MBeanAnalyzer.initMaps(MBeanAnalyzer.java:137)
    at java.management/com.sun.jmx.mbeanserver.MBeanAnalyzer.<init>(MBeanAnalyzer.java:118)
    ... 31 common frames omitted
Caused by: javax.management.openmbean.OpenDataException: Cannot convert type: java.time.Duration
    at java.management/com.sun.jmx.mbeanserver.DefaultMXBeanMappingFactory.openDataException(DefaultMXBeanMappingFactory.java:1445)
    at java.management/com.sun.jmx.mbeanserver.DefaultMXBeanMappingFactory.mappingForType(DefaultMXBeanMappingFactory.java:261)
    at java.management/com.sun.jmx.mbeanserver.ConvertingMethod.<init>(ConvertingMethod.java:212)
    at java.management/com.sun.jmx.mbeanserver.ConvertingMethod.from(ConvertingMethod.java:41)
    ... 35 common frames omitted
Caused by: javax.management.openmbean.OpenDataException: Cannot convert type: java.util.List<java.time.temporal.TemporalUnit>
    at java.management/com.sun.jmx.mbeanserver.DefaultMXBeanMappingFactory.openDataException(DefaultMXBeanMappingFactory.java:1445)
    at java.management/com.sun.jmx.mbeanserver.DefaultMXBeanMappingFactory.mappingForType(DefaultMXBeanMappingFactory.java:261)
    at java.management/com.sun.jmx.mbeanserver.DefaultMXBeanMappingFactory.makeCompositeMapping(DefaultMXBeanMappingFactory.java:473)
    at java.management/com.sun.jmx.mbeanserver.DefaultMXBeanMappingFactory.makeMapping(DefaultMXBeanMappingFactory.java:294)
    at java.management/com.sun.jmx.mbeanserver.DefaultMXBeanMappingFactory.mappingForType(DefaultMXBeanMappingFactory.java:259)
    ... 37 common frames omitted
Caused by: javax.management.openmbean.OpenDataException: Cannot convert type: java.time.temporal.TemporalUnit
    at java.management/com.sun.jmx.mbeanserver.DefaultMXBeanMappingFactory.openDataException(DefaultMXBeanMappingFactory.java:1445)
    at java.management/com.sun.jmx.mbeanserver.DefaultMXBeanMappingFactory.mappingForType(DefaultMXBeanMappingFactory.java:261)
    at java.management/com.sun.jmx.mbeanserver.DefaultMXBeanMappingFactory.makeArrayOrCollectionMapping(DefaultMXBeanMappingFactory.java:319)
    at java.management/com.sun.jmx.mbeanserver.DefaultMXBeanMappingFactory.makeParameterizedTypeMapping(DefaultMXBeanMappingFactory.java:398)
    at java.management/com.sun.jmx.mbeanserver.DefaultMXBeanMappingFactory.makeMapping(DefaultMXBeanMappingFactory.java:297)
    at java.management/com.sun.jmx.mbeanserver.DefaultMXBeanMappingFactory.mappingForType(DefaultMXBeanMappingFactory.java:259)
    ... 40 common frames omitted
Caused by: javax.management.openmbean.OpenDataException: Recursive data structure, including java.time.Duration
    at java.management/com.sun.jmx.mbeanserver.DefaultMXBeanMappingFactory.mappingForType(DefaultMXBeanMappingFactory.java:248)
    at java.management/com.sun.jmx.mbeanserver.DefaultMXBeanMappingFactory.makeCompositeMapping(DefaultMXBeanMappingFactory.java:473)
    at java.management/com.sun.jmx.mbeanserver.DefaultMXBeanMappingFactory.makeMapping(DefaultMXBeanMappingFactory.java:294)
    at java.management/com.sun.jmx.mbeanserver.DefaultMXBeanMappingFactory.mappingForType(DefaultMXBeanMappingFactory.java:259)
    ... 44 common frames omitted
</code>```

答:
This issue was happening when we were trying to create a BasicDataSource
BasicDataSource dataSource = new BasicDataSource(); which was imported from import org.apache.tomcat.dbcp.dbcp2.BasicDataSource;

So we found a workaround to remove the tomcat dbcp dependency by excluding it from spring-boot starter tomcat and tomcat jdbc.

```<code><dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-tomcat</artifactId>
    <scope>provided</scope>
    <exclusions>
        <exclusion>
            <groupId>org.apache.tomcat</groupId>
                <artifactId>tomcat-dbcp</artifactId>
        </exclusion>
    </exclusions>
</dependency>

<dependency>
    <groupId>org.apache.tomcat</groupId>
    <artifactId>tomcat-jdbc</artifactId>
</dependency>
</code>```

and Replacing the datasource to org.apache.tomcat.jdbc.pool.DataSource dataSource = new org.apache.tomcat.jdbc.pool.DataSource();

Body:
I'm getting this issue when upgrading Tomcat and Tomcat DBCP from v9.0.54 to v.9.0.58 with Java 11.

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2022-02-08T08:24:15,900Z ERROR [tartedMain] SpringApplication [SpringApplication.java:854] Application run failed
org.springframework.jmx.export.UnableToRegisterMBeanException: Unable to register MBean [org.apache.tomcat.dbcp.dbcp2.BasicDataSource@3b60547f] with key 'datasource'; nested exception is javax.management.NotCompliantMBeanException: org.apache.tomcat.dbcp.dbcp2.BasicDataSourceMXBean: Method org.apache.tomcat.dbcp.dbcp2.DataSourceMXBean.getSoftMinEvictableIdleDuration has parameter or return type that cannot be translated into an open type
    at org.springframework.jmx.export.MBeanExporter.registerBeanNameOrInstance(MBeanExporter.java:626)
    at org.springframework.jmx.export.MBeanExporter.lambda$registerBeans$2(MBeanExporter.java:552)
    at java.base/java.util.HashMap.forEach(HashMap.java:1336)
    at org.springframework.jmx.export.MBeanExporter.registerBeans(MBeanExporter.java:552)
    at org.springframework.jmx.export.MBeanExporter.afterSingletonsInstantiated(MBeanExporter.java:435)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:972)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:918)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:583)
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:145)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:765)
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:445)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:338)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1354)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1343)
    at com.wk.gbs.intakeportal.IntakePortalWarApplication.main(IntakePortalWarApplication.java:30)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49)
Caused by: javax.management.NotCompliantMBeanException: org.apache.tomcat.dbcp.dbcp2.BasicDataSourceMXBean: Method org.apache.tomcat.dbcp.dbcp2.DataSourceMXBean.getSoftMinEvictableIdleDuration has parameter or return type that cannot be translated into an open type
    at java.management/com.sun.jmx.mbeanserver.Introspector.throwException(Introspector.java:467)
    at java.management/com.sun.jmx.mbeanserver.MBeanAnalyzer.<init>(MBeanAnalyzer.java:120)
    at java.management/com.sun.jmx.mbeanserver.MBeanAnalyzer.analyzer(MBeanAnalyzer.java:102)
    at java.management/com.sun.jmx.mbeanserver.MXBeanIntrospector.getAnalyzer(MXBeanIntrospector.java:74)
    at java.management/com.sun.jmx.mbeanserver.MBeanIntrospector.getPerInterface(MBeanIntrospector.java:192)
    at java.management/com.sun.jmx.mbeanserver.MBeanSupport.<init>(MBeanSupport.java:138)
    at java.management/com.sun.jmx.mbeanserver.MXBeanSupport.<init>(MXBeanSupport.java:66)
    at java.management/com.sun.jmx.mbeanserver.Introspector.makeDynamicMBean(Introspector.java:203)
    at java.management/com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.registerObject(DefaultMBeanServerInterceptor.java:888)
    at java.management/com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.registerMBean(DefaultMBeanServerInterceptor.java:320)
    at java.management/com.sun.jmx.mbeanserver.JmxMBeanServer.registerMBean(JmxMBeanServer.java:522)
    at org.springframework.jmx.support.MBeanRegistrationSupport.doRegister(MBeanRegistrationSupport.java:138)
    at org.springframework.jmx.export.MBeanExporter.registerBeanInstance(MBeanExporter.java:672)
    at org.springframework.jmx.export.MBeanExporter.registerBeanNameOrInstance(MBeanExporter.java:616)
    ... 19 common frames omitted
Caused by: java.lang.IllegalArgumentException: Method org.apache.tomcat.dbcp.dbcp2.DataSourceMXBean.getSoftMinEvictableIdleDuration has parameter or return type that cannot be translated into an open type
    at java.management/com.sun.jmx.mbeanserver.ConvertingMethod.from(ConvertingMethod.java:46)
    at java.management/com.sun.jmx.mbeanserver.MXBeanIntrospector.mFrom(MXBeanIntrospector.java:84)
    at java.management/com.sun.jmx.mbeanserver.MXBeanIntrospector.mFrom(MXBeanIntrospector.java:54)
    at java.management/com.sun.jmx.mbeanserver.MBeanAnalyzer.initMaps(MBeanAnalyzer.java:137)
    at java.management/com.sun.jmx.mbeanserver.MBeanAnalyzer.<init>(MBeanAnalyzer.java:118)
    ... 31 common frames omitted
Caused by: javax.management.openmbean.OpenDataException: Cannot convert type: java.time.Duration
    at java.management/com.sun.jmx.mbeanserver.DefaultMXBeanMappingFactory.openDataException(DefaultMXBeanMappingFactory.java:1445)
    at java.management/com.sun.jmx.mbeanserver.DefaultMXBeanMappingFactory.mappingForType(DefaultMXBeanMappingFactory.java:261)
    at java.management/com.sun.jmx.mbeanserver.ConvertingMethod.<init>(ConvertingMethod.java:212)
    at java.management/com.sun.jmx.mbeanserver.ConvertingMethod.from(ConvertingMethod.java:41)
    ... 35 common frames omitted
Caused by: javax.management.openmbean.OpenDataException: Cannot convert type: java.util.List<java.time.temporal.TemporalUnit>
    at java.management/com.sun.jmx.mbeanserver.DefaultMXBeanMappingFactory.openDataException(DefaultMXBeanMappingFactory.java:1445)
    at java.management/com.sun.jmx.mbeanserver.DefaultMXBeanMappingFactory.mappingForType(DefaultMXBeanMappingFactory.java:261)
    at java.management/com.sun.jmx.mbeanserver.DefaultMXBeanMappingFactory.makeCompositeMapping(DefaultMXBeanMappingFactory.java:473)
    at java.management/com.sun.jmx.mbeanserver.DefaultMXBeanMappingFactory.makeMapping(DefaultMXBeanMappingFactory.java:294)
    at java.management/com.sun.jmx.mbeanserver.DefaultMXBeanMappingFactory.mappingForType(DefaultMXBeanMappingFactory.java:259)
    ... 37 common frames omitted
Caused by: javax.management.openmbean.OpenDataException: Cannot convert type: java.time.temporal.TemporalUnit
    at java.management/com.sun.jmx.mbeanserver.DefaultMXBeanMappingFactory.openDataException(DefaultMXBeanMappingFactory.java:1445)
    at java.management/com.sun.jmx.mbeanserver.DefaultMXBeanMappingFactory.mappingForType(DefaultMXBeanMappingFactory.java:261)
    at java.management/com.sun.jmx.mbeanserver.DefaultMXBeanMappingFactory.makeArrayOrCollectionMapping(DefaultMXBeanMappingFactory.java:319)
    at java.management/com.sun.jmx.mbeanserver.DefaultMXBeanMappingFactory.makeParameterizedTypeMapping(DefaultMXBeanMappingFactory.java:398)
    at java.management/com.sun.jmx.mbeanserver.DefaultMXBeanMappingFactory.makeMapping(DefaultMXBeanMappingFactory.java:297)
    at java.management/com.sun.jmx.mbeanserver.DefaultMXBeanMappingFactory.mappingForType(DefaultMXBeanMappingFactory.java:259)
    ... 40 common frames omitted
Caused by: javax.management.openmbean.OpenDataException: Recursive data structure, including java.time.Duration
    at java.management/com.sun.jmx.mbeanserver.DefaultMXBeanMappingFactory.mappingForType(DefaultMXBeanMappingFactory.java:248)
    at java.management/com.sun.jmx.mbeanserver.DefaultMXBeanMappingFactory.makeCompositeMapping(DefaultMXBeanMappingFactory.java:473)
    at java.management/com.sun.jmx.mbeanserver.DefaultMXBeanMappingFactory.makeMapping(DefaultMXBeanMappingFactory.java:294)
    at java.management/com.sun.jmx.mbeanserver.DefaultMXBeanMappingFactory.mappingForType(DefaultMXBeanMappingFactory.java:259)
    ... 44 common frames omitted

Body:
This issue was happening when we were trying to create a BasicDataSource
BasicDataSource dataSource = new BasicDataSource(); which was imported from import org.apache.tomcat.dbcp.dbcp2.BasicDataSource;

So we found a workaround to remove the tomcat dbcp dependency by excluding it from spring-boot starter tomcat and tomcat jdbc.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-tomcat</artifactId>
    <scope>provided</scope>
    <exclusions>
        <exclusion>
            <groupId>org.apache.tomcat</groupId>
                <artifactId>tomcat-dbcp</artifactId>
        </exclusion>
    </exclusions>
</dependency>

<dependency>
    <groupId>org.apache.tomcat</groupId>
    <artifactId>tomcat-jdbc</artifactId>
</dependency>

and Replacing the datasource to org.apache.tomcat.jdbc.pool.DataSource dataSource = new org.apache.tomcat.jdbc.pool.DataSource();


问:
Getting null pointer exception while clicking on the button in android studio
I have made the database and taking the values from checkboxes to the database.
But when the activity open the app crashes, stating the null pointer exception.

I have provided the code where the error is coming from and the error message from the logcat
Anyone have the answer for it. I do not want to redo the codes now please suggest the edits in this.

The code:

```<code>   public void statusCheck(){
    savebtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            sqLiteDatabase = feedDB.getWritableDatabase();
            ContentValues contentValues = new ContentValues();
            if(morning.isChecked()){
                contentValues.put(COLUMN_FEED_1,"Feeding in morning");
            }
            if(lunch.isChecked()){
                contentValues.put(COLUMN_FEED_2,"Feeding on Lunch time");
            }
            if(evening.isChecked()){
                contentValues.put(COLUMN_FEED_3,"Feeding in evening");
            }
            if(dinner.isChecked()){
                contentValues.put(COLUMN_FEED_4,"Feeding in dinner");
            }

            Long rec = sqLiteDatabase.insert("Feed",null,contentValues);

            if(rec != null){

                Toast.makeText(Feedone.this, "Data is saved", Toast.LENGTH_SHORT).show();
            }
        }
    });
}
</code>```

The error from Logcat:

```<code>          Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void
          android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null
          object reference
         at com.kidcave.pediacare.Feedone.statusCheck(Feedone.java:59)
</code>```

答:
You should call this function after.
Also check did you initialized it or not before on create.

```<code> Button saveButton;
 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bmet_card);
        saveButton = findViewById(R.id.save_button);
        //here you can call the function
</code>```

Hope by initializing after setContentView and calling it from onCreate after initializing view. It will be solved.

Also check are you inflating the right layout or not.

Body:
I have made the database and taking the values from checkboxes to the database.
But when the activity open the app crashes, stating the null pointer exception.

I have provided the code where the error is coming from and the error message from the logcat
Anyone have the answer for it. I do not want to redo the codes now please suggest the edits in this.

The code:

   public void statusCheck(){
    savebtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            sqLiteDatabase = feedDB.getWritableDatabase();
            ContentValues contentValues = new ContentValues();
            if(morning.isChecked()){
                contentValues.put(COLUMN_FEED_1,"Feeding in morning");
            }
            if(lunch.isChecked()){
                contentValues.put(COLUMN_FEED_2,"Feeding on Lunch time");
            }
            if(evening.isChecked()){
                contentValues.put(COLUMN_FEED_3,"Feeding in evening");
            }
            if(dinner.isChecked()){
                contentValues.put(COLUMN_FEED_4,"Feeding in dinner");
            }

            Long rec = sqLiteDatabase.insert("Feed",null,contentValues);

            if(rec != null){

                Toast.makeText(Feedone.this, "Data is saved", Toast.LENGTH_SHORT).show();
            }
        }
    });
}

The error from Logcat:

          Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void
          android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null
          object reference
         at com.kidcave.pediacare.Feedone.statusCheck(Feedone.java:59)

Body:
You should call this function after.
Also check did you initialized it or not before on create.

 Button saveButton;
 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bmet_card);
        saveButton = findViewById(R.id.save_button);
        //here you can call the function

Hope by initializing after setContentView and calling it from onCreate after initializing view. It will be solved.

Also check are you inflating the right layout or not.


问:
Need a help with a jquery click count
So far I have got this JavaScript:

```<code>$(document).ready(function() {
    $("#flash").click(function() {
        $(this).html('<img src="http://ruh.kz/sites/default/files/ajax-loader.gif" />');
        $(this).load("http://ruh.kz/sites/all/themes/ruh/sunit.php");
        $('#counter').html(function(i, val) {
            return val * 1 + 1
        });
    });
});
</code>```

Accompanying this HTML:

```<code><div id="flash">
    <img src="http://ruh.kz/sites/default/files/sunit.jpg" />
</div>
<div id="counter">0</div>
</code>```

(Demo)

One problem is that it resets after the page refreshes... How can I save the count number?

In the example on jsfiddle.net, it works well. On my Drupal page however, it doesn't. When I press on the
 the counter "0" dissapears. What might be the problem here?

答:
As others have mentioned here, cookies are one solution to storing the number of clicks across page refreshes. Another option is to store them in a database, associated with the logged in user. Cookies would certainly be much simpler, but if you're running this on a Drupal site and have decent PHP/MySQL experience then the database option is easy enough as well. Mainly, it depends on how critical this click count is. Does it need to be saved permanently? Should a user see the correct number no matter what computer he/she is using? If the answer to either of these questions is "yes", then the database solution is required.

As for why it's not working on your Drupal site, you'll have to provide more info. Do you get any JavaScript errors in your console?

Title: Need a help with a jquery click count

Body:
So far I have got this JavaScript:

$(document).ready(function() {
    $("#flash").click(function() {
        $(this).html('');
        $(this).load("http://ruh.kz/sites/all/themes/ruh/sunit.php");
        $('#counter').html(function(i, val) {
            return val * 1 + 1
        });
    });
});

Accompanying this HTML:

0

(Demo)

One problem is that it resets after the page refreshes... How can I save the count number?

In the example on jsfiddle.net, it works well. On my Drupal page however, it doesn't. When I press on the
 the counter "0" dissapears. What might be the problem here?


问:
Show word count after three words?
I am calling data from api in angular and it is a multiselect option what I want is if data is more than three words its should show count of remaining entries how can I do this can anyone help?

答:
If you are using an array you can do something like this in view:

```<code>arrayToShow.length > 3 ? arrayToShow.length - 3 : ''
</code>```

Or, You can use *ngIf

```<code><div *ngIf="arrayToShow.length > 3 "> arrayToShow.length - 3 <>
</code>```

If it's an object get the keys in the component and show them based on the length of the keys.

If you want to display the counts at multiple places make sure to compute them in component and reuse it.

Title: Show word count after three words?

Body:
If you are using an array you can do something like this in view:

arrayToShow.length > 3 ? arrayToShow.length - 3 : ''

Or, You can use *ngIf

<div *ngIf="arrayToShow.length > 3 "> arrayToShow.length - 3 <>

If it's an object get the keys in the component and show them based on the length of the keys.

If you want to display the counts at multiple places make sure to compute them in component and reuse it.


问:
Hiding Banner at a certain page
I'm currently attempting to hide the banner at a certain page. I have successfully hid the banner in all other pages except one with a page with a id. I have a dynamic folder named [content]</p>
```<code>import { useRouter } from "next/router";

const HIDDEN_BOARDLIST = ["/board/board_list"];
//this is successful

const HIDDEN_BOARDDETAILS = [`board/${content}`].
//this does not work
//http://localhost:3000/board/620471f057aad9002de7f04f. I have to enter the id manually but since this is a dynamic, the id will change every time

export default function Layout(props: ILayoutProps) {
  const router = useRouter();

  console.log(router.asPath);

  const isHiddenBoardList = HIDDEN_BOARDLIST.includes(router.asPath);

  return (
    <Wrapper>
      <Header />
      {!isHiddenBoardList && <Banner />}
      <BodyWrapper>
        <Body>{props.children}</Body>
      </BodyWrapper>
    </Wrapper>
  );
}

</code>```

答:
useRouter is a hook.

CSR

```<code>import React, { useState, useEffect } from 'React';
import { useRouter } from "next/router";

interface ILayoutProps {
  //...
}

export default function Layout(props: ILayoutProps) {
  const router = useRouter();
  const [hidden, setHidden] = useState(false);

  useEffect(() => {
    if(router.asPath.includes('board/')) {
      setHidden(true);
    }
  }, [router.asPath]);

  return (
    <Wrapper>
      <Header />
      {!hidden && <Banner />}
      <BodyWrapper>
        <Body>{props.children}</Body>
      </BodyWrapper>
    </Wrapper>
  );
}
</code>```

Since this code is CSR, flickering may occur. <Banner /> will disappear after being rendered.

If you don't want that, there is a way to pass the current url as props of the <Layout /> component via getServerSideProps.

SSR

```<code>// pages/board/[id].tsx
import { GetServerSideProps, NextPage } from 'next';
import Head from 'next/head';

interface Props {
  url: string;
}

const BoardPage: NextPage<Props> = (props: Props) => {
  return (
    <>
      <Layout {...props} />
    </>
  );
};

export const getServerSideProps: GetServerSideProps = async (context) => {
  const { resolvedUrl } = context; //ex) /board/12345?id=12345

  return {
    props: {
      url: resolvedUrl ,
    }, // will be passed to the page component as props
  };
};
</code>```
```<code>// components/Layout.tsx
import React, { useState, useEffect } from 'React';
import { useRouter } from "next/router";

interface ILayoutProps {
  url: string;
  // ...
}

export default function Layout(props: ILayoutProps) {
  return (
    <Wrapper>
      <Header />
      {props.url.includes('board/') && <Banner />}
      <BodyWrapper>
        <Body>{props.children}</Body>
      </BodyWrapper>
    </Wrapper>
  );
}
</code>```

I hope these two kinds of code are helpful.

Title: Hiding Banner at a certain page

Body:
I'm currently attempting to hide the banner at a certain page. I have successfully hid the banner in all other pages except one with a page with a id. I have a dynamic folder named [content]

import { useRouter } from "next/router";

const HIDDEN_BOARDLIST = ["/board/board_list"];
//this is successful

const HIDDEN_BOARDDETAILS = [`board/${content}`].
//this does not work
//http://localhost:3000/board/620471f057aad9002de7f04f. I have to enter the id manually but since this is a dynamic, the id will change every time

export default function Layout(props: ILayoutProps) {
  const router = useRouter();

  console.log(router.asPath);

  const isHiddenBoardList = HIDDEN_BOARDLIST.includes(router.asPath);

  return (
    <Wrapper>

      {!isHiddenBoardList && <Banner />}
      <BodyWrapper>
        {props.children}
      </BodyWrapper>
    </Wrapper>
  );
}

Body:
useRouter is a hook.

CSR

import React, { useState, useEffect } from 'React';
import { useRouter } from "next/router";

interface ILayoutProps {
  //...
}

export default function Layout(props: ILayoutProps) {
  const router = useRouter();
  const [hidden, setHidden] = useState(false);

  useEffect(() => {
    if(router.asPath.includes('board/')) {
      setHidden(true);
    }
  }, [router.asPath]);

  return (
    <Wrapper>
      <Header />
      {!hidden && <Banner />}
      <BodyWrapper>
        <Body>{props.children}</Body>
      </BodyWrapper>
    </Wrapper>
  );
}

Since this code is CSR, flickering may occur. <Banner /> will disappear after being rendered.

If you don't want that, there is a way to pass the current url as props of the <Layout /> component via getServerSideProps.

SSR

// pages/board/[id].tsx
import { GetServerSideProps, NextPage } from 'next';
import Head from 'next/head';

interface Props {
  url: string;
}

const BoardPage: NextPage<Props> = (props: Props) => {
  return (
    <>
      <Layout {...props} />
    </>
  );
};

export const getServerSideProps: GetServerSideProps = async (context) => {
  const { resolvedUrl } = context; //ex) /board/12345?id=12345

  return {
    props: {
      url: resolvedUrl ,
    }, // will be passed to the page component as props
  };
};

// components/Layout.tsx
import React, { useState, useEffect } from 'React';
import { useRouter } from "next/router";

interface ILayoutProps {
  url: string;
  // ...
}

export default function Layout(props: ILayoutProps) {
  return (
    <Wrapper>
      <Header />
      {props.url.includes('board/') && <Banner />}
      <BodyWrapper>
        <Body>{props.children}</Body>
      </BodyWrapper>
    </Wrapper>
  );
}

I hope these two kinds of code are helpful.


问:
How to get "tag name", "attribute name", "attribute value" in regex?
I'm trying to write a regular expression that needs to return every tag name, attribute name, and attribute value

Here is the code example

```<code>Hello, My name is Jack, This is my selfie:
[img id='4' src="imageurl"]
Below is the quick-link to my profile
[profile username='jackisbest']
</code>```

I need to get any text enclosed in [ ]

Also I need javascript regex to parse them and match them this way

```<code>> Match 1: img

> Match 2: id='4'
  Group 1: id
  Group 2: 4

> Match 3: src="imageurl"
  Group 1: src
  Group 2: imageurl
</code>```

This is the regex I am using, but it can only match attributes and value

```<code>(\S+)=["']?((?:.(?!["']?\s+(?:\S+)=|[>"']))+.)["']
</code>```

Thanks!!

答:
I modified your regex to catch the tag name and used named capture groups.

/\[?(?<tagName>\w+)\s?(?<attName>\S+)=['"]?(?<attValue>(?:.(?!["']?\s+(?:\S+)=|[>"']))+.)["']/gm

This might work for you.

Test here: https://regex101.com/r/kT7pG4/1

Body:
I'm trying to write a regular expression that needs to return every tag name, attribute name, and attribute value

Here is the code example

Hello, My name is Jack, This is my selfie:
[img id='4' src="imageurl"]
Below is the quick-link to my profile
[profile username='jackisbest']

I need to get any text enclosed in [ ]

Also I need javascript regex to parse them and match them this way

> Match 1: img

> Match 2: id='4'
  Group 1: id
  Group 2: 4

> Match 3: src="imageurl"
  Group 1: src
  Group 2: imageurl

This is the regex I am using, but it can only match attributes and value

(\S+)=["']?((?:.(?!["']?\s+(?:\S+)=|[>"']))+.)["']

Thanks!!


问:
Validate and store data in Laravel with axios
I am using React\NextJS as forntend and Laravel as backend,
Storing data with Axios post as per below,

```<code>  const storeExpense = async (expenseData) => {

    const response = await axios.post('/api/expenses/store/', {expenseData})
    return response.data;
  }

</code>```

Now this will be sent as a JSON object to Laravel, I am not sure how can I validate and store this JSON object data to MySQL.

Earlier I was using Jquery AJAX where it was easy to store with Request validation and then with create.

Below is the request payload to the backend,

```<code>
{"expenseData":{"expense_description":"React","expense_date":"2022-17-4","expense_amount":"123","expense_tax_amount":"14.15","expense_note":"given","expense_receipt_number":"Ok no","taxgroup_id":1,"paymentoption_id":1,"vendor_id":1,"accountcustomtype_id":2,"submit":null}}

</code>```

Below was Controller and Model, used when sending data as Form

```<code>     //Controller
    public function store(StoreExpenseRequest $request)
    {
        Expense::storeExpense($request);

        return response()->json([
            'val' => 1,
            'msg' => 'Success',
        ]);
    }

    //Model
    public static function storeExpense($request)
    {
        Expense::create([
            'vendor_id' => $request->vendor_id,
            'accountcustomtype_id' => $request->accountcustomtype_id,
            'expense_description' => $request->expense_description,
            'expense_date' => Carbon::parse($request->expense_date)->format('Y-m-d'),
            'expense_amount' => $request->expense_amount,
            'taxgroup_id' => $request->taxgroup_id,
            'expense_tax_amount' => $request->expense_tax_amount,
            'paymentoption_id' => $request->paymentoption_id,
            'expense_receipt_number' => $request->expense_receipt_number,
            'expense_note' => $request->expense_note,
        ]);
    }

</code>```

But now this doesn't work with JSON data,

How can I achieve this with Axios JSON data?

Thank you,

答:
It was resolved by changing Axios request Data,</p>
```<code>await axios.post('/api/expenses/store/', expenseData)

</code>```

Body:
I am using React\NextJS as forntend and Laravel as backend,
Storing data with Axios post as per below,

  const storeExpense = async (expenseData) => {

    const response = await axios.post('/api/expenses/store/', {expenseData})
    return response.data;
  }

Now this will be sent as a JSON object to Laravel, I am not sure how can I validate and store this JSON object data to MySQL.

Earlier I was using Jquery AJAX where it was easy to store with Request validation and then with create.

Below is the request payload to the backend,

{"expenseData":{"expense_description":"React","expense_date":"2022-17-4","expense_amount":"123","expense_tax_amount":"14.15","expense_note":"given","expense_receipt_number":"Ok no","taxgroup_id":1,"paymentoption_id":1,"vendor_id":1,"accountcustomtype_id":2,"submit":null}}

Below was Controller and Model, used when sending data as Form

     //Controller
    public function store(StoreExpenseRequest $request)
    {
        Expense::storeExpense($request);

        return response()->json([
            'val' => 1,
            'msg' => 'Success',
        ]);
    }

    //Model
    public static function storeExpense($request)
    {
        Expense::create([
            'vendor_id' => $request->vendor_id,
            'accountcustomtype_id' => $request->accountcustomtype_id,
            'expense_description' => $request->expense_description,
            'expense_date' => Carbon::parse($request->expense_date)->format('Y-m-d'),
            'expense_amount' => $request->expense_amount,
            'taxgroup_id' => $request->taxgroup_id,
            'expense_tax_amount' => $request->expense_tax_amount,
            'paymentoption_id' => $request->paymentoption_id,
            'expense_receipt_number' => $request->expense_receipt_number,
            'expense_note' => $request->expense_note,
        ]);
    }

But now this doesn't work with JSON data,

How can I achieve this with Axios JSON data?

Thank you,

Body:
It was resolved by changing Axios request Data,

await axios.post('/api/expenses/store/', expenseData)


问:
How can I convert an image into Base64 string using JavaScript?
I need to convert my image to a Base64 string so that I can send my image to a server.

Is there any JavaScript file for this? Else, how can I convert it?

答:
You can also simply extract base-64 only part of the URL by ding this:</p>
```<code>var Base64URL = canvas.toDataURL('image/webp')
var Base64 = Base64URL.split(",")[1] //Returns the base64 part
</code>```

Body:
You can also simply extract base-64 only part of the URL by ding this:

var Base64URL = canvas.toDataURL('image/webp')
var Base64 = Base64URL.split(",")[1] //Returns the base64 part


问:
What is "android_webview/Default/Web Data"?
We have developed an android app that configures the screen in webview.(vuejs)

What happened in webview seems to be saved in cache.

The path is app_webview/Default/Web Data.

However, it is not always saved.

When will it be saved?(How can I debug?)

Is there no problem deleting the file while running the application?

答:
```<code>webview.settings.savePassword = false
webview.settings.saveFormData = false
</code>```