问:
MongooseError - Operation `users.findOne()` buffering timed out after 10000ms
My code was working before initially but I don't know why it just stopped working and gave me this error:

```<code>MongooseError: Operation `users.findOne()` buffering timed out after 10000ms
    at Timeout.<anonymous> (/Users/nishant/Desktop/Yourfolio/backend/node_modules/mongoose/lib/drivers/node-mongodb-native/collection.js:184:20)
    at listOnTimeout (internal/timers.js:549:17)
    at processTimers (internal/timers.js:492:7)
</code>```

I am trying to authenticate the user by login with JWT. My client runs fine but in my backend I get this error. My backend code:

```<code>import neuron from '@yummyweb/neuronjs'
import bodyParser from 'body-parser'
import cors from 'cors'
import mongoose from 'mongoose'
import emailValidator from 'email-validator'
import passwordValidator from 'password-validator'
import User from './models/User.js'
import Portfolio from './models/Portfolio.js'
import bcrypt from 'bcryptjs'
import jwt from 'jsonwebtoken'
import auth from './utils/auth.js'

// Dot env
import dotenv from 'dotenv'
dotenv.config()

// Custom Password Specifications
// Username Schema
const usernameSchema = new passwordValidator()
usernameSchema.is().min(3).is().max(18).is().not().spaces()

// Password Schema
const passwordSchema = new passwordValidator()
passwordSchema.is().min(8).is().max(100).has().uppercase().has().lowercase().has().digits().is().not().spaces()

const PORT = process.env.PORT || 5000
const neuronjs = neuron()

// Middleware
neuronjs.use(bodyParser())
neuronjs.use(cors())

// Mongoose Connection
mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true }, () => console.log("MongoDB Connected"))

// API Routes
neuronjs.POST('/api/auth/signup', async (req, res) => {
    const { username, email, password, passwordConfirmation } = req.body

    // Validation: all fields are filled
    if (!username || !email || !password || !passwordConfirmation) {
        return res.status(400).json({
            "error": "true",
            "for": "fields",
            "msg": "fill all the fields"
        })
    }

    // Validation: username is valid
    if (usernameSchema.validate(username, { list: true }).length !== 0) {
        return res.status(400).json({
            "error": "true",
            "for": "username",
            "method_fail": usernameSchema.validate(username, { list: true }),
            "msg": "username is invalid"
        })
    }

    // Validation: email is valid
    if (!emailValidator.validate(email)) {
        return res.status(400).json({
            "error": "true",
            "for": "email",
            "msg": "email is invalid"
        })
    }

    // Validation: password is valid
    if (passwordSchema.validate(password, { list: true }).length !== 0) {
        return res.status(400).json({
            "error": "true",
            "for": "password",
            "method_fail": passwordSchema.validate(password, { list: true }),
            "msg": "password is invalid"
        })
    }

    // Validation: password is confirmed
    if (password !== passwordConfirmation) {
        return res.status(400).json({
            "error": "true",
            "for": "confirmation",
            "msg": "confirmation password needs to match password"
        })
    }

    // Check for existing user with email
    const existingUserWithEmail = await User.findOne({ email })
    if (existingUserWithEmail)
        return res.status(400).json({ "error": "true", "msg": "a user already exists with this email" })

    // Check for existing user with username
    const existingUserWithUsername = await User.findOne({ username })
    if (existingUserWithUsername)
        return res.status(400).json({ "error": "true", "msg": "a user already exists with this username" })

    // Generating salt
    const salt = bcrypt.genSalt()
    .then(salt => {
        // Hashing password with bcrypt
        const hashedPassword = bcrypt.hash(password, salt)
        .then(hash => {
            const newUser = new User({
                username,
                email,
                password: hash
            })
            // Saving the user
            newUser.save()
            .then(savedUser => {
                const newPortfolio = new Portfolio({
                    user: savedUser._id,
                    description: "",
                    socialMediaHandles: {
                        github: savedUser.username,
                        dribbble: savedUser.username,
                        twitter: savedUser.username,
                        devto: savedUser.username,
                        linkedin: savedUser.username,
                    }
                })

                // Save the portfolio
                newPortfolio.save()

                // Return the status code and the json
                return res.status(200).json({
                    savedUser
                })
            })
            .catch(err => console.log(err))
        })
        .catch(err => console.log(err))
    })
    .catch(err => console.log(err))
})

neuronjs.POST('/api/auth/login', async (req, res) => {
    try {
        const { username, password } = req.body

        // Validate
        if (!username || !password) {
            return res.status(400).json({ "error": "true", "msg": "fill all the fields", "for": "fields", })
        }

        const user = await User.findOne({ username })
        if (!user) {
            return res.status(400).json({ "error": "true", "msg": "no account is registered with this username", "for": "username" })
        }

        // Compare hashed password with plain text password
        const match = await bcrypt.compare(password, user.password)

        if (!match) {
            return res.status(400).json({ "error": "true", "msg": "invalid credentials", "for": "password" })
        }

        // Create JWT token
        const token = jwt.sign({ id: user._id }, process.env.JWT_SECRET)
        return res.json({ token, user: { "id": user._id, "username": user.username, "email": user.email } })
    }
    catch (e) {
        console.log(e)
    }
})

// Delete a user and their portfolio
neuronjs.DELETE("/api/users/delete", async (req, res) => {
    auth(req, res)
    const deletedPortfolio = await Portfolio.findOneAndDelete({ user: req.user })
    const deletedUser = await User.findByIdAndDelete(req.user)
    res.json(deletedUser)
})

neuronjs.POST("/api/isTokenValid", async (req, res) => {
    const token = req.headers["x-auth-token"]
    if (!token) return res.json(false)

    const verifiedToken = jwt.verify(token, process.env.JWT_SECRET)
    if (!verifiedToken) return res.json(false)

    const user = await User.findById(verifiedToken.id)
    if (!user) return res.json(false)

    return res.json(true)
})

// Getting one user
neuronjs.GET("/api/users/user", async (req, res) => {
    auth(req, res)
    const user = await User.findById(req.user)
    res.json({
        "username": user.username,
        "email": user.email,
        "id": user._id
    })
})

// Getting the porfolio based on username
neuronjs.GET("/api/portfolio/:username", async (req, res) => {
    try {
        const existingUser = await User.findOne({ username: req.params.username })
        // User exists
        if (existingUser) {
            const userPortfolio = await Portfolio.findOne({ user: existingUser._id })
            return res.status(200).json(userPortfolio)
        }
        // User does not exist
        else return res.status(400).json({ "error": "true", "msg": "user does not exist" })
    }
    catch (e) {
        console.log(e)
        return res.status(400).json({ "error": "true", "msg": "user does not exist" })
    }
})

// Update Portfolio info
neuronjs.POST("/api/portfolio/update", async (req, res) => {
    auth(req, res)

    // Find the portfolio
    const portfolio = await Portfolio.findOne({ user: req.user })
    // Then, update the portfolio
    if (portfolio) {
        // Call the update method
        const updatedPortfolio = await portfolio.updateOne({
             user: req.user,
             description: req.body.description,
             socialMediaHandles: req.body.socialMediaHandles,
             greetingText: req.body.greetingText,
             navColor: req.body.navColor,
             font: req.body.font,
             backgroundColor: req.body.backgroundColor,
             rssFeed: req.body.rssFeed,
             displayName: req.body.displayName,
             layout: req.body.layout,
             occupation: req.body.occupation
            })
        return res.status(200).json(portfolio)
    }
})

neuronjs.listen(PORT, () => console.log("Server is running on port " + PORT))

</code>```

The auth.js file function:

```<code>import jwt from 'jsonwebtoken'

const auth = (req, res) => {
    const token = req.headers["x-auth-token"]
    if (!token)
        return res.status(401).json({ "error": "true", "msg": "no authentication token" })

    const verifiedToken = jwt.verify(token, process.env.JWT_SECRET)
    if (!verifiedToken)
        return res.status(401).json({ "error": "true", "msg": "token failed" })

    req.user = verifiedToken.id
}

export default auth
</code>```

Any help is much appreciated and I have already tried a few solutions like deleting node_modules and re installing mongoose.

答:
Make sure that you're connecting to MongoDB at the top of your function(inside file) and doing (CRUD) operations after connecting to MongoDB Atlas.

Hope that makes sense.
I was getting error because in my file I'm loading data from other server and inserting into my MongoDB after that asynchronous operations I'm connecting to my MongoDB Server, that's why I was getting error.

CORRECT ↓

```<code>await mongoose.connect(MONGO_URL, {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});
await parseAndLoadPlanetsData();
</code>```

INCORRECT ↓

```<code>await parseAndLoadPlanetsData();
await mongoose.connect(MONGO_URL, {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});
</code>```

Body:
My code was working before initially but I don't know why it just stopped working and gave me this error:

MongooseError: Operation `users.findOne()` buffering timed out after 10000ms
    at Timeout.<anonymous> (/Users/nishant/Desktop/Yourfolio/backend/node_modules/mongoose/lib/drivers/node-mongodb-native/collection.js:184:20)
    at listOnTimeout (internal/timers.js:549:17)
    at processTimers (internal/timers.js:492:7)

I am trying to authenticate the user by login with JWT. My client runs fine but in my backend I get this error. My backend code:

import neuron from '@yummyweb/neuronjs'
import bodyParser from 'body-parser'
import cors from 'cors'
import mongoose from 'mongoose'
import emailValidator from 'email-validator'
import passwordValidator from 'password-validator'
import User from './models/User.js'
import Portfolio from './models/Portfolio.js'
import bcrypt from 'bcryptjs'
import jwt from 'jsonwebtoken'
import auth from './utils/auth.js'

// Dot env
import dotenv from 'dotenv'
dotenv.config()

// Custom Password Specifications
// Username Schema
const usernameSchema = new passwordValidator()
usernameSchema.is().min(3).is().max(18).is().not().spaces()

// Password Schema
const passwordSchema = new passwordValidator()
passwordSchema.is().min(8).is().max(100).has().uppercase().has().lowercase().has().digits().is().not().spaces()

const PORT = process.env.PORT || 5000
const neuronjs = neuron()

// Middleware
neuronjs.use(bodyParser())
neuronjs.use(cors())

// Mongoose Connection
mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true }, () => console.log("MongoDB Connected"))

// API Routes
neuronjs.POST('/api/auth/signup', async (req, res) => {
    const { username, email, password, passwordConfirmation } = req.body

    // Validation: all fields are filled
    if (!username || !email || !password || !passwordConfirmation) {
        return res.status(400).json({
            "error": "true",
            "for": "fields",
            "msg": "fill all the fields"
        })
    }

    // Validation: username is valid
    if (usernameSchema.validate(username, { list: true }).length !== 0) {
        return res.status(400).json({
            "error": "true",
            "for": "username",
            "method_fail": usernameSchema.validate(username, { list: true }),
            "msg": "username is invalid"
        })
    }

    // Validation: email is valid
    if (!emailValidator.validate(email)) {
        return res.status(400).json({
            "error": "true",
            "for": "email",
            "msg": "email is invalid"
        })
    }

    // Validation: password is valid
    if (passwordSchema.validate(password, { list: true }).length !== 0) {
        return res.status(400).json({
            "error": "true",
            "for": "password",
            "method_fail": passwordSchema.validate(password, { list: true }),
            "msg": "password is invalid"
        })
    }

    // Validation: password is confirmed
    if (password !== passwordConfirmation) {
        return res.status(400).json({
            "error": "true",
            "for": "confirmation",
            "msg": "confirmation password needs to match password"
        })
    }

    // Check for existing user with email
    const existingUserWithEmail = await User.findOne({ email })
    if (existingUserWithEmail)
        return res.status(400).json({ "error": "true", "msg": "a user already exists with this email" })

    // Check for existing user with username
    const existingUserWithUsername = await User.findOne({ username })
    if (existingUserWithUsername)
        return res.status(400).json({ "error": "true", "msg": "a user already exists with this username" })

    // Generating salt
    const salt = bcrypt.genSalt()
    .then(salt => {
        // Hashing password with bcrypt
        const hashedPassword = bcrypt.hash(password, salt)
        .then(hash => {
            const newUser = new User({
                username,
                email,
                password: hash
            })
            // Saving the user
            newUser.save()
            .then(savedUser => {
                const newPortfolio = new Portfolio({
                    user: savedUser._id,
                    description: "",
                    socialMediaHandles: {
                        github: savedUser.username,
                        dribbble: savedUser.username,
                        twitter: savedUser.username,
                        devto: savedUser.username,
                        linkedin: savedUser.username,
                    }
                })

                // Save the portfolio
                newPortfolio.save()

                // Return the status code and the json
                return res.status(200).json({
                    savedUser
                })
            })
            .catch(err => console.log(err))
        })
        .catch(err => console.log(err))
    })
    .catch(err => console.log(err))
})

neuronjs.POST('/api/auth/login', async (req, res) => {
    try {
        const { username, password } = req.body

        // Validate
        if (!username || !password) {
            return res.status(400).json({ "error": "true", "msg": "fill all the fields", "for": "fields", })
        }

        const user = await User.findOne({ username })
        if (!user) {
            return res.status(400).json({ "error": "true", "msg": "no account is registered with this username", "for": "username" })
        }

        // Compare hashed password with plain text password
        const match = await bcrypt.compare(password, user.password)

        if (!match) {
            return res.status(400).json({ "error": "true", "msg": "invalid credentials", "for": "password" })
        }

        // Create JWT token
        const token = jwt.sign({ id: user._id }, process.env.JWT_SECRET)
        return res.json({ token, user: { "id": user._id, "username": user.username, "email": user.email } })
    }
    catch (e) {
        console.log(e)
    }
})

// Delete a user and their portfolio
neuronjs.DELETE("/api/users/delete", async (req, res) => {
    auth(req, res)
    const deletedPortfolio = await Portfolio.findOneAndDelete({ user: req.user })
    const deletedUser = await User.findByIdAndDelete(req.user)
    res.json(deletedUser)
})

neuronjs.POST("/api/isTokenValid", async (req, res) => {
    const token = req.headers["x-auth-token"]
    if (!token) return res.json(false)

    const verifiedToken = jwt.verify(token, process.env.JWT_SECRET)
    if (!verifiedToken) return res.json(false)

    const user = await User.findById(verifiedToken.id)
    if (!user) return res.json(false)

    return res.json(true)
})

// Getting one user
neuronjs.GET("/api/users/user", async (req, res) => {
    auth(req, res)
    const user = await User.findById(req.user)
    res.json({
        "username": user.username,
        "email": user.email,
        "id": user._id
    })
})

// Getting the porfolio based on username
neuronjs.GET("/api/portfolio/:username", async (req, res) => {
    try {
        const existingUser = await User.findOne({ username: req.params.username })
        // User exists
        if (existingUser) {
            const userPortfolio = await Portfolio.findOne({ user: existingUser._id })
            return res.status(200).json(userPortfolio)
        }
        // User does not exist
        else return res.status(400).json({ "error": "true", "msg": "user does not exist" })
    }
    catch (e) {
        console.log(e)
        return res.status(400).json({ "error": "true", "msg": "user does not exist" })
    }
})

// Update Portfolio info
neuronjs.POST("/api/portfolio/update", async (req, res) => {
    auth(req, res)

    // Find the portfolio
    const portfolio = await Portfolio.findOne({ user: req.user })
    // Then, update the portfolio
    if (portfolio) {
        // Call the update method
        const updatedPortfolio = await portfolio.updateOne({
             user: req.user,
             description: req.body.description,
             socialMediaHandles: req.body.socialMediaHandles,
             greetingText: req.body.greetingText,
             navColor: req.body.navColor,
             font: req.body.font,
             backgroundColor: req.body.backgroundColor,
             rssFeed: req.body.rssFeed,
             displayName: req.body.displayName,
             layout: req.body.layout,
             occupation: req.body.occupation
            })
        return res.status(200).json(portfolio)
    }
})

neuronjs.listen(PORT, () => console.log("Server is running on port " + PORT))

The auth.js file function:

import jwt from 'jsonwebtoken'

const auth = (req, res) => {
    const token = req.headers["x-auth-token"]
    if (!token)
        return res.status(401).json({ "error": "true", "msg": "no authentication token" })

    const verifiedToken = jwt.verify(token, process.env.JWT_SECRET)
    if (!verifiedToken)
        return res.status(401).json({ "error": "true", "msg": "token failed" })

    req.user = verifiedToken.id
}

export default auth

Any help is much appreciated and I have already tried a few solutions like deleting node_modules and re installing mongoose.

Body:
Make sure that you're connecting to MongoDB at the top of your function(inside file) and doing (CRUD) operations after connecting to MongoDB Atlas.

Hope that makes sense.
I was getting error because in my file I'm loading data from other server and inserting into my MongoDB after that asynchronous operations I'm connecting to my MongoDB Server, that's why I was getting error.

CORRECT ↓

await mongoose.connect(MONGO_URL, {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});
await parseAndLoadPlanetsData();

INCORRECT ↓

await parseAndLoadPlanetsData();
await mongoose.connect(MONGO_URL, {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});


来源: stackexchange

问:
How to prevent opening a fragment from navigation drawer if that fragment is already opened
How to prevent opening a fragment from navigation drawer if that fragment is already opened, when the fragment is opened and click in the NavigationDrawer item the fragment reCreates again, So how to check if the fragment is already opened?</p>

```<code> public boolean onNavigationItemSelected(MenuItem item) {
    int id = item.getItemId();
    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);

    if (id == R.id.fragmentA) {
         {   FragmentA fragment = new FragmentA();
             transaction.add(R.id.main_screen, fragment1, "MainFrag").addToBackStack(null);
         }

    } else if (id == R.id.fragmentB) {
        FragmentB fragment = new FragmentB();
        transaction.add(R.id.main_screen, fragment).addToBackStack(null);

    } else if (id == R.id.fragmentC) {
        FragmentC fragment = new FragmentC();
        transaction.replace(R.id.main_screen, fragment).addToBackStack(null);

    }
</code>```

答:
I have also struggled with this for a while, I am using navigation components and Kotlin, so finally I got it sorted out. It might not be the best solution, but it's simple and works, so I wanted to share it with you:

```<code>            when (menuItem.itemId) {

            R.id.nav_board -> {
                if(findNavController(R.id.nav_host_fragment).currentDestination?.label != "listFragment")
                    findNavController(R.id.nav_host_fragment)
                        .navigate(R.id.action_global_listFragment)
            }
</code>```

The label is the destination label given in the navigation.xml

```<code><navigation xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/navigation"
    app:startDestination="@id/listFragment">

    <fragment
        android:id="@+id/listFragment"
        android:name="at.example.app.ui.ListFragment"
        android:label="listFragment"
        tools:layout="@layout/fragment_list">
...
</code>```

So this basically just checks if the current destination (where we're at) is the one that should not be re-opened and only navigates if the current destination is a different one.

ContentLicense: CC BY-SA 3.0

Body:
How to prevent opening a fragment from navigation drawer if that fragment is already opened, when the fragment is opened and click in the NavigationDrawer item the fragment reCreates again, So how to check if the fragment is already opened?

 public boolean onNavigationItemSelected(MenuItem item) {
    int id = item.getItemId();
    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);

    if (id == R.id.fragmentA) {
         {   FragmentA fragment = new FragmentA();
             transaction.add(R.id.main_screen, fragment1, "MainFrag").addToBackStack(null);
         }

    } else if (id == R.id.fragmentB) {
        FragmentB fragment = new FragmentB();
        transaction.add(R.id.main_screen, fragment).addToBackStack(null);

    } else if (id == R.id.fragmentC) {
        FragmentC fragment = new FragmentC();
        transaction.replace(R.id.main_screen, fragment).addToBackStack(null);

    }

Body:
I have also struggled with this for a while, I am using navigation components and Kotlin, so finally I got it sorted out. It might not be the best solution, but it's simple and works, so I wanted to share it with you:

            when (menuItem.itemId) {

            R.id.nav_board -> {
                if(findNavController(R.id.nav_host_fragment).currentDestination?.label != "listFragment")
                    findNavController(R.id.nav_host_fragment)
                        .navigate(R.id.action_global_listFragment)
            }

The label is the destination label given in the navigation.xml

<navigation xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/navigation"
    app:startDestination="@id/listFragment">

    <fragment
        android:id="@+id/listFragment"
        android:name="at.example.app.ui.ListFragment"
        android:label="listFragment"
        tools:layout="@layout/fragment_list">
...

So this basically just checks if the current destination (where we're at) is the one that should not be re-opened and only navigates if the current destination is a different one.

ContentLicense: CC BY-SA 4.0


问:
How to customize validation message for model?
I have a class TestClass and I want to customize the validation message instead of default one.

TestClass is the post model in the controller which inherits from ControllerBase.

Here is what I've tried:

TestClass.cs

```<code>public class TestClass
{
    [TestAtrribute(1.00, 99.99)]
    public double TestNumber { get; set; }
}
</code>```

TestAttribute.cs

```<code>public class TestAttribute : ValidationAttribute
{
    private double _min;
    private double _max;

    public TestAttribute(double min, double max)
    {
        _min = min;
        _max = max;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var error = $"{value} is invalid, must be between {_min} and {_max}";
        try
        {
            var convertNum = Convert.ToDouble(value);
            if (convertNum < _min || convertNum > _max)
                return new ValidationResult(errorMessage);
        }
        catch (Exception)
        {
            return new ValidationResult(error);
        }

        return ValidationResult.Success;
    }
}
</code>```

However, when I post string value, my custom attribute doesn't work.
It returns the default message:

Could not convert string to double: test. Path 'TestClass.TestNumber',
line 36, position 22.

What I expect is:

test is invalid, must be between 1.00 and 99.99

Please let me know how I can solve it.

答:
As per my understanding, I believe you have developed a WebApi and trying to pass data using PostMan. The error you have posted is rejected by .Net framework because of its type safety feature. Since you are passing 'string' instead of 'double'.

Considering, you are accepting data for model 'TestClass' using 'FormBody' or by passing any JSON or XML string object.

The best way is to Validate the input data by an if condition before assigning it to the Model 'TestClass'. If it contains string then your custom message.

Hope this will solve your query.

Body:
I have a class TestClass and I want to customize the validation message instead of default one.

TestClass is the post model in the controller which inherits from ControllerBase.

Here is what I've tried:

TestClass.cs

public class TestClass
{
    [TestAtrribute(1.00, 99.99)]
    public double TestNumber { get; set; }
}

TestAttribute.cs

public class TestAttribute : ValidationAttribute
{
    private double _min;
    private double _max;

    public TestAttribute(double min, double max)
    {
        _min = min;
        _max = max;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var error = $"{value} is invalid, must be between {_min} and {_max}";
        try
        {
            var convertNum = Convert.ToDouble(value);
            if (convertNum < _min || convertNum > _max)
                return new ValidationResult(errorMessage);
        }
        catch (Exception)
        {
            return new ValidationResult(error);
        }

        return ValidationResult.Success;
    }
}

However, when I post string value, my custom attribute doesn't work.
It returns the default message:

Could not convert string to double: test. Path 'TestClass.TestNumber',
line 36, position 22.

What I expect is:

test is invalid, must be between 1.00 and 99.99

Please let me know how I can solve it.


问:
Compare two values and add them to list if they match - code improvement
I am working with medical history data and need to figure out to find the series of diagnoses a patient has had.
I have a large database which includes data on unique ID, diagnosis, time of contact with healthcare, and so on.

I made some dummy data here to illustrate:

```<code>import pandas as pd
import numpy as np

columns = ["ID","DIAG","TYPE","IN","OUT","GENDER","DOB"]
diags = pd.DataFrame(np.random.randint(0,100,size=(2000,7)),columns=columns)
diags_counter = diags.groupby("ID")["DIAG"].count().to_frame()
diags_counter.reset_index(level=0,inplace=True)
</code>```

I reset the index, since the IDs in the database are more complex, and using .loc wouldn't work.

My idea was to make a list or dictionary of a list of dataframes for each patient, i.e. a patient might have only one diagnosis, while another might have 2 or more.
Following code is working, but extremely slow, and since I have over half a million patients, this is not going to work:

```<code>diags_seq = []
for i in range(0,len(diags_counter)):
  X= []
  for j in range(0,len(diags)):
    if diags_counter.ID.iloc[i] == diags.ID.iloc[j]:
      X.append(diags.iloc[j])
  diags_seq.append(X)
  print(f"\r{i+1} of {len(diags_counter)} found", end="")
</code>```

Any help to how to approach this otherwise would be greatly appreciated :)

答:
I think this will be fine:

```<code>unique_id = diags.ID.unique()
dict_of_specifics_id = {}
for id in unique_id:
   dict_of_specifics_id[id] = {}
   dict_of_specifics_id[id]['id_counter'] = 0
   dict_of_specifics_id[id]['diag_list'] = []
for index, row in diags.iterrows():
   dict_of_specifics_id[row.ID]['id_counter']+=1
   dict_of_specifics_id[row.ID]['diag_list'].append(row.DIAG)
dict_of_specifics_id
</code>```

Output:

```<code>{21: {'id_counter': 16,
  'diag_list': [45, 41, 92, 91, 62, 54, 16, 18, 23, 18, 0, 47, 9, 45, 2, 61]},
</code>```

Where 21 is ID and diag_list is list of diagnosis to this ID. id_counter is actualy len of diag_list.

Body:
I am working with medical history data and need to figure out to find the series of diagnoses a patient has had.
I have a large database which includes data on unique ID, diagnosis, time of contact with healthcare, and so on.

I made some dummy data here to illustrate:

import pandas as pd
import numpy as np

columns = ["ID","DIAG","TYPE","IN","OUT","GENDER","DOB"]
diags = pd.DataFrame(np.random.randint(0,100,size=(2000,7)),columns=columns)
diags_counter = diags.groupby("ID")["DIAG"].count().to_frame()
diags_counter.reset_index(level=0,inplace=True)

I reset the index, since the IDs in the database are more complex, and using .loc wouldn't work.

My idea was to make a list or dictionary of a list of dataframes for each patient, i.e. a patient might have only one diagnosis, while another might have 2 or more.
Following code is working, but extremely slow, and since I have over half a million patients, this is not going to work:

diags_seq = []
for i in range(0,len(diags_counter)):
  X= []
  for j in range(0,len(diags)):
    if diags_counter.ID.iloc[i] == diags.ID.iloc[j]:
      X.append(diags.iloc[j])
  diags_seq.append(X)
  print(f"\r{i+1} of {len(diags_counter)} found", end="")

Any help to how to approach this otherwise would be greatly appreciated :)

Body:
I think this will be fine:

unique_id = diags.ID.unique()
dict_of_specifics_id = {}
for id in unique_id:
   dict_of_specifics_id[id] = {}
   dict_of_specifics_id[id]['id_counter'] = 0
   dict_of_specifics_id[id]['diag_list'] = []
for index, row in diags.iterrows():
   dict_of_specifics_id[row.ID]['id_counter']+=1
   dict_of_specifics_id[row.ID]['diag_list'].append(row.DIAG)
dict_of_specifics_id

Output:

{21: {'id_counter': 16,
  'diag_list': [45, 41, 92, 91, 62, 54, 16, 18, 23, 18, 0, 47, 9, 45, 2, 61]},

Where 21 is ID and diag_list is list of diagnosis to this ID. id_counter is actualy len of diag_list.


问:
How do I make case-insensitive queries on Mongodb?
```<code>var thename = 'Andrew';
db.collection.find({'name':thename});
</code>```

How do I query case insensitive? I want to find result even if "andrew";

答:
You'd need to use a case-insensitive regular expression for this one, e.g.

```<code>db.collection.find( { "name" : { $regex : /Andrew/i } } );
</code>```

To use the regex pattern from your thename variable, construct a new RegExp object:

```<code>var thename = "Andrew";
db.collection.find( { "name" : { $regex : new RegExp(thename, "i") } } );
</code>```

Update: For exact match, you should use the regex "name": /^Andrew$/i. Thanks to  Yannick L.

Body:
var thename = 'Andrew';
db.collection.find({'name':thename});

How do I query case insensitive? I want to find result even if "andrew";

Body:
You'd need to use a case-insensitive regular expression for this one, e.g.

db.collection.find( { "name" : { $regex : /Andrew/i } } );

To use the regex pattern from your thename variable, construct a new RegExp object:

var thename = "Andrew";
db.collection.find( { "name" : { $regex : new RegExp(thename, "i") } } );

Update: For exact match, you should use the regex "name": /^Andrew$/i. Thanks to  Yannick L.


问:
How to put icon inside an input box
Can anyone help me to put the tick icon inside the input box at right corner?

Also is it possible to display a 'Field Saved' message along with the tick icon?

Update:

What if form contains multiple input in single row, then how to show icon inside the input boxes?

Fiddle: https://jsfiddle.net/sanadqazi/5Len09ad/1/

.test {
  position: relative;
}

.test .fas.fa-check {
  position: absolute;
  top: 0;
  right: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" integrity="sha384-AYmEC3Yw5cVb3ZcuHtOA93w35dYTsvhLPVnYs9eStHfGJvOvKxVfELGroGkvsg+p" crossorigin="anonymous" />

<div class="row">
  <div class="col-8">
    <div class="test">
      <input type="text">
      <i class="fas fa-check inp"></i>
    </div>
  </div>
  <div class="col-4">
    <div class="test">
      <input type="text">
      <i class="fas fa-check inp"></i>
    </div>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/js/bootstrap.bundle.min.js"></script></code>```

答:
.col-8,
.col-4 {
  position: relative;
}

.input-container {
  border: solid 1px #000;
  border-radius: 2px;
  position: absolute;
  display: flex;
  align-items: center;
  padding: 4px;
  gap: 4px;
}

.input-container i {
  display: flex;
  justify-content: center;
  align-items: center;
}

.inp {
  height: 36px;
  line-height: 36px;
}

input[type="text"] {
  /* padding-right: 100px; */
  border: none;
  outline: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" integrity="sha384-AYmEC3Yw5cVb3ZcuHtOA93w35dYTsvhLPVnYs9eStHfGJvOvKxVfELGroGkvsg+p" crossorigin="anonymous" />

<div class="row">
  <div class="col-8">
    <label class="input-container">
      <input type="text">
      <i class="fas fa-check inp"></i>
      <!-- <span>Field Saved</span> -->
    </label>
  </div>
  <div class="col-4">
    <label class="input-container">
      <input type="text">
      <i class="fas fa-check inp"></i>
      <!-- <span>Field Saved</span> -->
    </label>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/js/bootstrap.bundle.min.js"></script></code>```

You can add a container element to your textbox and tick icon. Then, you can remove all the styles of the textbox and put similar styles to the container to make it look like the container itself is a textbox. This way, you can make it look like the icon (and the Field Saved text) inside the textbox.

Title: How to put icon inside an input box

Body:
Can anyone help me to put the tick icon inside the input box at right corner?

Also is it possible to display a 'Field Saved' message along with the tick icon?

Update:

What if form contains multiple input in single row, then how to show icon inside the input boxes?

Fiddle: https://jsfiddle.net/sanadqazi/5Len09ad/1/

.test {
  position: relative;
}

.test .fas.fa-check {
  position: absolute;
  top: 0;
  right: 0;
}

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" integrity="sha384-AYmEC3Yw5cVb3ZcuHtOA93w35dYTsvhLPVnYs9eStHfGJvOvKxVfELGroGkvsg+p" crossorigin="anonymous" />

      <input type="text">

      <input type="text">

Body:
.col-8,
.col-4 {
  position: relative;
}

.input-container {
  border: solid 1px #000;
  border-radius: 2px;
  position: absolute;
  display: flex;
  align-items: center;
  padding: 4px;
  gap: 4px;
}

.input-container i {
  display: flex;
  justify-content: center;
  align-items: center;
}

.inp {
  height: 36px;
  line-height: 36px;
}

input[type="text"] {
  /* padding-right: 100px; */
  border: none;
  outline: none;
}

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" integrity="sha384-AYmEC3Yw5cVb3ZcuHtOA93w35dYTsvhLPVnYs9eStHfGJvOvKxVfELGroGkvsg+p" crossorigin="anonymous" />

<div class="row">
  <div class="col-8">
    <label class="input-container">
      <input type="text">
      <i class="fas fa-check inp"></i>
      <!-- <span>Field Saved</span> -->
    </label>
  </div>
  <div class="col-4">
    <label class="input-container">
      <input type="text">
      <i class="fas fa-check inp"></i>
      <!-- <span>Field Saved</span> -->
    </label>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/js/bootstrap.bundle.min.js"></script>

You can add a container element to your textbox and tick icon. Then, you can remove all the styles of the textbox and put similar styles to the container to make it look like the container itself is a textbox. This way, you can make it look like the icon (and the Field Saved text) inside the textbox.


问:
How can I recode a dictionary?
I have the received a dictionary that looks like this:

```<code>{('M6.9', 'M31.467', 'M3.733'): '2',
('M15.304', 'M12.063', 'M30.138', 'M20.463', 'M20.463'): '2',
('M29', 'M23.59'): '2'}
</code>```

I have created a second dictionary to decode it like so:

```<code>{('M6.9', 'M31.467', 'M3.733'): 'bedrooms',
('M15.304', 'M12.063', 'M30.138', 'M20.463', 'M20.463'): 'toilets',
('M29', 'M23.59'): 'occupants'}
</code>```

How can I recode my first dictionary with my second dictionary, so that I get as output a dictionary that looks like this?

```<code>{'bedrooms': '2',
'toilets': '2',
'occupants': '2'}
</code>```

Title: How can I recode a dictionary?

Body:
I have the received a dictionary that looks like this:

{('M6.9', 'M31.467', 'M3.733'): '2',
('M15.304', 'M12.063', 'M30.138', 'M20.463', 'M20.463'): '2',
('M29', 'M23.59'): '2'}

I have created a second dictionary to decode it like so:

{('M6.9', 'M31.467', 'M3.733'): 'bedrooms',
('M15.304', 'M12.063', 'M30.138', 'M20.463', 'M20.463'): 'toilets',
('M29', 'M23.59'): 'occupants'}

How can I recode my first dictionary with my second dictionary, so that I get as output a dictionary that looks like this?

{'bedrooms': '2',
'toilets': '2',
'occupants': '2'}

Body:
You can do it like this:

a = {('M6.9', 'M31.467', 'M3.733'): '2',
('M15.304', 'M12.063', 'M30.138', 'M20.463', 'M20.463'): '2',
('M29', 'M23.59'): '2'}

b = {('M6.9', 'M31.467', 'M3.733'): 'bedrooms',
('M15.304', 'M12.063', 'M30.138', 'M20.463', 'M20.463'): 'toilets',
('M29', 'M23.59'): 'occupants'}

c = {}

for k,v in b.items():
    c[v] = a[k]

print(c)

{'bedrooms': '2', 'toilets': '2', 'occupants': '2'}


答:
You can write a function which iterates over the keys of the dictionaries, since they are the same:

def recodeDict(dict_names, dict_numbers):
    new_dict = {}
    for key in dict_names:
        new_dict[dict_names[key]] = dict_numbers[key]
    return new_dict
```
<p>You can also do it this way:</p>
<pre class="lang-py prettyprint-override"><code>new_dict = {dict_names[key]: dict_numbers[key] for key in dict_names}
</code>```

EDIT:

Combining that with Sagi's answer:

```<code>c = { v: a[k] for k,v in b.items()}
</code>```

Title: How can I recode a dictionary?

Body:
You can write a function which iterates over the keys of the dictionaries, since they are the same:

def recodeDict(dict_names, dict_numbers):
    new_dict = {}
    for key in dict_names:
        new_dict[dict_names[key]] = dict_numbers[key]
    return new_dict

You can also do it this way:

new_dict = {dict_names[key]: dict_numbers[key] for key in dict_names}

EDIT:

Combining that with Sagi's answer:

c = { v: a[k] for k,v in b.items()}


问:
Problem with calling method from another class for use
So I have these two .java files, one that defines a Dice and another that is going to use the Dice.
I need to implement the roll method from the Dice.java file in the Yahtzee.java file but I'm not sure how to go about doing so.</p>
```<code>public class Dice {
    private int value;

    public Dice() {
        value = -1;
    }

    public Dice(int j) {
        value = j;
    }

    public void roll() {
        value = RandomNumber.getRandomNumber(1, 6);

    }
    public int getValue() {
        return value;
    }

}
</code>```
```<code>public class Yahtzee {

    private Dice[] dice;

    public Yahtzee() {

    }
}
</code>```

答:
one way to do it is this way:

```<code>public void roll() {
    Random ran = new Random();
    this.value = ran.nextInt(6) + 1;
    System.out.println(this.value);

}
</code>```

Don't forget to import  java.util.Random in your Dice class

Use this.value to update the value of current value in all your methods
And in your Yahtzee class, add the following.

```<code>Dice player1 = new Dice();
Dice player2 = new Dice();

player1.roll();
player2.roll();
</code>```

This is just a generalized version as I am not sure what you want to achieve and what you are trying to do.

Using array of objects:
You need to create an array of objects
initialize each index with an instance of the class
and invoke the method using . operator

```<code>Dice [] dice = new Dice[2];
dice[0] = new Dice();
dice[1] = new Dice();
dice[0].roll();
dice[1].roll();
</code>```

Body:
So I have these two .java files, one that defines a Dice and another that is going to use the Dice.
I need to implement the roll method from the Dice.java file in the Yahtzee.java file but I'm not sure how to go about doing so.

public class Dice {
    private int value;

    public Dice() {
        value = -1;
    }

    public Dice(int j) {
        value = j;
    }

    public void roll() {
        value = RandomNumber.getRandomNumber(1, 6);

    }
    public int getValue() {
        return value;
    }

}

public class Yahtzee {

    private Dice[] dice;

    public Yahtzee() {

    }
}

Body:
one way to do it is this way:

public void roll() {
    Random ran = new Random();
    this.value = ran.nextInt(6) + 1;
    System.out.println(this.value);

}

Don't forget to import  java.util.Random in your Dice class

Use this.value to update the value of current value in all your methods
And in your Yahtzee class, add the following.

Dice player1 = new Dice();
Dice player2 = new Dice();

player1.roll();
player2.roll();

This is just a generalized version as I am not sure what you want to achieve and what you are trying to do.

Using array of objects:
You need to create an array of objects
initialize each index with an instance of the class
and invoke the method using . operator

Dice [] dice = new Dice[2];
dice[0] = new Dice();
dice[1] = new Dice();
dice[0].roll();
dice[1].roll();


问:
Selecting Elements whilst using JSoup
Hi Everyone (this is my first question here at Stack Overflow)...

I have been looking into using JSoup to create a small program. What I am looking to do is select a specific piece of data to print out. For example I have this code:

```<code><div id="olpDivId">
<span class="olpCondLink">
    <a class="buyAction olpBlueLink" href="/gp/offer-listing/0747574480/ref=dp_olp_new?ie=UTF8&condition=new">26 new</a>  from
    <span class="price">£2.88</span>
</span>
<span class="olpCondLink">
    <a class="buyAction olpBlueLink" href="/gp/offer-listing/0747574480/ref=dp_olp_used?ie=UTF8&condition=used">14 used</a> from
    <span class="price">£0.01</span>
</span>
</div>
</code>```

I am looking to only get the two span class="price" pieces of data However the page also  has other pieces of data with the same span class. I am wondering if it would be possible to only show the elements with span class price, that are also a member of span class="olpCondLink" or div id="olpDivId" as the other HTML doesn't share the same ID.

I currently have the following code in Java:

```<code>Elements links = doc.select("div[id=olpDivId] > span[class=price]");
</code>```

But it isn't returning anything...

Any help is greatly appreciated, and I hope my question made sense.
Regards,
Jamie.

答:
In the current version (1.6.2), this should work.

```<code>Elements prices = doc.select("span.price");
</code>```

Look at the syntax.

Title: Selecting Elements whilst using JSoup

Body:
Hi Everyone (this is my first question here at Stack Overflow)...

I have been looking into using JSoup to create a small program. What I am looking to do is select a specific piece of data to print out. For example I have this code:

    26 new  from
    £2.88

    14 used from
    £0.01

I am looking to only get the two span class="price" pieces of data However the page also  has other pieces of data with the same span class. I am wondering if it would be possible to only show the elements with span class price, that are also a member of span class="olpCondLink" or div id="olpDivId" as the other HTML doesn't share the same ID.

I currently have the following code in Java:

Elements links = doc.select("div[id=olpDivId] > span[class=price]");

But it isn't returning anything...

Any help is greatly appreciated, and I hope my question made sense.
Regards,
Jamie.

Body:
In the current version (1.6.2), this should work.

Elements prices = doc.select("span.price");

Look at the syntax.


问:
Your project requires a newer version of the Kotlin Gradle plugin. (Android Studio)
I've just updated my flutter project packages to be null-safety compliant and now Android Studio wants me to update my project to use the latest version of Kotling Gradle Plugin. Can't see where to change this though. I have tried to change "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" into "org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.6.10" but this has no effect.

My build.grade-file looks like this:

```<code>def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
    localPropertiesFile.withReader('UTF-8') { reader ->
        localProperties.load(reader)
    }
}

def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
    throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}

def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
    flutterVersionCode = '1'
}

def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
    flutterVersionName = '1.0'
}

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"

def keystoreProperties = new Properties()
def keystorePropertiesFile = rootProject.file('key.properties')
if (keystorePropertiesFile.exists()) {
    keystoreProperties.load(new FileInputStream(keystorePropertiesFile))
}

android {
    compileSdkVersion 31

    sourceSets {
        main.java.srcDirs += 'src/main/kotlin'
    }

    lintOptions {
        disable 'InvalidPackage'
    }

    defaultConfig {
        // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
        applicationId "*********"
        minSdkVersion 30
        targetSdkVersion 30
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    signingConfigs {
        release {
            keyAlias keystoreProperties['keyAlias']
            keyPassword keystoreProperties['keyPassword']
            storeFile keystoreProperties['storeFile'] ? file(keystoreProperties['storeFile']) : null
            storePassword keystoreProperties['storePassword']
        }
    }
    buildTypes {
        release {
            signingConfig signingConfigs.release
        }
    }

}

flutter {
    source '../..'
}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'
    implementation 'com.google.firebase:firebase-analytics:17.2.2'
}
apply plugin: 'com.google.gms.google-services'
</code>```

Build output:

```<code>BUILD FAILED in 8s
[!] Your project requires a newer version of the Kotlin Gradle plugin.
    Find the latest version on https://kotlinlang.org/docs/gradle.html#plugin-and-versions, then update project/android/build.gradle:
    ext.kotlin_version = '<latest-version>'
Exception: Gradle task assembleDebug failed with exit code 1
</code>```

答:
In my case, I don't use kotlin in my flutter project, but some of my dependencies use it (It was assets_audio_player for me), so I had to go to build.gradle for that dependency and update the kotlin version as other answers here:

```<code>ext.kotlin_version = '<latest-version>'
</code>```

Note 1: you can open build.gradle for the library you want by opening the android module in Android Studio then go to Gradle Scripts from  Project tab.

Note 2: you can know which library is causing the error by looking at:

```<code>Execution failed for task ':assets_audio_player:compileDebugKotlin'.
</code>```

It could be more than one library, so after you change kotlin version the error will be changed.

Body:
I've just updated my flutter project packages to be null-safety compliant and now Android Studio wants me to update my project to use the latest version of Kotling Gradle Plugin. Can't see where to change this though. I have tried to change "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" into "org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.6.10" but this has no effect.

My build.grade-file looks like this:

def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
    localPropertiesFile.withReader('UTF-8') { reader ->
        localProperties.load(reader)
    }
}

def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
    throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}

def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
    flutterVersionCode = '1'
}

def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
    flutterVersionName = '1.0'
}

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"

def keystoreProperties = new Properties()
def keystorePropertiesFile = rootProject.file('key.properties')
if (keystorePropertiesFile.exists()) {
    keystoreProperties.load(new FileInputStream(keystorePropertiesFile))
}

android {
    compileSdkVersion 31

    sourceSets {
        main.java.srcDirs += 'src/main/kotlin'
    }

    lintOptions {
        disable 'InvalidPackage'
    }

    defaultConfig {
        // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
        applicationId "*********"
        minSdkVersion 30
        targetSdkVersion 30
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    signingConfigs {
        release {
            keyAlias keystoreProperties['keyAlias']
            keyPassword keystoreProperties['keyPassword']
            storeFile keystoreProperties['storeFile'] ? file(keystoreProperties['storeFile']) : null
            storePassword keystoreProperties['storePassword']
        }
    }
    buildTypes {
        release {
            signingConfig signingConfigs.release
        }
    }

}

flutter {
    source '../..'
}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'
    implementation 'com.google.firebase:firebase-analytics:17.2.2'
}
apply plugin: 'com.google.gms.google-services'

Build output:

BUILD FAILED in 8s
[!] Your project requires a newer version of the Kotlin Gradle plugin.
    Find the latest version on https://kotlinlang.org/docs/gradle.html#plugin-and-versions, then update project/android/build.gradle:
    ext.kotlin_version = '<latest-version>'
Exception: Gradle task assembleDebug failed with exit code 1

Body:
In my case, I don't use kotlin in my flutter project, but some of my dependencies use it (It was assets_audio_player for me), so I had to go to build.gradle for that dependency and update the kotlin version as other answers here:

ext.kotlin_version = '<latest-version>'

Note 1: you can open build.gradle for the library you want by opening the android module in Android Studio then go to Gradle Scripts from  Project tab.

Note 2: you can know which library is causing the error by looking at:

Execution failed for task ':assets_audio_player:compileDebugKotlin'.

It could be more than one library, so after you change kotlin version the error will be changed.


问:
Create chart with dynamic data source
I'm trying to use VBA to create a line chart based on a a dynamic range, I have tried using CurrentRegion, however, that threw an error. I then tried using xlCellTypeLastCell but that also throws an error.

Is there a way I can amend my code below to achieve this or is there a better way to set a dynamic range?

```<code>Sub styled_line_chart()

    Dim WS As Worksheet
    Set WS = ActiveSheet

    Set StartCell = Range("AK10")
    'Set dt = Range(StartCell.CurrentRegion.Select)

    Dim Lr As Long
    Dim Lc As Long
    Dim FirstCell As Range

    Lr = StartCell.SpecialCells(xlCellTypeLastCell).Row

    Lc = StartCell.SpecialCells(xlCellTypeLastCell).Column

    Set dt = Range(StartCell, WS.Cells(Lr, Lc))

    With ch

        .SetSourceData Source:=dt
        .ChartType = xlLine
        .ChartTitle.Text = "Sales by Year"
        .SetElement msoElementDataLabelOutSideEnd
        .SetElement msoElementPrimaryValueGridLinesNone
        .SetElement msoElementLegendTop
        .SetElement msoElementPrimaryValueAxisNone
        .SetElement msoElementPrimaryCategoryAxisTitleBelowAxis
        .Axes(xlCategory).AxisTitle.Text = "Region"
        .SeriesCollection("Sales 2016").Interior.Color = RGB(255, 0, 0)
        .SeriesCollection("Sales 2017").Interior.Color = RGB(100, 0, 0)
        .SeriesCollection("Sales 2018").Interior.Color = RGB(50, 0, 0)
        .ChartArea.Format.Fill.ForeColor.RGB = RGB(221, 217, 185)

    End With

End Sub
</code>```

Updated:

```<code>Sub styled_line_chart()

        Dim WS As Worksheet
        Set WS = ActiveSheet

        Set StartCell = Range("AK10")

        Dim lastRow As Long, dt As Range

        lastRow = Range("AK" & Rows.Count).End(xlUp).Row
        Set dt = Range("AK10:AN" & lastRow)

        Dim ch As Chart
        Set ch = Charts.Add2

        With ch
            .SetSourceData Source:=dt
            .ChartType = xlLine
            .ChartTitle.Text = "Sales by Year"
            .SetElement msoElementDataLabelOutSideEnd
            .SetElement msoElementPrimaryValueGridLinesNone
            .SetElement msoElementLegendTop
            .SetElement msoElementPrimaryValueAxisNone
            .SetElement msoElementPrimaryCategoryAxisTitleBelowAxis
            .Axes(xlCategory).AxisTitle.Text = "Region"
            .SeriesCollection("Sales 2016").Interior.Color = RGB(255, 0, 0)
            .SeriesCollection("Sales 2017").Interior.Color = RGB(100, 0, 0)
            .SeriesCollection("Sales 2018").Interior.Color = RGB(50, 0, 0)
            .ChartArea.Format.Fill.ForeColor.RGB = RGB(221, 217, 185)

        End With

    End Sub
</code>```

答:
Please, try the next way:</p>
```<code>Sub adaptChartRangeCode()
   Dim lastRow As Long, dt As Range
   lastRow = Range("AK" & Rows.count).End(xlUp).row
   Set dt = Range("AK10:AN" & lastRow)

   'your code using dt range...
End Sub
</code>```

Title: Create chart with dynamic data source

Body:
I'm trying to use VBA to create a line chart based on a a dynamic range, I have tried using CurrentRegion, however, that threw an error. I then tried using xlCellTypeLastCell but that also throws an error.

Is there a way I can amend my code below to achieve this or is there a better way to set a dynamic range?

Sub styled_line_chart()

    Dim WS As Worksheet
    Set WS = ActiveSheet

    Set StartCell = Range("AK10")
    'Set dt = Range(StartCell.CurrentRegion.Select)

    Dim Lr As Long
    Dim Lc As Long
    Dim FirstCell As Range

    Lr = StartCell.SpecialCells(xlCellTypeLastCell).Row

    Lc = StartCell.SpecialCells(xlCellTypeLastCell).Column

    Set dt = Range(StartCell, WS.Cells(Lr, Lc))

    With ch

        .SetSourceData Source:=dt
        .ChartType = xlLine
        .ChartTitle.Text = "Sales by Year"
        .SetElement msoElementDataLabelOutSideEnd
        .SetElement msoElementPrimaryValueGridLinesNone
        .SetElement msoElementLegendTop
        .SetElement msoElementPrimaryValueAxisNone
        .SetElement msoElementPrimaryCategoryAxisTitleBelowAxis
        .Axes(xlCategory).AxisTitle.Text = "Region"
        .SeriesCollection("Sales 2016").Interior.Color = RGB(255, 0, 0)
        .SeriesCollection("Sales 2017").Interior.Color = RGB(100, 0, 0)
        .SeriesCollection("Sales 2018").Interior.Color = RGB(50, 0, 0)
        .ChartArea.Format.Fill.ForeColor.RGB = RGB(221, 217, 185)

    End With

End Sub

Updated:

Sub styled_line_chart()

        Dim WS As Worksheet
        Set WS = ActiveSheet

        Set StartCell = Range("AK10")

        Dim lastRow As Long, dt As Range

        lastRow = Range("AK" & Rows.Count).End(xlUp).Row
        Set dt = Range("AK10:AN" & lastRow)

        Dim ch As Chart
        Set ch = Charts.Add2

        With ch
            .SetSourceData Source:=dt
            .ChartType = xlLine
            .ChartTitle.Text = "Sales by Year"
            .SetElement msoElementDataLabelOutSideEnd
            .SetElement msoElementPrimaryValueGridLinesNone
            .SetElement msoElementLegendTop
            .SetElement msoElementPrimaryValueAxisNone
            .SetElement msoElementPrimaryCategoryAxisTitleBelowAxis
            .Axes(xlCategory).AxisTitle.Text = "Region"
            .SeriesCollection("Sales 2016").Interior.Color = RGB(255, 0, 0)
            .SeriesCollection("Sales 2017").Interior.Color = RGB(100, 0, 0)
            .SeriesCollection("Sales 2018").Interior.Color = RGB(50, 0, 0)
            .ChartArea.Format.Fill.ForeColor.RGB = RGB(221, 217, 185)

        End With

    End Sub

Body:
Please, try the next way:

Sub adaptChartRangeCode()
   Dim lastRow As Long, dt As Range
   lastRow = Range("AK" & Rows.count).End(xlUp).row
   Set dt = Range("AK10:AN" & lastRow)

   'your code using dt range...
End Sub


问:
Flask app jinja 2 error in flask website Please help me resolve this issue
The file structure is at the bottom:
[FILE STRUCTURE][1]
The error is:

jinja2.exceptions.TemplateNotFound

jinja2.exceptions.TemplateNotFound: entry.html
The full error is:
[jinja 2 full error][2]

All files are working except the /entry file (Examine the flask_app code below)

**I am using python version 3 and flask to make a website.I have also imported jinja 2 **

**WARNING: DO NOT COPY PASTE ALL CODE IN ONE FILE.There are different files here.

All files code is given to you

```<code>import search4letters

app = Flask(__name__)

@app.route('/search4')
def do_search() -> 'html':
    return str(search4letters('life, the universe, and everything!', 'eiru,!'))
@app.route('/')
@app.route('/entry')
def entry_page() -> 'html':
    return render_template('entry.html', the_title = "Welcome to search4letters on the web!")

app.run(debug=True)

**The entry.html file  code is here: **
{% extends 'base.html' %}
{% block body %}
<h2>{{ the_title }}</h2>
<form method='POST' action='/search4'>
<table>
<p>Use this form to submit a search request:</p>
<tr><td>Phrase:</td><td><input name='phrase' type='TEXT'
width='60'></td></tr>
<tr><td>Letters:</td><td><input name='letters' type='TEXT'
value='aeiou'></td></tr>
</table>
<p>When you're ready, click this button:</p>
<p><input value='Do it!' type='SUBMIT'></p>
</form>
{% endblock %}

###The base.html file code is here: ###
<!doctype html>
<html>
 <head>
 <title>{{ the_title }}</title>
 <link rel="stylesheet" href="static/hf.css" />
 </head>
 <body>
 {% block body %}
 {% endblock %}
 </body>
</html>

**I have made the static folder. Inside it is the hf.css file. hf.css file code is given here: **
body {
    font-family:      Verdana, Geneva, Arial, sans-serif;
    font-size:        medium;
    background-color: grey;
    /* background-color: tan; */
    margin-top:       5%;
    margin-bottom:    5%;
    margin-left:      10%;
    margin-right:     10%;
    border:           1px dotted gray;
    padding:          10px 10px 10px 10px;
  }
  a {
    text-decoration:  none;
    font-weight:      600;
  }
  a:hover {
    text-decoration:  underline;
  }
  a img {
    border:           0;
  }
  h2 {
    font-size:        150%;
  }
  table {
    margin-left:      20px;
    margin-right:     20px;
    caption-side:     bottom;
    border-collapse:  collapse;
  }
  td, th {
    padding:          5px;
    text-align:       left;
  }
  .copyright {
    font-size:        75%;
    font-style:       italic;
  }
  .slogan {
    font-size:        75%;
    font-style:       italic;
  }
  .confirmentry {
    font-weight:      600;
  }

  /*** Tables ***/

  table {
  font-size:          1em;
  background-color:   #fafcff;
  border:             1px solid #909090;
  color:              #2a2a2a;
  padding:            5px 5px 2px;
  border-collapse:    collapse;
  }

  td, th {
  border:             thin dotted gray;
  }

  /*** Inputs ***/
  input[type=text] {
    font-size:        115%;
    width:            30em;
  }
  input[type=submit] {
    font-size:        125%;
  }
  select {
    font-size:        125%;
  }```
**Please help me resolve this problem.**
###results.html file code is given here - This file gives the results of to the user.###
{% extends 'base.html' %}
{% block body %}

{{ the_title }}

You submitted the following data:

Phrase:	{{ the_phrase }}

Letters:	{{ the_letters }}

When "{{the_phrase }}" is search for "{{ the_letters }}", the following
results are returned:

{{ the_results }}

{% endblock %}

  [1]: https://i.stack.imgur.com/B38GN.png
  [2]: https://i.stack.imgur.com/RIo1H.png
```

答:
You'll need to ensure all HTML files are placed within a templates folder within your application root directory.  Flask structures contain two standard folders, static and templates:

The static folder contains assets used by the templates, including
CSS files, JavaScript files, and images.

The templates folder contains only templates. These have an .html extension.

render_template has a default directory to /templates and therefore if the template does not exist within here, you'll receive the TemplateNotFound exception.

General structure layout for a flask application is:

```<code>my-flask-app
   ├── static/
   │   └── css/
   │       └── main.css
   ├── templates/
   │   ├── base.html
   │   └── entry.html
   ├── flask_app.py
</code>```

Body:
The file structure is at the bottom:
[FILE STRUCTURE][1]
The error is:

jinja2.exceptions.TemplateNotFound

jinja2.exceptions.TemplateNotFound: entry.html
The full error is:
[jinja 2 full error][2]

All files are working except the /entry file (Examine the flask_app code below)

**I am using python version 3 and flask to make a website.I have also imported jinja 2 **

**WARNING: DO NOT COPY PASTE ALL CODE IN ONE FILE.There are different files here.

All files code is given to you

import search4letters

app = Flask(__name__)

@app.route('/search4')
def do_search() -> 'html':
    return str(search4letters('life, the universe, and everything!', 'eiru,!'))
@app.route('/')
@app.route('/entry')
def entry_page() -> 'html':
    return render_template('entry.html', the_title = "Welcome to search4letters on the web!")

app.run(debug=True)

**The entry.html file  code is here: **
{% extends 'base.html' %}
{% block body %}

{{ the_title }}

<form method='POST' action='/search4'>

Use this form to submit a search request:

Phrase:	<input name='phrase' type='TEXT'
width='60'>

Letters:	<input name='letters' type='TEXT'
value='aeiou'>

When you're ready, click this button:

<input value='Do it!' type='SUBMIT'>

</form>
{% endblock %}

###The base.html file code is here: ###
<!doctype html>

 <title>{{ the_title }}</title>
 <link rel="stylesheet" href="static/hf.css" />

 {% block body %}
 {% endblock %}

**I have made the static folder. Inside it is the hf.css file. hf.css file code is given here: **
body {
    font-family:      Verdana, Geneva, Arial, sans-serif;
    font-size:        medium;
    background-color: grey;
    /* background-color: tan; */
    margin-top:       5%;
    margin-bottom:    5%;
    margin-left:      10%;
    margin-right:     10%;
    border:           1px dotted gray;
    padding:          10px 10px 10px 10px;
  }
  a {
    text-decoration:  none;
    font-weight:      600;
  }
  a:hover {
    text-decoration:  underline;
  }
  a img {
    border:           0;
  }
  h2 {
    font-size:        150%;
  }
  table {
    margin-left:      20px;
    margin-right:     20px;
    caption-side:     bottom;
    border-collapse:  collapse;
  }
  td, th {
    padding:          5px;
    text-align:       left;
  }
  .copyright {
    font-size:        75%;
    font-style:       italic;
  }
  .slogan {
    font-size:        75%;
    font-style:       italic;
  }
  .confirmentry {
    font-weight:      600;
  }

  /*** Tables ***/

  table {
  font-size:          1em;
  background-color:   #fafcff;
  border:             1px solid #909090;
  color:              #2a2a2a;
  padding:            5px 5px 2px;
  border-collapse:    collapse;
  }

  td, th {
  border:             thin dotted gray;
  }

  /*** Inputs ***/
  input[type=text] {
    font-size:        115%;
    width:            30em;
  }
  input[type=submit] {
    font-size:        125%;
  }
  select {
    font-size:        125%;
  }```
**Please help me resolve this problem.**
###results.html file code is given here - This file gives the results of to the user.###
{% extends 'base.html' %}
{% block body %}

{{ the_title }}

You submitted the following data:

Phrase:	{{ the_phrase }}

Letters:	{{ the_letters }}

When "{{the_phrase }}" is search for "{{ the_letters }}", the following
results are returned:

{{ the_results }}

{% endblock %}

  [1]: https://i.stack.imgur.com/B38GN.png
  [2]: https://i.stack.imgur.com/RIo1H.png

Body:
You'll need to ensure all HTML files are placed within a templates folder within your application root directory.  Flask structures contain two standard folders, static and templates:

The static folder contains assets used by the templates, including
CSS files, JavaScript files, and images.

The templates folder contains only templates. These have an .html extension.

render_template has a default directory to /templates and therefore if the template does not exist within here, you'll receive the TemplateNotFound exception.

General structure layout for a flask application is:

my-flask-app
   ├── static/
   │   └── css/
   │       └── main.css
   ├── templates/
   │   ├── base.html
   │   └── entry.html
   ├── flask_app.py


问:
Order levels of factors change after write csv and read csv in R
I have a hard time to figure out why order of levels of factor change after reading csv. When I am working on data, I always change order of levels by template of my report. Then I write it into csv file. Then I read that file again by read.csv with StringasFactor = False, or StringasFactor = True, it doesn't matter, the order of levels of factor change again, it's not look like the first time I set, so I have to set again to make tables like template. There is any package read csv without changing order of levels of factor. I appreciate. </p>

答:
if you really want to have your data in csv format and keep your factor levels, you can use csvy package:

```<code># library load
library(csvy)
library(dplyr)

# relevel factos
iris_releveled = iris %>% mutate(Species = relevel(Species, "virginica","setosa","versicolor"))
# write csv file
write.csv2(iris_releveled,"iris_releveled.csv")
# load exported dataset
iris_relevel_loaded = read.csv2("iris_releveled.csv",stringsAsFactors = T)
# now factor levels are lost
iris_relevel_loaded$Species %>% levels()

# write CSVy file from dataset with releveled factors
write_csvy(iris_releveled,  file = "iris_releveled.csvy")
# read csv file with original factor levels
iris_relevel_loaded = read_csvy("iris_releveled.csvy", stringsAsFactors = T)
# now factor levels are kept
iris_relevel_loaded$Species %>% levels()
</code>```

Body:
if you really want to have your data in csv format and keep your factor levels, you can use csvy package:

# library load
library(csvy)
library(dplyr)

# relevel factos
iris_releveled = iris %>% mutate(Species = relevel(Species, "virginica","setosa","versicolor"))
# write csv file
write.csv2(iris_releveled,"iris_releveled.csv")
# load exported dataset
iris_relevel_loaded = read.csv2("iris_releveled.csv",stringsAsFactors = T)
# now factor levels are lost
iris_relevel_loaded$Species %>% levels()

# write CSVy file from dataset with releveled factors
write_csvy(iris_releveled,  file = "iris_releveled.csvy")
# read csv file with original factor levels
iris_relevel_loaded = read_csvy("iris_releveled.csvy", stringsAsFactors = T)
# now factor levels are kept
iris_relevel_loaded$Species %>% levels()


问:
Jax-RS @JsonIgnore not working after adding the service endpoint to Application.getClasses
I'm working on my first REST API and I had it working for a minute. Basically, I have a Entity class User which has a reference to another database table Bookmark. I used @JsonIgnore at that field to exclude it from User's JSON representation:

```<code>import org.codehaus.jackson.annotate.JsonIgnore;
import javax.persistence.*;

@Entity
@Table(name = "user")
public class User implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    private String id;

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "user", fetch = FetchType.LAZY)
    @JsonIgnore
    private List<Bookmark> bookmarks = new ArrayList<>();

    @Column(name = "name")
    private String name;
}
</code>```

To get it running, I added an Application class (empty for now):

```<code>import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;

@ApplicationPath("/api")
public class RestApplication extends Application {

}
</code>```

And finally, I took my good old UserService and added a REST endpoint:

```<code>@Dependent
@Named
@Path("/userService")
public class UserService {
    @Inject
    private UserDAO userDAO;

    @GET
    @Path("/getUserById/{id}")
    @Produces(MediaType.APPLICATION_JSON)
    public User getUserById(@PathParam("id") String id) {
        return userDAO.getUserById(id);
    }
}
</code>```

Now I was able to access .../api/userService/getUserById/XYZ and get back a JSON representation of User including only id and name.

However, when trying to access the API from a second project running on the same machine, I stumbled upon the necessity to enable Cross-Origin Resource Sharing. I did so by following the many online guides and implemented a CorsFilter:

```<code>import java.io.IOException;

import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.ext.Provider;

@Provider
public class CorsFilter implements ContainerResponseFilter {

    @Override
    public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
            throws IOException {
        responseContext.getHeaders().add("Access-Control-Allow-Origin", "*");
        responseContext.getHeaders().add("Access-Control-Allow-Credentials", "true");
        responseContext.getHeaders().add("Access-Control-Allow-Headers", "origin, content-type, accept, authorization");
        responseContext.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
    }
}
</code>```

It had no effect at first, but it worked when I included CorsFilter.class in the RestApplication's getClasses() method. Curling the API now showed the correct headers with CORS enabled, but the endpoints returned nothing, so I also included the UserService.class.

That's my RestApplication class right now:

```<code>import java.util.HashSet;
import java.util.Set;

import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;

@ApplicationPath("/api")
public class RestApplication extends Application {

    @Override
    public Set<Class<?>> getClasses() {
        final Set<Class<?>> classes = new HashSet<>();
        classes.add(UserService.class);
        classes.add(CorsFilter.class);
        return classes;
    }
}
</code>```

However, now I get the infamous RESTEASY008205: JSON Binding serialization error org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.xyz.User.bookmarks, could not initialize proxy - no Session. Trying to access a different endpoint results in RESTEASY008205: JSON Binding serialization error javax.json.bind.JsonbException: Error getting value on: org.hibernate.proxy.pojo.bytebuddy.ByteBuddyInterceptor@2ba18598, by the way, even though I can't figure out the difference between both endpoints.

At this point I'm kind of lost, it all went downhill when I tried to add the filter. Any advice on where I went wrong?
By the way, it's running on jboss-eap-7.2 and I added the following dependency to my POM to access org.codehaus.jackson.annotate.JsonIgnore:

```<code>        <dependency>
            <groupId>org.jboss.resteasy</groupId>
            <artifactId>resteasy-jackson-provider</artifactId>
            <version>3.6.1.SP2</version>
        </dependency>
</code>```

答:
According to the specification:

When an Application subclass is present in the archive, if both Application.getClasses and Application.getSingletons return an empty collection then all root resource classes and providers packaged in the web application MUST be included and the JAX-RS implementation is REQUIRED to discover them automatically by scanning a .war file as described above. If either getClasses or getSingletons returns a non-empty collection then only those classes or singletons returned MUST be included in the published JAX-RS application.

So once you provide the getClasses override, the automatic discovery is turned off, and you must register explicitely the resources and the providers, including the Jackson features.

Body:
I'm working on my first REST API and I had it working for a minute. Basically, I have a Entity class User which has a reference to another database table Bookmark. I used @JsonIgnore at that field to exclude it from User's JSON representation:

import org.codehaus.jackson.annotate.JsonIgnore;
import javax.persistence.*;

@Entity
@Table(name = "user")
public class User implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    private String id;

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "user", fetch = FetchType.LAZY)
    @JsonIgnore
    private List<Bookmark> bookmarks = new ArrayList<>();

    @Column(name = "name")
    private String name;
}

To get it running, I added an Application class (empty for now):

import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;

@ApplicationPath("/api")
public class RestApplication extends Application {

}

And finally, I took my good old UserService and added a REST endpoint:

@Dependent
@Named
@Path("/userService")
public class UserService {
    @Inject
    private UserDAO userDAO;

    @GET
    @Path("/getUserById/{id}")
    @Produces(MediaType.APPLICATION_JSON)
    public User getUserById(@PathParam("id") String id) {
        return userDAO.getUserById(id);
    }
}

Now I was able to access .../api/userService/getUserById/XYZ and get back a JSON representation of User including only id and name.

However, when trying to access the API from a second project running on the same machine, I stumbled upon the necessity to enable Cross-Origin Resource Sharing. I did so by following the many online guides and implemented a CorsFilter:

import java.io.IOException;

import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.ext.Provider;

@Provider
public class CorsFilter implements ContainerResponseFilter {

    @Override
    public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
            throws IOException {
        responseContext.getHeaders().add("Access-Control-Allow-Origin", "*");
        responseContext.getHeaders().add("Access-Control-Allow-Credentials", "true");
        responseContext.getHeaders().add("Access-Control-Allow-Headers", "origin, content-type, accept, authorization");
        responseContext.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
    }
}

It had no effect at first, but it worked when I included CorsFilter.class in the RestApplication's getClasses() method. Curling the API now showed the correct headers with CORS enabled, but the endpoints returned nothing, so I also included the UserService.class.

That's my RestApplication class right now:

import java.util.HashSet;
import java.util.Set;

import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;

@ApplicationPath("/api")
public class RestApplication extends Application {

    @Override
    public Set<Class<?>> getClasses() {
        final Set<Class<?>> classes = new HashSet<>();
        classes.add(UserService.class);
        classes.add(CorsFilter.class);
        return classes;
    }
}

However, now I get the infamous RESTEASY008205: JSON Binding serialization error org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.xyz.User.bookmarks, could not initialize proxy - no Session. Trying to access a different endpoint results in RESTEASY008205: JSON Binding serialization error javax.json.bind.JsonbException: Error getting value on: org.hibernate.proxy.pojo.bytebuddy.ByteBuddyInterceptor@2ba18598, by the way, even though I can't figure out the difference between both endpoints.

At this point I'm kind of lost, it all went downhill when I tried to add the filter. Any advice on where I went wrong?
By the way, it's running on jboss-eap-7.2 and I added the following dependency to my POM to access org.codehaus.jackson.annotate.JsonIgnore:

        <dependency>
            <groupId>org.jboss.resteasy</groupId>
            <artifactId>resteasy-jackson-provider</artifactId>
            <version>3.6.1.SP2</version>
        </dependency>


问:
How can I select distinct rows when a text field is part of the returned fields in MS SQL Server 2000?
I have a database-driven FAQ that is organised into sections and I am trying to get the section data for only those sections who have a question/answer associated with them.

Here is the schema:

```<code>|---------------------|      |----------------------|
|       Section       |      |       Quest-Ans      |
|---------------------|      |----------------------|
| PK | id(int)        |<--|  | PK     | id(int)     |
|    | title(varchar) |   |--| FK     | Sec_id(int) |
|    | desc(text)     |      |        | body(text)  |
|---------------------|      |----------------------|
</code>```

When I try this query:

```<code>SELECT DISTINCT s.id, s.title, s.desc
FROM Section as s INNER JOIN Quest-Ans as q ON s.id = q.Sec_id
</code>```

I get an error saying that DISCRETE cannot be applied to a text field. How can I get the data I want?

If it matters, this is an SQL2000 database.

EDIT:

Ok, so it seems like there are two ways to go about this. Either with EXISTS and a subquery in the where clause, or with the subquery in the inner join. Which is faster?

答:
This should do it:</p>

```<code>SELECT s.id, s.title, s.desc
FROM Section as s
WHERE EXISTS (SELECT * FROM Quest-Ans as q where q.Sec_id = s.id)
</code>```

OwnerDisplayName: cdeszaq

ContentLicense: CC BY-SA 2.5

Body:
I have a database-driven FAQ that is organised into sections and I am trying to get the section data for only those sections who have a question/answer associated with them.

Here is the schema:

|---------------------|      |----------------------|
|       Section       |      |       Quest-Ans      |
|---------------------|      |----------------------|
| PK | id(int)        |<--|  | PK     | id(int)     |
|    | title(varchar) |   |--| FK     | Sec_id(int) |
|    | desc(text)     |      |        | body(text)  |
|---------------------|      |----------------------|

When I try this query:

SELECT DISTINCT s.id, s.title, s.desc
FROM Section as s INNER JOIN Quest-Ans as q ON s.id = q.Sec_id

I get an error saying that DISCRETE cannot be applied to a text field. How can I get the data I want?

If it matters, this is an SQL2000 database.

EDIT:

Ok, so it seems like there are two ways to go about this. Either with EXISTS and a subquery in the where clause, or with the subquery in the inner join. Which is faster?

Body:
This should do it:

SELECT s.id, s.title, s.desc
FROM Section as s
WHERE EXISTS (SELECT * FROM Quest-Ans as q where q.Sec_id = s.id)

OwnerDisplayName: ck


问:
I have base class which implemented IClientValidatable
I have base class(CompareAttribute) which implemented IClientValidatable

```<code>[AttributeUsage(AttributeTargets.Property)]
public class NotContainsAttribute : CompareAttribute
{
}
</code>```

I want to override method IEnumerable<ModelClientValidationRule> GetClientValidationRules

but i can't do that because it is not virtual(cannot override inherited member, because it is not marked virtual, abstract, or override).

So i just declare my own method in my NotContainsAttribute class

```<code>public new IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
}
</code>```

After i run the program all working like expected but i get warning in compile time that my class hides inherited member, (Warning "NotContainsAttribute" hides inherited member Use the new keyword if hiding was intended.)

But if I use new keyword

```<code>public new IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            yield return new ModelClientValidationNotContains (this.FormatErrorMessage(metadata.GetDisplayName()), CompareAttribute.FormatPropertyForClientValidation(this.OtherProperty));
            yield break;
        }
</code>```

In such case my method not used, base class method used instead.

I want my method to be used, without new keyword i get it used but why compiler saying that i need to use new keyword if hiding was intended?

I understand that if hiding was intended means that if you want to hide base method and use your method insteard mark it with new keyword but on practice it is really hiding my method.

May be some one may clarify that and is it good practice to declare method with the same name if that method in base class not allowed to be overridden but really you need to override it?

答:
Its just a warning when upon using in the caller method to call this method, you might accidentally call this hiding method which your intention was not to. By providing new scope to it, your giving a new definition rather than masking it.

Warning doesnt mean that your code is imperfect or wrong, its just a heads up for you to not oversee your mistake and bang head in future.

Body:
I have base class(CompareAttribute) which implemented IClientValidatable

[AttributeUsage(AttributeTargets.Property)]
public class NotContainsAttribute : CompareAttribute
{
}

I want to override method IEnumerable<ModelClientValidationRule> GetClientValidationRules

but i can't do that because it is not virtual(cannot override inherited member, because it is not marked virtual, abstract, or override).

So i just declare my own method in my NotContainsAttribute class

public new IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
}

After i run the program all working like expected but i get warning in compile time that my class hides inherited member, (Warning "NotContainsAttribute" hides inherited member Use the new keyword if hiding was intended.)

But if I use new keyword

public new IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            yield return new ModelClientValidationNotContains (this.FormatErrorMessage(metadata.GetDisplayName()), CompareAttribute.FormatPropertyForClientValidation(this.OtherProperty));
            yield break;
        }

In such case my method not used, base class method used instead.

I want my method to be used, without new keyword i get it used but why compiler saying that i need to use new keyword if hiding was intended?

I understand that if hiding was intended means that if you want to hide base method and use your method insteard mark it with new keyword but on practice it is really hiding my method.

May be some one may clarify that and is it good practice to declare method with the same name if that method in base class not allowed to be overridden but really you need to override it?


问:
How do I find the previous URL for login using pure JavaScript? document.referrer is not working for me
I am using express with pug templates and pure JavaScript,for the log in system I want to save the URL someone came to the login page with so I can move them back to it after they finish to log in, however I can't find it.

I tried using document.referrer and put it inside an hidden input to store it inside the pug template,it responded with an error message saying document is not defined, type error, when I rendered the login page.do I need to define something or download some module for me to use document properties? if I simply cant do it that way how can I do it?

here is my get route handler in the my router:

```<code>router.get('/login', function(req,res,next) {
  res.render('login', {backUrl: document.referrer});
});
</code>```

Thanks!

答:
```<code>req.originalUrl
</code>```

According to express documentation:

This property is much like req.url; however, it retains the original request URL, allowing you to rewrite req.url freely for internal routing purposes

Body:
I am using express with pug templates and pure JavaScript,for the log in system I want to save the URL someone came to the login page with so I can move them back to it after they finish to log in, however I can't find it.

I tried using document.referrer and put it inside an hidden input to store it inside the pug template,it responded with an error message saying document is not defined, type error, when I rendered the login page.do I need to define something or download some module for me to use document properties? if I simply cant do it that way how can I do it?

here is my get route handler in the my router:

router.get('/login', function(req,res,next) {
  res.render('login', {backUrl: document.referrer});
});

Thanks!

Body:
req.originalUrl

According to express documentation:

This property is much like req.url; however, it retains the original request URL, allowing you to rewrite req.url freely for internal routing purposes


问:
AD users that have specific word in the description field via Powershell
I am new to PowerShell and I am trying to extract username and name of users that contain a word or specific words in the description field of an AD user.

In the description field we have added user job titles and I am trying to search for specific job titles to display full names and usernames.

What I have gathered from my quick googling is this:

Get-ADUser -Filter * -Properties Description | Select Name,SamAccountName

This displays all AD users with name and username details.

I believe this area I need to change is the -Filter but when I try something like this the command fails

Get-ADUser -Filter -like "developer" -Properties Description | Select Name,SamAccountName

This is probably going to be pretty straightforward for a powershell guy but I am struggling here.

Update to the command

Get-ADUser -Properties Description -Filter 'Description -like "developer"' | Select Name,SamAccountName

Nothing is getting outputted after I enter the command.

Further update the command that worked for me was:

Get-ADUser -Properties Description -Filter 'Description -like "*developer*"' | Select Name,SamAccountName

答:
Using -Filter Parameter:

```<code>Get-ADUser -Properties Description -Filter {Description -like "developer"}
OR
Get-ADUser -Properties Description -Filter 'Description -like "*developer*"'
</code>```

Using Where-Object

```<code>Get-ADUser -Properties Description -Filter * | ? Description -match "developer"
</code>```

Add your Final Select at the end of the pipeline if you just need this specific properties:

```<code>| Select Name,SamAccountName,Description
</code>```

Body:
Using -Filter Parameter:

Get-ADUser -Properties Description -Filter {Description -like "developer"}
OR
Get-ADUser -Properties Description -Filter 'Description -like "*developer*"'

Using Where-Object

Get-ADUser -Properties Description -Filter * | ? Description -match "developer"

Add your Final Select at the end of the pipeline if you just need this specific properties:

| Select Name,SamAccountName,Description


问:
Add text into Image and share it as Image
I need some help here.
I want to add a new feature to my app. I have a page that displays some text and I have a share button with it. Now the user can share this text with anyone, So what I want is that the user can share this text as an Image, So Instead of sharing this just like a text, I will add this new feature to also can share it as an Image.

Now I already created the Image that will include this text to be shared,
What I need to do is, When the user clicks on the share button, it is should send this text to the Image a Put it into it "It will be empty and the text will be like drawing on it. And after the text adds to the Image, The user can send this image with the text.

I made some searches on Google and I found some people who say you can add Textview into the ImageView and send this text with Intent then display the text in the Textview and then share it. But of course, this will not work because the text didn't actually add to the Image and It is just a view, so the Image will share as it is "Empty".

Any suggestions for how can I make something like that?

答:
There are 3 steps to this .

Create the view you want to send

Convert the view to Bitmap

Send it via an intent after saving it in your app or use it for your imageview

Create the view you wanto to send

So create a constraint layout which has that textview which is populated by the text you want to give it from the previous activity via a `intent.getExtra("text")

Have the images and other data in the *same constraint layout which you want to send. Once yo're satisfied with how the view/viewgroup  aka the constraint layout looks. we are ready to convert that to bitmap

2.Convert the viewgroup to Bitmap

```<code>v.measure(MeasureSpec.makeMeasureSpec(v.getLayoutParams().width, MeasureSpec.EXACTLY),
        MeasureSpec.makeMeasureSpec(v.getLayoutParams().height, MeasureSpec.EXACTLY));
v.layout(0, 0, v.getMeasuredWidth(), v.getMeasuredHeight());

Bitmap b = Bitmap.createBitmap(v.getWidth(), v.getHeight(), Bitmap.Config.RGB_565);
Canvas c = new Canvas(b);
v.draw(c);
</code>```

where v is the viewgroup you want to convert to bitmap

Viewgroup to Bitmap Stackoverflow

3.Send that bitmap as an intent

```<code> String pathofBmp = Images.Media.insertImage(getContentResolver(), bitmap,"title", null);
    Uri bmpUri = Uri.parse(pathofBmp);
    final Intent emailIntent1 = new Intent(     android.content.Intent.ACTION_SEND);
    emailIntent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    emailIntent1.putExtra(Intent.EXTRA_STREAM, bmpUri);
    emailIntent1.setType("image/png");
</code>```

and for imageview it's as simple as
imageview.setSrc(bitmap)

Share Bitmap via Android Stackoverllow answer

Body:
There are 3 steps to this .

Create the view you want to send

Convert the view to Bitmap

Send it via an intent after saving it in your app or use it for your imageview

Create the view you wanto to send

So create a constraint layout which has that textview which is populated by the text you want to give it from the previous activity via a `intent.getExtra("text")

Have the images and other data in the *same constraint layout which you want to send. Once yo're satisfied with how the view/viewgroup  aka the constraint layout looks. we are ready to convert that to bitmap

2.Convert the viewgroup to Bitmap

v.measure(MeasureSpec.makeMeasureSpec(v.getLayoutParams().width, MeasureSpec.EXACTLY),
        MeasureSpec.makeMeasureSpec(v.getLayoutParams().height, MeasureSpec.EXACTLY));
v.layout(0, 0, v.getMeasuredWidth(), v.getMeasuredHeight());

Bitmap b = Bitmap.createBitmap(v.getWidth(), v.getHeight(), Bitmap.Config.RGB_565);
Canvas c = new Canvas(b);
v.draw(c);

where v is the viewgroup you want to convert to bitmap

Viewgroup to Bitmap Stackoverflow

3.Send that bitmap as an intent

 String pathofBmp = Images.Media.insertImage(getContentResolver(), bitmap,"title", null);
    Uri bmpUri = Uri.parse(pathofBmp);
    final Intent emailIntent1 = new Intent(     android.content.Intent.ACTION_SEND);
    emailIntent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    emailIntent1.putExtra(Intent.EXTRA_STREAM, bmpUri);
    emailIntent1.setType("image/png");

and for imageview it's as simple as
imageview.setSrc(bitmap)

Share Bitmap via Android Stackoverllow answer