问:
Loopback4 - How to increase default time out for a test case when using `@loopback/testlab`
I have some APIs which take more than 2 seconds. When I execute the test cases for these APIs I am getting the below error

```<code>Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves. (xxxxx/dist/__tests__/acceptance/employee.controller.acceptance.js)
      at listOnTimeout (node:internal/timers:559:17)
      at processTimers (node:internal/timers:502:7)
</code>```

I followed the answers in these thread How to increase timeout for a single test case in mocha.
It helps me to increase the timeout of one test case as below. How can I configure the timeout for a group of test cases or for all test cases ?

```<code>describe('EmployeeController', () => {

  let app: ExpressServer;
  let client: Client;

  afterEach(async() => {

    clearDatabase();
    await app.stop();

  });

  beforeEach(async() => {

    ({app, client} = await setupApplication());

  });

  it('Create an employee - Fresh User', async() => {

    const token = await generateUserToken(client, 'user.1@5by.one');
    const resL = await client.get('/api/auth/users/my-account')
    .set({Authorization: `Bearer ${token}`}).send()
      .expect(200);
    const permissions = {
      ...accouontingPermissions,
      ...systemPermissions
    };
    await client.post('/api/auth/employees')
    .set({Authorization: `Bearer ${token}`}).send({
      name: 'Emp One',
      email: 'employee.1@5by.one',
      permissions,
      role: 'user',
    })
      .expect(200);

  }).timeout(5000);;

});
</code>```

Body:
I have some APIs which take more than 2 seconds. When I execute the test cases for these APIs I am getting the below error

Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves. (xxxxx/dist/__tests__/acceptance/employee.controller.acceptance.js)
      at listOnTimeout (node:internal/timers:559:17)
      at processTimers (node:internal/timers:502:7)

I followed the answers in these thread How to increase timeout for a single test case in mocha.
It helps me to increase the timeout of one test case as below. How can I configure the timeout for a group of test cases or for all test cases ?

describe('EmployeeController', () => {

  let app: ExpressServer;
  let client: Client;

  afterEach(async() => {

    clearDatabase();
    await app.stop();

  });

  beforeEach(async() => {

    ({app, client} = await setupApplication());

  });

  it('Create an employee - Fresh User', async() => {

    const token = await generateUserToken(client, 'user.1@5by.one');
    const resL = await client.get('/api/auth/users/my-account')
    .set({Authorization: `Bearer ${token}`}).send()
      .expect(200);
    const permissions = {
      ...accouontingPermissions,
      ...systemPermissions
    };
    await client.post('/api/auth/employees')
    .set({Authorization: `Bearer ${token}`}).send({
      name: 'Emp One',
      email: 'employee.1@5by.one',
      permissions,
      role: 'user',
    })
      .expect(200);

  }).timeout(5000);;

});


来源: stackexchange

问:
How can I get the updated variable state in App.Js?
Signin.js

```<code>const Signin = () => {
  const { login, setCookie } = useGlobalContext();
  const [returnedUser, setReturnedUser] = useState({
    email: "",
    password: "",
  });
  const navigate = useNavigate();

  const login_navigate = async () => {
    try {
      const resp = await login(returnedUser);
      setCookie("Email", returnedUser.email, { path: "/" });
      navigate("/student/landingpage");
      console.log(`response ${resp.user.email}`);
    } catch (error) {
      console.log("Could not sign in");
    }
  };
  const handleSubmit = (event) => {
    event.preventDefault();
    if (returnedUser.email && returnedUser.password) {
      login_navigate();
      setReturnedUser({
        email: "",
        password: "",
      });
    }
  };
}
</code>```

Notes:
I have checked the browser application, I am able to setCookie from signin.
login(returnedUser); is an async await function inside context.js

context.js

```<code>const AppProvider = ({ children }) => {
  const [user, setUser] = useState({});
  const [signin, setSignin] = useState(false);
  const [cookies, setCookie] = useCookies(["user"]);
  const usersCollectionRef = collection(database, "users");

  //Retrieve saved Cookie
  function getCookie(name) {
    var cookieValue;
    if (document.cookie && document.cookie !== "") {
      var cookies = document.cookie.split(";");
      for (var i = 0; i < cookies.length; i++) {
        var cookie = cookies[i].trim();
        if (cookie.substring(0, name.length + 1) === name + "=") {
          cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
          break;
        }
      }
    }
    return cookieValue;
  }
  //end the retreiving

  //login
  const login = async ({ ...UserCredentials }) => {
    var user = "null";
    // console.log("Login ", UserCredentials.email, " ", UserCredentials.password);
    try {
      user = await signInWithEmailAndPassword(
        auth,
        UserCredentials.email,
        UserCredentials.password
      );
      // setCookie("Email", UserCredentials.email, { path: "/" });
    } catch (error) {
      console.log(`There is an error: ${error.message}`);
    }
    return user;
  };
  // end Firebase authentication

  return (
    <AppContext.Provider
      value={{
        user, setUser, login, register, cookies, setCookie, getCookie, signin, setSignin,
      }}
    >
      {children}
    </AppContext.Provider>
  );
};

export const useGlobalContext = () => {
  return useContext(AppContext);
};

export { AppContext, AppProvider };
</code>```

App.js

```<code>function App() {
  const { cookies, getCookie } = useGlobalContext();

  console.log(
    `getCookie function ${getCookie("Email")} cookies state ${cookies.Email}`
  );

  return (
    <BrowserRouter>
      <Routes>
        {/* {cookies.Email && console.log(`From APP.JS: ${cookies.Email}`)} */}
        <Route path="signin" element={<Signin />} />
        <Route path="/" index element={<Signup />} />
        <Route path="forgotpassword" element={<Forgotpassword />} />

        <Route path="/student" element={<SharedLayOut />}>
          <Route
            path="landingpage"
            element={
              <ProtectedRoute userCookie={getCookie("Email")}>
                {" "}
                <LandingPage userCookie={getCookie("Email")} />
              </ProtectedRoute>
            }
          />
        </Route>
        <Route path="*" element={<Error />}></Route>
      </Routes>
    </BrowserRouter>
  );
}

export default App;
</code>```

Observation:
If I login it does not navigate to LandingPage. getCookie("Email") usually returned undefined. at first I thought the getCookie("Email") function is not working, I discovered it was working only if I refresh the browser.

If I do not refresh the browser the below log returned undefined for both variable

```<code>console.log(`getCookie function ${getCookie("Email")} cookies state ${cookies.Email}`);
</code>```

If I refresh the browser the below log returned the expected result which is email

```<code>console.log(`getCookie function ${getCookie("Email")} cookies state ${cookies.Email}`);
</code>```

I have tried to use navigate("/student/landingpage"); inside context.js, I usually get navigate cannot be called because context.js is not a react function component or hook.

Please help me.

ContentLicense: CC BY-SA 4.0

Body:
Signin.js

const Signin = () => {
  const { login, setCookie } = useGlobalContext();
  const [returnedUser, setReturnedUser] = useState({
    email: "",
    password: "",
  });
  const navigate = useNavigate();

  const login_navigate = async () => {
    try {
      const resp = await login(returnedUser);
      setCookie("Email", returnedUser.email, { path: "/" });
      navigate("/student/landingpage");
      console.log(`response ${resp.user.email}`);
    } catch (error) {
      console.log("Could not sign in");
    }
  };
  const handleSubmit = (event) => {
    event.preventDefault();
    if (returnedUser.email && returnedUser.password) {
      login_navigate();
      setReturnedUser({
        email: "",
        password: "",
      });
    }
  };
}

Notes:
I have checked the browser application, I am able to setCookie from signin.
login(returnedUser); is an async await function inside context.js

context.js

const AppProvider = ({ children }) => {
  const [user, setUser] = useState({});
  const [signin, setSignin] = useState(false);
  const [cookies, setCookie] = useCookies(["user"]);
  const usersCollectionRef = collection(database, "users");

  //Retrieve saved Cookie
  function getCookie(name) {
    var cookieValue;
    if (document.cookie && document.cookie !== "") {
      var cookies = document.cookie.split(";");
      for (var i = 0; i < cookies.length; i++) {
        var cookie = cookies[i].trim();
        if (cookie.substring(0, name.length + 1) === name + "=") {
          cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
          break;
        }
      }
    }
    return cookieValue;
  }
  //end the retreiving

  //login
  const login = async ({ ...UserCredentials }) => {
    var user = "null";
    // console.log("Login ", UserCredentials.email, " ", UserCredentials.password);
    try {
      user = await signInWithEmailAndPassword(
        auth,
        UserCredentials.email,
        UserCredentials.password
      );
      // setCookie("Email", UserCredentials.email, { path: "/" });
    } catch (error) {
      console.log(`There is an error: ${error.message}`);
    }
    return user;
  };
  // end Firebase authentication

  return (
    <AppContext.Provider
      value={{
        user, setUser, login, register, cookies, setCookie, getCookie, signin, setSignin,
      }}
    >
      {children}
    </AppContext.Provider>
  );
};

export const useGlobalContext = () => {
  return useContext(AppContext);
};

export { AppContext, AppProvider };

App.js

function App() {
  const { cookies, getCookie } = useGlobalContext();

  console.log(
    `getCookie function ${getCookie("Email")} cookies state ${cookies.Email}`
  );

  return (
    <BrowserRouter>
      <Routes>
        {/* {cookies.Email && console.log(`From APP.JS: ${cookies.Email}`)} */}
        <Route path="signin" element={<Signin />} />
        <Route path="/" index element={<Signup />} />
        <Route path="forgotpassword" element={<Forgotpassword />} />

        <Route path="/student" element={<SharedLayOut />}>
          <Route
            path="landingpage"
            element={
              <ProtectedRoute userCookie={getCookie("Email")}>
                {" "}
                <LandingPage userCookie={getCookie("Email")} />
              </ProtectedRoute>
            }
          />
        </Route>
        <Route path="*" element={<Error />}></Route>
      </Routes>
    </BrowserRouter>
  );
}

export default App;

Observation:
If I login it does not navigate to LandingPage. getCookie("Email") usually returned undefined. at first I thought the getCookie("Email") function is not working, I discovered it was working only if I refresh the browser.

If I do not refresh the browser the below log returned undefined for both variable

console.log(`getCookie function ${getCookie("Email")} cookies state ${cookies.Email}`);

If I refresh the browser the below log returned the expected result which is email

console.log(`getCookie function ${getCookie("Email")} cookies state ${cookies.Email}`);

I have tried to use navigate("/student/landingpage"); inside context.js, I usually get navigate cannot be called because context.js is not a react function component or hook.

Please help me.


问:
Multilines text depending on the TreeView width
I am building a plugin for thonny and I have a problem about building a TreeView.
I have a tree view that contains only one column and it has several rows. Each row has its text, and the text can be too long. I should tell the tree view to cut the text so that it appears in the next line.

Here's my code:

class TestTreeView(ttk.Frame):
    def __init__(self, master):
        ttk.Frame.__init__(self, master)
        self._init_widgets()

    def _init_widgets(self):
        # init and place scrollbar
        self.vert_scrollbar = SafeScrollbar(self, orient=tk.VERTICAL)
        self.vert_scrollbar.grid(row=0, column=1, sticky=tk.NSEW)

        self.horz_scrollbar = SafeScrollbar(self, orient=tk.HORIZONTAL)
        self.horz_scrollbar.grid(row=1, column=0, sticky=tk.NSEW)

        self.tree = ttk.Treeview(self)

        # scrollbars
        self.vert_scrollbar["command"] = self.tree.yview
        self.horz_scrollbar["command"] = self.tree.xview

        self.tree.grid(row=0, column=0, sticky=tk.NSEW)

        # configure the scroll bars on the tree view
        self.tree.configure(yscrollcommand=self.vert_scrollbar.set, xscrollcommand=self.horz_scrollbar.set)

        # set single-cell frame
        self.columnconfigure(0, weight=1)
        self.rowconfigure(0, weight=1)

        # init tree events
        self.tree.bind("<<TreeviewSelect>>", self._on_select, True)

        # configure the only tree column
        self.tree.column("#0", anchor=tk.W, stretch=True, width=1000, minwidth=1000)
        self.tree["show"] = ("tree",)

        self.tree.tag_configure('orange', foreground='orange')
        self.tree.tag_configure('red', foreground='red')
        self.tree.tag_configure('green', foreground='darkgreen')

        ttk.Style().configure('Treeview', rowheight=40, rowwidth=40)
```

As you can see in the following picture, I want the last line (Tests Run: 2, Failures...) to be on several lines if the width of the view is small than the width of the rows.

In general, I want something responsive depending on the size of the view.

Is this possible?

Body:
I am building a plugin for thonny and I have a problem about building a TreeView.
I have a tree view that contains only one column and it has several rows. Each row has its text, and the text can be too long. I should tell the tree view to cut the text so that it appears in the next line.

Here's my code:

class TestTreeView(ttk.Frame):
    def __init__(self, master):
        ttk.Frame.__init__(self, master)
        self._init_widgets()

    def _init_widgets(self):
        # init and place scrollbar
        self.vert_scrollbar = SafeScrollbar(self, orient=tk.VERTICAL)
        self.vert_scrollbar.grid(row=0, column=1, sticky=tk.NSEW)

        self.horz_scrollbar = SafeScrollbar(self, orient=tk.HORIZONTAL)
        self.horz_scrollbar.grid(row=1, column=0, sticky=tk.NSEW)

        self.tree = ttk.Treeview(self)

        # scrollbars
        self.vert_scrollbar["command"] = self.tree.yview
        self.horz_scrollbar["command"] = self.tree.xview

        self.tree.grid(row=0, column=0, sticky=tk.NSEW)

        # configure the scroll bars on the tree view
        self.tree.configure(yscrollcommand=self.vert_scrollbar.set, xscrollcommand=self.horz_scrollbar.set)

        # set single-cell frame
        self.columnconfigure(0, weight=1)
        self.rowconfigure(0, weight=1)

        # init tree events
        self.tree.bind("<<TreeviewSelect>>", self._on_select, True)

        # configure the only tree column
        self.tree.column("#0", anchor=tk.W, stretch=True, width=1000, minwidth=1000)
        self.tree["show"] = ("tree",)

        self.tree.tag_configure('orange', foreground='orange')
        self.tree.tag_configure('red', foreground='red')
        self.tree.tag_configure('green', foreground='darkgreen')

        ttk.Style().configure('Treeview', rowheight=40, rowwidth=40)

As you can see in the following picture, I want the last line (Tests Run: 2, Failures...) to be on several lines if the width of the view is small than the width of the rows.

In general, I want something responsive depending on the size of the view.

Is this possible?


问:
Which technology supports creating a web application for graph and tree visualisation?
I am looking for a technology which offers the best and the easiest way to create a specific web application. Besides the standard features like registration, login, CRUD etc., the application needs to give a user the ability to interact with graph/tree structures:

Create a graph/tree

Add/remove/edit nodes and edges

Visualise the current version of a graph/tree

Visualisation and interaction with the visual is the only challenge here. Animations are nice to have, but not mandatory.

If you have any tutorial or example project, I would appreciate it.


问:
How to close video widget window once video is done playing QVideoWidget?
I want to display a video when a button is clicked and close the video widget once the video is done playing in QT 6.4, and if there is no workaround that, if I could somehow display the video in a widget I create on QTDesigner that would work well too, thank you!</p>
```<code>QMediaPlayer* player = new QMediaPlayer;
player->setSource(QUrl("C:/Users/QTDev/Desktop/final.mp4"));

QAudioOutput * audioOutput = new QAudioOutput;

player->setAudioOutput(audioOutput);
audioOutput->setVolume(1.0);

QVideoWidget* videoWidget = new QVideoWidget;
player->setVideoOutput(videoWidget);

videoWidget->showFullScreen();
player->play();
</code>```

Body:
I want to display a video when a button is clicked and close the video widget once the video is done playing in QT 6.4, and if there is no workaround that, if I could somehow display the video in a widget I create on QTDesigner that would work well too, thank you!

QMediaPlayer* player = new QMediaPlayer;
player->setSource(QUrl("C:/Users/QTDev/Desktop/final.mp4"));

QAudioOutput * audioOutput = new QAudioOutput;

player->setAudioOutput(audioOutput);
audioOutput->setVolume(1.0);

QVideoWidget* videoWidget = new QVideoWidget;
player->setVideoOutput(videoWidget);

videoWidget->showFullScreen();
player->play();


问:
SQL Server DBCC CLONEDATABASE WITH VERIFY_CLONEDB and the database is still read-only?
I tried to use the CLONEDATABASE WITH VERIFY_CLONEDB. It does what I want, except that the CLONE is read-only. What is the point of WITH VERIFY_CLONEDB then?

I thought this will make a 100% clone of my selected database which will be ready for production and than this new cloned database can be used for "testing/inserting/updating/deleting". If this is not the way of making a "copy" of a database, can someone please tell me how to make a copy of a database "programmatically", not by hand doing a backup and than restoring that backup into a new database ...

If this won't work, I will simply use sqlcmd to create a backup and sqlcmd to import that backup into a new database.


问:
Eureka client registration with external git repo configuration files
I have an external configuration repository on git containing all my propertie files.
My eureka client is microservice-order with this application file :

```<code>spring.application.name=microservice-order
spring.config.import=configserver:http://localhost:9101
</code>```

This application file point to "microservice-order" propertie files :

```<code>server.port=9001
</code>```

spring.data.mongodb.uri=mongodb+srv://admin:************@cluster0.yqhwqrj.mongodb.net/Facebouffe?retryWrites=true&w=majority

```<code>#configurations
configs.setOrderLimit= 5

#eureka
spring.application.name = microservice-order
eureka.client.serviceUrl.defaultZone: http://localhost:9102/eureka/
</code>```

My eureka server has this propertie file :
 spring.application.name=eureka-server spring.config.import=configserver:http://localhost:9101

pointing to exteral repo file "eureka-server.properties":
`

```<code>server.port= 9102

eureka.client.serviceUrl.defaultZone = http://localhost:9102/eureka/

eureka.client.registerWithEureka=false

eureka.client.fetchRegistry=false

spring.cloud.config.import-check.enabled=false`
</code>```

I wrote "@EnableEurekaServer" (eureka-service-discovery) for server class and "@EnableEurekaClient" for client class (microservice-order)
When i start configserver, its running on 9101 port
When i start eureka-service-discovery, its running on 9102 port
When i start microservice-order, its running on 9001 port
So, each class load its own propertie files, but when i connect to http://localhost:9102/ , there is no service registered.
Do you have any idea ?
thank you !

I'm trying to register an eureka client to eureka server with external propertie files repository on github.

Body:
I have an external configuration repository on git containing all my propertie files.
My eureka client is microservice-order with this application file :

spring.application.name=microservice-order
spring.config.import=configserver:http://localhost:9101

This application file point to "microservice-order" propertie files :

server.port=9001

spring.data.mongodb.uri=mongodb+srv://admin:************@cluster0.yqhwqrj.mongodb.net/Facebouffe?retryWrites=true&w=majority

#configurations
configs.setOrderLimit= 5

#eureka
spring.application.name = microservice-order
eureka.client.serviceUrl.defaultZone: http://localhost:9102/eureka/

My eureka server has this propertie file :
 spring.application.name=eureka-server spring.config.import=configserver:http://localhost:9101

pointing to exteral repo file "eureka-server.properties":
`

server.port= 9102

eureka.client.serviceUrl.defaultZone = http://localhost:9102/eureka/

eureka.client.registerWithEureka=false

eureka.client.fetchRegistry=false

spring.cloud.config.import-check.enabled=false`

I wrote "@EnableEurekaServer" (eureka-service-discovery) for server class and "@EnableEurekaClient" for client class (microservice-order)
When i start configserver, its running on 9101 port
When i start eureka-service-discovery, its running on 9102 port
When i start microservice-order, its running on 9001 port
So, each class load its own propertie files, but when i connect to http://localhost:9102/ , there is no service registered.
Do you have any idea ?
thank you !

I'm trying to register an eureka client to eureka server with external propertie files repository on github.


问:
Getting cors error in express and react app while redirecting when I use passport-local strategy and not when I use passport-google-oauth20
This is my back-end code.

```<code>import { config } from "dotenv"
import express,{Request,Response} from "express"
import mongoose, {ConnectOptions, Error} from "mongoose";
import DeckModal from './models/deck';
import cors from "cors"
import session from "express-session";
import passport from "passport";
import User from "./models/user";
import bcrypt from "bcryptjs"
import { UserDetails } from "./types/UserDetails";
import passportLocal from "passport-local"

const LocalStrategy=passportLocal.Strategy
const MongoDBStore = require('connect-mongodb-session')(session);
const GoogleStrategy =require("passport-google-oauth20")
config()

let PORT:number=5000

const app = express()

app.use(express.json())

const  store = new MongoDBStore({
  uri: process.env.MONGO_URI!,
  collection: 'mysessions'
});

store.on('error', function(error:Error) {
  console.log(error);
});

app.use(cors({ origin:"http://localhost:5173" ,credentials:true}))

app.set('trust proxy', 1)

// create session
app.use(session({
  secret:process.env.SESSION_SECRET!,
  resave:true,
  saveUninitialized:true,
  store:store,
  // cookie:{
  //   httpOnly:true, //An HttpOnly Cookie is a tag added to a browser cookie that prevents client-side scripts from accessing data
  //   sameSite:"none", // If your frontend and backend is hosted on different origin then use sameSite:none in order to share cookie.
  //   secure:true,      // it allows only https requests
  //   maxAge: 1000 * 60 * 60 * 24 * 7
  // }

}))

app.use(passport.initialize())
app.use(passport.session())

// local strategy
passport.use(new LocalStrategy(
  {usernameField:"email"},
  function(username, password, done) {
    User.findOne({ email: username }, function (err:Error, user:UserDetails) {
      if (err) { return done(err); }  // If there is error we will return an error to done function.
      if (!user) { return done(null, false); } // If we don't find any user then we will return null and as there is no error we will send false
      bcrypt.compare(password,user.password!,(err,result)=>{
        if(err) throw err
        if(result===true){
          return done(null,user)
        }
        else{
          return done(null,false)
        }
      })
    });
  }
));

//gooogle strategy

passport.use(
  new GoogleStrategy(
    {
      callbackURL: "/auth/google/callback",
      clientID: process.env.CLIENT_ID,
      clientSecret: process.env.CLIENT_SECRET,
    },
    async (accessToken:any, refreshToken:any, profile:any, done:any) => {
      const userInfo:UserDetails={
        email:profile.emails[0].value,
        profile_picture:profile.photos[0].value,
        username:profile.displayName
      }

      try{
        const user= await User.findOne({ email: profile.emails[0].value })
        if(!user){
           const newUser= new User(userInfo)
           await newUser.save()
    return done(null,newUser)
       }
      return  done(null,user)
      }
      catch(err){
         return  done(null,false,err)
      }

    }
  )
);

passport.serializeUser((user:any,done)=>{
  return done(null,user._id)
 })

 passport.deserializeUser((id:string,done)=>{

   User.findById(id,(err:Error,doc:any)=>{
    const userInfo={
      username:doc.username,
  email:doc.email,
  profile_picture:doc.profile_picture,
    }
     return done(null,userInfo)

   })
 })

// This is the recomended way to connect to the mongodb database using mongoose. source: https://docs.cyclic.sh/how-to/using-mongo-db#connection-example-mongoclient

mongoose.connect(process.env.MONGO_URI!,{
  useUnifiedTopology: true,
  useNewUrlParser: true
} as ConnectOptions )
.then(()=>{console.log("Connected to mongodb successfully");
// We will start to listen for request once the DB is connected
app.listen(process.env.PORT || PORT,()=>{
  console.log("server is running on port "+PORT)
})
})
.catch((err:Error)=>{console.log(err)});

//Google auth
app.get('/auth/google', passport.authenticate('google', {
  scope: ['profile','email']
  // scope:['openid','profile', 'email']
}));

app.get('/auth/google/callback',
  passport.authenticate('google', { failureRedirect: "http://localhost:5173/login", failureMessage: true,successRedirect:"http://localhost:5173/auth/success"}));

 app.get("/getuser",(req,res)=>{
  if(req.user){

    res.json(req.user) // here we get user in req.user because passports deserialize function attaches it automatically
  }
  else{
    res.json(null)
  }
 })

 app.post('/auth/logout', function(req, res, next) {
  req.logout(function(err) {
    if (err) { return next(err); }
    res.send('done');
  });
});

// Local auth
app.post("/signup",async(req:Request,res:Response)=>{
 const {username,email,password}=req?.body
 if(!username && !password && !email){
  res.send("Please provide name, email and password")
  return
 }
 try{
  const user:UserDetails | null=await User.findOne({username})
  if(!user){
   const hashedPassword=await bcrypt.hash(password,10)
   const newUser= new User({
     username,
     email,
     password:hashedPassword
   })
   await newUser.save()
   res.send("success")

  }
  else{
   res.send("User already exist")
  }
 }
 catch(error){
  console.log(error)
 }

})

  app.post('/login',
  passport.authenticate('local'),
  (req, res) => {
    if(req.user){
res.redirect("http://localhost:5173/auth/success")
    }
    else{
      res.status(200).json({success:false});

    }
  }
);
</code>```

I tried redirecting using successRedirect but that is also giving me same error

```<code>app.post('/login',
passport.authenticate('local',{successRedirect:"http://localhost:5173/auth/success"}));
</code>```

**
When I authenticate using google auth it successfully redirects me but when I use local startegy for authentication it gives me cors error.**

Error message:
Access to XMLHttpRequest at 'http://localhost:5173/' (redirected from 'http://localhost:5000/login') from origin 'http://localhost:5173' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

The front-tend request looks like this-

for local strategy:

```<code>const handleLogin = async (e:FormEvent<HTMLFormElement>) => {
  e.preventDefault()

    const data = {  email, password };

    axios.post("http://localhost:5000/login",data,{withCredentials:true})

}
</code>```

for google strategy:

```<code>  const handleGoogleLogin = async () => {
    window.open("http://localhost:5000/auth/google","_self")
  }
</code>```

Body:
This is my back-end code.

import { config } from "dotenv"
import express,{Request,Response} from "express"
import mongoose, {ConnectOptions, Error} from "mongoose";
import DeckModal from './models/deck';
import cors from "cors"
import session from "express-session";
import passport from "passport";
import User from "./models/user";
import bcrypt from "bcryptjs"
import { UserDetails } from "./types/UserDetails";
import passportLocal from "passport-local"

const LocalStrategy=passportLocal.Strategy
const MongoDBStore = require('connect-mongodb-session')(session);
const GoogleStrategy =require("passport-google-oauth20")
config()

let PORT:number=5000

const app = express()

app.use(express.json())

const  store = new MongoDBStore({
  uri: process.env.MONGO_URI!,
  collection: 'mysessions'
});

store.on('error', function(error:Error) {
  console.log(error);
});

app.use(cors({ origin:"http://localhost:5173" ,credentials:true}))

app.set('trust proxy', 1)

// create session
app.use(session({
  secret:process.env.SESSION_SECRET!,
  resave:true,
  saveUninitialized:true,
  store:store,
  // cookie:{
  //   httpOnly:true, //An HttpOnly Cookie is a tag added to a browser cookie that prevents client-side scripts from accessing data
  //   sameSite:"none", // If your frontend and backend is hosted on different origin then use sameSite:none in order to share cookie.
  //   secure:true,      // it allows only https requests
  //   maxAge: 1000 * 60 * 60 * 24 * 7
  // }

}))

app.use(passport.initialize())
app.use(passport.session())

// local strategy
passport.use(new LocalStrategy(
  {usernameField:"email"},
  function(username, password, done) {
    User.findOne({ email: username }, function (err:Error, user:UserDetails) {
      if (err) { return done(err); }  // If there is error we will return an error to done function.
      if (!user) { return done(null, false); } // If we don't find any user then we will return null and as there is no error we will send false
      bcrypt.compare(password,user.password!,(err,result)=>{
        if(err) throw err
        if(result===true){
          return done(null,user)
        }
        else{
          return done(null,false)
        }
      })
    });
  }
));

//gooogle strategy

passport.use(
  new GoogleStrategy(
    {
      callbackURL: "/auth/google/callback",
      clientID: process.env.CLIENT_ID,
      clientSecret: process.env.CLIENT_SECRET,
    },
    async (accessToken:any, refreshToken:any, profile:any, done:any) => {
      const userInfo:UserDetails={
        email:profile.emails[0].value,
        profile_picture:profile.photos[0].value,
        username:profile.displayName
      }

      try{
        const user= await User.findOne({ email: profile.emails[0].value })
        if(!user){
           const newUser= new User(userInfo)
           await newUser.save()
    return done(null,newUser)
       }
      return  done(null,user)
      }
      catch(err){
         return  done(null,false,err)
      }

    }
  )
);

passport.serializeUser((user:any,done)=>{
  return done(null,user._id)
 })

 passport.deserializeUser((id:string,done)=>{

   User.findById(id,(err:Error,doc:any)=>{
    const userInfo={
      username:doc.username,
  email:doc.email,
  profile_picture:doc.profile_picture,
    }
     return done(null,userInfo)

   })
 })

// This is the recomended way to connect to the mongodb database using mongoose. source: https://docs.cyclic.sh/how-to/using-mongo-db#connection-example-mongoclient

mongoose.connect(process.env.MONGO_URI!,{
  useUnifiedTopology: true,
  useNewUrlParser: true
} as ConnectOptions )
.then(()=>{console.log("Connected to mongodb successfully");
// We will start to listen for request once the DB is connected
app.listen(process.env.PORT || PORT,()=>{
  console.log("server is running on port "+PORT)
})
})
.catch((err:Error)=>{console.log(err)});

//Google auth
app.get('/auth/google', passport.authenticate('google', {
  scope: ['profile','email']
  // scope:['openid','profile', 'email']
}));

app.get('/auth/google/callback',
  passport.authenticate('google', { failureRedirect: "http://localhost:5173/login", failureMessage: true,successRedirect:"http://localhost:5173/auth/success"}));

 app.get("/getuser",(req,res)=>{
  if(req.user){

    res.json(req.user) // here we get user in req.user because passports deserialize function attaches it automatically
  }
  else{
    res.json(null)
  }
 })

 app.post('/auth/logout', function(req, res, next) {
  req.logout(function(err) {
    if (err) { return next(err); }
    res.send('done');
  });
});

// Local auth
app.post("/signup",async(req:Request,res:Response)=>{
 const {username,email,password}=req?.body
 if(!username && !password && !email){
  res.send("Please provide name, email and password")
  return
 }
 try{
  const user:UserDetails | null=await User.findOne({username})
  if(!user){
   const hashedPassword=await bcrypt.hash(password,10)
   const newUser= new User({
     username,
     email,
     password:hashedPassword
   })
   await newUser.save()
   res.send("success")

  }
  else{
   res.send("User already exist")
  }
 }
 catch(error){
  console.log(error)
 }

})

  app.post('/login',
  passport.authenticate('local'),
  (req, res) => {
    if(req.user){
res.redirect("http://localhost:5173/auth/success")
    }
    else{
      res.status(200).json({success:false});

    }
  }
);

I tried redirecting using successRedirect but that is also giving me same error

app.post('/login',
passport.authenticate('local',{successRedirect:"http://localhost:5173/auth/success"}));

**
When I authenticate using google auth it successfully redirects me but when I use local startegy for authentication it gives me cors error.**

Error message:
Access to XMLHttpRequest at 'http://localhost:5173/' (redirected from 'http://localhost:5000/login') from origin 'http://localhost:5173' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

The front-tend request looks like this-

for local strategy:

const handleLogin = async (e:FormEvent<HTMLFormElement>) => {
  e.preventDefault()

    const data = {  email, password };

    axios.post("http://localhost:5000/login",data,{withCredentials:true})

}

for google strategy:

  const handleGoogleLogin = async () => {
    window.open("http://localhost:5000/auth/google","_self")
  }


问:
How to deal with unstable queries in Firebase Realtime database in Android
I have been dealing with a really weird and frustrating problem for almost a year now. I have an Android app that (unfortunately) uses Firebase Realtime database. While some queries are stable, meaning they return the correct number of matching items, others are not stable. They just don't see the latest version of the database and thus return a wrong number of matching items. Here is for example a discussion I started 10 months ago, which has not been resolved (Firebase Query in Android returns random number of items altough multiple items match the query).

The problem with the unstable queries is, that they somehow query an internal representation of the database that is not always the current version. When I make some specific changes on the database, they don't see them.

Extremely weirdly, there are some countermeasures  that sometimes help, like for example

Execute the same query multiple times (about 20 times) within one second

Execute a stable query on the same database

Execute a generic query that just returns every item of the node before executing the real query

Querying on another attribute.

Strangely, for different unstable queries, different countermeasures may or may not work and there is no rationale behind that.

Once a unstable query has "updated its internal view" on the real database, it always returns the correct number of matching units, if the real database itself does not change.

I have already contacted the Firebase Google team but they could not help so far. What I can definitely rule out, is that the code of the query (Java) itself is wrong. My code is correct but somehow there seem to be some strange conflicts with something else.

My question to you is whether you have also experienced something similar and could think about a reason as to why this is happening or if you can think about a more universal coutermeasure. Especially I would like to know if there is a way to tell the Firebase handling threads in Android to update their "internal view" on the firebase before doing a query. This should not be confused with something like livedata. My problem is a fundamental one dealing with how the queries are exactly executed in Android.

Strangely, in my app I also have stable queries that always return the correct number of matching units. I'd say about 70 % are stable queries that always work with the current view of the real database. Unfortunately I have about 5 unstable queries and I am becoming more and more "anxious" of using Firebase as it provides an unreliable and random database querying system (and I am already quite frustrated as I have never seen anything like this before).

Does anyone of you have and idea what else I could do? I'll highly appreciate every comment.

Edit:
Here is an example of an unstable Firebase query:

```<code>DatabaseReference rootRef_Firebase = FirebaseDatabase.getInstance(FIREBASE_URL).getReference();
rootRef_Firebase
    .child("Orders")
    .orderByChild("oderID")
    .equalTo(2)
    .addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            for (DataSnapshot ds: dataSnapshot.getChildren()) {

                String itemName="";
                if (ds.child("name").getValue(String.class)!=null) {
                    itemName= ds.child("name").getValue(String.class);
                }

                }
            }
        }
        @Override
        public void onCancelled(DatabaseError databaseError) {
            throw databaseError.toException();
        }
    });
</code>```

Executed on this database:

```<code> "Orders": {
    "table_1_order_7_date_29-04-22_time_18-17-49": {
      "comment_Text": "",
      "name": "Order_A",
      "orderDate": "18:17 (29.04.22)",
      "orderDateInMilliseconds": 1651249069304,
      "orderID": 2,
      "orderOtherInfo": "",
      "orderStatus": "ordered",
      "quantity": 1,
      "tableNumber": 1
    },
    "table_1_order_8_date_29-04-22_time_18-17-52": {
      "comment_Text": "",
      "name": "Order_B",
      "orderDate": "18:17 (29.04.22)",
      "orderDateInMilliseconds": 1651249072115,
      "orderID": 2,
      "orderOtherInfo": "",
      "orderStatus": "prepared",
      "quantity": 1,
      "tableNumber": 1
    },
    "table_1_order_9_date_29-04-22_time_18-17-54": {
      "comment_Text": "",
      "name": "Order_C",
      "orderDate": "18:17 (29.04.22)",
      "orderDateInMilliseconds": 1651249074747,
      "orderID": 9,
      "orderOtherInfo": "",
      "orderStatus": "prepared",
      "quantity": 1,
      "tableNumber": 1
    }
  },
</code>```

Although there are 2 matching items, the unreliable service provided by the Firebase queries don't always return 2 items. Sometimes they don't return anything, sometimes only 1 item, sometimes 2.

Reminder: Unfortunately I still have this problem and the Firebase support Team could not help (or does not want to). Does anyone of you have any advice what I can do in order to deal with the unstable queries in Firebase Realtime Database?

Body:
I have been dealing with a really weird and frustrating problem for almost a year now. I have an Android app that (unfortunately) uses Firebase Realtime database. While some queries are stable, meaning they return the correct number of matching items, others are not stable. They just don't see the latest version of the database and thus return a wrong number of matching items. Here is for example a discussion I started 10 months ago, which has not been resolved (Firebase Query in Android returns random number of items altough multiple items match the query).

The problem with the unstable queries is, that they somehow query an internal representation of the database that is not always the current version. When I make some specific changes on the database, they don't see them.

Extremely weirdly, there are some countermeasures  that sometimes help, like for example

Execute the same query multiple times (about 20 times) within one second

Execute a stable query on the same database

Execute a generic query that just returns every item of the node before executing the real query

Querying on another attribute.

Strangely, for different unstable queries, different countermeasures may or may not work and there is no rationale behind that.

Once a unstable query has "updated its internal view" on the real database, it always returns the correct number of matching units, if the real database itself does not change.

I have already contacted the Firebase Google team but they could not help so far. What I can definitely rule out, is that the code of the query (Java) itself is wrong. My code is correct but somehow there seem to be some strange conflicts with something else.

My question to you is whether you have also experienced something similar and could think about a reason as to why this is happening or if you can think about a more universal coutermeasure. Especially I would like to know if there is a way to tell the Firebase handling threads in Android to update their "internal view" on the firebase before doing a query. This should not be confused with something like livedata. My problem is a fundamental one dealing with how the queries are exactly executed in Android.

Strangely, in my app I also have stable queries that always return the correct number of matching units. I'd say about 70 % are stable queries that always work with the current view of the real database. Unfortunately I have about 5 unstable queries and I am becoming more and more "anxious" of using Firebase as it provides an unreliable and random database querying system (and I am already quite frustrated as I have never seen anything like this before).

Does anyone of you have and idea what else I could do? I'll highly appreciate every comment.

Edit:
Here is an example of an unstable Firebase query:

DatabaseReference rootRef_Firebase = FirebaseDatabase.getInstance(FIREBASE_URL).getReference();
rootRef_Firebase
    .child("Orders")
    .orderByChild("oderID")
    .equalTo(2)
    .addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            for (DataSnapshot ds: dataSnapshot.getChildren()) {

                String itemName="";
                if (ds.child("name").getValue(String.class)!=null) {
                    itemName= ds.child("name").getValue(String.class);
                }

                }
            }
        }
        @Override
        public void onCancelled(DatabaseError databaseError) {
            throw databaseError.toException();
        }
    });

Executed on this database:

 "Orders": {
    "table_1_order_7_date_29-04-22_time_18-17-49": {
      "comment_Text": "",
      "name": "Order_A",
      "orderDate": "18:17 (29.04.22)",
      "orderDateInMilliseconds": 1651249069304,
      "orderID": 2,
      "orderOtherInfo": "",
      "orderStatus": "ordered",
      "quantity": 1,
      "tableNumber": 1
    },
    "table_1_order_8_date_29-04-22_time_18-17-52": {
      "comment_Text": "",
      "name": "Order_B",
      "orderDate": "18:17 (29.04.22)",
      "orderDateInMilliseconds": 1651249072115,
      "orderID": 2,
      "orderOtherInfo": "",
      "orderStatus": "prepared",
      "quantity": 1,
      "tableNumber": 1
    },
    "table_1_order_9_date_29-04-22_time_18-17-54": {
      "comment_Text": "",
      "name": "Order_C",
      "orderDate": "18:17 (29.04.22)",
      "orderDateInMilliseconds": 1651249074747,
      "orderID": 9,
      "orderOtherInfo": "",
      "orderStatus": "prepared",
      "quantity": 1,
      "tableNumber": 1
    }
  },

Although there are 2 matching items, the unreliable service provided by the Firebase queries don't always return 2 items. Sometimes they don't return anything, sometimes only 1 item, sometimes 2.

Reminder: Unfortunately I still have this problem and the Firebase support Team could not help (or does not want to). Does anyone of you have any advice what I can do in order to deal with the unstable queries in Firebase Realtime Database?


问:
Angular patch mapping headers in lazy update
I am new to angular, I am trying to build a simple crud angular application with jwt authentication and spring boot as backend. While using patch mapping headers are not set to headers array instead it was set to lazy update and I am getting not headers found in spring boot. Could anyone please help us on how to set the headers for patch mapping in angular. please find the below code.

```<code>resetPasswordRequest(token : string, userId : string, newPassword : string):Observable<any>{
var headers = new HttpHeaders().append("Authorization", "Bearer " + token);
headers.append('Content-Type', 'application/json');

const params = new HttpParams();
params.set('newPassword',newPassword);
console.log(headers);
return this.http.patch("http://localhost:8081/api/v1.0/apple/resetPassword/"+userId,{headers:headers});}
</code>```

Body:
I am new to angular, I am trying to build a simple crud angular application with jwt authentication and spring boot as backend. While using patch mapping headers are not set to headers array instead it was set to lazy update and I am getting not headers found in spring boot. Could anyone please help us on how to set the headers for patch mapping in angular. please find the below code.

resetPasswordRequest(token : string, userId : string, newPassword : string):Observable<any>{
var headers = new HttpHeaders().append("Authorization", "Bearer " + token);
headers.append('Content-Type', 'application/json');

const params = new HttpParams();
params.set('newPassword',newPassword);
console.log(headers);
return this.http.patch("http://localhost:8081/api/v1.0/apple/resetPassword/"+userId,{headers:headers});}


问:
C# telegram bot - need inline buttons to behave like / commands
I am creating a telegram bot and am currently using / commands to navigate through the bots menus and options, however I would like to use inline buttons for a neater look. The help I’ve found online has helped me to print buttons to the chat but I cannot figure out how to use them to act in a similar way as the / commands do

for example a command I have is /Topup which when clicked takes you to the topup menu (another telegram message with more / commands, I would like an inline button with the text “Topup” to do the same job however I can’t figure out the callback methods. I am using Telegram.bot version 18.0.0 in C#

I realize in older versions of Telegram.bot you can add an event listener using += but with 18.0.0 I am using

Bot.StartReceiving(updatehandler etc etc


问:
Oracle SQL Developer Debugger Date Parameter is always NULL
I am using SQL Developer Version 21.4.1.349.

I am using the interactive debugger with a procedure that accepts a Date parameter.

When the debugger launches, it presents a dialog so that I can provide a value for the parameter.

But, I don't know how to provide the date value.  I have tried the following:

providing a date string in the format of my NLS setting.

providing to_date('12/27/2022 10:20:00','mm/dd/yyyy hh24:mi:ss')

Neither test worked.  The date parameter is just set to NULL.

Is there a specific way a Date parameter should be provided when using the debugger?

Thanks


问:
How to keep empty space in xml tags as it is using xmbuilderjs2?
I am getting my xml response as below. It has empty space in between the tags.

```<code>............
<name> </name>
<address> </address>
<phone> </phone>
<zip> </zip>
.........
</code>```

When I parse my XML to json using xmlbuilderjs2 using below, it converts empty strings to empty object

```<code>const data = convert(xmlData, {
    format: 'object',
});

// response
{
  name:{},
  address: {},
  phone: {},
  zip: {},
}
</code>```

Expected response should be empty strings like below

```<code>{
  name:" ",
  address: " ",
  phone: " ",
  zip: " "
}
</code>```

How can I achieve this?

Thanks in advance.

Body:
I am getting my xml response as below. It has empty space in between the tags.

............
<name> </name>
<address> </address>
<phone> </phone>
<zip> </zip>
.........

When I parse my XML to json using xmlbuilderjs2 using below, it converts empty strings to empty object

const data = convert(xmlData, {
    format: 'object',
});

// response
{
  name:{},
  address: {},
  phone: {},
  zip: {},
}

Expected response should be empty strings like below

{
  name:" ",
  address: " ",
  phone: " ",
  zip: " "
}

How can I achieve this?

Thanks in advance.


问:
Copy all content of XML file from one to another XML file in groovy
I have 2 settings.xml file in 2 different servers, one is complete and the other has only one element  I want to copy only the contents of one xml file to another, I am carrying these operation through jenkins pipeline using groovy,

I have parsed both the files but not able to append one parsed data to another

Example of the complete settings.xml present in one file

```<code><settings>
    <servers>
        <server>
            <id>server1-pass</id>
            <username>${server.id}</username>
            <password>${server.password}</password>
        </server>
        <server>
            <id>server2-pass</id>
            <username>${server.id}</username>
            <password>${server.password}</password>
        </server>

    </servers>

    <mirrors>
        <mirror>
            <id>directory</id>
            <mirrorOf>external:*</mirrorOf>
            <url>http://stackoverflow.com</url>
        </mirror>
    </mirrors>

</settings>
</code>```

Another settings file

```<code><settings>
</settings>
</code>```

Method I tried to use to accomplish it

settingsObj2 contains the parsed data of needed to be filled settings.xml file and settingsObj contains parsed data the completed settings.xml file

```<code>settingsObj2.appendNode(settingsObj.servers)
</code>```

I tried the same with append() function but even that doesnot seem to work

Please help me with this

Body:
I have 2 settings.xml file in 2 different servers, one is complete and the other has only one element  I want to copy only the contents of one xml file to another, I am carrying these operation through jenkins pipeline using groovy,

I have parsed both the files but not able to append one parsed data to another

Example of the complete settings.xml present in one file

<settings>
    <servers>
        <server>
            <id>server1-pass</id>
            <username>${server.id}</username>
            <password>${server.password}</password>
        </server>
        <server>
            <id>server2-pass</id>
            <username>${server.id}</username>
            <password>${server.password}</password>
        </server>

    </servers>

    <mirrors>
        <mirror>
            <id>directory</id>
            <mirrorOf>external:*</mirrorOf>
            <url>http://stackoverflow.com</url>
        </mirror>
    </mirrors>

</settings>

Another settings file

<settings>
</settings>

Method I tried to use to accomplish it

settingsObj2 contains the parsed data of needed to be filled settings.xml file and settingsObj contains parsed data the completed settings.xml file

settingsObj2.appendNode(settingsObj.servers)

I tried the same with append() function but even that doesnot seem to work

Please help me with this


问:
Is there aws region latency test tool?
Is there a tool to test the latency of specific regions?

I have tried the cloudping.cloud but it only test the latency of my local network to other regions.

Is there a way to test latency between Austria to Zurich region? Or Austria to Milan Region?

Title: Is there aws region latency test tool?


问:
Telegram Bot & OpenAI - AttributeError: module 'telegram' has no attribute 'Bot'
The code of the Telegram bot is as followings:

```<code>import openai
import logging

# Set up logging
logging.basicConfig(level=logging.INFO)

# Set up the OpenAI API client
openai.api_key = "YOUR_API_KEY"

# Set up the Telegram API client
import telegram

bot = telegram.Bot(token="YOUR_BOT_TOKEN")

def handle_update(update):
  # Log the update
  logging.info("Received update: %s", update)

  # Get the message text and sender from the update
  text = update.message.text
  sender = update.message.from_user

  # Use the OpenAI API to generate a response
  response = openai.Completion.create(
    model="text-davinci-002",
    prompt=text,
    temperature=0.5,
    max_tokens=1024
  )

  # Log the response
  logging.info("Generated response: %s", response.text)

  # Send the response back to the sender
  bot.send_message(chat_id=sender.id, text=response.text)

# Set the update handler to our function
bot.set_update_handler(handle_update)

# Start the bot
bot.start_polling()
</code>```

The error message I got is:

```<code> File "/root/tgbot4.py", line 13, in <module>
    bot = telegram.bot(token="XXXXXXXXXXXX")
AttributeError: module 'telegram' has no attribute 'bot'`
</code>```

I used Telegram packages, one after one, to ensure I hit the right one. Just a stupid testing:

python-telegram-bot
pyTelegramBotAPI-4.8.0
telegram 0.0.1

Does anyone knows how I can solute it?

Body:
The code of the Telegram bot is as followings:

import openai
import logging

# Set up logging
logging.basicConfig(level=logging.INFO)

# Set up the OpenAI API client
openai.api_key = "YOUR_API_KEY"

# Set up the Telegram API client
import telegram

bot = telegram.Bot(token="YOUR_BOT_TOKEN")

def handle_update(update):
  # Log the update
  logging.info("Received update: %s", update)

  # Get the message text and sender from the update
  text = update.message.text
  sender = update.message.from_user

  # Use the OpenAI API to generate a response
  response = openai.Completion.create(
    model="text-davinci-002",
    prompt=text,
    temperature=0.5,
    max_tokens=1024
  )

  # Log the response
  logging.info("Generated response: %s", response.text)

  # Send the response back to the sender
  bot.send_message(chat_id=sender.id, text=response.text)

# Set the update handler to our function
bot.set_update_handler(handle_update)

# Start the bot
bot.start_polling()

The error message I got is:

 File "/root/tgbot4.py", line 13, in <module>
    bot = telegram.bot(token="XXXXXXXXXXXX")
AttributeError: module 'telegram' has no attribute 'bot'`

I used Telegram packages, one after one, to ensure I hit the right one. Just a stupid testing:

python-telegram-bot
pyTelegramBotAPI-4.8.0
telegram 0.0.1

Does anyone knows how I can solute it?


问:
How to do a partial contains search of mongdb object id with C#
we have a grid and there have multiple columns in the grid like product name,product details ,product id etc. all other fields working fine with partial contains search

But have issue with objectid in partial serach throws a below error.
Index was outside the bounds of the array .

Here is the code block

```<code>   var builder = Builders<T>.Filter;

            var filterQuery = builder.Where(s => s.Id != null);

         if (!string.IsNullOrWhiteSpace(ProductName))
            {
                filterQuery &= builder.Where(s => s.ProductName.ToLower().Contains(ProductName.ToLower()));
            }

     // Working fine with contains partial search

            if (!string.IsNullOrWhiteSpace(ProductId))
            {

soln 1: Not working
                 BsonObjectId id = new BsonObjectId(new ObjectId(ProductId));

                  filterQuery &= builder.Where(s => s.Id.Equals(id));

     //    solution 2

            filterQuery &= builder.Eq("_id", ObjectId.Parse(ProductId)); // now tried this not working

               }

soln 3: not working

   //filterQuery &= builder.Where(s=>s.Id==ObjectId.Parse(ProductId)).ToString();

finally we are passing the filter query variable into find for multiple filter

          var recordCount = await Collection.Find(filterQuery).CountDocumentsAsync();
            var endQuery = Collection.Find(filterQuery).SortBy(x => x.InitiationTimestamp).Skip((page - 1) * pagesize).Limit(pagesize);
            return (await endQuery.ToListAsync(), recordCount);
</code>```

tried below one not working.
https://stackoverflow.com/questions/14315684/query-mongodb-using-objectid#:~:text=In%20C%23%20for%20latest%20official%20MongoDB.Driver%20write%20this-,result%20without%20converting%20id%20from%20string%20to%20ObjectId.

Note : equal is working, problem with partial search

input:

**Actual Object id: "50ed4e7d5baffd13a44d0153"

Tried input id: "50ed4e7d"

O.p: error  index was outside the bounds of the array**

Body:
we have a grid and there have multiple columns in the grid like product name,product details ,product id etc. all other fields working fine with partial contains search

But have issue with objectid in partial serach throws a below error.
Index was outside the bounds of the array .

Here is the code block

   var builder = Builders<T>.Filter;

            var filterQuery = builder.Where(s => s.Id != null);

         if (!string.IsNullOrWhiteSpace(ProductName))
            {
                filterQuery &= builder.Where(s => s.ProductName.ToLower().Contains(ProductName.ToLower()));
            }

     // Working fine with contains partial search

            if (!string.IsNullOrWhiteSpace(ProductId))
            {

soln 1: Not working
                 BsonObjectId id = new BsonObjectId(new ObjectId(ProductId));

                  filterQuery &= builder.Where(s => s.Id.Equals(id));

     //    solution 2

            filterQuery &= builder.Eq("_id", ObjectId.Parse(ProductId)); // now tried this not working

               }

soln 3: not working

   //filterQuery &= builder.Where(s=>s.Id==ObjectId.Parse(ProductId)).ToString();

finally we are passing the filter query variable into find for multiple filter

          var recordCount = await Collection.Find(filterQuery).CountDocumentsAsync();
            var endQuery = Collection.Find(filterQuery).SortBy(x => x.InitiationTimestamp).Skip((page - 1) * pagesize).Limit(pagesize);
            return (await endQuery.ToListAsync(), recordCount);

tried below one not working.
https://stackoverflow.com/questions/14315684/query-mongodb-using-objectid#:~:text=In%20C%23%20for%20latest%20official%20MongoDB.Driver%20write%20this-,result%20without%20converting%20id%20from%20string%20to%20ObjectId.

Note : equal is working, problem with partial search

input:

**Actual Object id: "50ed4e7d5baffd13a44d0153"

Tried input id: "50ed4e7d"

O.p: error  index was outside the bounds of the array**


问:
What is the appropriate frequency and start/end date in R for ts()?
I have the following dataset which I want to make a time series object of for auto.arima forecasting:

```<code>head(df)

total_score return
1539    121.77
1074    422.18
901    -229.79
843     96.30
1101   -55.25
961    -48.28
</code>```

This data set contains of 13104 rows with each row representing sentiment score of tweets and BTC return on hourly basis, i.e. first row is 2021-01-01 00:00 and second row is 2021-01-01 01:00 and so on up until 2022-06-30 23:00. I have looked up how many hours fits in this range and that is 13103. How can I make my ts function such that I can use it for forecasting purposes in R auto.arima?
Moreover, I understand that auto.arima takes homoscedastic errors, whereas I need it to work for heteroscedastic errors. I also read that for this, I might use a GARCH model. However, if my auto.arima functions results in using a order of (2,0,0), does this mean that my GARCH model should be a (0,0,2)?

PS: I am still confused on why my data seems to be stationary, I was under the impression that crypto currencies are most likely NOT stationary, that is, the returns as well. But that is something for another time.

Body:
I have the following dataset which I want to make a time series object of for auto.arima forecasting:

head(df)

total_score return
1539    121.77
1074    422.18
901    -229.79
843     96.30
1101   -55.25
961    -48.28

This data set contains of 13104 rows with each row representing sentiment score of tweets and BTC return on hourly basis, i.e. first row is 2021-01-01 00:00 and second row is 2021-01-01 01:00 and so on up until 2022-06-30 23:00. I have looked up how many hours fits in this range and that is 13103. How can I make my ts function such that I can use it for forecasting purposes in R auto.arima?
Moreover, I understand that auto.arima takes homoscedastic errors, whereas I need it to work for heteroscedastic errors. I also read that for this, I might use a GARCH model. However, if my auto.arima functions results in using a order of (2,0,0), does this mean that my GARCH model should be a (0,0,2)?

PS: I am still confused on why my data seems to be stationary, I was under the impression that crypto currencies are most likely NOT stationary, that is, the returns as well. But that is something for another time.


问:
I want to perform a right click on the system tray icon but right click does not work in pywinauto when executed on RDP
I'm running the script in rdp session where i have installed pywinauto

click_input gives me an error like win32api.SetCursorPos((200,95)) error: (5, 'SetCursorPos', 'Access is denied.')

thereby i replaced it with click method,

but i wanted to do a right click on system tray icon, where click_input(button='right') doesn't work. Please help me with any alternate method of right click which works on rdp session.

thanks in advance


问:
Unity scripting, highlight UI button
I know that you can use EventSystem.current.SetSelectedGameObject(gameObject); to change button to select color, but how do you make it to highlighted color?

https://docs.unity3d.com/2019.1/Documentation/ScriptReference/EventSystems.EventSystem.SetSelectedGameObject.html
there's a EventSystems.BaseEventData pointer variable not sure what option i have under that, it might be the solution?

Title: Unity scripting, highlight UI button


问:
How can I send Message.info from admin to another user in Django
When someone user tries to publish an article. The user must wait for the approval/disapproval of this article from the admin.

after approving/disapproving their articles, the users must get Message.info. But these messages showed on the admin page, not on a user page

the disapproved message:

this is model.py

```<code>
class Article(models.Model):
    auther = models.ForeignKey(User, on_delete= models.CASCADE)
    title = models.CharField(max_length= 200, null = False)
    bio = models.CharField(max_length = 450, null = False)
    tags = TaggableManager()
    body = RichTextField()
    created_at = models.DateTimeField(auto_now_add = True)
    updated_at = models.DateTimeField(auto_now = True)
    approved = models.BooleanField('approved', default = 'False')

    def __str__(self):
        return self.title

</code>```

this viws.py :

```<code>
from django.contrib.auth.models import User
from article.models import Article

def delete_article(request, pk):
    model_article = apps.get_model('article','Article')
    if request.user.is_superuser:
        id_user = model_article.objects.get(pk = pk).auther_id

        model_article.objects.get(pk = pk).delete()
        messages.info(request,'  تم تنفيذ العملية بنجاح!' )
    for x in User.objects.all():
        if(x.id == id_user):
            messages.info(request,
        'تم حذف مقالك الجديد لأنه يخالف سياسة الموقع !')
            return redirect('main')

</code>```

But i want the message shwon to user who want to publish an article

Body:
When someone user tries to publish an article. The user must wait for the approval/disapproval of this article from the admin.

after approving/disapproving their articles, the users must get Message.info. But these messages showed on the admin page, not on a user page

the disapproved message:

this is model.py

class Article(models.Model):
    auther = models.ForeignKey(User, on_delete= models.CASCADE)
    title = models.CharField(max_length= 200, null = False)
    bio = models.CharField(max_length = 450, null = False)
    tags = TaggableManager()
    body = RichTextField()
    created_at = models.DateTimeField(auto_now_add = True)
    updated_at = models.DateTimeField(auto_now = True)
    approved = models.BooleanField('approved', default = 'False')

    def __str__(self):
        return self.title

this viws.py :

from django.contrib.auth.models import User
from article.models import Article

def delete_article(request, pk):
    model_article = apps.get_model('article','Article')
    if request.user.is_superuser:
        id_user = model_article.objects.get(pk = pk).auther_id

        model_article.objects.get(pk = pk).delete()
        messages.info(request,'  تم تنفيذ العملية بنجاح!' )
    for x in User.objects.all():
        if(x.id == id_user):
            messages.info(request,
        'تم حذف مقالك الجديد لأنه يخالف سياسة الموقع !')
            return redirect('main')

But i want the message shwon to user who want to publish an article


问:
Kubevirt vm ip different from pod ip?
i've read in the kubeivrt documentation that you can configure the vmi to use the pod ip. i am wondering why does my ip insde the machine is different from the pod ip.

vmi object ip -> vmi ip

inside vm ip -> inside vm ip

i am adding my vm object yaml:

```<code>apiVersion: kubevirt.io/v1alpha3
kind: VirtualMachine
metadata:
  generation: 1
  labels:
    kubevirt.io/os: windows
  name: vm3
spec:
  running: true
  template:
    metadata:
      labels:
        kubevirt.io/domain: vm3
    spec:
      domain:
        cpu:
          cores: 2
        devices:
          disks:
          - cdrom:
              bus: sata
            bootOrder: 2
            name: iso
          - disk:
              bus: virtio
            name: harddrive
            bootOrder: 1
          - cdrom:
              bus: sata
              readonly: true
            name: virtio-drivers
          interfaces:
            - name: default
              masquerade: {}
        machine:
          type: q35
        resources:
          requests:
            memory: 4096M
      networks:
      - name: default
        pod: {}
      volumes:
      - name: harddrive
        persistentVolumeClaim:
          claimName: premium-amen-2
      - name: iso
        persistentVolumeClaim:
          claimName: win2k19-iso-2
      - name:  virtio-drivers
        containerDisk:
          image: kubevirt/virtio-container-disk
</code>```

if anyone could help me, i would appreciate this a lot.

i tried to use the default pod networking (i am using kubenet in aks)

Title: Kubevirt vm ip different from pod ip?

Body:
i've read in the kubeivrt documentation that you can configure the vmi to use the pod ip. i am wondering why does my ip insde the machine is different from the pod ip.

vmi object ip -> vmi ip

inside vm ip -> inside vm ip

i am adding my vm object yaml:

apiVersion: kubevirt.io/v1alpha3
kind: VirtualMachine
metadata:
  generation: 1
  labels:
    kubevirt.io/os: windows
  name: vm3
spec:
  running: true
  template:
    metadata:
      labels:
        kubevirt.io/domain: vm3
    spec:
      domain:
        cpu:
          cores: 2
        devices:
          disks:
          - cdrom:
              bus: sata
            bootOrder: 2
            name: iso
          - disk:
              bus: virtio
            name: harddrive
            bootOrder: 1
          - cdrom:
              bus: sata
              readonly: true
            name: virtio-drivers
          interfaces:
            - name: default
              masquerade: {}
        machine:
          type: q35
        resources:
          requests:
            memory: 4096M
      networks:
      - name: default
        pod: {}
      volumes:
      - name: harddrive
        persistentVolumeClaim:
          claimName: premium-amen-2
      - name: iso
        persistentVolumeClaim:
          claimName: win2k19-iso-2
      - name:  virtio-drivers
        containerDisk:
          image: kubevirt/virtio-container-disk

if anyone could help me, i would appreciate this a lot.

i tried to use the default pod networking (i am using kubenet in aks)


问:
Intellij maven project "Could not find artifact ..."
I'm learning Intellj and Maven. This is my first Maven Archtype project and it ended up with errors:

Could not find artifact com.sun.jersey:jersey-client:jar:1.20-SNAPSHOT

Unresolved dependency: 'com.sun.jersey:jersey-servlet:jar:1.20-SNAPSHOT'

I need help with the following questions:

What caused these errors?

How can I resolve these errors?


问:
How to get a gif to show up on a blob
I have a function that brings users to a blob when a button is clicked and selections are made. The point is for them to click a download button and it take them to a blob with the gif on the page made based off their selections. I have working js/html/css that creates and downloads the gif for them but I am trying to now make code that makes the gif appear on the blob. It is successfully taking users to the blob but the gif is not appearing on the page. Any help would be appreciated.

js for creating the gif and sending users to the blob.

```<code>   var directory = '/directory/here';
// add an event listener for the 'change' event on the dropdown menu
dropdown_fg2.addEventListener('change', function() {

// check if the selectedValue1 and selectedValue2 variables have been assigned values
if (!isNaN(selectedValue1) && !isNaN(selectedValue2)) {

    // create an array of images
    var images = [];

    // set the starting image
    var startImage = selectedValue1;

    // set the ending image
    var endImage = selectedValue2;

    // set the step size for the images
    var step = 6;

    // create a loop to add the images to the array
    for (var i = startImage; i <= endImage; i += step) {
      var filePath = directory +"gfs_6hr_2m_temp_hour_"+i+ '.png';
      // add the image to the array
      images.push(filePath);
    }
      const downloadButton = document.getElementById('download-button2');

    // Handle the button click
    downloadButton.addEventListener('click', function () {
      /// Generate gif
    gifshot.createGIF({
      'images': images,
      'gifWidth': 1144,
      'gifHeight': 894,
      'interval': 0.33
    },function(obj) {
      if(!obj.error) {

const reader = new FileReader();

// Read the contents of the image file as a ArrayBuffer
reader.readAsArrayBuffer(obj.image);
reader.onload = function() {

// Create a Blob object that represents the GIF file
   const gifBlob = new Blob([reader.result], {type: 'image/gif'});

// Use the URL.createObjectURL() method to create a URL for the Blob
const gifUrl = URL.createObjectURL(gifBlob);
console.log(gifUrl)

window.open(gifUrl);
// You can then use the URL to open the GIF file in a new window or to display it on your website

// var animatedImage = document.createElement('img');
 var animatedImage =  document.getElementById('my-image')
animatedImage.src = gifUrl;
console.log(animatedImage)

      }
    });

    });
    console.log(images);
   }
})
</code>```

Title: How to get a gif to show up on a blob

Body:
I have a function that brings users to a blob when a button is clicked and selections are made. The point is for them to click a download button and it take them to a blob with the gif on the page made based off their selections. I have working js/html/css that creates and downloads the gif for them but I am trying to now make code that makes the gif appear on the blob. It is successfully taking users to the blob but the gif is not appearing on the page. Any help would be appreciated.

js for creating the gif and sending users to the blob.

   var directory = '/directory/here';
// add an event listener for the 'change' event on the dropdown menu
dropdown_fg2.addEventListener('change', function() {

// check if the selectedValue1 and selectedValue2 variables have been assigned values
if (!isNaN(selectedValue1) && !isNaN(selectedValue2)) {

    // create an array of images
    var images = [];

    // set the starting image
    var startImage = selectedValue1;

    // set the ending image
    var endImage = selectedValue2;

    // set the step size for the images
    var step = 6;

    // create a loop to add the images to the array
    for (var i = startImage; i <= endImage; i += step) {
      var filePath = directory +"gfs_6hr_2m_temp_hour_"+i+ '.png';
      // add the image to the array
      images.push(filePath);
    }
      const downloadButton = document.getElementById('download-button2');

    // Handle the button click
    downloadButton.addEventListener('click', function () {
      /// Generate gif
    gifshot.createGIF({
      'images': images,
      'gifWidth': 1144,
      'gifHeight': 894,
      'interval': 0.33
    },function(obj) {
      if(!obj.error) {

const reader = new FileReader();

// Read the contents of the image file as a ArrayBuffer
reader.readAsArrayBuffer(obj.image);
reader.onload = function() {

// Create a Blob object that represents the GIF file
   const gifBlob = new Blob([reader.result], {type: 'image/gif'});

// Use the URL.createObjectURL() method to create a URL for the Blob
const gifUrl = URL.createObjectURL(gifBlob);
console.log(gifUrl)

window.open(gifUrl);
// You can then use the URL to open the GIF file in a new window or to display it on your website

// var animatedImage = document.createElement('img');
 var animatedImage =  document.getElementById('my-image')
animatedImage.src = gifUrl;
console.log(animatedImage)

      }
    });

    });
    console.log(images);
   }
})


问:
map_dbl not found when clustening using silhouette method
I have a dataset that I want to cluster using the silhouette method, but when I get to line "avg_sil_values <- map_dbl(k.values, avg_sil)" I get the error: map_dbl not found. I have installed tidyverse and have also installed just purrr, but I am still getting the same error.

What can I do?

```<code>avg_sil <- function(k) {km.res <- kmeans(country_norm_ok, centers = k, nstart = 25)
s <- silhouette(km.res$cluster, dist(df))
mean(ss[, 3])}
k.values <- 2:15
avg_sil_values <- map_dbl(k.values, avg_sil)
plot(k.values, avg_sil_values, type = "b", pch = 19, frame = FALSE, xlab = "Number of clusters K", ylab = "Average Silhouettes")
</code>```

updated:

```<code>> avg_sil <- function(k) {km.res <- kmeans(country_norm_ok, centers = k, nstart = 25)
+ s <- silhouette(km.res$cluster, dist(df))
+ mean(ss[, 3])}
> k.values <- 2:15
> avg_sil_values <- map_dbl(k.values, avg_sil)
Error in silhouette(km.res$cluster, dist(df)) :
  no se pudo encontrar la función "silhouette"
Called from: .f(.x[[i]], ...)
Browse[1]> plot(k.values, avg_sil_values, type = "b", pch = 19, frame = FALSE, xlab = "Number of clusters K", ylab = "Average Silhouettes")
Error durante el wrapup: objeto 'avg_sil_values' no encontrado
Error: no more error handlers available (recursive errors?); invoking 'abort' restart
Browse[1]> function(k) {km.res <- kmeans(country_norm_ok, centers = k, nstart = 25)
+ s <- silhouette(km.res$cluster, dist(df))
+ mean(ss[, 3])}
function(k) {km.res <- kmeans(country_norm_ok, centers = k, nstart = 25)
s <- silhouette(km.res$cluster, dist(df))
mean(ss[, 3])}
<environment: 0x7f8429fa8f88>
Browse[1]>
</code>```

Body:
I have a dataset that I want to cluster using the silhouette method, but when I get to line "avg_sil_values <- map_dbl(k.values, avg_sil)" I get the error: map_dbl not found. I have installed tidyverse and have also installed just purrr, but I am still getting the same error.

What can I do?

avg_sil <- function(k) {km.res <- kmeans(country_norm_ok, centers = k, nstart = 25)
s <- silhouette(km.res$cluster, dist(df))
mean(ss[, 3])}
k.values <- 2:15
avg_sil_values <- map_dbl(k.values, avg_sil)
plot(k.values, avg_sil_values, type = "b", pch = 19, frame = FALSE, xlab = "Number of clusters K", ylab = "Average Silhouettes")

updated:

> avg_sil <- function(k) {km.res <- kmeans(country_norm_ok, centers = k, nstart = 25)
+ s <- silhouette(km.res$cluster, dist(df))
+ mean(ss[, 3])}
> k.values <- 2:15
> avg_sil_values <- map_dbl(k.values, avg_sil)
Error in silhouette(km.res$cluster, dist(df)) :
  no se pudo encontrar la función "silhouette"
Called from: .f(.x[[i]], ...)
Browse[1]> plot(k.values, avg_sil_values, type = "b", pch = 19, frame = FALSE, xlab = "Number of clusters K", ylab = "Average Silhouettes")
Error durante el wrapup: objeto 'avg_sil_values' no encontrado
Error: no more error handlers available (recursive errors?); invoking 'abort' restart
Browse[1]> function(k) {km.res <- kmeans(country_norm_ok, centers = k, nstart = 25)
+ s <- silhouette(km.res$cluster, dist(df))
+ mean(ss[, 3])}
function(k) {km.res <- kmeans(country_norm_ok, centers = k, nstart = 25)
s <- silhouette(km.res$cluster, dist(df))
mean(ss[, 3])}
<environment: 0x7f8429fa8f88>
Browse[1]>


问:
How to access MAMP Sub Domain over LAN
I'm currently working with MAMP and trying to set up a subdomain.

The root of my MAMP site is /Users/conor/Dev and this can be accessed at localhost on the actual machine and on my local network it can be accessed at http://conors-mac-mini.local and this works without any issues.

I have a folder within the folder above MyDojo which I would like to set up as a sub domain.

I have edited /Applications/MAMP/conf/appache/httpd.conf to contain the following

```<code>NameVirtualHost *:80

<VirtualHost *:80>
ServerName: localhost
DocumentRoot: /Users/conor/Dev
</VirtualHost>

<VirtualHost *:80>
ServerName: mydojo.localhost
DocumentRoot: /Users/conor/Dev/MyDojo
</VirtualHost>
</code>```

I have also edited /private/etc/hosts and added the following line

```<code>127.0.0.1    mydojo.localhost
</code>```

After the above changes, when I visit localhost on the local machine it displays the correct content and mydojo.localhost also displays the correct content.
However when I try from another machine on my network http://conors-mac-mini.local works fine but http://mydojo.conors-mac-mini.local gives an error saying it can't reach the page and DNS_PROBE_FINISHED_NXDOMAIN.

I think I may be missing something to be able to access the subdomain using http://mydojo.conors-mac-mini.local on my local network but I can't work out what.

Title: How to access MAMP Sub Domain over LAN

Body:
I'm currently working with MAMP and trying to set up a subdomain.

The root of my MAMP site is /Users/conor/Dev and this can be accessed at localhost on the actual machine and on my local network it can be accessed at http://conors-mac-mini.local and this works without any issues.

I have a folder within the folder above MyDojo which I would like to set up as a sub domain.

I have edited /Applications/MAMP/conf/appache/httpd.conf to contain the following

NameVirtualHost *:80

<VirtualHost *:80>
ServerName: localhost
DocumentRoot: /Users/conor/Dev
</VirtualHost>

<VirtualHost *:80>
ServerName: mydojo.localhost
DocumentRoot: /Users/conor/Dev/MyDojo
</VirtualHost>

I have also edited /private/etc/hosts and added the following line

127.0.0.1    mydojo.localhost

After the above changes, when I visit localhost on the local machine it displays the correct content and mydojo.localhost also displays the correct content.
However when I try from another machine on my network http://conors-mac-mini.local works fine but http://mydojo.conors-mac-mini.local gives an error saying it can't reach the page and DNS_PROBE_FINISHED_NXDOMAIN.

I think I may be missing something to be able to access the subdomain using http://mydojo.conors-mac-mini.local on my local network but I can't work out what.


问:
How to make python recognize env variables when is executed with sudo?
when without sudo like this:

```<code>alex@x-space:~$ ipython

In [1]: import os

In [2]: os.system('echo $LD_LIBRARY_PATH')
......
/root/.mujoco/mjpro150/bin:
</code>```

python can recognize env vars,but when with sudo to excute python:

```<code>alex@x-space:~$ sudo ipython   <------- sudo python

In [1]: import os

In [2]: os.system('echo $LD_LIBRARY_PATH')

Out[2]: 0
</code>```

As you can see $LD_LIBRARY_PATH is empty.

And I have add

```<code>export LD_LIBRARY_PATH=/root/.mujoco/mjpro150/bin:$LD_LIBRARY_PATH
</code>```

to

```<code>/root/.bashrc
/root/.profile
/etc/profile
/home/user/.bashrc
/home/user/.profile
</code>```

All doesn't work.So question is:

How to make python recognize env variables when is executed with sudo?

Body:
when without sudo like this:

alex@x-space:~$ ipython

In [1]: import os

In [2]: os.system('echo $LD_LIBRARY_PATH')
......
/root/.mujoco/mjpro150/bin:

python can recognize env vars,but when with sudo to excute python:

alex@x-space:~$ sudo ipython   <------- sudo python

In [1]: import os

In [2]: os.system('echo $LD_LIBRARY_PATH')

Out[2]: 0

As you can see $LD_LIBRARY_PATH is empty.

And I have add

export LD_LIBRARY_PATH=/root/.mujoco/mjpro150/bin:$LD_LIBRARY_PATH

to

/root/.bashrc
/root/.profile
/etc/profile
/home/user/.bashrc
/home/user/.profile

All doesn't work.So question is:

How to make python recognize env variables when is executed with sudo?


问:
In keycloak, the same password can have different secrets?
I was wondering if the same password on keycloak can have different secrets.
I am asking this because I had a pod with postgres and one with keycloak and the admin password was not working when accessing the keycloak admin page on the browser.
The reason for this was because on the sql dump file I used to restore the DB, there was already an admin user with a secret.
When I removed all the entries for the user admin on the DB dump it worked.
I assume the password for that user was admin and as such was wondering if my keycloak instance would add a different salt and as such the secret created on my machine be different than the secret stored in the DB dump, even for the same password.</p>


问:
NEXT-AUTH Sigin error callback with next-auth on production
I have a project build vith next and next-auth for authentication
On my local , run wirh 'yarn dev', everything is ok
On my build , run with 'yarn build' and 'yarn start', everything is ok
enter image description hereBut when i deploy it to production, i recieve a callback error signin
enter image description here

I have seen some issue on github about use NEXTAUTH_SECRECT in config env but it not working with me
here is my next auth config

```<code>export const authOptions: NextAuthOptions = {
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_ID,
      clientSecret: process.env.GOOGLE_SECRET,
    }),
    LineProvider({
      clientId: process.env.LINE_CLIENT_ID,
      clientSecret: process.env.LINE_CLIENT_SECRET,
    }),
    InstagramProvider({
      clientId: process.env.INSTAGRAM_CLIENT_ID,
      clientSecret: process.env.INSTAGRAM_SECRET_KEY,
    }),
    FacebookProvider({
      clientId: process.env.FACEBOOK_CLIENT_ID,
      clientSecret: process.env.FACEBOOK_CLIENT_SECRET,
      authorization: {
        params: { scope: undefined },
      },
    }),
    CredentialsProvider({
      id: 'ginCustomProvider',
      name: 'ginCustomProvider',
      credentials: {
        token: { type: 'text' },
      },
      async authorize(
        credentials
      ): Promise<Required<User & token & tokenGin> | null> {
        if (!credentials) return null;
        const res = await authSocialGin(credentials.token);
        if (!res) {
          return null;
        }
        return res;
      },
    }),
    CredentialsProvider({
      id: 'credentials',
      name: 'credentials',
      type: 'credentials',
      credentials: {
        username: { label: 'Username', type: 'text' },
        password: { label: 'Password', type: 'password' },
      },
      async authorize(credentials): Promise<Required<User & token> | null> {
        const res = await credentialLogin({
          username: credentials?.username,
          password: credentials?.password,
        });
        if (!res) {
          return null;
        }
        return res;
      },
    }),
  ],
  secret: process.env.NEXTAUTH_SECRET,
  session: {
    strategy: 'jwt',
  },
  theme: {
    colorScheme: 'light',
  },
  cookies: {
    sessionToken: {
      name: 'accessToken',
      options: { httpOnly: true, sameSite: 'lax', path: '/', secure: true },
    },
  },
  callbacks: {
    async jwt({ token, user, account }) {
      try {
        if (account && account?.provider === 'google' && account?.id_token) {
          const res = await authSocialGoogle(account.id_token);
          if (
            user &&
            isTokenExpired((<any>res)?.accessToken) &&
            (<any>res)?.refreshToken
          ) {
            const response = await requestToken((<any>res)?.refreshToken);
            return { ...token, ...response };
          }
          return {
            ...token,
            ...res,
            ...user,
          };
        }
        if (
          account &&
          account?.provider === 'instagram' &&
          account?.access_token
        ) {
          const res = await authSocialInstagram(account.access_token);
          if (
            user &&
            isTokenExpired((<any>res)?.accessToken) &&
            (<any>res)?.refreshToken
          ) {
            const response = await requestToken((<any>res)?.refreshToken);
            return { ...token, ...response };
          }
          return {
            ...token,
            ...res,
            ...user,
          };
        }
        if (
          account &&
          account?.provider === 'facebook' &&
          account?.access_token
        ) {
          const res = await authSocialFaceBook(account.access_token);
          if (
            user &&
            isTokenExpired((<any>res)?.accessToken) &&
            (<any>res)?.refreshToken
          ) {
            const response = await requestToken((<any>res)?.refreshToken);
            return { ...token, ...response };
          }
          return {
            ...token,
            ...res,
            ...user,
          };
        }
        if (account && account?.provider === 'line' && account?.id_token) {
          const res = await authSocialLine(account.id_token);
          return {
            ...token,
            ...user,
            ...res,
          };
        }
        if (account && account?.provider === 'credentials') {
          return {
            ...token,
            ...user,
          };
        }
        if (account && account?.provider === 'ginCustomProvider') {
          return {
            ...token,
            ...user,
          };
        }
        if (
          token &&
          isTokenExpired(<any>token?.accessToken) &&
          token?.refreshToken
        ) {
          const responseRefreshToken = await requestToken(
            (<any>token)?.refreshToken
          );
          return { ...token, ...responseRefreshToken };
        }
        return token;
      } catch (error) {
        throw error;
      }
    },
    async session({ session, token }): Promise<Session> {
      const tokenId = token.accessToken;
      try {
        if (tokenId) {
          session.user = tokenId;
        } else {
          session.user = { name: '', email: '' };
        }
        return session;
      } catch (error) {
        throw error;
      }
    },
    async redirect({ url, baseUrl }) {
      // Allows relative callback URLs
      if (url.startsWith('/ginCustomProvider')) {
        const fullUrl = `${baseUrl}/${url}`;
        return fullUrl.split('?')[0];
      }
      // Allows callback URLs on the same origin
      else if (new URL(url).origin === baseUrl) return url;
      return baseUrl;
    },
  },
};

export default NextAuth(authOptions);
</code>```

here is my package.json

```<code>{
  "name": "minakomi-frontend-webpage",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint"
  },
  "dependencies": {
    "@emotion/react": "^11.10.5",
    "@emotion/styled": "^11.10.5",
    "@hookform/resolvers": "^2.9.10",
    "@mui/icons-material": "^5.10.16",
    "@mui/material": "^5.10.17",
    "@mui/x-date-pickers": "^5.0.7",
    "@reduxjs/toolkit": "^1.9.0",
    "@sls-next/serverless-component": "3.7.0",
    "ahooks": "^3.7.2",
    "axios": "^1.1.3",
    "dayjs": "^1.11.6",
    "i18next": "^22.0.6",
    "lodash": "^4.17.21",
    "moment": "^2.29.4",
    "next": "12.2.5",
    "next-auth": "4.15.1",
    "next-i18next": "^13.0.0",
    "next-share": "^0.19.0",
    "notistack": "^2.0.8",
    "qs": "^6.11.0",
    "react": "18.2.0",
    "react-dom": "18.2.0",
    "react-hook-form": "^7.39.3",
    "react-i18next": "^12.0.0",
    "react-infinite-scroll-component": "^6.1.0",
    "react-loader-spinner": "^5.3.4",
    "react-phone-number-input": "^3.2.12",
    "react-query": "^3.39.2",
    "react-redux": "^8.0.5",
    "react-toastify": "^9.1.1",
    "styled-components": "^5.3.5",
    "yup": "^0.32.11"
  },
  "devDependencies": {
    "@babel/parser": "^7.19.1",
    "@types/node": "^18.7.18",
    "@types/qs": "^6.9.7",
    "@types/react": "18.0.20",
    "@types/react-dom": "18.0.6",
    "@types/styled-components": "^5.1.26",
    "@typescript-eslint/eslint-plugin": "^5.42.0",
    "@typescript-eslint/parser": "^5.42.0",
    "eslint": "^8.26.0",
    "eslint-config-next": "12.3.0",
    "eslint-config-prettier": "^8.5.0",
    "eslint-import-resolver-typescript": "^3.5.2",
    "eslint-plugin-prettier": "^4.2.1",
    "prettier": "^2.7.1",
    "typescript": "4.8.3"
  }
}

</code>```

I don't know about this bug, I've read lots of doccument but can't resolve, so please anyone tell me what's wrong on production

Body:
I have a project build vith next and next-auth for authentication
On my local , run wirh 'yarn dev', everything is ok
On my build , run with 'yarn build' and 'yarn start', everything is ok
enter image description hereBut when i deploy it to production, i recieve a callback error signin
enter image description here

I have seen some issue on github about use NEXTAUTH_SECRECT in config env but it not working with me
here is my next auth config

export const authOptions: NextAuthOptions = {
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_ID,
      clientSecret: process.env.GOOGLE_SECRET,
    }),
    LineProvider({
      clientId: process.env.LINE_CLIENT_ID,
      clientSecret: process.env.LINE_CLIENT_SECRET,
    }),
    InstagramProvider({
      clientId: process.env.INSTAGRAM_CLIENT_ID,
      clientSecret: process.env.INSTAGRAM_SECRET_KEY,
    }),
    FacebookProvider({
      clientId: process.env.FACEBOOK_CLIENT_ID,
      clientSecret: process.env.FACEBOOK_CLIENT_SECRET,
      authorization: {
        params: { scope: undefined },
      },
    }),
    CredentialsProvider({
      id: 'ginCustomProvider',
      name: 'ginCustomProvider',
      credentials: {
        token: { type: 'text' },
      },
      async authorize(
        credentials
      ): Promise<Required<User & token & tokenGin> | null> {
        if (!credentials) return null;
        const res = await authSocialGin(credentials.token);
        if (!res) {
          return null;
        }
        return res;
      },
    }),
    CredentialsProvider({
      id: 'credentials',
      name: 'credentials',
      type: 'credentials',
      credentials: {
        username: { label: 'Username', type: 'text' },
        password: { label: 'Password', type: 'password' },
      },
      async authorize(credentials): Promise<Required<User & token> | null> {
        const res = await credentialLogin({
          username: credentials?.username,
          password: credentials?.password,
        });
        if (!res) {
          return null;
        }
        return res;
      },
    }),
  ],
  secret: process.env.NEXTAUTH_SECRET,
  session: {
    strategy: 'jwt',
  },
  theme: {
    colorScheme: 'light',
  },
  cookies: {
    sessionToken: {
      name: 'accessToken',
      options: { httpOnly: true, sameSite: 'lax', path: '/', secure: true },
    },
  },
  callbacks: {
    async jwt({ token, user, account }) {
      try {
        if (account && account?.provider === 'google' && account?.id_token) {
          const res = await authSocialGoogle(account.id_token);
          if (
            user &&
            isTokenExpired((<any>res)?.accessToken) &&
            (<any>res)?.refreshToken
          ) {
            const response = await requestToken((<any>res)?.refreshToken);
            return { ...token, ...response };
          }
          return {
            ...token,
            ...res,
            ...user,
          };
        }
        if (
          account &&
          account?.provider === 'instagram' &&
          account?.access_token
        ) {
          const res = await authSocialInstagram(account.access_token);
          if (
            user &&
            isTokenExpired((<any>res)?.accessToken) &&
            (<any>res)?.refreshToken
          ) {
            const response = await requestToken((<any>res)?.refreshToken);
            return { ...token, ...response };
          }
          return {
            ...token,
            ...res,
            ...user,
          };
        }
        if (
          account &&
          account?.provider === 'facebook' &&
          account?.access_token
        ) {
          const res = await authSocialFaceBook(account.access_token);
          if (
            user &&
            isTokenExpired((<any>res)?.accessToken) &&
            (<any>res)?.refreshToken
          ) {
            const response = await requestToken((<any>res)?.refreshToken);
            return { ...token, ...response };
          }
          return {
            ...token,
            ...res,
            ...user,
          };
        }
        if (account && account?.provider === 'line' && account?.id_token) {
          const res = await authSocialLine(account.id_token);
          return {
            ...token,
            ...user,
            ...res,
          };
        }
        if (account && account?.provider === 'credentials') {
          return {
            ...token,
            ...user,
          };
        }
        if (account && account?.provider === 'ginCustomProvider') {
          return {
            ...token,
            ...user,
          };
        }
        if (
          token &&
          isTokenExpired(<any>token?.accessToken) &&
          token?.refreshToken
        ) {
          const responseRefreshToken = await requestToken(
            (<any>token)?.refreshToken
          );
          return { ...token, ...responseRefreshToken };
        }
        return token;
      } catch (error) {
        throw error;
      }
    },
    async session({ session, token }): Promise<Session> {
      const tokenId = token.accessToken;
      try {
        if (tokenId) {
          session.user = tokenId;
        } else {
          session.user = { name: '', email: '' };
        }
        return session;
      } catch (error) {
        throw error;
      }
    },
    async redirect({ url, baseUrl }) {
      // Allows relative callback URLs
      if (url.startsWith('/ginCustomProvider')) {
        const fullUrl = `${baseUrl}/${url}`;
        return fullUrl.split('?')[0];
      }
      // Allows callback URLs on the same origin
      else if (new URL(url).origin === baseUrl) return url;
      return baseUrl;
    },
  },
};

export default NextAuth(authOptions);

here is my package.json

{
  "name": "minakomi-frontend-webpage",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint"
  },
  "dependencies": {
    "@emotion/react": "^11.10.5",
    "@emotion/styled": "^11.10.5",
    "@hookform/resolvers": "^2.9.10",
    "@mui/icons-material": "^5.10.16",
    "@mui/material": "^5.10.17",
    "@mui/x-date-pickers": "^5.0.7",
    "@reduxjs/toolkit": "^1.9.0",
    "@sls-next/serverless-component": "3.7.0",
    "ahooks": "^3.7.2",
    "axios": "^1.1.3",
    "dayjs": "^1.11.6",
    "i18next": "^22.0.6",
    "lodash": "^4.17.21",
    "moment": "^2.29.4",
    "next": "12.2.5",
    "next-auth": "4.15.1",
    "next-i18next": "^13.0.0",
    "next-share": "^0.19.0",
    "notistack": "^2.0.8",
    "qs": "^6.11.0",
    "react": "18.2.0",
    "react-dom": "18.2.0",
    "react-hook-form": "^7.39.3",
    "react-i18next": "^12.0.0",
    "react-infinite-scroll-component": "^6.1.0",
    "react-loader-spinner": "^5.3.4",
    "react-phone-number-input": "^3.2.12",
    "react-query": "^3.39.2",
    "react-redux": "^8.0.5",
    "react-toastify": "^9.1.1",
    "styled-components": "^5.3.5",
    "yup": "^0.32.11"
  },
  "devDependencies": {
    "@babel/parser": "^7.19.1",
    "@types/node": "^18.7.18",
    "@types/qs": "^6.9.7",
    "@types/react": "18.0.20",
    "@types/react-dom": "18.0.6",
    "@types/styled-components": "^5.1.26",
    "@typescript-eslint/eslint-plugin": "^5.42.0",
    "@typescript-eslint/parser": "^5.42.0",
    "eslint": "^8.26.0",
    "eslint-config-next": "12.3.0",
    "eslint-config-prettier": "^8.5.0",
    "eslint-import-resolver-typescript": "^3.5.2",
    "eslint-plugin-prettier": "^4.2.1",
    "prettier": "^2.7.1",
    "typescript": "4.8.3"
  }
}

I don't know about this bug, I've read lots of doccument but can't resolve, so please anyone tell me what's wrong on production