问:
How to use lazy initialization together with DIContainer in Spring4D
I'm new to Spring4D and trying to understand how to combine DIContainers with lazy loaded objects. I think i get the concept of pushing all the creation of the objects back in the callstack to the root of the application and register the types and invoke something or pass the solved objects using constructor/property/method injection. This way the project will only get dependency to interfaces in the seperate units and only get dependency to Spring in the root unit.

```<code>IMyClass = interface ['{593ABC29-B882-4B70-903F-52F381DD53BF}']
  procedure DoSomething;
end;

TMyClass = class(TInterfacedObject, IMyClass)
public
  procedure DoSomething;
end;

// In root of application
Container.RegisterType<TMyClass>;
Container.Resolve<IMyClass>.DoSomething;
</code>```

I see Spring4D has something called Lazy<T> for lazy loading, so in following example an instance of TMyClass is not created before referencing Value e.g.

```<code>  var LazyMyClassObjectFactory := TLazy<TMyClass>.Create;
  LazyMyClassObjectFactory.Value.DoSomething;
</code>```

My problem is 1. how do i combine a DIContainer with lazy loading (not quite sure how to resolve the interfaced lazy objects) and 2. can it be done without requiring Lazy<T> since i dont like the idea of becoming dependant on "spring" in all my units.

答:
Got it working some what, though I don't use Lazy\<T\>. Instead I register a factory and pass down the line. Not sure if this is the right way to go about it, but I only get dependencies to my unit with the interfaces this way.

```<code>IMyClass = interface ['{735BA720-F1D9-4138-85E1-44EA9DCAA773}']
  procedure DoSomething;
end;

IMyClassFactory = interface ['{7B1125D7-2639-4D4E-9909-28A08543F5FF}']
  function Create: IMyClass
end;

TMyClass = class(TInterfacedObject, IMyClass)
public
  procedure DoSomething;
end;

// From top-level root
GlobalContainer.RegisterType<IMyClass>;
GlobalContainer.RegisterFactory<IMyClassFactory>;
GlobalContainer.Build;

// Instanciate MyClassFactoryObject and pass it down to other units having params of type IMyClassFactory
var MyClassFactoryObject := GlobalContainer.Resolve<IMyClassFactory>;

// inside some other class
var MyClassObject := MyClassFactoryObject.Create;
MyClassObject.DoSomething;
</code>```

Body:
I'm new to Spring4D and trying to understand how to combine DIContainers with lazy loaded objects. I think i get the concept of pushing all the creation of the objects back in the callstack to the root of the application and register the types and invoke something or pass the solved objects using constructor/property/method injection. This way the project will only get dependency to interfaces in the seperate units and only get dependency to Spring in the root unit.

IMyClass = interface ['{593ABC29-B882-4B70-903F-52F381DD53BF}']
  procedure DoSomething;
end;

TMyClass = class(TInterfacedObject, IMyClass)
public
  procedure DoSomething;
end;

// In root of application
Container.RegisterType<TMyClass>;
Container.Resolve<IMyClass>.DoSomething;

I see Spring4D has something called Lazy<T> for lazy loading, so in following example an instance of TMyClass is not created before referencing Value e.g.

  var LazyMyClassObjectFactory := TLazy<TMyClass>.Create;
  LazyMyClassObjectFactory.Value.DoSomething;

My problem is 1. how do i combine a DIContainer with lazy loading (not quite sure how to resolve the interfaced lazy objects) and 2. can it be done without requiring Lazy<T> since i dont like the idea of becoming dependant on "spring" in all my units.

Body:
Got it working some what, though I don't use Lazy\<T\>. Instead I register a factory and pass down the line. Not sure if this is the right way to go about it, but I only get dependencies to my unit with the interfaces this way.

IMyClass = interface ['{735BA720-F1D9-4138-85E1-44EA9DCAA773}']
  procedure DoSomething;
end;

IMyClassFactory = interface ['{7B1125D7-2639-4D4E-9909-28A08543F5FF}']
  function Create: IMyClass
end;

TMyClass = class(TInterfacedObject, IMyClass)
public
  procedure DoSomething;
end;

// From top-level root
GlobalContainer.RegisterType<IMyClass>;
GlobalContainer.RegisterFactory<IMyClassFactory>;
GlobalContainer.Build;

// Instanciate MyClassFactoryObject and pass it down to other units having params of type IMyClassFactory
var MyClassFactoryObject := GlobalContainer.Resolve<IMyClassFactory>;

// inside some other class
var MyClassObject := MyClassFactoryObject.Create;
MyClassObject.DoSomething;


来源: stackexchange

问:
Minimum car required to accommodate given people
I had one coding round where question statement was like this

*You have a given number of friends and seating capacity of their cars now you need to find minimum number of cars required to accommodate them all.

Example:

```<code>People = [1, 4, 1]
SeatingCapacity = [1, 5, 1]
</code>```

In this case we need minimum 2 cars as number of people on 0th index can adjust with index 1 car.

Example 2:

```<code>People = [4, 4, 5, 3]
SeatingCapacity = [5, 5, 7, 3]
</code>```

This case answer will be as index 3 people can be accommodate into 0,1,2 or 1,2 index car*

I wrote code like this

int numberOfCars(int[] p, int[] s) {
    int noOfCars=p.length;
    Int extraSeats=0;

    for(int i=0;i<p.length;i++) {
        extraSeats+= (s[i] - p[i])
    }
    for(int i=0;i
=0){
            extraSeats-= p[i] ;
            noOfCars--;
        }
    }
    return noOfCars;
   }
```

However my code failed for many cases as well as it was saying some performance issue.
Can anyone please tell me which cases I missed?

答:
This can be solved by just greedy approach. Like below:

```<code>people = [1,4,1]
p = sum(people) //6
cars = [1,5,1]
sort(cars, descending) //cars = [5,1,1]
idx = 0
while(p > 0) { p -= cars[idx]; idx += 1 }
answer = idx
</code>```

Handle the corner case where total capacity in cars is less than number of people.

Complexity : sorting cars O(n log n) + while loop O(n) = O(n log n)

ContentLicense: CC BY-SA 4.0

Body:
I had one coding round where question statement was like this

*You have a given number of friends and seating capacity of their cars now you need to find minimum number of cars required to accommodate them all.

Example:

People = [1, 4, 1]
SeatingCapacity = [1, 5, 1]

In this case we need minimum 2 cars as number of people on 0th index can adjust with index 1 car.

Example 2:

People = [4, 4, 5, 3]
SeatingCapacity = [5, 5, 7, 3]

This case answer will be as index 3 people can be accommodate into 0,1,2 or 1,2 index car*

I wrote code like this

int numberOfCars(int[] p, int[] s) {
    int noOfCars=p.length;
    Int extraSeats=0;

    for(int i=0;i<p.length;i++) {
        extraSeats+= (s[i] - p[i])
    }
    for(int i=0;i
=0){
            extraSeats-= p[i] ;
            noOfCars--;
        }
    }
    return noOfCars;
   }

However my code failed for many cases as well as it was saying some performance issue.
Can anyone please tell me which cases I missed?

Body:
This can be solved by just greedy approach. Like below:

people = [1,4,1]
p = sum(people) //6
cars = [1,5,1]
sort(cars, descending) //cars = [5,1,1]
idx = 0
while(p > 0) { p -= cars[idx]; idx += 1 }
answer = idx

Handle the corner case where total capacity in cars is less than number of people.

Complexity : sorting cars O(n log n) + while loop O(n) = O(n log n)


问:
res.render showing html code than rendering the page
I am new to ejs and I am trying to render a page using it. Here is the code

```<code>app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.get ("/user",(req,res) =>{
  res.header("Content-Type",'application/json');
  var id_token_decode=jwt_decoder(req.session.tokenSet.id_token);
  var decoded = jwt_decoder(req.session.tokenSet.access_token);
  console.log(id_token_decode)
  console.log(decoded);
  console.log(path.join(__dirname + '/views/citizenHome.html'))
  res.render('citizenHome.ejs')

})
</code>```

It is showing the html code rather than actually rendering the page. Can anyone help me?

答:
Remove res.header("Content-Type",'application/json');   this line from the route

```<code>app.get ("/user",(req,res) =>{
  // res.header("Content-Type",'application/json');    <-- remove this line
  var id_token_decode=jwt_decoder(req.session.tokenSet.id_token);
  var decoded = jwt_decoder(req.session.tokenSet.access_token);
  console.log(id_token_decode)
  console.log(decoded);
  console.log(path.join(__dirname + '/views/citizenHome.html'))
  res.render('citizenHome.ejs')

})
</code>```

And also, what does /views/citizenHome.html this file do?

Body:
I am new to ejs and I am trying to render a page using it. Here is the code

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.get ("/user",(req,res) =>{
  res.header("Content-Type",'application/json');
  var id_token_decode=jwt_decoder(req.session.tokenSet.id_token);
  var decoded = jwt_decoder(req.session.tokenSet.access_token);
  console.log(id_token_decode)
  console.log(decoded);
  console.log(path.join(__dirname + '/views/citizenHome.html'))
  res.render('citizenHome.ejs')

})

It is showing the html code rather than actually rendering the page. Can anyone help me?

Body:
Remove res.header("Content-Type",'application/json');   this line from the route

app.get ("/user",(req,res) =>{
  // res.header("Content-Type",'application/json');    <-- remove this line
  var id_token_decode=jwt_decoder(req.session.tokenSet.id_token);
  var decoded = jwt_decoder(req.session.tokenSet.access_token);
  console.log(id_token_decode)
  console.log(decoded);
  console.log(path.join(__dirname + '/views/citizenHome.html'))
  res.render('citizenHome.ejs')

})

And also, what does /views/citizenHome.html this file do?


问:
Python: How to parse variables from several pandas dataframes?
I want to extract the x and y variables from several pandas dataframes (before proceeding to next steps). I initialize the tab-delimited .txt file, before I extract the information.
Error raised is ValueError: too many values to unpack (expected 2).

```<code>import pandas as pd

class DataProcessing:

    def __init__(self, data):
        self.df = pd.read_csv(data, sep="\t")
        X, y = self.df.iloc[1:, 1:]
        return X, y

dp_linear_cna = DataProcessing("data_linear_cna.txt")
dp_mrna_seq_v2_rsem = DataProcessing("data_mrna_seq_v2_rsem.txt")

dp_linear_cna.extract_info()
dp_mrna_seq_v2_rsem.extract_info()
</code>```

Traceback:

ValueError: too many values to unpack (expected 2)

答:
The sep="/t" is supposed to be sep="\t".

Never iterate over rows/columns, select data using index.
e.g. selecting a column: df['some_column_name']

Body:
I want to extract the x and y variables from several pandas dataframes (before proceeding to next steps). I initialize the tab-delimited .txt file, before I extract the information.
Error raised is ValueError: too many values to unpack (expected 2).

import pandas as pd

class DataProcessing:

    def __init__(self, data):
        self.df = pd.read_csv(data, sep="\t")
        X, y = self.df.iloc[1:, 1:]
        return X, y

dp_linear_cna = DataProcessing("data_linear_cna.txt")
dp_mrna_seq_v2_rsem = DataProcessing("data_mrna_seq_v2_rsem.txt")

dp_linear_cna.extract_info()
dp_mrna_seq_v2_rsem.extract_info()

Traceback:

ValueError: too many values to unpack (expected 2)


问:
test class type without specifying template argument in c++20
I would like to select instance by type while iterating via std::apply in a std::tuple.
Since I have multiple times the same class in my tuple I can not just use std::get

Is there a way to express that I want all the variant of A  instead of writting
 A< ... >

```<code>#include <iostream>
#include <tuple>

template <typename T>
struct A
{
    public:
        T val;

        A(T t) : val(t)
        {};
};

using MyType = std::tuple< A<double> , A<double> , A<int>, bool>;

template<typename T>
void logic(T& c)
{
    if constexpr ( std::is_same<T, A< ... > >::value)
        std::cout << c.val << std::endl;
}

void printOnlyA(MyType& v)
{
    std::apply([&](auto &&...c) { ( logic(c), ...); }, v);
}

int main() {

    A<double> a{3.5};
    A<double> b{5.5};
    A<int> c{2};

    MyType dd{std::make_tuple(a,b,c , false)};
    printOnlyA(dd);

    return 0;
}
</code>```

I m using c++ 20, and would like to avoid the old c++11 approach to std::false_type and std::true_type. I can not figure out the way to do it with concept

Thanks in advance

答:
You can use partial template specialization. Since partial specialization for functions is not a part of the language a dedicated class template is required:

```<code>#include <iostream>
#include <tuple>

template <typename T>
struct A
{
    public:
        T val;

        A(T t) : val(t)
        {};
};

using MyType = std::tuple< A<double> , A<double> , A<int>, bool>;

template<typename T>
struct logic_impl
{
    static void exec([[maybe_unused]] T & c)
    {
        // nothing
    }
};

template<typename T>
struct logic_impl<A<T>>
{
    static void exec(A<T> & c)
    {
        std::cout << c.val << std::endl;
    }
};

template<typename T>
void logic(T& c)
{
    logic_impl<T>::exec(c);
}

void printOnlyA(MyType& v)
{
    std::apply([&](auto &&... c) { (logic(c), ...); }, v);
}

int main() {

    A<double> a{3.5};
    A<double> b{5.5};
    A<int> c{2};

    MyType dd{std::make_tuple(a,b,c , false)};
    printOnlyA(dd);

    return 0;
}
</code>```

online compiler

Body:
I would like to select instance by type while iterating via std::apply in a std::tuple.
Since I have multiple times the same class in my tuple I can not just use std::get

Is there a way to express that I want all the variant of A  instead of writting
 A< ... >

#include <iostream>
#include <tuple>

template <typename T>
struct A
{
    public:
        T val;

        A(T t) : val(t)
        {};
};

using MyType = std::tuple< A<double> , A<double> , A<int>, bool>;

template<typename T>
void logic(T& c)
{
    if constexpr ( std::is_same<T, A< ... > >::value)
        std::cout << c.val << std::endl;
}

void printOnlyA(MyType& v)
{
    std::apply([&](auto &&...c) { ( logic(c), ...); }, v);
}

int main() {

    A<double> a{3.5};
    A<double> b{5.5};
    A<int> c{2};

    MyType dd{std::make_tuple(a,b,c , false)};
    printOnlyA(dd);

    return 0;
}

I m using c++ 20, and would like to avoid the old c++11 approach to std::false_type and std::true_type. I can not figure out the way to do it with concept

Thanks in advance

Body:
You can use partial template specialization. Since partial specialization for functions is not a part of the language a dedicated class template is required:

#include <iostream>
#include <tuple>

template <typename T>
struct A
{
    public:
        T val;

        A(T t) : val(t)
        {};
};

using MyType = std::tuple< A<double> , A<double> , A<int>, bool>;

template<typename T>
struct logic_impl
{
    static void exec([[maybe_unused]] T & c)
    {
        // nothing
    }
};

template<typename T>
struct logic_impl<A<T>>
{
    static void exec(A<T> & c)
    {
        std::cout << c.val << std::endl;
    }
};

template<typename T>
void logic(T& c)
{
    logic_impl<T>::exec(c);
}

void printOnlyA(MyType& v)
{
    std::apply([&](auto &&... c) { (logic(c), ...); }, v);
}

int main() {

    A<double> a{3.5};
    A<double> b{5.5};
    A<int> c{2};

    MyType dd{std::make_tuple(a,b,c , false)};
    printOnlyA(dd);

    return 0;
}

<a href="https://gcc.godbolt.org/#z:OYLghAFBqd5QCxAYwPYBMCmBRdBLAF1QCcAaPECAMzwBtMA7AQwFtMQByARg9KtQYEAysib0QXACx8BBAKoBnTAAUAHpwAMvAFYTStJg1DIApACYAQuYukl9ZATwDKjdAGFUtAK4sGEgMykrgAyeAyYAHI%2BAEaYxBLSAA6oCoRODB7evgGkyamOAqHhUSyx8VK2mPYFDEIETMQEmT5%2BAOyV1el1DQRFkTFxCbb1jc3Z7QojvWH9pYNSAJS2qF7EyOwc5v5hyN5YANQm/m5Ok8SYrEfYJhoAgls7e5iHxwReifRXN/d3BJgsHyYfxebgIAE9EoxWM8ACpfO5nLwOfY/e6tKx3fZY/aJLzRWh4ZAgb7Y0n7GH7ABuYiOGNuZOxJIZKIgFIIC32ICpYgg7KZDJM6MFABFad8RWK7t8vKkjPsALJgmEQ55HYX7SboEAgN4fTBHNwog3oFb4/X%2BbD7UhG44mvGfC1Wm0nQRXa3RVCeL7%2BOnfP4Agx/A3gyHMNjk%2BG3RHI2ioYCEgD6eAD4qFmOxkyBhKpqDw6H2mFUmGQEBMAFYrBWWEwwbEE14GDLMOhy6Ky%2BqKeYAGz7ZALfmHNP05kAehH%2BwYqAICDCwAHEqlrVFPvFv3%2BgKDrxVYdhkejBH2sfjyCTKeO92OcItkcFdNJmccyBzeYLRZLF7cV8t3d7/fTWNvAd7wILUUBWA8DQNXsADpqVoEEoM1bVXFoSVhwApdU2XX01wDIFzVBbdoQja87kpXN8yPQlWR/PtUzvbEqJPZMPgNL9kLfCA6JXRdRSlMiKJxYgwgIAB5BhaDBW4IEVZVIR/Sk/zRBisSQkAmESD4wVLCtu1bCAmC8IhDjMLtu2gizf0HCx9ggJiuKWfYLOg/sfUHYVrUUtCF1RET9mrMIIA5QD/0OUKPztM0rn2Jhb38aCywlHj0OdSKHUtaJbzLBKkpU50ROi0x0TMXL534lLZJVfZ0BbdE1OrABrTAE11egDNIaJSCfa0qDEJR%2B0w5LSUSYTBHEyTpJq1y8qAxlQvON5iAYfYNG8zC7g4JZaE4MteD8DgtFIVBODcaxrA1FY1lVMx/B4UgCE0TalgakAyw0fROEkPbHqOzheAUEB3oeg7NtIOBYBgRAwIBOg4nISg0Bh%2Bh4mALguDMPg6D%2BYgAYgaIfuiMIGjBTg7sRtgxokkmQdILBqyMcQafwc4HDwSlMABmnC2LIyNjukSqh%2BglomIYmPCwH6CGElhSdBqgDGABQADU8EwAB3UTQ1lmRBBEMR2AqfhBEUFR1Bp3QuH0QxjDOyx9DwaIAcgJZUESGpOYAWg9zU1VMSxrDMDR9g9gB1MR4NDwspaYYOQ8hdBDEff6qmLGoXAYdxPBaPQQhmEoyj0PI0gEMY/Etouaj6fP5g6VOuimUu9DsOuBG6Roq4Gcphh6RvLczdu887iQlgUS71j0KXMD50Hto4XbSH2w7jo4VQAA4uw9rtJH2YBkCfNHoLMWzTv9u39lwQgSBM27rQ8JG4mvrgFl4YGtAWZ7Xve2evtIGW3oXn6y9/qA3uo9JY4MobgVxAQeGXFUD3y7s2S%2BXcjbCFEOIQ2sgTZqElucaepA1ai0SLLLaO1vo02XqJIy0D9ioCoPsNeG8t47z3vsA%2BR8IB30SLDYgj9n6gJBu/UgCALhYHiEFD6HAf5/3eovXgQDbAgNfk9UgL1/6z38OQpef0BFv1IRwMwWj5E6OUUI9mON0ggEkEAA%3D" rel="nofollow noreferrer">online compiler


问:
get object response value
I got a response from the backend the response is an object how can I get the arrays from the object I tried to use Object entries but I can't get the arrays can you please help me

答:
You can use a for:

Example:

```<code>const cars = ["BMW", "Volvo", "Saab", "Ford", "Fiat", "Audi"];

let text = "";
for (let i = 0; i < cars.length; i++) {
  text += cars[i] + "<br>";
}

document.getElementById("demo").innerHTML = text;
</code>```

Source: https://www.w3schools.com/js/tryit.asp?filename=tryjs_loop_for

Title: get object response value

Body:
You can use a for:

Example:

const cars = ["BMW", "Volvo", "Saab", "Ford", "Fiat", "Audi"];

let text = "";
for (let i = 0; i < cars.length; i++) {
  text += cars[i] + "<br>";
}

document.getElementById("demo").innerHTML = text;

Source: https://www.w3schools.com/js/tryit.asp?filename=tryjs_loop_for


问:
how to handle assynchronous SQL query execution in node.js
I am new to node.js and mysql, I asked a similar question before, but my whole server is chaos, so I took sometime improving it. But I got back to the asynchronous problem:
How can I handle synchronous and assynchrounous MYSQL query execution: my function of signup would firstly run a query to look if the user is already registerd, and if not, create a user in the database.

```<code>// create a new user
User.signUp = (user, result) => {
    flag = true
    // Does Email adress has been registered?
    sql.query(`SELECT * FROM user_info WHERE EMAIL_ADRESS = ?`, user.username, (err, res) => {
        if (err) {
            console.log("error: ", err);
            result(err, null);
            return;
        }
        if (res.length) {
            //=========tell that it is registered=======/
            console.log("found user: ", res[0]);
            let judge = {
                isRegistered: true,
            };
            result(null, judge);
            flag = false
            return;
        }
    });
    // If not found: insert the user
    if(flag){
        console.log('No!!!!!!! in')
        const uLoginAuth = {
            USER_ID: user.id,
            EMAIL_ADRESS: user.username,
            PSWORD:user.password,
            VERIFIED: false,
            VERIFYCODE: uuid.v1()
        };

        const uInfo = {
            USER_ID: user.id,
            FIRST_NME: user.firstName,
            LAST_NME: user.lastName,
            USER_ROLE: user.role,
            EMAIL_ADRESS: user.username
        };

        sql.query("INSERT INTO user_info SET ?", uInfo, (err, res) => {
            if (err) {
                console.log("error: ", err);
                result(err, null);
                return;
            }
            console.log("created user: ", { id: res.insertId, ...user });
        });

        sql.query('INSERT INTO login_authentication SET ?', uLoginAuth, (err, res) => {
            if (err) {
                console.log("error: ", err);
                result(err, null);
                return;
            }
            console.log("created user: ", { id: res.insertId, ...user });
        });
        let judge = {
            isRegistered: true,
        };
        result(null, judge);
        return;
    }
};
</code>```

However, I am getting an error of: error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client which means I sent back my response twice, so I set the console.log to see, then I realize, when the user is already registered, I do get the correct response:

```<code>{
  "isRegistered": true
}
</code>```

but the code executes the lines that handle normal registration after comment // If not found
And here is the output of the program:

```<code>Server is running on port 8080.
Successfully connected to the database.
No!!!!!!! in
found user:  RowDataPacket {
  USER_ID: 'b7f632ef-a8b9-489f-b3eb-c8f25c2b5a32',
  FIRST_NME: 'Test',
  LAST_NME: 'Test',
  USER_ROLE: 'student',
  EMAIL_ADRESS: 'test@gmail.com'
}
</code>```

I have tried multiple way of wait until first query done to execute next line, but it does not work, in this case, can someone please help me on this? How could I wait until query is done?? Thank you!!!!!!!!

答:
So if I'm not wrong, here's what you're trying to here:

On user signUp, you're trying to check if the user already exists in DB.

If not, you're inserting it into the DB.

In either scenario, you're returning this as a response:

{
    isRegistered: true
}
```
<p>The <code>if</code> check you've put is not waiting for the first find/SELECT operation to finish and therefore is fired right when the <code>signUp</code> function is invoked (most probably when the user visits the signUp route).</p>
<p>This is the reason you can see the "No!!!!!!! in" console (synchronous, shown immediately) coming before the "found user: ..." log (async, shown after DB operation).</p>
<p>To fix this, you can structure your code like this:</p>
<pre class="lang-js prettyprint-override"><code>User.signUp = (user, result) => {
  let judge = {
    isRegistered: true,
  };

  // Does Email adress has been registered?
  sql.query(`SELECT * FROM user_info WHERE EMAIL_ADRESS = ?`, user.username, (err, res) => {
      if (err) {
          console.log("error: ", err);
          result(err, null);
          return;
      }
      if (res.length) {
          //=========tell that it is registered=======/
          console.log("found user: ", res[0]);
      } else { // <-------------- can make it "else if (preferred condition)" too
        console.log('No!!!!!!! in')
        const uLoginAuth = {
            USER_ID: user.id,
            EMAIL_ADRESS: user.username,
            PSWORD:user.password,
            VERIFIED: false,
            VERIFYCODE: uuid.v1()
        };

        const uInfo = {
            USER_ID: user.id,
            FIRST_NME: user.firstName,
            LAST_NME: user.lastName,
            USER_ROLE: user.role,
            EMAIL_ADRESS: user.username
        };

        sql.query("INSERT INTO user_info SET ?", uInfo, (err, res) => {
            if (err) {
                console.log("error: ", err);
                result(err, null);
                return;
            }
            console.log("created user: ", { id: res.insertId, ...user });
        });

        sql.query('INSERT INTO login_authentication SET ?', uLoginAuth, (err, res) => {
            if (err) {
                console.log("error: ", err);
                result(err, null);
                return;
            }
            console.log("created user: ", { id: res.insertId, ...user });
        });
      }

      result(null, judge);
  });
};
</code>```

Body:
I am new to node.js and mysql, I asked a similar question before, but my whole server is chaos, so I took sometime improving it. But I got back to the asynchronous problem:
How can I handle synchronous and assynchrounous MYSQL query execution: my function of signup would firstly run a query to look if the user is already registerd, and if not, create a user in the database.

// create a new user
User.signUp = (user, result) => {
    flag = true
    // Does Email adress has been registered?
    sql.query(`SELECT * FROM user_info WHERE EMAIL_ADRESS = ?`, user.username, (err, res) => {
        if (err) {
            console.log("error: ", err);
            result(err, null);
            return;
        }
        if (res.length) {
            //=========tell that it is registered=======/
            console.log("found user: ", res[0]);
            let judge = {
                isRegistered: true,
            };
            result(null, judge);
            flag = false
            return;
        }
    });
    // If not found: insert the user
    if(flag){
        console.log('No!!!!!!! in')
        const uLoginAuth = {
            USER_ID: user.id,
            EMAIL_ADRESS: user.username,
            PSWORD:user.password,
            VERIFIED: false,
            VERIFYCODE: uuid.v1()
        };

        const uInfo = {
            USER_ID: user.id,
            FIRST_NME: user.firstName,
            LAST_NME: user.lastName,
            USER_ROLE: user.role,
            EMAIL_ADRESS: user.username
        };

        sql.query("INSERT INTO user_info SET ?", uInfo, (err, res) => {
            if (err) {
                console.log("error: ", err);
                result(err, null);
                return;
            }
            console.log("created user: ", { id: res.insertId, ...user });
        });

        sql.query('INSERT INTO login_authentication SET ?', uLoginAuth, (err, res) => {
            if (err) {
                console.log("error: ", err);
                result(err, null);
                return;
            }
            console.log("created user: ", { id: res.insertId, ...user });
        });
        let judge = {
            isRegistered: true,
        };
        result(null, judge);
        return;
    }
};

However, I am getting an error of: error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client which means I sent back my response twice, so I set the console.log to see, then I realize, when the user is already registered, I do get the correct response:

{
  "isRegistered": true
}

but the code executes the lines that handle normal registration after comment // If not found
And here is the output of the program:

Server is running on port 8080.
Successfully connected to the database.
No!!!!!!! in
found user:  RowDataPacket {
  USER_ID: 'b7f632ef-a8b9-489f-b3eb-c8f25c2b5a32',
  FIRST_NME: 'Test',
  LAST_NME: 'Test',
  USER_ROLE: 'student',
  EMAIL_ADRESS: 'test@gmail.com'
}

I have tried multiple way of wait until first query done to execute next line, but it does not work, in this case, can someone please help me on this? How could I wait until query is done?? Thank you!!!!!!!!

Body:
So if I'm not wrong, here's what you're trying to here:

On user signUp, you're trying to check if the user already exists in DB.

If not, you're inserting it into the DB.

In either scenario, you're returning this as a response:

{
    isRegistered: true
}

The if check you've put is not waiting for the first find/SELECT operation to finish and therefore is fired right when the signUp function is invoked (most probably when the user visits the signUp route).

This is the reason you can see the "No!!!!!!! in" console (synchronous, shown immediately) coming before the "found user: ..." log (async, shown after DB operation).

To fix this, you can structure your code like this:

User.signUp = (user, result) => {
  let judge = {
    isRegistered: true,
  };

  // Does Email adress has been registered?
  sql.query(`SELECT * FROM user_info WHERE EMAIL_ADRESS = ?`, user.username, (err, res) => {
      if (err) {
          console.log("error: ", err);
          result(err, null);
          return;
      }
      if (res.length) {
          //=========tell that it is registered=======/
          console.log("found user: ", res[0]);
      } else { // <-------------- can make it "else if (preferred condition)" too
        console.log('No!!!!!!! in')
        const uLoginAuth = {
            USER_ID: user.id,
            EMAIL_ADRESS: user.username,
            PSWORD:user.password,
            VERIFIED: false,
            VERIFYCODE: uuid.v1()
        };

        const uInfo = {
            USER_ID: user.id,
            FIRST_NME: user.firstName,
            LAST_NME: user.lastName,
            USER_ROLE: user.role,
            EMAIL_ADRESS: user.username
        };

        sql.query("INSERT INTO user_info SET ?", uInfo, (err, res) => {
            if (err) {
                console.log("error: ", err);
                result(err, null);
                return;
            }
            console.log("created user: ", { id: res.insertId, ...user });
        });

        sql.query('INSERT INTO login_authentication SET ?', uLoginAuth, (err, res) => {
            if (err) {
                console.log("error: ", err);
                result(err, null);
                return;
            }
            console.log("created user: ", { id: res.insertId, ...user });
        });
      }

      result(null, judge);
  });
};


问:
Learning about Computer Vision
I am really intrigued by the field of computer vision and the potential it has. Are there any examples (preferably implemented in .NET) which I can study along with a reference book?</p>

答: I've done a bit of work with SIFT in the recent past and it seems to be a rather interesting modern algorithm for feature detection, which is one of the major (and perhaps more advanced) topics within machine vision. Someone has written a C# library for SIFT with a pretty nice example that can automatically stitch together separate photographs of the same scene. Admittedly, this isn't a very complete answer, and I can't recommend a reference book, but hopefully it should be of some use to you anyway...</p>

OwnerDisplayName: Ali Kazmi

ContentLicense: CC BY-SA 2.5

Title: Learning about Computer Vision

LastEditorDisplayName: Gortok

OwnerDisplayName: Noldorin


问:
IMAP Fetch Encoding
I'm trying to fetch some email info from gmail using imap like this

```<code>"(BODY.PEEK[HEADER.FIELDS (subject from date)] X-GM-MSGID X-GM-LABELS X-GM-THRID)"
</code>```

The problem is that it doesn't work well with special and accented characters. For example,

```<code>Stéphane Maniaci
</code>```

is rendered as

```<code>=?ISO-8859-1?Q?St=E9phane_Maniaci?=
</code>```

How do I tell Gmail to return the strings with an encoding of my choice, say I want Charset to be UTF-8.

How to adjust that in the IMAP command I mentioned above?

答:
Okay. I found out that email.utils can help out a lot here.

It has methods to parse date, emails, and any other information from imap messages.

It also has methods to decode imap strings. Like this

```<code>from email.header import decode_header
value, charset = decode_header(string_to_be_decoded)
</code>```

ContentLicense: CC BY-SA 3.0

Title: IMAP Fetch Encoding

Body:
I'm trying to fetch some email info from gmail using imap like this

"(BODY.PEEK[HEADER.FIELDS (subject from date)] X-GM-MSGID X-GM-LABELS X-GM-THRID)"

The problem is that it doesn't work well with special and accented characters. For example,

Stéphane Maniaci

is rendered as

=?ISO-8859-1?Q?St=E9phane_Maniaci?=

How do I tell Gmail to return the strings with an encoding of my choice, say I want Charset to be UTF-8.

How to adjust that in the IMAP command I mentioned above?

Body:
Okay. I found out that email.utils can help out a lot here.

It has methods to parse date, emails, and any other information from imap messages.

It also has methods to decode imap strings. Like this

from email.header import decode_header
value, charset = decode_header(string_to_be_decoded)


问:
Jackson Convert Object to String, property type is Integer, and getter return int, when property is null ,then throws null point exception?
I want convert Object to readable String , so I use Jackson to convert

```<code>public static class Test1{
    private String testStr;
    private Integer testInt;

    public String getTestStr() {
        return testStr;
    }

    public void setTestStr(String testStr) {
        this.testStr = testStr;
    }

    public int getTestInt() {
        return testInt;
    }

    public void setTestInt(int testInt) {
        this.testInt = testInt;
    }
}

public static ObjectWriter getWriter(){
    return new ObjectMapper()
            .setSerializationInclusion(JsonInclude.Include.NON_NULL)
            .writer();
}

@Test
public void testJackson(){
    Test1 test = new Test1();
    test.setTestStr("3333");

    try{
        String str = getWriter().writeValueAsString(test);
        System.out.println(str);
    } catch (JsonProcessingException e){
        log.warn("JsonUtil object to Str parse json error",e);
    }

}
</code>```

when i run testJackson, throws NullPointException

```<code> com.fasterxml.jackson.databind.JsonMappingException: (was java.lang.NullPointerException) (through reference chain: com.sino.test.order.OrderTest$Test1["testInt"])
at com.fasterxml.jackson.databind.JsonMappingException.wrapWithPath(JsonMappingException.java:390)
at com.fasterxml.jackson.databind.JsonMappingException.wrapWithPath(JsonMappingException.java:349)
at com.fasterxml.jackson.databind.ser.std.StdSerializer.wrapAndThrow(StdSerializer.java:316)
at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:778)
at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:178)
at com.fasterxml.jackson.databind.ser.DefaultSerializerProvider._serialize(DefaultSerializerProvider.java:480)
at com.fasterxml.jackson.databind.ser.DefaultSerializerProvider.serializeValue(DefaultSerializerProvider.java:319)
at com.fasterxml.jackson.databind.ObjectWriter$Prefetch.serialize(ObjectWriter.java:1514)
at com.fasterxml.jackson.databind.ObjectWriter._writeValueAndClose(ObjectWriter.java:1215)
at com.fasterxml.jackson.databind.ObjectWriter.writeValueAsString(ObjectWriter.java:1085). Caused by: java.lang.NullPointerException: null
at com.sino.test.order.OrderTest$Test1.getTestInt(OrderTest.java:54)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:689)
at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:770)
at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:178)
at com.fasterxml.jackson.databind.ser.DefaultSerializerProvider._serialize(DefaultSerializerProvider.java:480)
at com.fasterxml.jackson.databind.ser.DefaultSerializerProvider.serializeValue(DefaultSerializerProvider.java:319)
</code>```

if the entity return Integer, run test ok, but the entity is not created by me ,i can not edit the entity. And the entity not implements Serializable, so i want to know how to convert this object to string ?

答:
I find a solution.

not use jackson and fasterjson ,but Gson

```<code>Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
        String json = gson.toJson(test);
</code>```

Body:
I want convert Object to readable String , so I use Jackson to convert

public static class Test1{
    private String testStr;
    private Integer testInt;

    public String getTestStr() {
        return testStr;
    }

    public void setTestStr(String testStr) {
        this.testStr = testStr;
    }

    public int getTestInt() {
        return testInt;
    }

    public void setTestInt(int testInt) {
        this.testInt = testInt;
    }
}

public static ObjectWriter getWriter(){
    return new ObjectMapper()
            .setSerializationInclusion(JsonInclude.Include.NON_NULL)
            .writer();
}

@Test
public void testJackson(){
    Test1 test = new Test1();
    test.setTestStr("3333");

    try{
        String str = getWriter().writeValueAsString(test);
        System.out.println(str);
    } catch (JsonProcessingException e){
        log.warn("JsonUtil object to Str parse json error",e);
    }

}

when i run testJackson, throws NullPointException

 com.fasterxml.jackson.databind.JsonMappingException: (was java.lang.NullPointerException) (through reference chain: com.sino.test.order.OrderTest$Test1["testInt"])
at com.fasterxml.jackson.databind.JsonMappingException.wrapWithPath(JsonMappingException.java:390)
at com.fasterxml.jackson.databind.JsonMappingException.wrapWithPath(JsonMappingException.java:349)
at com.fasterxml.jackson.databind.ser.std.StdSerializer.wrapAndThrow(StdSerializer.java:316)
at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:778)
at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:178)
at com.fasterxml.jackson.databind.ser.DefaultSerializerProvider._serialize(DefaultSerializerProvider.java:480)
at com.fasterxml.jackson.databind.ser.DefaultSerializerProvider.serializeValue(DefaultSerializerProvider.java:319)
at com.fasterxml.jackson.databind.ObjectWriter$Prefetch.serialize(ObjectWriter.java:1514)
at com.fasterxml.jackson.databind.ObjectWriter._writeValueAndClose(ObjectWriter.java:1215)
at com.fasterxml.jackson.databind.ObjectWriter.writeValueAsString(ObjectWriter.java:1085). Caused by: java.lang.NullPointerException: null
at com.sino.test.order.OrderTest$Test1.getTestInt(OrderTest.java:54)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:689)
at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:770)
at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:178)
at com.fasterxml.jackson.databind.ser.DefaultSerializerProvider._serialize(DefaultSerializerProvider.java:480)
at com.fasterxml.jackson.databind.ser.DefaultSerializerProvider.serializeValue(DefaultSerializerProvider.java:319)

if the entity return Integer, run test ok, but the entity is not created by me ,i can not edit the entity. And the entity not implements Serializable, so i want to know how to convert this object to string ?

Body:
I find a solution.

not use jackson and fasterjson ,but Gson

Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
        String json = gson.toJson(test);


问:
How to enable swipe gesture to move to next tab for tabs module in Angular Material? (looking for a solution that works for more than 2 tabs)
I am using the tabs component in angular material: https://material.angular.io/components/component/tabs

Is there a way to make it such that I can swipe on the content area of the tab to trigger moving to the next tab?

My current template html:

```<code><md-tab-group>
  <md-tab label="Tab 1">Content 1</md-tab>
  <md-tab label="Tab 2">Content 2</md-tab>
</md-tab-group>
</code>```

I have hammerjs imported, and the documentation appears to not mention anything about this even though I could have sworn I've seen something like this before...

Specifically I want to be able to click and drag my mouse towards the left to have it swipe left to the left tab. And click and drag my mouse towards the right to have it swipe right ot the right tab.

答: None of the proposed solutions support interactive swipe gestures. If you need it; consider using a library like SwiperJs.</p>

Body:
I am using the tabs component in angular material: https://material.angular.io/components/component/tabs

Is there a way to make it such that I can swipe on the content area of the tab to trigger moving to the next tab?

My current template html:

<md-tab-group>
  <md-tab label="Tab 1">Content 1</md-tab>
  <md-tab label="Tab 2">Content 2</md-tab>
</md-tab-group>

I have hammerjs imported, and the documentation appears to not mention anything about this even though I could have sworn I've seen something like this before...

Specifically I want to be able to click and drag my mouse towards the left to have it swipe left to the left tab. And click and drag my mouse towards the right to have it swipe right ot the right tab.


问:
onPreviewFrame returns skewed YUV data
All right, I'm at my wit's end.  I'm writing a droid app that receives preview data, processes it, and then displays the altered data to the screen.  So far so good -- except for the fact that after some indeterminate amount of time (usually a minute or two) the YUV data that comes in during the onPreviewFrame callback is...rolled...horizontally.  I captured the raw yuv to the sd card:

[looks like I can't post pictures here yet, so here's the url: raw yuv capture]

This is my first droid app, but I've spent a lot of time working on various desktop video software.  The thing that immediately came to mind when I saw this was that I had a thread synchronization problem, and the buffer was getting overwritten in some strange way because of it.

And my code did use a worker thread initially.  So to eliminate this possibility that the issue was thread-releated, I took the worker thread out and put everything inside of onPreviewFrame.  Again, the same problem: skewed YUV data.

Then I did some googling and discovered that heavy processing inside of onPreviewFrame could result in random weirdness.  To circumvent that, I changed my callback to the OneShot variety, which resulted in the code I'm using now:

```<code>public void surfaceCreated(SurfaceHolder holder) {
    Log.i(TAG, "surfaceCreated");
    mCamera = Camera.open();
    mCamera.setOneShotPreviewCallback(new PreviewCallback() {

        public void onPreviewFrame(byte[] data, Camera camera) {

            Canvas canvas = mHolder.lockCanvas();
            try
            {
                Bitmap bmp = processFrame(data);
                if (bmp != null) {

                    if (canvas != null) {
                        canvas.drawBitmap(bmp, (canvas.getWidth() - getFrameWidth()) / 2, (canvas.getHeight() - getFrameHeight()) / 2, null);
                    }
                    bmp.recycle();
                }
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }
            finally
            {
                mHolder.unlockCanvasAndPost(canvas);
                mCamera.setOneShotPreviewCallback(this);
            }
        }
    });
}
</code>```

Unfortunately, I still get the skewed yuv data.

My testing device is an HTC EVO 4G.  I know this phone has its issues, but I'm wary to chalk this up to a hardware bug just yet, mainly because I'm almost certain it's due to programmer error.  Problem is, I've pared my code down to the bone, and the problem is still manifesting.

Has anybody encountered this before?

答:
Well, it looks like it's an issue with HTC phones.  This is the exact problem I'm having.  Over here they say it's caused by the rear camera lens coming loose and the solution is to push it in hard with your thumb for a few seconds to reseat it.

Not a software problem after all.

Title: onPreviewFrame returns skewed YUV data

Body:
All right, I'm at my wit's end.  I'm writing a droid app that receives preview data, processes it, and then displays the altered data to the screen.  So far so good -- except for the fact that after some indeterminate amount of time (usually a minute or two) the YUV data that comes in during the onPreviewFrame callback is...rolled...horizontally.  I captured the raw yuv to the sd card:

[looks like I can't post pictures here yet, so here's the url: raw yuv capture]

This is my first droid app, but I've spent a lot of time working on various desktop video software.  The thing that immediately came to mind when I saw this was that I had a thread synchronization problem, and the buffer was getting overwritten in some strange way because of it.

And my code did use a worker thread initially.  So to eliminate this possibility that the issue was thread-releated, I took the worker thread out and put everything inside of onPreviewFrame.  Again, the same problem: skewed YUV data.

Then I did some googling and discovered that heavy processing inside of onPreviewFrame could result in random weirdness.  To circumvent that, I changed my callback to the OneShot variety, which resulted in the code I'm using now:

public void surfaceCreated(SurfaceHolder holder) {
    Log.i(TAG, "surfaceCreated");
    mCamera = Camera.open();
    mCamera.setOneShotPreviewCallback(new PreviewCallback() {

        public void onPreviewFrame(byte[] data, Camera camera) {

            Canvas canvas = mHolder.lockCanvas();
            try
            {
                Bitmap bmp = processFrame(data);
                if (bmp != null) {

                    if (canvas != null) {
                        canvas.drawBitmap(bmp, (canvas.getWidth() - getFrameWidth()) / 2, (canvas.getHeight() - getFrameHeight()) / 2, null);
                    }
                    bmp.recycle();
                }
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }
            finally
            {
                mHolder.unlockCanvasAndPost(canvas);
                mCamera.setOneShotPreviewCallback(this);
            }
        }
    });
}

Unfortunately, I still get the skewed yuv data.

My testing device is an HTC EVO 4G.  I know this phone has its issues, but I'm wary to chalk this up to a hardware bug just yet, mainly because I'm almost certain it's due to programmer error.  Problem is, I've pared my code down to the bone, and the problem is still manifesting.

Has anybody encountered this before?


问:
Deserialize XML containing Properties and Values with Jackson
I'm trying to deserialize the following XML.

```<code><RESPONSE>
    <FIELDS>
        <FIELD KEY="MSG_VERSION">003</FIELD>
        <FIELD KEY="CUSTOMER_NBR">001</FIELD>
        ...
        <FIELD KEY="ORIGINAL_TYPE">RM1</FIELD>
    </FIELDS>
</RESPONSE>
</code>```

I need to capture the values from KEY properties and the values. Following is the Java class I have created.

```<code>package io.app.domain;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlText;
import lombok.Data;

import java.util.ArrayList;
import java.util.List;

@Data
@JsonInclude(JsonInclude.Include.NON_NULL)
@JacksonXmlRootElement(localName = "RESPONSE")
public class ResponseData {
    @JacksonXmlElementWrapper(localName = "FIELDS")
    @JacksonXmlProperty(localName = "FIELD")
    private List<Field> fields = new ArrayList<>();
    @Data
    public static class Field {
        @JacksonXmlProperty(isAttribute = true)
        private String key;
        @JacksonXmlText(value = true)
        private String content;
    }
}
</code>```

The XmlMapper has been initialized as follows.

```<code>private final XmlMapper xmlMapper = new XmlMapper();

xmlMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
xmlMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
</code>```

The issue is that, although the content is properly getting set, the key value is always null. What am I doing wrong here?

答:
Or you can have like below. (I haven't tried). More readable.

```<code>@JacksonXmlRootElement(localName = "RESPONSE")
class ResponseFields {

    @JacksonXmlProperty(localName = "FIELDS")
    @JacksonXmlElementWrapper(useWrapping = false)
    private Fields[] fields;

    //getters, setters, toString
}

class Fields {
    @JacksonXmlProperty(localName = "FIELD")
    private Field[] field;

    //getters, setters, toString
}

class Field {
    @JacksonXmlProperty(isAttribute = true)
    private String key;
    @JacksonXmlText(value = true)
    private String value;

    //getters, setters, toString
}
</code>```

And then;

```<code>XmlMapper mapper = new XmlMapper();
ResponseFields responseFields = mapper.readValue(XML, ResponseFields.class);
System.out.println(responseFields);
</code>```

Body:
I'm trying to deserialize the following XML.

<RESPONSE>
    <FIELDS>
        <FIELD KEY="MSG_VERSION">003</FIELD>
        <FIELD KEY="CUSTOMER_NBR">001</FIELD>
        ...
        <FIELD KEY="ORIGINAL_TYPE">RM1</FIELD>
    </FIELDS>
</RESPONSE>

I need to capture the values from KEY properties and the values. Following is the Java class I have created.

package io.app.domain;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlText;
import lombok.Data;

import java.util.ArrayList;
import java.util.List;

@Data
@JsonInclude(JsonInclude.Include.NON_NULL)
@JacksonXmlRootElement(localName = "RESPONSE")
public class ResponseData {
    @JacksonXmlElementWrapper(localName = "FIELDS")
    @JacksonXmlProperty(localName = "FIELD")
    private List<Field> fields = new ArrayList<>();
    @Data
    public static class Field {
        @JacksonXmlProperty(isAttribute = true)
        private String key;
        @JacksonXmlText(value = true)
        private String content;
    }
}

The XmlMapper has been initialized as follows.

private final XmlMapper xmlMapper = new XmlMapper();

xmlMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
xmlMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

The issue is that, although the content is properly getting set, the key value is always null. What am I doing wrong here?

Body:
Or you can have like below. (I haven't tried). More readable.

@JacksonXmlRootElement(localName = "RESPONSE")
class ResponseFields {

    @JacksonXmlProperty(localName = "FIELDS")
    @JacksonXmlElementWrapper(useWrapping = false)
    private Fields[] fields;

    //getters, setters, toString
}

class Fields {
    @JacksonXmlProperty(localName = "FIELD")
    private Field[] field;

    //getters, setters, toString
}

class Field {
    @JacksonXmlProperty(isAttribute = true)
    private String key;
    @JacksonXmlText(value = true)
    private String value;

    //getters, setters, toString
}

And then;

XmlMapper mapper = new XmlMapper();
ResponseFields responseFields = mapper.readValue(XML, ResponseFields.class);
System.out.println(responseFields);


问:
Changing position of the Dialog on screen android
I made a simple AlertDialog in my Activity:

```<code>View view = layoutInflater.inflate(R.layout.my_dialog, null);
AlertDialog infoDialog = new AlertDialog.Builder(MyActivity.this)
                    .setView(view)
                    .create();

infoDialog.show();
</code>```

With above code, the dialog shows at the (about) the center of the screen.

I am wondering, how can I customize the dialog position to make it showing just under the top Action Bar ? (Is there anyway to change the gravity or something of the dialog?) and how to do it based on my code??

答:
Java version of kotlin code suggested by A.I.Shakil :</p>
```<code> AlertDialog dialog = new AlertDialog.Builder(MainActivity.this)
            .setView(v)
            .setCancelable(false).create();
    dialog.getWindow().setGravity(Gravity.TOP);
    dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
    dialog.show();
</code>```

Body:
I made a simple AlertDialog in my Activity:

View view = layoutInflater.inflate(R.layout.my_dialog, null);
AlertDialog infoDialog = new AlertDialog.Builder(MyActivity.this)
                    .setView(view)
                    .create();

infoDialog.show();

With above code, the dialog shows at the (about) the center of the screen.

I am wondering, how can I customize the dialog position to make it showing just under the top Action Bar ? (Is there anyway to change the gravity or something of the dialog?) and how to do it based on my code??

Body:
Java version of kotlin code suggested by A.I.Shakil :

 AlertDialog dialog = new AlertDialog.Builder(MainActivity.this)
            .setView(v)
            .setCancelable(false).create();
    dialog.getWindow().setGravity(Gravity.TOP);
    dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
    dialog.show();


问:
PYQT: Issue when creating labels dynamically under layout using QThread
Have been working on project recently that includes creating labels labels on the fly based on the data coming from the API call. As Api call returns different data based on device config, thought it would be better to proceed with this approach. Instead of putting static labels and resetting them with each iteration.
The code works without issue as long it is not running using QThread but when trying to run it using QThread getting this error for each label that trying to add dynamically
Code block

```<code>self.vpn_label1 = QLabel('k')
self.vpn_label1.setObjectName('k')
self.vpn_label2 = QLabel('expired')
self.vpn_label2.setObjectName('k1')
self.grid.addWidget(self.vpn_label1, 0, 0)
self.grid.addWidget(self.vpn_label2, 0, 1)
</code>```

QObject::setParent: Cannot set parent, new parent is in a different thread
This is the sample code with code to add dynamic labels outside the QThreadpool function

```<code>from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *

import time
import traceback, sys

class WorkerSignals(QObject):
    finished = pyqtSignal()
    error = pyqtSignal(tuple)
    result = pyqtSignal(object)
    progress = pyqtSignal(float)

class Worker(QRunnable):
    """
    Worker thread

    Inherits from QRunnable to handler worker thread setup, signals and wrap-up.

    :param callback: The function callback to run on this worker thread. Supplied args and
                     kwargs will be passed through to the runner.
    :type callback: function
    :param args: Arguments to pass to the callback function
    :param kwargs: Keywords to pass to the callback function

    """

    def __init__(self, fn, *args, **kwargs):
        super(Worker, self).__init__()

        # Store constructor arguments (re-used for processing)
        self.fn = fn
        self.args = args
        self.kwargs = kwargs
        self.signals = WorkerSignals()

        # Add the callback to our kwargs
        self.kwargs['progress_callback'] = self.signals.progress

    @pyqtSlot()
    def run(self):
        """
        Initialise the runner function with passed args, kwargs.
        """

        # Retrieve args/kwargs here; and fire processing using them
        try:
            result = self.fn(*self.args, **self.kwargs)
        except:
            traceback.print_exc()
            exctype, value = sys.exc_info()[:2]
            self.signals.error.emit((exctype, value, traceback.format_exc()))
        else:
            self.signals.result.emit(result)  # Return the result of the processing
        finally:
            self.signals.finished.emit()  # Done

class MainWindow(QMainWindow):
    def __init__(self, *args, **kwargs):
        super(MainWindow, self).__init__(*args, **kwargs)

        self.vpn_label2 = None
        self.vpn_label1 = None
        self.n = None
        self.counter = 0

        layout = QVBoxLayout()

        self.l = QLabel("Start")
        b = QPushButton("DANGER!")
        b.pressed.connect(self.oh_no)
        self.grid = QGridLayout()

        layout.addWidget(self.l)
        layout.addWidget(b)
        layout.addLayout(self.grid)

        w = QWidget()
        w.setLayout(layout)

        self.vpn_label1 = QLabel('k') # <-----------------
        self.vpn_label1.setObjectName('k') #<--------------
        self.vpn_label2 = QLabel('expired') #<------------
        self.vpn_label2.setObjectName('k1') #<-------------
        self.grid.addWidget(self.vpn_label1, 0, 0) #<--------------
        self.grid.addWidget(self.vpn_label2, 0, 1) #<-------------

        self.setCentralWidget(w)
        self.show()
        self.threadpool = QThreadPool()
        print("Multithreading with maximum %d threads" % self.threadpool.maxThreadCount())

        self.timer = QTimer()
        self.timer.setInterval(1000)
        self.timer.timeout.connect(self.recurring_timer)
        self.timer.start()

    def progress_fn(self, n):
        print("%d%% done" % n)

    def execute_this_fn(self, progress_callback):

        self.n = 1
        self.check_flow(self.n)
        progress_callback.emit(self.n * 100 / 4)
        self.n += 1
        time.sleep(2)
        self.check_flow(self.n)
        progress_callback.emit(self.n * 100 / 4)
        self.n += 1
        time.sleep(2)
        self.check_flow(self.n)
        progress_callback.emit(self.n * 100 / 4)
        self.n += 1
        time.sleep(2)
        self.check_flow(self.n)
        progress_callback.emit(self.n * 100 / 4)

        return "Done."

    def print_output(self, s):
        print(s)

    def thread_complete(self):
        print("THREAD COMPLETE!")

    def check_flow(self, val):
        self.l.setText("Counter: %d" % val)

    def oh_no(self):
        # Pass the function to execute
        worker = Worker(self.execute_this_fn) # Any other args, kwargs are passed to the run function
        worker.signals.result.connect(self.print_output)
        worker.signals.finished.connect(self.thread_complete)
        worker.signals.progress.connect(self.progress_fn)

        # Execute
        self.threadpool.start(worker)

    def recurring_timer(self):
        self.counter +=1
        # self.l.setText("Counter: %d" % self.counter)

if __name__ == '__main__':
    app = QApplication([])
    window = MainWindow()
    app.exec_()
</code>```

The above code works without any issue. It can be seen in this screenshot where label with value 'k' and 'expired' are added to gridlayout in window
Works without issue

But when putting the code block inside the threadpool function execute_this_fn it throws error and it does not show those labels added to grid in window and it can be seen in this screenshot, where label with value 'k' and 'expired' are missing from gridlayout and cannot be seen in window.
Problem with QThread function

```<code> def execute_this_fn(self, progress_callback):
        # for n in range(0, 5):
        #     time.sleep(1)
        #     progress_callback.emit(n*100/4)

        self.vpn_label1 = QLabel('k') #<------------
        self.vpn_label1.setObjectName('k') #<------------
        self.vpn_label2 = QLabel('expired') #<------------
        self.vpn_label2.setObjectName('k1') #<------------
        self.grid.addWidget(self.vpn_label1, 0, 0) #<------------
        self.grid.addWidget(self.vpn_label2, 0, 1) #<------------

        self.n = 1
        self.check_flow(self.n)
        progress_callback.emit(self.n * 100 / 4)
        self.n += 1
        time.sleep(2)
        self.check_flow(self.n)
        progress_callback.emit(self.n * 100 / 4)
        self.n += 1
        time.sleep(2)
        self.check_flow(self.n)
        progress_callback.emit(self.n * 100 / 4)
        self.n += 1
        time.sleep(2)
        self.check_flow(self.n)
        progress_callback.emit(self.n * 100 / 4)

        return "Done."
</code>```
```<code>QObject::setParent: Cannot set parent, new parent is in a different thread
QObject::setParent: Cannot set parent, new parent is in a different thread

</code>```

This is just sample code but it illustrates the exact problem that getting.
Can someone please assist in figuring out the issue and suggest how to overcome it. Would be really helpful and much appreciated.

答:
In Qt, you can only update the GUI from the main thread. You can trigger changes to the GUI from another thread by using signals and slots. You emit a signal from another thread, and the slot will be executed in the main thread.

In your example, the execute_this_fn method is executed in another thread, so you can't change the GUI from there. The calls to progress_callback.emit in execute_this_fn results in the progress_fn method being executed in the main thread. If you put these 6 lines in progress_fn you won't have any issues:

        self.vpn_label1 = QLabel('k') #<------------
        self.vpn_label1.setObjectName('k') #<------------
        self.vpn_label2 = QLabel('expired') #<------------
        self.vpn_label2.setObjectName('k1') #<------------
        self.grid.addWidget(self.vpn_label1, 0, 0) #<------------
        self.grid.addWidget(self.vpn_label2, 0, 1) #<------------
```

There is a lot to learn about both Qt and multithreaded programming before you stop tripping up. I would recommend you at least finish reading Martin Fitzpatrick's book/blogs, which is where your code has come from. The documentation and articles on the Qt website are very good and are essential reading. I've also found the videos released by KDAB to be exceptionally good.

Body:
Have been working on project recently that includes creating labels labels on the fly based on the data coming from the API call. As Api call returns different data based on device config, thought it would be better to proceed with this approach. Instead of putting static labels and resetting them with each iteration.
The code works without issue as long it is not running using QThread but when trying to run it using QThread getting this error for each label that trying to add dynamically
Code block

self.vpn_label1 = QLabel('k')
self.vpn_label1.setObjectName('k')
self.vpn_label2 = QLabel('expired')
self.vpn_label2.setObjectName('k1')
self.grid.addWidget(self.vpn_label1, 0, 0)
self.grid.addWidget(self.vpn_label2, 0, 1)

QObject::setParent: Cannot set parent, new parent is in a different thread
This is the sample code with code to add dynamic labels outside the QThreadpool function

from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *

import time
import traceback, sys

class WorkerSignals(QObject):
    finished = pyqtSignal()
    error = pyqtSignal(tuple)
    result = pyqtSignal(object)
    progress = pyqtSignal(float)

class Worker(QRunnable):
    """
    Worker thread

    Inherits from QRunnable to handler worker thread setup, signals and wrap-up.

    :param callback: The function callback to run on this worker thread. Supplied args and
                     kwargs will be passed through to the runner.
    :type callback: function
    :param args: Arguments to pass to the callback function
    :param kwargs: Keywords to pass to the callback function

    """

    def __init__(self, fn, *args, **kwargs):
        super(Worker, self).__init__()

        # Store constructor arguments (re-used for processing)
        self.fn = fn
        self.args = args
        self.kwargs = kwargs
        self.signals = WorkerSignals()

        # Add the callback to our kwargs
        self.kwargs['progress_callback'] = self.signals.progress

    @pyqtSlot()
    def run(self):
        """
        Initialise the runner function with passed args, kwargs.
        """

        # Retrieve args/kwargs here; and fire processing using them
        try:
            result = self.fn(*self.args, **self.kwargs)
        except:
            traceback.print_exc()
            exctype, value = sys.exc_info()[:2]
            self.signals.error.emit((exctype, value, traceback.format_exc()))
        else:
            self.signals.result.emit(result)  # Return the result of the processing
        finally:
            self.signals.finished.emit()  # Done

class MainWindow(QMainWindow):
    def __init__(self, *args, **kwargs):
        super(MainWindow, self).__init__(*args, **kwargs)

        self.vpn_label2 = None
        self.vpn_label1 = None
        self.n = None
        self.counter = 0

        layout = QVBoxLayout()

        self.l = QLabel("Start")
        b = QPushButton("DANGER!")
        b.pressed.connect(self.oh_no)
        self.grid = QGridLayout()

        layout.addWidget(self.l)
        layout.addWidget(b)
        layout.addLayout(self.grid)

        w = QWidget()
        w.setLayout(layout)

        self.vpn_label1 = QLabel('k') # <-----------------
        self.vpn_label1.setObjectName('k') #<--------------
        self.vpn_label2 = QLabel('expired') #<------------
        self.vpn_label2.setObjectName('k1') #<-------------
        self.grid.addWidget(self.vpn_label1, 0, 0) #<--------------
        self.grid.addWidget(self.vpn_label2, 0, 1) #<-------------

        self.setCentralWidget(w)
        self.show()
        self.threadpool = QThreadPool()
        print("Multithreading with maximum %d threads" % self.threadpool.maxThreadCount())

        self.timer = QTimer()
        self.timer.setInterval(1000)
        self.timer.timeout.connect(self.recurring_timer)
        self.timer.start()

    def progress_fn(self, n):
        print("%d%% done" % n)

    def execute_this_fn(self, progress_callback):

        self.n = 1
        self.check_flow(self.n)
        progress_callback.emit(self.n * 100 / 4)
        self.n += 1
        time.sleep(2)
        self.check_flow(self.n)
        progress_callback.emit(self.n * 100 / 4)
        self.n += 1
        time.sleep(2)
        self.check_flow(self.n)
        progress_callback.emit(self.n * 100 / 4)
        self.n += 1
        time.sleep(2)
        self.check_flow(self.n)
        progress_callback.emit(self.n * 100 / 4)

        return "Done."

    def print_output(self, s):
        print(s)

    def thread_complete(self):
        print("THREAD COMPLETE!")

    def check_flow(self, val):
        self.l.setText("Counter: %d" % val)

    def oh_no(self):
        # Pass the function to execute
        worker = Worker(self.execute_this_fn) # Any other args, kwargs are passed to the run function
        worker.signals.result.connect(self.print_output)
        worker.signals.finished.connect(self.thread_complete)
        worker.signals.progress.connect(self.progress_fn)

        # Execute
        self.threadpool.start(worker)

    def recurring_timer(self):
        self.counter +=1
        # self.l.setText("Counter: %d" % self.counter)

if __name__ == '__main__':
    app = QApplication([])
    window = MainWindow()
    app.exec_()

The above code works without any issue. It can be seen in this screenshot where label with value 'k' and 'expired' are added to gridlayout in window
Works without issue

But when putting the code block inside the threadpool function execute_this_fn it throws error and it does not show those labels added to grid in window and it can be seen in this screenshot, where label with value 'k' and 'expired' are missing from gridlayout and cannot be seen in window.
Problem with QThread function

 def execute_this_fn(self, progress_callback):
        # for n in range(0, 5):
        #     time.sleep(1)
        #     progress_callback.emit(n*100/4)

        self.vpn_label1 = QLabel('k') #<------------
        self.vpn_label1.setObjectName('k') #<------------
        self.vpn_label2 = QLabel('expired') #<------------
        self.vpn_label2.setObjectName('k1') #<------------
        self.grid.addWidget(self.vpn_label1, 0, 0) #<------------
        self.grid.addWidget(self.vpn_label2, 0, 1) #<------------

        self.n = 1
        self.check_flow(self.n)
        progress_callback.emit(self.n * 100 / 4)
        self.n += 1
        time.sleep(2)
        self.check_flow(self.n)
        progress_callback.emit(self.n * 100 / 4)
        self.n += 1
        time.sleep(2)
        self.check_flow(self.n)
        progress_callback.emit(self.n * 100 / 4)
        self.n += 1
        time.sleep(2)
        self.check_flow(self.n)
        progress_callback.emit(self.n * 100 / 4)

        return "Done."

QObject::setParent: Cannot set parent, new parent is in a different thread
QObject::setParent: Cannot set parent, new parent is in a different thread

This is just sample code but it illustrates the exact problem that getting.
Can someone please assist in figuring out the issue and suggest how to overcome it. Would be really helpful and much appreciated.

Body:
In Qt, you can only update the GUI from the main thread. You can trigger changes to the GUI from another thread by using signals and slots. You emit a signal from another thread, and the slot will be executed in the main thread.

In your example, the execute_this_fn method is executed in another thread, so you can't change the GUI from there. The calls to progress_callback.emit in execute_this_fn results in the progress_fn method being executed in the main thread. If you put these 6 lines in progress_fn you won't have any issues:

        self.vpn_label1 = QLabel('k') #<------------
        self.vpn_label1.setObjectName('k') #<------------
        self.vpn_label2 = QLabel('expired') #<------------
        self.vpn_label2.setObjectName('k1') #<------------
        self.grid.addWidget(self.vpn_label1, 0, 0) #<------------
        self.grid.addWidget(self.vpn_label2, 0, 1) #<------------

There is a lot to learn about both Qt and multithreaded programming before you stop tripping up. I would recommend you at least finish reading Martin Fitzpatrick's book/blogs, which is where your code has come from. The documentation and articles on the Qt website are very good and are essential reading. I've also found the videos released by KDAB to be exceptionally good.


答:
You can use groupby and apply to apply a custom function to each group. The function then needs to compare the date1 with the previous row's date2 which can be done using shift. This will give a boolean value (True or False), to get a string value you can use np.where. For example:

```<code>import numpy as np

def func(x):
    return x['date1'] == x['date2'].shift(1)

df['NewColumn'] = np.where(df.groupby('ID').apply(func), 'YES', '')
</code>```

Result:

```<code>   ID  date1           date2         NewColumn
0   1  31/01/2022      01/02/2022
1   1  01/02/2022      02/02/2022       YES
2   1  07/02/2022      08/02/2022
3   2  02/02/2022      02/02/2022
4   3  02/02/2022      03/02/2022
</code>```

Title: Comparing two different column values for the records having same primary key value

Body:
I want to compare the two columns (date1 and date2) for same ID and set the value of column NewColumn to 'Yes' if date1 matches with the previous date2.

INPUT:

ID
Date1
date2
NewColumn

1
31 Jan 2022
1 Feb 2022

1
1 Feb 2022
2 Feb 2022

1
7 Feb 2022
8 Feb 2022

2
2 Feb 2022
2 Feb 2022

3
2 Feb 2022
3 Feb 2022

Input in CSV format:

ID,date1,date2,NewColumn
1,31/01/2022,01/02/2022,
1,01/02/2022,02/02/2022,
1,07/02/2022,08/02/2022,
2,02/02/2022,02/02/2022,
3,02/02/2022,03/02/2022,

Output:

ID
date1
date2
NewColumn

1
31 Jan 2022
1 Feb 2022

1
1 Feb 2022
2 Feb 2022
YES

1
7 Feb 2022
8 Feb 2022

2
2 Feb 2022
2 Feb 2022

3
2 Feb 2022
3 Feb 2022

In CSV format:

ID,date1,date2,NewColumn
1,31/01/2022,01/02/2022,
1,01/02/2022,02/02/2022, YES
1,07/02/2022,08/02/2022,
2,02/02/2022,02/02/2022,
3,02/02/2022,03/02/2022,

Body:
You can use groupby and apply to apply a custom function to each group. The function then needs to compare the date1 with the previous row's date2 which can be done using shift. This will give a boolean value (True or False), to get a string value you can use np.where. For example:

import numpy as np

def func(x):
    return x['date1'] == x['date2'].shift(1)

df['NewColumn'] = np.where(df.groupby('ID').apply(func), 'YES', '')

Result:

   ID  date1           date2         NewColumn
0   1  31/01/2022      01/02/2022
1   1  01/02/2022      02/02/2022       YES
2   1  07/02/2022      08/02/2022
3   2  02/02/2022      02/02/2022
4   3  02/02/2022      03/02/2022


问:
Intellij Maven dependency not resolved while following guide
I am currently trying to follow this guide and every time I try to run the test code I am getting this error:

[ERROR] Failed to execute goal on project MyBot: Could not resolve
dependencies for project org.example:MyBot:jar:1.0-SNAPSHOT:
org.javacord:javacord:jar:3.4.0 was not found in
https://repo.maven.apache.org/maven2 during a previous attempt. This
failure was cached in the local repository and resolution is not
reattempted until the update interval of central has elapsed or
updates are forced -> [Help 1]

pom.xml

答: Should the answer from Kaspatoo not working for you you can try to add the repository from Javacord to your project.</p>


问:
[value='"+ row.type +"']")
I don't know what that code meaning?
$("input[name='modelType'][value='"+ row.type +"']").click();

This is a jsp file to export a view from spring mvc.

$("#labelStatus").hide();

$("#selStatus").show();
$("#rowID").val(row.rowID);
$("#type").val(row.type);
$("#type").attr("readonly", "readonly");
$("input[name='modelType']").attr("disabled", false);
$("input[name='modelType'][value='"+ row.type +"']").click();
$("input[name='modelType']").attr("disabled", "disabled");
$("#totalCost").val(row.totalCost);
$("#totalRevenue").val(row.totalRevenue);
$("#netRevenue").val(row.netRevenue);
$("#dataStatus").val(row.dataStatus);
$("#useTime").val(row.useTime);
$("#createTime").val(row.createTime);
$ ("#ModifyTime").val(row.ModifyTime);
dialogExportIncome(false);
```

答:
This is a CSS attribute selector that selects:

inputs

which have their name property equal to "modelType"

and the value property equal to the value of row.type.

Title: [value='"+ row.type +"']")


问:
Rename opened workbook without firstly close it?
If I want to rename an opened workbook, I need to close it firstly, and then rename it which is a little tedious.

on 3rd party software “Office Tab” , It has this feature to Rename opened workbook without firstly close it.

Is it possible to be done by Excel without using other software ,even by using VBA soultion.

In advance , greatful for any help.

答:
Rename an Open Workbook

Option Explicit

Sub RenameMe()

    Const ibPrompt As String = "Enter a new file name"
    Const ibTitle As String = "Rename Me"

    Dim wb As Workbook: Set wb = ActiveWorkbook
    Dim DotPosition As Long: DotPosition = InStr(1, wb.Name, ".")
    If DotPosition = 0 Then Exit Sub

    Dim ibDefault As String: ibDefault = Left(wb.Name, DotPosition - 1)

    Dim NewBaseName As String
    NewBaseName = InputBox(ibPrompt, ibTitle, ibDefault)
    If Len(NewBaseName) = 0 Then Exit Sub

    Dim FilePath As String: FilePath = wb.FullName
    Dim FolderPath As String: FolderPath = wb.Path & Application.PathSeparator
    Dim Extension As String: Extension = Right(Extension, DotPosition)

    Dim ErrNum As Long
    On Error Resume Next
        wb.SaveAs FolderPath & NewBaseName & Extension
        ErrNum = Err.Number
    On Error GoTo 0

    If ErrNum = 0 Then
        Kill FilePath
    Else
        MsgBox "Could not rename.", vbCritical, "Rename Me"
    End If

End Sub
```


问:
stylesheet does not apply to html files
I've run my css through a validator (nothing is wrong)

My header looks as following (with irrelevant pieces removed)

     <link href="https://fonts.googleapis.com/css2?family=Lato:wght@400&display=swap" rel="Stylesheet">
     <title>Projekter</title>
     <link rel="Stylesheet" href="Stylesheet.css">
```

and my stylesheet is named Stylesheet.css in the following folder hierachy

What could possibly be wrong here?

Please do tell me if I'm missing giving some relevant information.

答:
The stylesheet call path is invalid.

The index.html file is in the HTML folder and Stylesheet.css is outside the HTML folder.

Please correct it as follows.

     <link rel="stylesheet" href="../Stylesheet.css">
```

Chrome DevTools makes it easier to determine the cause.

Title: stylesheet does not apply to html files

Body:
I've run my css through a validator (nothing is wrong)

My header looks as following (with irrelevant pieces removed)

     <link href="https://fonts.googleapis.com/css2?family=Lato:wght@400&display=swap" rel="Stylesheet">
     <title>Projekter</title>
     <link rel="Stylesheet" href="Stylesheet.css">

and my stylesheet is named Stylesheet.css in the following folder hierachy

What could possibly be wrong here?

Please do tell me if I'm missing giving some relevant information.

Body:
The stylesheet call path is invalid.

The index.html file is in the HTML folder and Stylesheet.css is outside the HTML folder.

Please correct it as follows.

     <link rel="stylesheet" href="../Stylesheet.css">

Chrome DevTools makes it easier to determine the cause.


问:
Whats wrong in the following cpp Bucubic interpolation code for Image Resizing
I am trying to upsample an Image using Bicubic Interpoloation, I need the accurate values matching the cvResize() function of opencv, but the results of following code is not matching the results from cvResize(), can you take a look and help me to fix the bug.
```
Image *Image::resize_using_Bicubic(int w, int h) {
    float dx,dy;
    float x,y;
    float tx, ty;
    float i,j,m,n;</p>

<code>Image *result=new Image(w, h);
tx = (float)this->m_width/(float)w;
ty = (float)this->m_height/(float)h;
for(i=0; i< w; i++)
{
    for(j=0; j< h; j++)
    {
        x = i*tx;
        y = j*ty;
        dx = float(i-x)-(int)(i-x);
        dy = float(j-y)-(int)(j-y);
        float temp=0.0;
        for(m=-1;m<=2;m++)
        {
            for(n=-1;n<=2;n++)
            {

                int HIndex,WIndex;
                HIndex=(y+n);
                WIndex=(x+m);

                if (HIndex<0) {
                    HIndex=0;
                }
                else if(HIndex>this->getHeight())
                {
                    HIndex=this->getHeight()-1;

                }
                if (WIndex<0) {
                    WIndex=0;
                }
                else if(WIndex>this->getWidth())
                {
                    WIndex=this->getWidth()-1;

                }

                temp+=this->getPixel(HIndex,WIndex)*R(m-dx)*R(dy-n);
            }
        }

        result->setPixel(j, i, temp);
    }
}
return result;
</code>```

<p>}</p>

答:
Change:

```<code>            else if(HIndex>this->getHeight())
</code>```

to:

```<code>            else if(HIndex >= this->getHeight())
</code>```

and change:

```<code>            else if(WIndex>this->getWidth())
</code>```

to:

```<code>            else if(WIndex >= this->getWidth())
</code>```

EDIT

Also change:

```<code>    for(m=-1;m<=2;m++)
    {
        for(n=-1;n<=2;n++)
</code>```

to:

```<code>    for(m = -1; m <= 1; m++)
    {
        for(n = -1; n <= 1; n++)
</code>```

Body:
I am trying to upsample an Image using Bicubic Interpoloation, I need the accurate values matching the cvResize() function of opencv, but the results of following code is not matching the results from cvResize(), can you take a look and help me to fix the bug.

Image *Image::resize_using_Bicubic(int w, int h) {
    float dx,dy;
    float x,y;
    float tx, ty;
    float i,j,m,n;

Image *result=new Image(w, h);
tx = (float)this->m_width/(float)w;
ty = (float)this->m_height/(float)h;
for(i=0; i< w; i++)
{
    for(j=0; j< h; j++)
    {
        x = i*tx;
        y = j*ty;
        dx = float(i-x)-(int)(i-x);
        dy = float(j-y)-(int)(j-y);
        float temp=0.0;
        for(m=-1;m<=2;m++)
        {
            for(n=-1;n<=2;n++)
            {

                int HIndex,WIndex;
                HIndex=(y+n);
                WIndex=(x+m);

                if (HIndex<0) {
                    HIndex=0;
                }
                else if(HIndex>this->getHeight())
                {
                    HIndex=this->getHeight()-1;

                }
                if (WIndex<0) {
                    WIndex=0;
                }
                else if(WIndex>this->getWidth())
                {
                    WIndex=this->getWidth()-1;

                }

                temp+=this->getPixel(HIndex,WIndex)*R(m-dx)*R(dy-n);
            }
        }

        result->setPixel(j, i, temp);
    }
}
return result;

}

Body:
Change:

            else if(HIndex>this->getHeight())

to:

            else if(HIndex >= this->getHeight())

and change:

            else if(WIndex>this->getWidth())

to:

            else if(WIndex >= this->getWidth())

EDIT

Also change:

    for(m=-1;m<=2;m++)
    {
        for(n=-1;n<=2;n++)

to:

    for(m = -1; m <= 1; m++)
    {
        for(n = -1; n <= 1; n++)


问:
Navbar desktop to mobile
I wanted to create a navbar hamburger in mobile view. But The issue is, I have two ULs, and when I created a hamburger The two UL's will split into mobile versions. Is there any way I can fix that thing?

This is my code:

          PRACTICE FOR NAVBAR HAMBURGER

                HOME

                SHOP

                BLOG

                ABOUT US

                CONTACT

                MY ACCOUNT

```

I wanted to stay the desktop view as this

The first
 is in the HOME section then the second
 is MY ACCOUNT

答: I think the best solution is to wrap both of your ul into a single one in mobile screen sizes using JavaScript</p>

Title: Navbar desktop to mobile

Body:
I wanted to create a navbar hamburger in mobile view. But The issue is, I have two ULs, and when I created a hamburger The two UL's will split into mobile versions. Is there any way I can fix that thing?

This is my code:

          PRACTICE FOR NAVBAR HAMBURGER

                HOME

                SHOP

                BLOG

                ABOUT US

                CONTACT

                MY ACCOUNT

I wanted to stay the desktop view as this

The first
 is in the HOME section then the second
 is MY ACCOUNT


问:
Error on Using Async in Azure Text Analytics Client
I was trying to use async on Azure to speed up the processing time but it gave me an error when I ran it, which is RuntimeError: asyncio.run() cannot be called from a running event loop

Here is my code, the inputs are azure client, and a list of documents.

```<code>import os
import asyncio
import pandas as pd
from azure.ai.textanalytics import TextAnalyticsClient
from azure.core.credentials import AzureKeyCredential

ace = [{'doc_name': 'doc_1',
        'mention': 'Chris Evans',
        'title': 'Chris Evans',
        'full_text': "Chris Evans started as human torch......."},
        {'doc_name': 'doc_2',
        'mention': 'Tony Stark',
        'title': 'Chris Evans',
        'full_text': "Tony Stark is ironman which likes......."},
        {'doc_name': 'doc_3',
        'mention': 'Chris Evans',
        'title': 'Thor',
        'full_text': "Thor loves to drink......."},
        ....... more docs......
        }]

key = "my-key"
endpoint = "my-endpoint"

def authenticate_client():
    ta_credential = AzureKeyCredential(key)
    text_analytics_client = TextAnalyticsClient(
            endpoint=endpoint,
            credential=ta_credential)
    return text_analytics_client

client = authenticate_client()

async def entity_linking(client, doc):

    name = []
    i_d = []
    url = []
    temp = []
    text = []
    doc_n = []

    for i in range(len(doc)):

        try:
            documents = [doc[i]['full_text']]

            async with client:

                result = await client.recognize_linked_entities(documents = documents)[0]

    #         print("Linked Entities:\n")
            for entity in result.entities:
                doc_n.append(doc[i]['doc_name'])
                name.append(entity.name)
                i_d.append(entity.data_source_entity_id)
                url.append(entity.url)
                temp.append(entity.matches)

        except:
            doc_n.append('')
            name.append('')
            i_d.append('')
            url.append('')
            text.append('')

    for i in range(len(temp)):
        text.append(temp[i][0]['text'])

    dataframe = pd.DataFrame({
        'doc_name': doc_n,
        'name': name,
        'id': i_d,
        'text': text,
        'wiki_url': url
    })

    return dataframe
#     except Exception as err:
#         print("Encountered exception. {}".format(err))

async def main():
    await entity_linking2(client,ace)

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

I tried to run it with my code with async above but received an error RuntimeError: asyncio.run() cannot be called from a running event loop. I am wondering did I set it up wrong in my code above or some other problems. Also, if I am intered in getting the latency for Azure when I run the code above, are there any build in functions for Azure for me to get it? Thanks everyone!

答:
The documentation for asyncio.run()  states:

When another asyncio event loop is running in the same thread, this function  cannot  be called.

RuntimeError: asyncio.run() cannot be called from a running event loop

Even if your code is outside of any asynchronous function, you don't need to start the event loop yourself and can instead call await main(url) directly.

References :

Run time error Asyncio run cannot be called from a running event loop

Asyncio Runtime error

Body:
I was trying to use async on Azure to speed up the processing time but it gave me an error when I ran it, which is RuntimeError: asyncio.run() cannot be called from a running event loop

Here is my code, the inputs are azure client, and a list of documents.

import os
import asyncio
import pandas as pd
from azure.ai.textanalytics import TextAnalyticsClient
from azure.core.credentials import AzureKeyCredential

ace = [{'doc_name': 'doc_1',
        'mention': 'Chris Evans',
        'title': 'Chris Evans',
        'full_text': "Chris Evans started as human torch......."},
        {'doc_name': 'doc_2',
        'mention': 'Tony Stark',
        'title': 'Chris Evans',
        'full_text': "Tony Stark is ironman which likes......."},
        {'doc_name': 'doc_3',
        'mention': 'Chris Evans',
        'title': 'Thor',
        'full_text': "Thor loves to drink......."},
        ....... more docs......
        }]

key = "my-key"
endpoint = "my-endpoint"

def authenticate_client():
    ta_credential = AzureKeyCredential(key)
    text_analytics_client = TextAnalyticsClient(
            endpoint=endpoint,
            credential=ta_credential)
    return text_analytics_client

client = authenticate_client()

async def entity_linking(client, doc):

    name = []
    i_d = []
    url = []
    temp = []
    text = []
    doc_n = []

    for i in range(len(doc)):

        try:
            documents = [doc[i]['full_text']]

            async with client:

                result = await client.recognize_linked_entities(documents = documents)[0]

    #         print("Linked Entities:\n")
            for entity in result.entities:
                doc_n.append(doc[i]['doc_name'])
                name.append(entity.name)
                i_d.append(entity.data_source_entity_id)
                url.append(entity.url)
                temp.append(entity.matches)

        except:
            doc_n.append('')
            name.append('')
            i_d.append('')
            url.append('')
            text.append('')

    for i in range(len(temp)):
        text.append(temp[i][0]['text'])

    dataframe = pd.DataFrame({
        'doc_name': doc_n,
        'name': name,
        'id': i_d,
        'text': text,
        'wiki_url': url
    })

    return dataframe
#     except Exception as err:
#         print("Encountered exception. {}".format(err))

async def main():
    await entity_linking2(client,ace)

if __name__ == '__main__':
    asyncio.run(main())

I tried to run it with my code with async above but received an error RuntimeError: asyncio.run() cannot be called from a running event loop. I am wondering did I set it up wrong in my code above or some other problems. Also, if I am intered in getting the latency for Azure when I run the code above, are there any build in functions for Azure for me to get it? Thanks everyone!


问:
Can you debundle a react component?
I'm trying to figure out how some things are being done on a website. I unminified its Webpack bundle, but wondered if it's possible to reconstruct a react component using the partially minified code, the react dev extension, and some time. I found out how some parts work in webpack, but the debundlers I found did not yield any results.
I tried debundle, reliable-debundle, and debundle-v2

debundle v2 detected the entry but returned extracting 0 chunks

Example snippet looks like this:

    5332: function(t, e, i) {
      'use strict';
      Object.defineProperty(e, '__esModule', { value: !0 }),
        (e.default = void 0);
      var n,
        a = (function(t) {
          if (t && t.__esModule) return t;
          if (null === t || ('object' != typeof t && 'function' != typeof t))
            return { default: t };
          var e = l();
          if (e && e.has(t)) return e.get(t);
          var i = {},
            n = Object.defineProperty && Object.getOwnPropertyDescriptor;
          for (var a in t)
            if (Object.prototype.hasOwnProperty.call(t, a)) {
              var r = n ? Object.getOwnPropertyDescriptor(t, a) : null;
              r && (r.get || r.set)
                ? Object.defineProperty(i, a, r)
                : (i[a] = t[a]);
            }
          (i.default = t), e && e.set(t, i);
          return i;
        })(i(0)),
        r = o(i(8)),
        s = o(i(5409));
      function o(t) {
        return t && t.__esModule ? t : { default: t };
      }
      function l() {
        if ('function' != typeof WeakMap) return null;
        var t = new WeakMap();
        return (
          (l = function() {
            return t;
          }),
          t
        );
      }
      function h(t, e, i, a) {
        n ||
          (n =
            ('function' == typeof Symbol &&
              Symbol.for &&
              Symbol.for('react.element')) ||
            60103);
        var r = t && t.defaultProps,
          s = arguments.length - 3;
        if ((e || 0 === s || (e = { children: void 0 }), 1 === s))
          e.children = a;
        else if (s > 1) {
          for (var o = new Array(s), l = 0; l < s; l++) o[l] = arguments[l + 3];
          e.children = o;
        }
        if (e && r) for (var h in r) void 0 === e[h] && (e[h] = r[h]);
        else e || (e = r || {});
        return {
          $$typeof: n,
          type: t,
          key: void 0 === i ? null : '' + i,
          ref: null,
          props: e,
          _owner: null,
        };
      }
      function u() {
        return (u =
          Object.assign ||
          function(t) {
            for (var e = 1; e < arguments.length; e++) {
              var i = arguments[e];
              for (var n in i)
                Object.prototype.hasOwnProperty.call(i, n) && (t[n] = i[n]);
            }
            return t;
          }).apply(this, arguments);
      }
      var d = (function(t) {
        var e, i;
        function n(e) {
          var i;
          return (
            ((i = t.call(this, e) || this).unmounting = !1),
            (i.state = { loaded: !1 }),
            i.initialize(),
            i
          );
        }
        (i = t),
          ((e = n).prototype = Object.create(i.prototype)),
          (e.prototype.constructor = e),
          (e.__proto__ = i);
        var a = n.prototype;
        return (
          (a.componentDidUpdate = function(t) {
            var e = this;
            t.src !== this.props.src &&
              this.setState({ loaded: !1 }, function() {
                return e.initialize();
              });
          }),
          (a.initialize = function() {
            var t,
              e = this;
            ((t = this.props.src),
            new Promise(function(e, i) {
              null == t && i(new Error('No image src passed'));
              var n = new Image();
              (n.src = t),
                (n.onload = function() {
                  return e(n);
                }),
                (n.onerror = function(t) {
                  return i(t);
                });
            })).then(function() {
              e.unmounting || e.setState({ loaded: !0 });
            });
          }),
          (a.componentWillUnmount = function() {
            this.unmounting = !0;
          }),
          (a.render = function() {
            var t,
              e = this.props,
              i = e.className,
              n = e.src,
              a = e.alt,
              o = e.width,
              l = e.height,
              d = e.onLoad,
              c = e.style,
              f = this.state.loaded;
            return h(
              'div',
              { className: i, style: u({}, c, { width: o, height: l }) },
              void 0,
              h('img', {
                className: (0, r.default)(
                  s.default.image,
                  ((t = {}), (t[s.default.loaded] = f), t)
                ),
                width: o,
                height: l,
                src: n,
                alt: a,
                onLoad: d,
              })
            );
          }),
          n
        );
      })(a.PureComponent);
      (d.displayName = 'LazySplash'),
        (d.defaultProps = { width: 0, height: 0, alt: '' });
      var c = d;
      e.default = c;
    },
```

答:
A very basic debundler for Javascript bundles compiled with React Native's bundler.

Debundles a large React Native bundle by walking the compiled AST and extracts individual module declarations and writes them to their own modules & attempts to resolve dependeny import relationships.

```<code>      __d(function() {
  "use strict";
}, 0, []);
__d(function(v) {
  "use strict";
}, 1, [0]);

var a = "foo bar baz";
</code>```

For more

Title: Can you debundle a react component?

Body:
A very basic debundler for Javascript bundles compiled with React Native's bundler.

Debundles a large React Native bundle by walking the compiled AST and extracts individual module declarations and writes them to their own modules & attempts to resolve dependeny import relationships.

      __d(function() {
  "use strict";
}, 0, []);
__d(function(v) {
  "use strict";
}, 1, [0]);

var a = "foo bar baz";

For more