问:
how to extract template derived class's method into non-template base class
I want using polymorphism in C++, I am try to extract method shows in all derived class into base class.

For example:

I have two class, HouseA and HouseB, they are template class.
And they are derived from base class BaseHouse.

```<code>class BaseHouse
{
public:
    //other thing
private:
};

template <typename Type>
class HouseA : public BaseHouse
{
public:
    HouseA(Type object_input) : object(object_input)
    {
    }
    // other thing about HouseA
    Type &getObject()
    {
        std::cout << "this is House A" << std::endl;
        return object;
    }

private:
    Type object;
};

template <typename Type>
class HouseB : public BaseHouse
{
public:
    HouseB(Type object_input) : object(object_input)
    {
    }
    // other thing about HouseB
    Type &getObject()
    {
        std::cout << "this is House B" << std::endl;
        return object;
    }

private:
    Type object;
};
</code>```

Bacause of polymorphism, we using base class's pointer to access derivated class object. When I need to call method defined in derivated class, I am always transfer base class pointer into derivated class pointer:

```<code>int main()
{
    HouseA<int> house_a(5);
    int x = house_a.getObject();

    BaseHouse *base_ptr = &house_a;

    // suppose after some complicate calculate calculation
    // we only have the base class pointer can access derivated class object

    HouseA<int> *ptr_a = (HouseA<int> *)base_ptr; //transfer base class pointer into derivated class pointer
    ptr_a->getObject();
    return 0;
}
</code>```

But the derived class HouseA and HouseB both have the method getObject.

So I want to extract template derived class's method into non-template base class.

For some reason, we suppose that the base class BaseHouse can not be template class.

Is there any way I can do that?

Thanks in advance.

答:
Maybe not exactly a classical Visitor, but...

Okay, the basic idea is we have to somehow capture and encapsulate templated processing into a single entity ready-to-use in a run-time polymorphic construct.

Let's start with a simple class hierarchy:

struct Consumer;

struct Base {
    virtual void giveObject(Consumer const &) const = 0;
    virtual ~Base() = default;
};

struct Derived1: Base {
    Derived1(int x): x(x) {}
    void giveObject(Consumer const &c) const override {
        c(x);
    }
private:
    int x;
};

struct Derived2: Base {
    Derived2(double y): y(y) {}
    void giveObject(Consumer const &c) const override {
        c(y);
    }
private:
    double y;
};
```

<p>So far, it is very simple: the <code>Base</code> class has a pure virtual method that accepts an object of type <code>Consumer</code> and a concrete implementation of this method is expected to expose to <code>Consumer</code> the relevant part of the internal state of its particular implementor (which is a subtype of <code>Base</code>). In other words, we have taken that 'virtual template' idiom and hid it inside the <code>Consumer</code>. Ok, what could it possibly be?</p>

<p>First option, if you know in advance at compile-time (at source code-time, more exactly) what it could possibly do, i.e. there's only one algorithm of consumption per each object type, and the set of types is fixed, it is quite straightforward:</p>

<pre class="lang-cpp prettyprint-override"><code>struct Consumer {
    void consume(int x) const { std::cout << x << " is an int.\n"; }
    void consume(double y) const { std::cout << y << " is a double.\n"; }
    template<typename T> void consume(T t) const {
        std::cout << "Default implementation called for an unknown type.\n";
    }
};
</code>```

etc.

More elaborate implementation would allow run-time construction of a templated entity. How is that even possible?

Alexandrescu in his "Modern C++ Design" uses typeid to store particular type handlers in a single data structure. In a brief, this could be something like:

struct Handler {
    virtual ~Handler() = default; // now it's an empty polymorphic base
};

template<typename T> struct RealHandler: Handler {
    RealHandler(std::function<void(T)> f): f(std::move(f)) {}
    void handle(T x) {
        f(x);
    }
private:
    std::function<void(T)> f;
};

#include <map>
#include <type_info>
#include <functional>

struct Consumer {
    template<typename T> void consume(T t) const {
        auto f{knownHandlers.find(typeid(t))};
        if(f != knownHandlers.end()) {
            RealHandler<T> const &rh{
                dynamic_cast<RealHandler<T> const &>(*f->second)};
            rh.handle(t);
        }
        else {
            // default implementation for unregistered types here
        }
    }
    template<typename T> Consumer &register(std::function<void(T)> f) {
        knownHandlers[typeid(T)] = std::make_unique<RealHandler<T>>(std::move(f));
    }
private:
    std::map<std::type_info, std::unique_ptr<Handler>> knownHandlers;
};
```

<p>Haven't actually tested it, as I don't like typeids and other RTTI much. What I have quickly tested is another solution that requires neither maps nor typeinfo to store handlers in a templated manner. Still it uses a small trick, like how can we possibly pass, keep and retrieve information of an arbitrary type with the same call.</p>

```struct Consumer {
    Consumer() {}
    template<typename T> void consume(T t) const {
        auto f{setSlot<T>()};
        if(f) f(t);
        else {
            // default implementation for an unset slot
            std::cout << t / 2 << '\n';
        }
    }
    template<typename T>
    std::function<void(T)> &setSlot(
            std::function<void(T)> f = std::function<void(T)>{}) const
    {
        static std::function<void(T)> slot;
        if(f) { // setter
            slot = std::move(f);
        }
        return slot;
    }
};
```

<p>Here, <code>setSlot()</code> is used to store a handler for a particular type: when called with a non-empty argument, it stores that argument; and then returns its currently kept value. With <code>Consumer</code> so defined, the class hierarchy from above works as:</p>

<pre class="lang-cpp prettyprint-override"><code>int main() {
    Consumer c;
    c.setSlot<int>([](int x){ std::cout << x << " is an int!\n"; });
    Base const &b1{Derived1{42}};
    Base const &b2{Derived2{3.14}};
    b1.giveObject(c);
    b2.giveObject(c);
}
</code>```

Output:

```<code>42 is an int!
1.57
</code>```

In the first line we see a message printed by a custom int handler; in the second line, a default message is printed for the double type, as no custom handler for double was installed.

One obvious drawback of this implementation is that handlers are stored in static variables thus all Consumers share the same handlers for all types, so Consumer here is actually a monostate. At least, you can change implementations for types at run-time, unlike if you had fixed Consumers of the very first approach. The maps-of-typeids approach from above shouldn't have this drawback, in exchange for some performance cost.

Body:
I want using polymorphism in C++, I am try to extract method shows in all derived class into base class.

For example:

I have two class, HouseA and HouseB, they are template class.
And they are derived from base class BaseHouse.

class BaseHouse
{
public:
    //other thing
private:
};

template <typename Type>
class HouseA : public BaseHouse
{
public:
    HouseA(Type object_input) : object(object_input)
    {
    }
    // other thing about HouseA
    Type &getObject()
    {
        std::cout << "this is House A" << std::endl;
        return object;
    }

private:
    Type object;
};

template <typename Type>
class HouseB : public BaseHouse
{
public:
    HouseB(Type object_input) : object(object_input)
    {
    }
    // other thing about HouseB
    Type &getObject()
    {
        std::cout << "this is House B" << std::endl;
        return object;
    }

private:
    Type object;
};

Bacause of polymorphism, we using base class's pointer to access derivated class object. When I need to call method defined in derivated class, I am always transfer base class pointer into derivated class pointer:

int main()
{
    HouseA<int> house_a(5);
    int x = house_a.getObject();

    BaseHouse *base_ptr = &house_a;

    // suppose after some complicate calculate calculation
    // we only have the base class pointer can access derivated class object

    HouseA<int> *ptr_a = (HouseA<int> *)base_ptr; //transfer base class pointer into derivated class pointer
    ptr_a->getObject();
    return 0;
}

But the derived class HouseA and HouseB both have the method getObject.

So I want to extract template derived class's method into non-template base class.

For some reason, we suppose that the base class BaseHouse can not be template class.

Is there any way I can do that?

Thanks in advance.

Body:
Maybe not exactly a classical Visitor, but...

Okay, the basic idea is we have to somehow capture and encapsulate templated processing into a single entity ready-to-use in a run-time polymorphic construct.

Let's start with a simple class hierarchy:

struct Consumer;

struct Base {
    virtual void giveObject(Consumer const &) const = 0;
    virtual ~Base() = default;
};

struct Derived1: Base {
    Derived1(int x): x(x) {}
    void giveObject(Consumer const &c) const override {
        c(x);
    }
private:
    int x;
};

struct Derived2: Base {
    Derived2(double y): y(y) {}
    void giveObject(Consumer const &c) const override {
        c(y);
    }
private:
    double y;
};

So far, it is very simple: the Base class has a pure virtual method that accepts an object of type Consumer and a concrete implementation of this method is expected to expose to Consumer the relevant part of the internal state of its particular implementor (which is a subtype of Base). In other words, we have taken that 'virtual template' idiom and hid it inside the Consumer. Ok, what could it possibly be?

First option, if you know in advance at compile-time (at source code-time, more exactly) what it could possibly do, i.e. there's only one algorithm of consumption per each object type, and the set of types is fixed, it is quite straightforward:

struct Consumer {
    void consume(int x) const { std::cout << x << " is an int.\n"; }
    void consume(double y) const { std::cout << y << " is a double.\n"; }
    template<typename T> void consume(T t) const {
        std::cout << "Default implementation called for an unknown type.\n";
    }
};

etc.

More elaborate implementation would allow run-time construction of a templated entity. How is that even possible?

Alexandrescu in his "Modern C++ Design" uses typeid to store particular type handlers in a single data structure. In a brief, this could be something like:

struct Handler {
    virtual ~Handler() = default; // now it's an empty polymorphic base
};

template<typename T> struct RealHandler: Handler {
    RealHandler(std::function<void(T)> f): f(std::move(f)) {}
    void handle(T x) {
        f(x);
    }
private:
    std::function<void(T)> f;
};

#include <map>
#include <type_info>
#include <functional>

struct Consumer {
    template<typename T> void consume(T t) const {
        auto f{knownHandlers.find(typeid(t))};
        if(f != knownHandlers.end()) {
            RealHandler<T> const &rh{
                dynamic_cast<RealHandler<T> const &>(*f->second)};
            rh.handle(t);
        }
        else {
            // default implementation for unregistered types here
        }
    }
    template<typename T> Consumer &register(std::function<void(T)> f) {
        knownHandlers[typeid(T)] = std::make_unique<RealHandler<T>>(std::move(f));
    }
private:
    std::map<std::type_info, std::unique_ptr<Handler>> knownHandlers;
};

Haven't actually tested it, as I don't like typeids and other RTTI much. What I have quickly tested is another solution that requires neither maps nor typeinfo to store handlers in a templated manner. Still it uses a small trick, like how can we possibly pass, keep and retrieve information of an arbitrary type with the same call.

struct Consumer {
    Consumer() {}
    template<typename T> void consume(T t) const {
        auto f{setSlot<T>()};
        if(f) f(t);
        else {
            // default implementation for an unset slot
            std::cout << t / 2 << '\n';
        }
    }
    template<typename T>
    std::function<void(T)> &setSlot(
            std::function<void(T)> f = std::function<void(T)>{}) const
    {
        static std::function<void(T)> slot;
        if(f) { // setter
            slot = std::move(f);
        }
        return slot;
    }
};

Here, setSlot() is used to store a handler for a particular type: when called with a non-empty argument, it stores that argument; and then returns its currently kept value. With Consumer so defined, the class hierarchy from above works as:

int main() {
    Consumer c;
    c.setSlot<int>([](int x){ std::cout << x << " is an int!\n"; });
    Base const &b1{Derived1{42}};
    Base const &b2{Derived2{3.14}};
    b1.giveObject(c);
    b2.giveObject(c);
}

Output:

42 is an int!
1.57

In the first line we see a message printed by a custom int handler; in the second line, a default message is printed for the double type, as no custom handler for double was installed.

One obvious drawback of this implementation is that handlers are stored in static variables thus all Consumers share the same handlers for all types, so Consumer here is actually a monostate. At least, you can change implementations for types at run-time, unlike if you had fixed Consumers of the very first approach. The maps-of-typeids approach from above shouldn't have this drawback, in exchange for some performance cost.


来源: stackexchange

问:
QSqlDatabase: QMYSQL driver not loaded
I have a problem with Qt connecting with MySql, when i run this code

    QSqlDatabase DBObject = QSqlDatabase::addDatabase("QMYSQL");
    DBObject.setHostName("localhost");
    DBObject.setDatabaseName("SingleDB");
    DBObject.setUserName("root");
    DBObject.setPassword("abc123");
    bool ok = DBObject.open();
```

<p>I got this...
QSqlDatabase: QMYSQL driver not loaded</p>

<p>I Have already done this also:
sudo apt-get install libmysqlclient</p>

<p>and</p>

```/home/wrm/Qt/5.12.3/gcc_64/bin/qmake "INCLUDEPATH+=/usr/local/include" "LIBS+=-L/usr/local/lib -lmysqlclient_r" mysql.pro
```

and here i have this error:
Project ERROR: Library 'mysql' is not defined

Any idea?

答:
Usually, when you get a "driver not loaded" error, the problem is the path where the libqsqlmysql.so is.

That library is contained in the plugins/sqldrivers folder of your Qt installation and that (sqldrivers) folder should be available to your executable.

You have to make sure that the sqldrivers folder is in the same folder of your executable (that is one of the default lookup paths) or change those paths within your code using QCoreApplication::addLibraryPath

So, to sum it up:

be sure of the path of the sqldrivers folder (or change the plugin lookup path)

be sure to link against libmysqlclient as well (on my system libmysqlclient_r is just a link to libmysqlclient)

Try posting some small piece of code that does not work for you.

OwnerDisplayName: Walter Morales

ContentLicense: CC BY-SA 4.0

Title: QSqlDatabase: QMYSQL driver not loaded

Body:
I have a problem with Qt connecting with MySql, when i run this code

    QSqlDatabase DBObject = QSqlDatabase::addDatabase("QMYSQL");
    DBObject.setHostName("localhost");
    DBObject.setDatabaseName("SingleDB");
    DBObject.setUserName("root");
    DBObject.setPassword("abc123");
    bool ok = DBObject.open();

I got this...
QSqlDatabase: QMYSQL driver not loaded

I Have already done this also:
sudo apt-get install libmysqlclient

and

/home/wrm/Qt/5.12.3/gcc_64/bin/qmake "INCLUDEPATH+=/usr/local/include" "LIBS+=-L/usr/local/lib -lmysqlclient_r" mysql.pro

and here i have this error:
Project ERROR: Library 'mysql' is not defined

Any idea?


问:
Private method returned as string
I'm developing a simple jquery plugin and im having a difficulties setting up the method structure. Could someone please enlighten me. I am using the plugin structure as described in the official Jquery Authoring documentation.

The problem I am having is when calling the private function _generateID, the function actually returns the function text ( function() { return this.. ) instead of 'hi'.

```<code>(function( $ ){

    var methods = {
        init : function( options ) {
            return this.each(function() {

            });
        },

        _generateID : function() {
            return this.each(function() {
                return 'hi';
            });
        },

        create : function( options ) {
            return this.each(function() {
                var settings = {
                    'id' : methods._generateID,
                };
                if ( options ) { $.extend( settings, options ); }
                $('<div>', {
                    id : settings.id,
                }).appendTo(this);
            });
        },

        destroy : function( id ) {
            return this.each(function(){
                $(window).unbind('#'+id);
                $('#'+id).remove();
            });
        }
    };

    $.fn.workzone = function( method ) {
        if ( methods[method] ) {
            return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
        } else if ( typeof method === 'object' || ! method ) {
            return methods.init.apply( this, arguments );
        } else {
            $.error( 'Method ' +  method + ' does not exist on jQuery.workzone' );
        }
    };

})( jQuery );
</code>```

答:
From where you are calling. Within the plugin or calling from out side.

Headshota's answer for calling the method within the plugin.

```<code>$('div').pluginName('_generateID', arg0, arg1, ...); //Way to call a plugin method from outside out side plugin and pass arguements.
</code>```

Note that, passing method name as first string argument and then other parameters.

ContentLicense: CC BY-SA 3.0

Title: Private method returned as string

Body:
I'm developing a simple jquery plugin and im having a difficulties setting up the method structure. Could someone please enlighten me. I am using the plugin structure as described in the official Jquery Authoring documentation.

The problem I am having is when calling the private function _generateID, the function actually returns the function text ( function() { return this.. ) instead of 'hi'.

(function( $ ){

    var methods = {
        init : function( options ) {
            return this.each(function() {

            });
        },

        _generateID : function() {
            return this.each(function() {
                return 'hi';
            });
        },

        create : function( options ) {
            return this.each(function() {
                var settings = {
                    'id' : methods._generateID,
                };
                if ( options ) { $.extend( settings, options ); }
                $('
', {
                    id : settings.id,
                }).appendTo(this);
            });
        },

        destroy : function( id ) {
            return this.each(function(){
                $(window).unbind('#'+id);
                $('#'+id).remove();
            });
        }
    };

    $.fn.workzone = function( method ) {
        if ( methods[method] ) {
            return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
        } else if ( typeof method === 'object' || ! method ) {
            return methods.init.apply( this, arguments );
        } else {
            $.error( 'Method ' +  method + ' does not exist on jQuery.workzone' );
        }
    };

})( jQuery );

Body:
From where you are calling. Within the plugin or calling from out side.

Headshota's answer for calling the method within the plugin.

$('div').pluginName('_generateID', arg0, arg1, ...); //Way to call a plugin method from outside out side plugin and pass arguements.

Note that, passing method name as first string argument and then other parameters.


问:
How to recheck required input fields in JavaScript/HTML5
I'm trying to stay away from JQuery for this one (nothing against JQuery, I just don't want to load a huge library into this project for something small like this).

I'm curious how I might tell HTML5 to recheck all the required input fields in a given form. For example, I have this form (albeit slightly more complicated but you get the point):

```<code><form action="here" onsubmit="check()">
    <input required name="something">
    <input type="submit">
</form>
</code>```

If I don't have anything in that required field, HTML5 shows a popup error, something to the effect of "Please fill in this required field". What is stopping the user from putting in a single space, or some nonsense character like % or >? I'd like to partially validate this client-side (in addition to server side) so it isn't particularly inconvenient when the page redirects to the form submission page and then shows the error, and then goes back to the form, prompting the user to enter everything over again.

Assuming in my onsubmit function check I've removed all whitespace and/or nonsense characters from the ends of the string, how can that function then tell HTML5 to recheck the form to see if the required fields are still not empty?

答:
Instead of onsubmit="check()" use  addEventListener.
Now you can do everything with input data.

document.getElementById("submit").addEventListener("click", function(event){
  var something = document.getElementById("something").value;
  document.getElementById("something").value = something.replace(/[^A-Z0-9]/ig, "");
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form action="here">
    <input required name="something" id="something">
    <input type="submit" id="submit">
</form></code>```

Body:
I'm trying to stay away from JQuery for this one (nothing against JQuery, I just don't want to load a huge library into this project for something small like this).

I'm curious how I might tell HTML5 to recheck all the required input fields in a given form. For example, I have this form (albeit slightly more complicated but you get the point):

<form action="here" onsubmit="check()">
    <input required name="something">
    <input type="submit">
</form>

If I don't have anything in that required field, HTML5 shows a popup error, something to the effect of "Please fill in this required field". What is stopping the user from putting in a single space, or some nonsense character like % or >? I'd like to partially validate this client-side (in addition to server side) so it isn't particularly inconvenient when the page redirects to the form submission page and then shows the error, and then goes back to the form, prompting the user to enter everything over again.

Assuming in my onsubmit function check I've removed all whitespace and/or nonsense characters from the ends of the string, how can that function then tell HTML5 to recheck the form to see if the required fields are still not empty?

Body:
Instead of onsubmit="check()" use  addEventListener.
Now you can do everything with input data.

document.getElementById("submit").addEventListener("click", function(event){
  var something = document.getElementById("something").value;
  document.getElementById("something").value = something.replace(/[^A-Z0-9]/ig, "");
});

<form action="here">
    <input required name="something" id="something">
    <input type="submit" id="submit">
</form>


问:
Cypress requests are async - but what about new object creation?
I tried to perform the request using Cypress and then create new objects with the value received in response but new objects are created instantly and the request is being sent after all objects are already created:

```<code>describe("example", function() {

    it("of test", function() {

        console.log("1");

        cy.request({
            url: Cypress.env("URL"),
            method: "POST",
            headers: auth_req.authHeaders,
            body: merged_body
        })
            .as("/authorize")
            .then((resp) => {
                console.log("2");
                Cypress.env("resp_code", resp.status);
                console.log("RESP CODE FROM RESPONSE:");
                console.log(resp.status);
            })
            .its("headers")
            .its("content-type")
            .should("include", "application/json");

        console.log("3");
        const var1 = new something.NotImportant;
        console.log("4");
        const var2 = new something.AlsoNotImportant;
        console.log("5");

    }

}
</code>```

I expected to get "1", "2", "3", "4" and "5" in console. However, I get "1", "3", "4" and "5" almost instantly and after a few seconds (slow response from server) I see that the request is being sent and "2" is being spit out to my console.

My question is: If I get this correctly, requests are async and Cypress is waiting for them to finish, so why the test is not waiting for receiving the response and THEN creating the objects? How can I modify the code to be sure that the objects that I want to create after the request are using the value received from the request during new objects creation? I tried to use Cypress.env, but objects are created BEFORE the request and an incorrect value is used instead of the value read from the response.

Bonus question: Why is this code not working as intended (hanging the computer)?

```<code>    while (true) {
        cy.wait(5000);
        var resp_code = Cypress.env("resp_code");
        console.log("RESP CODE:");
        console.log(Cypress.env("resp_code"));
    }
</code>```

"RESP CODE" is printed to console like every 100 ms, I suppose it's because the test is async and I try to use the sync approach here. Am I correct?

答:
Because it is async you have to keep chaining commands to queue them up.  Cypress does wait for commands (promises) to complete, but only if you tell it to with a then().

You can either do this:

```<code>describe("example", function() {

    it("of test", function() {

        console.log("1");

        cy.request({
            url: Cypress.env("URL"),
            method: "POST",
            headers: auth_req.authHeaders,
            body: merged_body
        })
            .as("/authorize")
            .then((resp) => {
                console.log("2");
                Cypress.env("resp_code", resp.status);
                console.log("RESP CODE FROM RESPONSE:");
                console.log(resp.status);

                console.log("3");
                const var1 = new something.NotImportant;
                console.log("4");
                const var2 = new something.AlsoNotImportant;
                console.log("5");
            })
            .its("headers")
            .its("content-type")
            .should("include", "application/json");
    }

}
</code>```

Or this:

```<code>describe("example", function() {

    it("of test", function() {

        console.log("1");

        cy.request({
            url: Cypress.env("URL"),
            method: "POST",
            headers: auth_req.authHeaders,
            body: merged_body
        })
            .as("/authorize")
            .then((resp) => {
                console.log("2");
                Cypress.env("resp_code", resp.status);
                console.log("RESP CODE FROM RESPONSE:");
                console.log(resp.status);
            })
            .its("headers")
            .its("content-type")
            .should("include", "application/json")
            .then(() => {
                console.log("3");
                const var1 = new something.NotImportant;
                console.log("4");
                const var2 = new something.AlsoNotImportant;
                console.log("5");
            });
    }

}
</code>```

Body:
I tried to perform the request using Cypress and then create new objects with the value received in response but new objects are created instantly and the request is being sent after all objects are already created:

describe("example", function() {

    it("of test", function() {

        console.log("1");

        cy.request({
            url: Cypress.env("URL"),
            method: "POST",
            headers: auth_req.authHeaders,
            body: merged_body
        })
            .as("/authorize")
            .then((resp) => {
                console.log("2");
                Cypress.env("resp_code", resp.status);
                console.log("RESP CODE FROM RESPONSE:");
                console.log(resp.status);
            })
            .its("headers")
            .its("content-type")
            .should("include", "application/json");

        console.log("3");
        const var1 = new something.NotImportant;
        console.log("4");
        const var2 = new something.AlsoNotImportant;
        console.log("5");

    }

}

I expected to get "1", "2", "3", "4" and "5" in console. However, I get "1", "3", "4" and "5" almost instantly and after a few seconds (slow response from server) I see that the request is being sent and "2" is being spit out to my console.

My question is: If I get this correctly, requests are async and Cypress is waiting for them to finish, so why the test is not waiting for receiving the response and THEN creating the objects? How can I modify the code to be sure that the objects that I want to create after the request are using the value received from the request during new objects creation? I tried to use Cypress.env, but objects are created BEFORE the request and an incorrect value is used instead of the value read from the response.

Bonus question: Why is this code not working as intended (hanging the computer)?

    while (true) {
        cy.wait(5000);
        var resp_code = Cypress.env("resp_code");
        console.log("RESP CODE:");
        console.log(Cypress.env("resp_code"));
    }

"RESP CODE" is printed to console like every 100 ms, I suppose it's because the test is async and I try to use the sync approach here. Am I correct?

Body:
Because it is async you have to keep chaining commands to queue them up.  Cypress does wait for commands (promises) to complete, but only if you tell it to with a then().

You can either do this:

describe("example", function() {

    it("of test", function() {

        console.log("1");

        cy.request({
            url: Cypress.env("URL"),
            method: "POST",
            headers: auth_req.authHeaders,
            body: merged_body
        })
            .as("/authorize")
            .then((resp) => {
                console.log("2");
                Cypress.env("resp_code", resp.status);
                console.log("RESP CODE FROM RESPONSE:");
                console.log(resp.status);

                console.log("3");
                const var1 = new something.NotImportant;
                console.log("4");
                const var2 = new something.AlsoNotImportant;
                console.log("5");
            })
            .its("headers")
            .its("content-type")
            .should("include", "application/json");
    }

}

Or this:

describe("example", function() {

    it("of test", function() {

        console.log("1");

        cy.request({
            url: Cypress.env("URL"),
            method: "POST",
            headers: auth_req.authHeaders,
            body: merged_body
        })
            .as("/authorize")
            .then((resp) => {
                console.log("2");
                Cypress.env("resp_code", resp.status);
                console.log("RESP CODE FROM RESPONSE:");
                console.log(resp.status);
            })
            .its("headers")
            .its("content-type")
            .should("include", "application/json")
            .then(() => {
                console.log("3");
                const var1 = new something.NotImportant;
                console.log("4");
                const var2 = new something.AlsoNotImportant;
                console.log("5");
            });
    }

}


问:
how do I shorten the number that is calculated to match the correct suffix
I have got to shorten the number that comes out of a calculation down to the smallest possible whilst being easy to read, such as 999,000 - 999k, and 999,000,000 - 999m.

I believe I have the code I need but I am not sure how I am meant to implement it into my code

while True:
    bands  = input("Please enter your first band colour: ").upper()
    print("")
    if bands== 'BLACK':
        print("The colour black may only be entered in the 2nd or 3rd colour slots.")
        continue
    bands1 = input("Please enter your second band colour: ").upper()
    print("")
    bands2 = input("Please enter your third band colour: ").upper()
    print("")

    print("Ohm value of resistor:", (dict[bands]*10 + dict[bands1]) * (10 ** dict[bands2]),"Ω", )
def print_prefix(value):
    prefix=('', 'K', 'M', 'G')
    i = 0
    if (1000<bands//1000**i):
        i=i+1
        print(str(value/(1000**i))+prefix[i])
```

I expect the result of it to be shortened so a prefix can be added

答:
Well it should be possible with using the code below:

```<code>def print_prefix(value):
    prefix=('', 'K', 'M', 'G')
    i = 0
    while(value >= 1000):
        value = value/1000
        i += 1

    print("{} {}".format(value, prefix[i]))

</code>```

Basically You are dividing the number while it is larger or equal than 1000. Since each of the letters K, M, G means the number 1000 times bigger than previous. This allows You to find which letter should you use and create the shortened number at the same time.

Body:
I have got to shorten the number that comes out of a calculation down to the smallest possible whilst being easy to read, such as 999,000 - 999k, and 999,000,000 - 999m.

I believe I have the code I need but I am not sure how I am meant to implement it into my code

while True:
    bands  = input("Please enter your first band colour: ").upper()
    print("")
    if bands== 'BLACK':
        print("The colour black may only be entered in the 2nd or 3rd colour slots.")
        continue
    bands1 = input("Please enter your second band colour: ").upper()
    print("")
    bands2 = input("Please enter your third band colour: ").upper()
    print("")

    print("Ohm value of resistor:", (dict[bands]*10 + dict[bands1]) * (10 ** dict[bands2]),"Ω", )
def print_prefix(value):
    prefix=('', 'K', 'M', 'G')
    i = 0
    if (1000<bands//1000**i):
        i=i+1
        print(str(value/(1000**i))+prefix[i])

I expect the result of it to be shortened so a prefix can be added

Body:
Well it should be possible with using the code below:

def print_prefix(value):
    prefix=('', 'K', 'M', 'G')
    i = 0
    while(value >= 1000):
        value = value/1000
        i += 1

    print("{} {}".format(value, prefix[i]))

Basically You are dividing the number while it is larger or equal than 1000. Since each of the letters K, M, G means the number 1000 times bigger than previous. This allows You to find which letter should you use and create the shortened number at the same time.


问:
Is 100 training examples sufficient for training custom NER using spacy?
I have trained NER model for names data. I generated some random sentences which contain names of the person. I generated some 70 sentences and annotated the data in spacy's format.

I trained custom NER using both blank 'en' model and 'en_core_web_sm' but when I tested on any string. It is able to detect in very few examples.

Is this number of examples are insufficient?

```<code>My data looks like this -:

[("'Hi, I am looking for a house on rent for a year. Best Regards, Rajesh',\r",
  {'entities': [(56, 63, 'name')]}),
 ("'Hello everyone, I am Gunjan Arora',\r", {'entities': [(22, 34, 'name')]}),
 ("'Greetings!, I am 34 years old. I want a car for my wife Bella Roy',\r",
  {'entities': [(60, 69, 'name')]}),
 ("'Heyo, I lived with my family comprises 4 people and myself Randy Lao',\r",
  {'entities': [(60, 69, 'name')]}),
 ("'I am Geetanjali. ',\r", {'entities': [(6, 16, 'name')]})]

I have generated some 70 examples like this.

Losses during training -:

 - 1.Losses {'ner': 6.307317615201415}
 - 2.Losses {'ner': 11.182436657139132}
 - 3.Losses {'ner': 6.014345924849759}
 - 4.Losses {'ner': 6.442589285506237}
 - 5.Losses {'ner': 5.328383899880891}
 - 6.Losses {'ner': 1.706726450400089}
 - 7.Losses {'ner': 3.9960324752880005}
 - 8.Losses {'ner': 5.415169572852782}

These losses when I am using blank 'en' model
</code>```

Please suggest.

I wanted to detect names as the pre-trained model itself is not able to detect names in most of the cases as well.

答:
for a better result, you will need to generate more examples, 70 examples is not Ok to train your model although it may work on a non-sophisticated problem.
I would suggest to triple your generated examples for a good fit</p>

Body:
I have trained NER model for names data. I generated some random sentences which contain names of the person. I generated some 70 sentences and annotated the data in spacy's format.

I trained custom NER using both blank 'en' model and 'en_core_web_sm' but when I tested on any string. It is able to detect in very few examples.

Is this number of examples are insufficient?

My data looks like this -:

[("'Hi, I am looking for a house on rent for a year. Best Regards, Rajesh',\r",
  {'entities': [(56, 63, 'name')]}),
 ("'Hello everyone, I am Gunjan Arora',\r", {'entities': [(22, 34, 'name')]}),
 ("'Greetings!, I am 34 years old. I want a car for my wife Bella Roy',\r",
  {'entities': [(60, 69, 'name')]}),
 ("'Heyo, I lived with my family comprises 4 people and myself Randy Lao',\r",
  {'entities': [(60, 69, 'name')]}),
 ("'I am Geetanjali. ',\r", {'entities': [(6, 16, 'name')]})]

I have generated some 70 examples like this.

Losses during training -:

 - 1.Losses {'ner': 6.307317615201415}
 - 2.Losses {'ner': 11.182436657139132}
 - 3.Losses {'ner': 6.014345924849759}
 - 4.Losses {'ner': 6.442589285506237}
 - 5.Losses {'ner': 5.328383899880891}
 - 6.Losses {'ner': 1.706726450400089}
 - 7.Losses {'ner': 3.9960324752880005}
 - 8.Losses {'ner': 5.415169572852782}

These losses when I am using blank 'en' model

Please suggest.

I wanted to detect names as the pre-trained model itself is not able to detect names in most of the cases as well.


问:
Why do I get 404 error on RESTEasy (wildfly) after deploy?
I have created simple 3 files in Java, and used mvn clean package wildfly:deploy command to run it. It all deployed successfully (at least thats what is written in console). However, when I go to

http://localhost:8080/lab-rest-api/library/book

I get 404 error. My project is located in module lab-rest-api (its just a part of a project, other modules are for web consume - ejb, ear etc)

I did web service and simple web consuming and it worked out fine. However, REST API is not working.

Here is my pom.xml:

```<code> <dependency>
        <groupId>org.jboss.resteasy</groupId>
        <artifactId>resteasy-jaxrs</artifactId>
        <version>3.6.3.Final</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.jboss.resteasy</groupId>
        <artifactId>resteasy-client</artifactId>
        <version>3.6.3.Final</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.jboss.resteasy</groupId>
        <artifactId>resteasy-jaxb-provider</artifactId>
        <version>3.6.3.Final</version>
        <scope>provided</scope>
    </dependency>
</code>```

My extend Application:

```<code>@ApplicationPath("/")
public class RESTMain extends Application {
    public RESTMain() {
        System.out.println("whatever");
    }

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

And my service:

```<code>@Path("/library")
@Consumes({"application/json"})
@Produces({"application/json"})
public class ServicesInterface {

    Book booky = new Book();

    @GET
    @Path("/book/{title}")
    public Book getBook(@PathParam("title") String title){
        return booky;
    }

    @PUT
    @Path("/book/{title}")
    public Book addBook(@PathParam("title") String title, @QueryParam("author") String author){
        return booky;
    }

    @POST
    @Path("/book/{title}")
    public Book updateBook(@PathParam("title") String title, String author){
        return booky;
    }

    @DELETE
    @Path("/book/{title}")
    public Book removeBook(@PathParam("title") String title){
        return booky;
    }

}
</code>```

"Book" is a simple class with 2 Strings (author and title) and getters and setters for it.

答:
Okay so,

Steps to fix this :

1) Packaging a war

Add <packaging>war</packaging> to your pom file.
Also add

```<code><plugin>
  <artifactId>maven-war-plugin</artifactId>
  <version>2.4</version>
  <configuration>
    <failOnMissingWebXml>false</failOnMissingWebXml>
    </configuration>
</plugin>
</code>```

2) Upgrade wildfly maven plugin

```<code><version.wildfly.maven.plugin>2.0.1.Final</version.wildfly.maven.plugin>
</code>```

3) Remove duplicate dependency

```<code><dependency>
    <groupId>javax.validation</groupId>
    <artifactId>validation-api</artifactId>
    <version>2.0.1.Final</version>
    <scope>compile</scope>
</dependency>
</code>```

4) Remove this extra stuff from wildfly-maven-plugin configuration

```<code><inherited>true</inherited>
<configuration>
    <skip>true</skip>
</configuration>
</code>```

5) Run your mvn clean package wildfly:deploy

6) Browse to http://localhost:8080/lab-rest-api-1.0-SNAPSHOT/library/book/asd

BONUS : Accepted answer of this shows how to remove -1.0-SNAPSHOT from the URL.

Body:
I have created simple 3 files in Java, and used mvn clean package wildfly:deploy command to run it. It all deployed successfully (at least thats what is written in console). However, when I go to

http://localhost:8080/lab-rest-api/library/book

I get 404 error. My project is located in module lab-rest-api (its just a part of a project, other modules are for web consume - ejb, ear etc)

I did web service and simple web consuming and it worked out fine. However, REST API is not working.

Here is my pom.xml:

 <dependency>
        <groupId>org.jboss.resteasy</groupId>
        <artifactId>resteasy-jaxrs</artifactId>
        <version>3.6.3.Final</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.jboss.resteasy</groupId>
        <artifactId>resteasy-client</artifactId>
        <version>3.6.3.Final</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.jboss.resteasy</groupId>
        <artifactId>resteasy-jaxb-provider</artifactId>
        <version>3.6.3.Final</version>
        <scope>provided</scope>
    </dependency>

My extend Application:

@ApplicationPath("/")
public class RESTMain extends Application {
    public RESTMain() {
        System.out.println("whatever");
    }

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

And my service:

@Path("/library")
@Consumes({"application/json"})
@Produces({"application/json"})
public class ServicesInterface {

    Book booky = new Book();

    @GET
    @Path("/book/{title}")
    public Book getBook(@PathParam("title") String title){
        return booky;
    }

    @PUT
    @Path("/book/{title}")
    public Book addBook(@PathParam("title") String title, @QueryParam("author") String author){
        return booky;
    }

    @POST
    @Path("/book/{title}")
    public Book updateBook(@PathParam("title") String title, String author){
        return booky;
    }

    @DELETE
    @Path("/book/{title}")
    public Book removeBook(@PathParam("title") String title){
        return booky;
    }

}

"Book" is a simple class with 2 Strings (author and title) and getters and setters for it.

Body:
Okay so,

Steps to fix this :

1) Packaging a war

Add <packaging>war</packaging> to your pom file.
Also add

<plugin>
  <artifactId>maven-war-plugin</artifactId>
  <version>2.4</version>
  <configuration>
    <failOnMissingWebXml>false</failOnMissingWebXml>
    </configuration>
</plugin>

2) Upgrade wildfly maven plugin

<version.wildfly.maven.plugin>2.0.1.Final</version.wildfly.maven.plugin>

3) Remove duplicate dependency

<dependency>
    <groupId>javax.validation</groupId>
    <artifactId>validation-api</artifactId>
    <version>2.0.1.Final</version>
    <scope>compile</scope>
</dependency>

4) Remove this extra stuff from wildfly-maven-plugin configuration

<inherited>true</inherited>
<configuration>
    <skip>true</skip>
</configuration>

5) Run your mvn clean package wildfly:deploy

6) Browse to http://localhost:8080/lab-rest-api-1.0-SNAPSHOT/library/book/asd

BONUS : Accepted answer of this shows how to remove -1.0-SNAPSHOT from the URL.


问:
Node.js - "PROTOCOL_ENQUEUE_AFTER_FATAL_ERROR" in MySQL
I am trying to write an Node + Express to provide REST services. Everything goes well when the application starts.

However, after several hours, I got an error: "code":"PROTOCOL_ENQUEUE_AFTER_FATAL_ERROR","fatal":false. It seems some resources are running out. Did someone know how to fix it.

Here is the main part of code:

```<code>var mysql   = require("mysql");
var _ = require('underscore')
var Q = require("q");

function REST_ROUTER(router,connection,md5) {
    var self = this;
    self.handleRoutes(router,connection,md5);
}

var queryWithPromise = function (connection, query) {
    var deferred = Q.defer();
    connection.query(query, function(err, rows, fields) {
        if (err) {
            deferred.reject(err);
        };
        if (!rows||(rows.length === 0)) {
          deferred.reject("No record!");
        }
        deferred.resolve(rows);
    });
    return deferred.promise;
};

REST_ROUTER.prototype.handleRoutes = function(router,connection,md5) {
    var self = this;
    router.get("/",function(req,res){
        res.json({"Message" : "Hello World !"});
    });
    router.get("/data/:token/:latlng",function(req,res){
        //console.log(req.params.token);
        query = mysql.format("SELECT * FROM TOKEN WHERE token=?",[req.params.token]);
        queryWithPromise(connection, query).then(function (tokens) {
            var latlngs = req.params.latlng.split(',');
            var lat = parseFloat(latlngs[0]);
            var lng = parseFloat(latlngs[1]);
            var queryLatLng = mysql.format("SELECT * FROM device WHERE longitude > ? AND longitude < ? AND latitude > ? AND latitude < ?", [lng-0.1, lng+0.1, lat-0.1, lat+0.1]);
            return queryWithPromise(connection, queryLatLng);
        }).then(function (devices) {
            var latlngs = req.params.latlng.split(',');
            var computeDistance = function (fromLatlng, toLatlng) {
                var toRad = function (degree) {
                    return degree * Math.PI / 180;
                };
                var EARTH_RADIUS = 6378137; // in meter
                var lat1 = toRad(fromLatlng.lat);
                var lng1 = toRad(fromLatlng.lng);
                var lat2 = toRad(toLatlng.lat);
                var lng2 = toRad(toLatlng.lng);
                var d = EARTH_RADIUS*Math.acos(Math.sin(lat1)*Math.sin(lat2) + Math.cos(lat1)*Math.cos(lat2)*Math.cos(lng1 - lng2));
                return d;
            };
            var closestDevice = _.min(devices, function(device) {
                return computeDistance({lat: parseFloat(latlngs[0]), lng: parseFloat(latlngs[1])}, {lat: device.latitude, lng: device.longitude});
            });
            var queryDevice = mysql.format("SELECT * FROM ?? ORDER BY UploadTime DESC LIMIT 100", [closestDevice.device_id]);
            return queryWithPromise(connection, queryDevice);
        }).then(function (data) {
            var latlngs = req.params.latlng.split(',');
            res.json({
                "latitude": parseFloat(latlngs[0]),
                "longitude": parseFloat(latlngs[1]),
                "timezone": "Asia/Shanghai",
                "offset": 8,
                 "hourly": {
                    "data": _.map(data, function(item) {
                        return {
                            "time": item.UploadTime.getTime()/1000,
                            "precipIntensity": item.rainfall,
                            "temperature": item.airtemp,
                            "humidity": item.airhumidity,
                            "windSpeed": item.windspeed,
                            "windBearing": item.winddirection,
                            "pressure": item.atmosphericpressure,
                            "soiltemp": item.soiltemp,
                            "soilhumidity": item.soilhumidity
                        };
                    })
                 }
            });
        }).catch(function (error) {
            res.json({"Error" : true, "Message" : "Success", "Data" : error});
        })
        .done();
    });
}

module.exports = REST_ROUTER;
</code>```

答:
In my experience, that problem was due to creating a connection directly (with mysqljs/mysql library, using createConnection()) instead of using createPool() that allows to run query() and releases the connection automatically after execution (doing getConnection() + query() + release()).

Without that the connection is not released and, at the next attempt to query, there happens the fatal error.

See Pooling Connections.

Body:
I am trying to write an Node + Express to provide REST services. Everything goes well when the application starts.

However, after several hours, I got an error: "code":"PROTOCOL_ENQUEUE_AFTER_FATAL_ERROR","fatal":false. It seems some resources are running out. Did someone know how to fix it.

Here is the main part of code:

var mysql   = require("mysql");
var _ = require('underscore')
var Q = require("q");

function REST_ROUTER(router,connection,md5) {
    var self = this;
    self.handleRoutes(router,connection,md5);
}

var queryWithPromise = function (connection, query) {
    var deferred = Q.defer();
    connection.query(query, function(err, rows, fields) {
        if (err) {
            deferred.reject(err);
        };
        if (!rows||(rows.length === 0)) {
          deferred.reject("No record!");
        }
        deferred.resolve(rows);
    });
    return deferred.promise;
};

REST_ROUTER.prototype.handleRoutes = function(router,connection,md5) {
    var self = this;
    router.get("/",function(req,res){
        res.json({"Message" : "Hello World !"});
    });
    router.get("/data/:token/:latlng",function(req,res){
        //console.log(req.params.token);
        query = mysql.format("SELECT * FROM TOKEN WHERE token=?",[req.params.token]);
        queryWithPromise(connection, query).then(function (tokens) {
            var latlngs = req.params.latlng.split(',');
            var lat = parseFloat(latlngs[0]);
            var lng = parseFloat(latlngs[1]);
            var queryLatLng = mysql.format("SELECT * FROM device WHERE longitude > ? AND longitude < ? AND latitude > ? AND latitude < ?", [lng-0.1, lng+0.1, lat-0.1, lat+0.1]);
            return queryWithPromise(connection, queryLatLng);
        }).then(function (devices) {
            var latlngs = req.params.latlng.split(',');
            var computeDistance = function (fromLatlng, toLatlng) {
                var toRad = function (degree) {
                    return degree * Math.PI / 180;
                };
                var EARTH_RADIUS = 6378137; // in meter
                var lat1 = toRad(fromLatlng.lat);
                var lng1 = toRad(fromLatlng.lng);
                var lat2 = toRad(toLatlng.lat);
                var lng2 = toRad(toLatlng.lng);
                var d = EARTH_RADIUS*Math.acos(Math.sin(lat1)*Math.sin(lat2) + Math.cos(lat1)*Math.cos(lat2)*Math.cos(lng1 - lng2));
                return d;
            };
            var closestDevice = _.min(devices, function(device) {
                return computeDistance({lat: parseFloat(latlngs[0]), lng: parseFloat(latlngs[1])}, {lat: device.latitude, lng: device.longitude});
            });
            var queryDevice = mysql.format("SELECT * FROM ?? ORDER BY UploadTime DESC LIMIT 100", [closestDevice.device_id]);
            return queryWithPromise(connection, queryDevice);
        }).then(function (data) {
            var latlngs = req.params.latlng.split(',');
            res.json({
                "latitude": parseFloat(latlngs[0]),
                "longitude": parseFloat(latlngs[1]),
                "timezone": "Asia/Shanghai",
                "offset": 8,
                 "hourly": {
                    "data": _.map(data, function(item) {
                        return {
                            "time": item.UploadTime.getTime()/1000,
                            "precipIntensity": item.rainfall,
                            "temperature": item.airtemp,
                            "humidity": item.airhumidity,
                            "windSpeed": item.windspeed,
                            "windBearing": item.winddirection,
                            "pressure": item.atmosphericpressure,
                            "soiltemp": item.soiltemp,
                            "soilhumidity": item.soilhumidity
                        };
                    })
                 }
            });
        }).catch(function (error) {
            res.json({"Error" : true, "Message" : "Success", "Data" : error});
        })
        .done();
    });
}

module.exports = REST_ROUTER;


问:
CORS/JavaScript/Laravel: Sending request to Digital Ocean server and receiving data (Headers issues)
So, what I'm trying to do is use a Digital Ocean droplet as an api for an application hosted on a different server. Currently, I'm just developing so this server is from my localhost:3000.

On my client side code (JavaScript) I have:

```<code>  handleSendData = () => {
    const request = new XMLHttpRequest()
    request.open('POST', 'http://my-droplet-ip/api/create-image')
    request.setRequestHeader('Content-Type', 'application/json; charset=UTF-8')
    request.setRequestHeader('Access-Control-Allow-Origin', 'http://my-droplet-ip')
    request.send(JSON.stringify(data-object))
  }
</code>```

Finally, in my Laravel application (Laravel Framework 5.8.18) I have a route under routes/api.php:

```<code>Route::post('/create-image', 'CreateData');
</code>```

And I have a controller CreateData.php:

```<code><?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class CreateImage extends Controller
{
    /**
     * Handle the incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function __invoke(Request $request)
    {
        return response('Hello World', 200)
            ->header('Content-Type', 'application/json; charset=UTF-8')
            ->header('Access-Control-Allow-Origin', '*');
    }
}
</code>```

The problem is when I try to run this request, I get a CORS error:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://my-droplet-ip/api/create-image. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing)

Under the networking tab I get a 404 not found and the Access header is not there in the response.

Any thoughts out there on this issue?

答:
There is a simple solution to this and it is ok for testing on you local machine.

You could just put in index file to allow cors, but I suggest you building middleware for this.

Here is a link it is explained really nice:)

https://medium.com/@petehouston/allow-cors-in-laravel-2b574c51d0c1

You can put also this in index.php

```<code>header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
</code>```

Hope it helps :D

Body:
So, what I'm trying to do is use a Digital Ocean droplet as an api for an application hosted on a different server. Currently, I'm just developing so this server is from my localhost:3000.

On my client side code (JavaScript) I have:

  handleSendData = () => {
    const request = new XMLHttpRequest()
    request.open('POST', 'http://my-droplet-ip/api/create-image')
    request.setRequestHeader('Content-Type', 'application/json; charset=UTF-8')
    request.setRequestHeader('Access-Control-Allow-Origin', 'http://my-droplet-ip')
    request.send(JSON.stringify(data-object))
  }

Finally, in my Laravel application (Laravel Framework 5.8.18) I have a route under routes/api.php:

Route::post('/create-image', 'CreateData');

And I have a controller CreateData.php:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class CreateImage extends Controller
{
    /**
     * Handle the incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function __invoke(Request $request)
    {
        return response('Hello World', 200)
            ->header('Content-Type', 'application/json; charset=UTF-8')
            ->header('Access-Control-Allow-Origin', '*');
    }
}

The problem is when I try to run this request, I get a CORS error:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://my-droplet-ip/api/create-image. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing)

Under the networking tab I get a 404 not found and the Access header is not there in the response.

Any thoughts out there on this issue?

Body:
There is a simple solution to this and it is ok for testing on you local machine.

You could just put in index file to allow cors, but I suggest you building middleware for this.

Here is a link it is explained really nice:)

https://medium.com/@petehouston/allow-cors-in-laravel-2b574c51d0c1

You can put also this in index.php

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");

Hope it helps :D


问:
How to use @material-ui/core/useScrollTrigger in Next.js?
I am studying the documentation Material-UI useScrollTrigger and trying to apply it to Next to repeat the Elevate App Bar.

https://material-ui.com/components/app-bar/#usescrolltrigger-options-trigger

```<code>import React from "react";
import AppBar from "@material-ui/core/AppBar";
import useScrollTrigger from "@material-ui/core/useScrollTrigger";

interface Props {
  children: React.ReactElement;
}

function ElevationScroll(props: Props) {
  const children = props;
  const trigger = useScrollTrigger({
    disableHysteresis: true,
    threshold: 0
  });

  return React.cloneElement(children, {
    elevation: trigger ? 4 : 0
  });
}

export default class HeaderAppBar {
  render() {
    return (
      <ElevationScroll {...props}>
        <AppBar />
      </ElevationScroll {...props}>
    );
  }
}
</code>```

But I get the error ReferenceError: props is not defined. Please help solve the problem.

答:
HeaderAppBar is a class component, so you need to refer to this.props instead of just props.

Also, you’ll need to destructure children off of props in ElevationScroll:

const { children } = props

Body:
I am studying the documentation Material-UI useScrollTrigger and trying to apply it to Next to repeat the Elevate App Bar.

https://material-ui.com/components/app-bar/#usescrolltrigger-options-trigger

import React from "react";
import AppBar from "@material-ui/core/AppBar";
import useScrollTrigger from "@material-ui/core/useScrollTrigger";

interface Props {
  children: React.ReactElement;
}

function ElevationScroll(props: Props) {
  const children = props;
  const trigger = useScrollTrigger({
    disableHysteresis: true,
    threshold: 0
  });

  return React.cloneElement(children, {
    elevation: trigger ? 4 : 0
  });
}

export default class HeaderAppBar {
  render() {
    return (
      <ElevationScroll {...props}>
        <AppBar />
      </ElevationScroll {...props}>
    );
  }
}

But I get the error ReferenceError: props is not defined. Please help solve the problem.


问:
How to remove duplicated words in csv rows in python?
I am working with csv file and I have many rows that contain duplicated words and I want to remove any duplicates (I also don't want to lose the order of the sentences).

csv file example (userID and description are the columns name):

```<code>userID, description

12, hello world hello world

13, I will keep the 2000 followers same I will keep the 2000 followers same

14, I paid $2000 to the car I paid $2000 to the car I paid $2000 to the car

.

.
</code>```

I would like to have the output as:

```<code>userID, description

12, hello world

13, I will keep the 2000 followers same

14, I paid $2000 to the car

.

.
</code>```

I already tried the post such as 1 2 3 but none of them fixed my problem and did not change anything. (Order for my output file matters, since I don't want to lose the orders). It would be great if you can provide your help with a code sample that I can run in my side and learn.
Thank you

[I am using python 3.7 version]

答:
Solution taken from here:

```<code>def principal_period(s):
    i = (s+s).find(s, 1)
    return s[:i]

df['description'].apply(principal_period)
</code>```

Output:

```<code>0                                 hello world
1     I will keep the 2000 followers the same
2                     I paid $2000 to the car
Name: description, dtype: object
</code>```

Since this uses apply on string, it might be slow.

Body:
I am working with csv file and I have many rows that contain duplicated words and I want to remove any duplicates (I also don't want to lose the order of the sentences).

csv file example (userID and description are the columns name):

userID, description

12, hello world hello world

13, I will keep the 2000 followers same I will keep the 2000 followers same

14, I paid $2000 to the car I paid $2000 to the car I paid $2000 to the car

.

.

I would like to have the output as:

userID, description

12, hello world

13, I will keep the 2000 followers same

14, I paid $2000 to the car

.

.

I already tried the post such as 1 2 3 but none of them fixed my problem and did not change anything. (Order for my output file matters, since I don't want to lose the orders). It would be great if you can provide your help with a code sample that I can run in my side and learn.
Thank you

[I am using python 3.7 version]

Body:
Solution taken from here:

def principal_period(s):
    i = (s+s).find(s, 1)
    return s[:i]

df['description'].apply(principal_period)

Output:

0                                 hello world
1     I will keep the 2000 followers the same
2                     I paid $2000 to the car
Name: description, dtype: object

Since this uses apply on string, it might be slow.


问:
Can you find all classes in a package using reflection?
Is it possible to find all classes or interfaces in a given package? (Quickly looking at e.g. Package, it would seem like no.)

答:
plain java: FindAllClassesUsingPlainJavaReflectionTest.java

@Slf4j
class FindAllClassesUsingPlainJavaReflectionTest {

  private static final Function<Throwable, RuntimeException> asRuntimeException = throwable -> {
    log.error(throwable.getLocalizedMessage());
    return new RuntimeException(throwable);
  };

  private static final Function<String, Collection<Class<?>>> findAllPackageClasses = basePackageName -> {

    Locale locale = Locale.getDefault();
    Charset charset = StandardCharsets.UTF_8;
    val fileManager = ToolProvider.getSystemJavaCompiler()
                                  .getStandardFileManager(/* diagnosticListener */ null, locale, charset);

    StandardLocation location = StandardLocation.CLASS_PATH;
    JavaFileObject.Kind kind = JavaFileObject.Kind.CLASS;
    Set<JavaFileObject.Kind> kinds = Collections.singleton(kind);
    val javaFileObjects = Try.of(() -> fileManager.list(location, basePackageName, kinds, /* recurse */ true))
                             .getOrElseThrow(asRuntimeException);

    String pathToPackageAndClass = basePackageName.replace(".", File.separator);
    Function<String, String> mapToClassName = s -> {
      String prefix = Arrays.stream(s.split(pathToPackageAndClass))
                            .findFirst()
                            .orElse("");
      return s.replaceFirst(prefix, "")
              .replaceAll(File.separator, ".");
    };

    return StreamSupport.stream(javaFileObjects.spliterator(), /* parallel */ true)
                        .filter(javaFileObject -> javaFileObject.getKind().equals(kind))
                        .map(FileObject::getName)
                        .map(fileObjectName -> fileObjectName.replace(".class", ""))
                        .map(mapToClassName)
                        .map(className -> Try.of(() -> Class.forName(className))
                                             .getOrElseThrow(asRuntimeException))
                        .collect(Collectors.toList());
  };

  @Test
  @DisplayName("should get classes recursively in given package")
  void test() {
    Collection<Class<?>> classes = findAllPackageClasses.apply(getClass().getPackage().getName());
    assertThat(classes).hasSizeGreaterThan(4);
    classes.stream().map(String::valueOf).forEach(log::info);
  }
}
```

PS: to simplify boilerplates for handling errors, etc, I'm using here vavr and lombok libraries

other implementations could be found in my GitHub daggerok/java-reflection-find-annotated-classes-or-methods repo

OwnerDisplayName: Jonik

Body:
plain java: FindAllClassesUsingPlainJavaReflectionTest.java

@Slf4j
class FindAllClassesUsingPlainJavaReflectionTest {

  private static final Function<Throwable, RuntimeException> asRuntimeException = throwable -> {
    log.error(throwable.getLocalizedMessage());
    return new RuntimeException(throwable);
  };

  private static final Function<String, Collection<Class<?>>> findAllPackageClasses = basePackageName -> {

    Locale locale = Locale.getDefault();
    Charset charset = StandardCharsets.UTF_8;
    val fileManager = ToolProvider.getSystemJavaCompiler()
                                  .getStandardFileManager(/* diagnosticListener */ null, locale, charset);

    StandardLocation location = StandardLocation.CLASS_PATH;
    JavaFileObject.Kind kind = JavaFileObject.Kind.CLASS;
    Set<JavaFileObject.Kind> kinds = Collections.singleton(kind);
    val javaFileObjects = Try.of(() -> fileManager.list(location, basePackageName, kinds, /* recurse */ true))
                             .getOrElseThrow(asRuntimeException);

    String pathToPackageAndClass = basePackageName.replace(".", File.separator);
    Function<String, String> mapToClassName = s -> {
      String prefix = Arrays.stream(s.split(pathToPackageAndClass))
                            .findFirst()
                            .orElse("");
      return s.replaceFirst(prefix, "")
              .replaceAll(File.separator, ".");
    };

    return StreamSupport.stream(javaFileObjects.spliterator(), /* parallel */ true)
                        .filter(javaFileObject -> javaFileObject.getKind().equals(kind))
                        .map(FileObject::getName)
                        .map(fileObjectName -> fileObjectName.replace(".class", ""))
                        .map(mapToClassName)
                        .map(className -> Try.of(() -> Class.forName(className))
                                             .getOrElseThrow(asRuntimeException))
                        .collect(Collectors.toList());
  };

  @Test
  @DisplayName("should get classes recursively in given package")
  void test() {
    Collection<Class<?>> classes = findAllPackageClasses.apply(getClass().getPackage().getName());
    assertThat(classes).hasSizeGreaterThan(4);
    classes.stream().map(String::valueOf).forEach(log::info);
  }
}

PS: to simplify boilerplates for handling errors, etc, I'm using here vavr and lombok libraries

other implementations could be found in my GitHub daggerok/java-reflection-find-annotated-classes-or-methods repo


问:
Title on other Activities
I need that the sentence in the mainActivity "datos tarjeta credito" appears also in the top of the second activity. The xml layouts are the same, I don't understand where can I change this. This is what is now:

I tried to attach the xml layouts, but its not working.

答:
In your Activity theme put that:

(I used Theme.AppCompat.Light.DarkActionBar as an example, but anyone should do)

```<code><style name="yourTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="windowActionBar">true</item>
    <item name="windowNoTitle">true</item>
</style>

<application
    ...
    android:theme="@style/yourTheme"> <!-- apply to all activities ->
    <activity
        android:name=".MainActivity"
        android:theme="@style/yourTheme"> <!-- apply to one activity ->
    </activity>
</application>
</code>```

Title: Title on other Activities

Body:
In your Activity theme put that:

(I used Theme.AppCompat.Light.DarkActionBar as an example, but anyone should do)

<style name="yourTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="windowActionBar">true</item>
    <item name="windowNoTitle">true</item>
</style>

<application
    ...
    android:theme="@style/yourTheme"> <!-- apply to all activities ->
    <activity
        android:name=".MainActivity"
        android:theme="@style/yourTheme"> <!-- apply to one activity ->
    </activity>
</application>


问:
How to compile a Delphi projectgroup using MSBuild called from an Embarcadero Makefile
I am trying to compile the two components from Virtual Treeview (VirtualTreesR.bpl and VirtualTreesD.bpl) which I combined in a Delphi project group called VirtualTrees.groupproj. They should be compiled using MSBuild, but this call is done from a (Embarcadero) Makefile. The relevant part in the Makefile looks like:

```<code>msbuild.exe /nologo /v:m /t:build /p:Config=Release "$(VTVDIR)\Packages\Delphi 2010\VirtualTrees.groupproj"
</code>```

Unfortunately this results in MSB4040, because the environment variable BDS is not set in cmd.exe, but it is in the Makefile. I tried a SET BDS=$(BDS) before the call to msbuild, but to no avail. I also tried to set BDS as property(/p:BDS=($BDS);Config=Release) which caused another error (something liks: Could not find compiler at %BDS%\bin\dcc32.exe).

This call from the Makefile is part of a preparation to build our product on a CI server, and I cannot guarantee that the BDS variable is set there. So how can I provide the BDS variable which I have in the Makefile to msbuild that it accepts it?

答:
In my batch files, I use rsvars.bat:

```<code>call "C:\Program Files (x86)\CodeGear\RAD Studio\5.0\bin\rsvars.bat"
MSBuild SomeProject.dproj ...
</code>```

(You'd have to adjust the path obviously.)

Body:
I am trying to compile the two components from Virtual Treeview (VirtualTreesR.bpl and VirtualTreesD.bpl) which I combined in a Delphi project group called VirtualTrees.groupproj. They should be compiled using MSBuild, but this call is done from a (Embarcadero) Makefile. The relevant part in the Makefile looks like:

msbuild.exe /nologo /v:m /t:build /p:Config=Release "$(VTVDIR)\Packages\Delphi 2010\VirtualTrees.groupproj"

Unfortunately this results in MSB4040, because the environment variable BDS is not set in cmd.exe, but it is in the Makefile. I tried a SET BDS=$(BDS) before the call to msbuild, but to no avail. I also tried to set BDS as property(/p:BDS=($BDS);Config=Release) which caused another error (something liks: Could not find compiler at %BDS%\bin\dcc32.exe).

This call from the Makefile is part of a preparation to build our product on a CI server, and I cannot guarantee that the BDS variable is set there. So how can I provide the BDS variable which I have in the Makefile to msbuild that it accepts it?

Body:
In my batch files, I use rsvars.bat:

call "C:\Program Files (x86)\CodeGear\RAD Studio\5.0\bin\rsvars.bat"
MSBuild SomeProject.dproj ...

(You'd have to adjust the path obviously.)


问:
How to reset a RXJS scan operator based on another Observable
I have a component which triggers an onScrollEnd event when the last item in a virtual list is rendered. This event will do a new API request to fetch the next page and merge them with the previous results using the scan operator.

This component also has a search field which triggers an onSearch event.

How do I clear the previous accumulated results from the scan operator when a search event is triggered? Or do I need to refactor my logic here?

```<code>const loading$ = new BehaviorSubject(false);
const offset$ = new BehaviorSubject(0);
const search$ = new BehaviorSubject(null);

const options$: Observable<any[]> = merge(offset$, search$).pipe(
  // 1. Start the loading indicator.
  tap(() => loading$.next(true)),
  // 2. Fetch new items based on the offset.
  switchMap(([offset, searchterm]) => userService.getUsers(offset, searchterm)),
  // 3. Stop the loading indicator.
  tap(() => loading$.next(false)),
  // 4. Complete the Observable when there is no 'next' link.
  takeWhile((response) => response.links.next),
  // 5. Map the response.
  map(({ data }) =>
    data.map((user) => ({
      label: user.name,
      value: user.id
    }))
  ),
  // 6. Accumulate the new options with the previous options.
  scan((acc, curr) => {
    // TODO: Dont merge on search$.next
    return [...acc, ...curr]);
  }
);

// Fetch next page
onScrollEnd: (offset: number) => offset$.next(offset);
// Fetch search results
onSearch: (term) => {
  search$.next(term);
};
</code>```

答:
This is an interesting stream. Thinking about it, offset$ and search$ are really 2 separate streams, though, with different logic, and so should be merged at the very end and not the beginning.

Also, it seems to me that searching should reset the offset to 0, and I don't see that in the current logic.

So here's my idea:

```<code>const offsettedOptions$ = offset$.pipe(
    tap(() => loading$.next(true)),
    withLatestFrom(search$),
    concatMap(([offset, searchterm]) => userService.getUsers(offset, searchterm)),
    tap(() => loading$.next(false)),
    map(({ data }) =>
    data.map((user) => ({
      label: user.name,
      value: user.id
    })),
    scan((acc, curr) => [...acc, ...curr])
);

const searchedOptions$ = search$.pipe(
    tap(() => loading$.next(true)),
    concatMap(searchTerm => userService.getUsers(0, searchterm)),
    tap(() => loading$.next(false)),
    map(({ data }) =>
    data.map((user) => ({
      label: user.name,
      value: user.id
    })),
);

const options$ = merge(offsettedOptions, searchedOptions);
</code>```

See if that works or would make sense. I may be missing some context.

Body:
I have a component which triggers an onScrollEnd event when the last item in a virtual list is rendered. This event will do a new API request to fetch the next page and merge them with the previous results using the scan operator.

This component also has a search field which triggers an onSearch event.

How do I clear the previous accumulated results from the scan operator when a search event is triggered? Or do I need to refactor my logic here?

const loading$ = new BehaviorSubject(false);
const offset$ = new BehaviorSubject(0);
const search$ = new BehaviorSubject(null);

const options$: Observable<any[]> = merge(offset$, search$).pipe(
  // 1. Start the loading indicator.
  tap(() => loading$.next(true)),
  // 2. Fetch new items based on the offset.
  switchMap(([offset, searchterm]) => userService.getUsers(offset, searchterm)),
  // 3. Stop the loading indicator.
  tap(() => loading$.next(false)),
  // 4. Complete the Observable when there is no 'next' link.
  takeWhile((response) => response.links.next),
  // 5. Map the response.
  map(({ data }) =>
    data.map((user) => ({
      label: user.name,
      value: user.id
    }))
  ),
  // 6. Accumulate the new options with the previous options.
  scan((acc, curr) => {
    // TODO: Dont merge on search$.next
    return [...acc, ...curr]);
  }
);

// Fetch next page
onScrollEnd: (offset: number) => offset$.next(offset);
// Fetch search results
onSearch: (term) => {
  search$.next(term);
};

Body:
This is an interesting stream. Thinking about it, offset$ and search$ are really 2 separate streams, though, with different logic, and so should be merged at the very end and not the beginning.

Also, it seems to me that searching should reset the offset to 0, and I don't see that in the current logic.

So here's my idea:

const offsettedOptions$ = offset$.pipe(
    tap(() => loading$.next(true)),
    withLatestFrom(search$),
    concatMap(([offset, searchterm]) => userService.getUsers(offset, searchterm)),
    tap(() => loading$.next(false)),
    map(({ data }) =>
    data.map((user) => ({
      label: user.name,
      value: user.id
    })),
    scan((acc, curr) => [...acc, ...curr])
);

const searchedOptions$ = search$.pipe(
    tap(() => loading$.next(true)),
    concatMap(searchTerm => userService.getUsers(0, searchterm)),
    tap(() => loading$.next(false)),
    map(({ data }) =>
    data.map((user) => ({
      label: user.name,
      value: user.id
    })),
);

const options$ = merge(offsettedOptions, searchedOptions);

See if that works or would make sense. I may be missing some context.


问:
How to fix error of saving file Laravel using File facade?
I get the following error:

```<code>{"errors":"Method Illuminate\\Filesystem\\Filesystem::create does not exist."}
</code>```

Imports are:

```<code>use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\File;
</code>```

Code is:

```<code>$created = File::create(["path" => $path.$filename]);
</code>```

答:
to save file uploading from a form, simply use Storage</p>

```<code>use Illuminate\Support\Facades\Storage;

$path = Storage::putFile('path/avatars', $request->file('avatar'));
</code>```

Body:
I get the following error:

{"errors":"Method Illuminate\\Filesystem\\Filesystem::create does not exist."}

Imports are:

use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\File;

Code is:

$created = File::create(["path" => $path.$filename]);

Body:
to save file uploading from a form, simply use Storage

use Illuminate\Support\Facades\Storage;

$path = Storage::putFile('path/avatars', $request->file('avatar'));


问:
Custom implementing like button in ASP .NET CORE with SignalR
Hy everyone,

sorry if my question is duplicate of some, but i didn't found solution for my problem.

However, i'm trying to implement custom like button for posts in my asp.net core mvc application and everything works fine, except when i click on like button, it changes color (like on facebook, blue color etc.) not just for current logged user, but for all logged users. But when other users refresh window, everything is back to normal...

What I want is, when I click on "like" button, to update "like counter" FOR EVERYONE and to change color JUST FOR ME (when I came back some other day, that I know that I liked that post.)

Does someone know how to acomplish this?
Here's my code

Index.cshtml

```<code>@using Fitness_Centar.Data
@using Fitness_Centar.Data.Models
@using Fitness_Centar.Web.Areas.ModulClan.ViewModels
@using Fitness_Centar.Web.Helper
@model List<TimelineVM>

@{
    ViewData["Title"] = "Index";
    MyContext _ctx = (MyContext)ViewData["_ctx"];

User u = Context.GetLoggedUser();
int userId = -1;
if (u.Coach != null)
{
    userId = u.Coach.CoachId;
}
if (u.Employee != null)
{
    userId = u.Employee.EmployeeId;
}
if (u.Member != null)
{
    userId = u.Member.MemberId;
}
}

<div class="row">
<div class="col-sm-12 col-md-9 col-lg-9">
    <div class="box box-info custom aktivnosti">
        <div class="box-header with-border padding-l-25">
            <h3 class="box-title">Activities</h3>
        </div>

        <div class="box-body">
            @foreach (var p in Model)
            {
                <div id="@p.Post.PostClanovaId" class="post">
                    <div class="user-info">
                        <img class="img-circle img-bordered-sm" src="~/AdminLTE/dist/img/avatar5.png" />
                        <div class="desc">
                            <span class="username">@p.Post.User.Name @p.Post.User.LastName</span>
                            <span class="post-description">Published: @p.Post.PostDate</span>
                        </div>
                    </div>
                    <div class="post-content text-justify">
                        <p>@p.Post.Content</p>
                    </div>
                    <div class="post-footer">
                        @{int n = p.Post.PostId + 1594;}
                        @{
                            var c = _ctx.Likes.Where(x => x.UserId == userId && x.PostId == p.Post.PostId).FirstOrDefault();

                            if (c != null && c.UserId == userId)
                            {
                                <a href="" id="post-@n" class="likeButton link-black liked" data-postid="@p.Post.PostId" data-userid="@userId">
                                    <i class="fa fa-thumbs-o-up margin-r-5"></i>
                                    Like
                                </a>
                            }
                            else
                            {
                                <a href="" id="post-@n" class="likeButton link-black" data-postid="@p.Post.PostId" data-userid="@userId">
                                    <i class="fa fa-thumbs-o-up margin-r-5"></i>
                                    Like
                                </a>
                            }
                        }
                        <div class="num-of-likes" id="post-@n-numOfLikes">
                            @p.Likes.Count()
                            <span class="usersThatLiked">
                                @{
                                    string g = "";
                                    foreach (var l in p.Likes)
                                    {
                                        g += l.User.Ime + " " + l.Clan.Prezime;
                                    }
                                    @g;
                                }
                            </span>
                        </div>
                        <div class="comment pull-right">
                            <a href="#" class="link-black">
                                <i class="fa fa-comments-o margin-r-5"></i>
                                Comments
                            </a>
                        </div>
                        <div class="input-group">
                            <input type="text" class="form-control" placeholder="Komentiraj...">
                            <span class="input-group-btn">
                                <button type="button" class="btn btn-info btn-flat"><i class="fa fa-check"></i></button>
                            </span>
                        </div>
                    </div>
                </div>
            }
        </div>
    </div>
</div>
</code>```

javascript.js

```<code>"use strict";
var $connection = new signalR.HubConnectionBuilder().withUrl("/ModulClan/Helper/LajkHub").build();

$(".likeButton").prop("disabled", true);

$connection.on("ReceiveMessage", function (numOfLikes, postId) {
    var x = postId + 1594;
    var s = "#post-" + x;
    if ($(s).hasClass("liked")) {
        $(s).removeClass("liked");
    } else {
        $(s).addClass("liked");
    }
    $(s + "-num-of-likes").text(numOfLikes);
});

$connection.start().then(function () {
    $(".likeButton").prop("disabled", false);
}).catch(function (err) {
    return console.error(err.toString());
});

$(".likeButton").bind("click", function (event) {
    var userId = $(this).attr("data-userid");
    var postId = $(this).attr("data-postid");

    $connection.invoke("SetLike", userId, postId).catch(function (err) {
        return console.error(err.toString());
    });
    event.preventDefault();
});
</code>```

LikeHub.cs

```<code>public class LikeHub : Hub
{
    private readonly MyContext _ctx;
    public LikeHub (MyContext context)
    {
        _ctx = context;
    }

    public async Task SetLike(int userId, int postId)
    {
        Likes l = new Likes();
        Likes temp = _ctx.Likes.Where(x => x.PostId == postId && x.UserId == userId).FirstOrDefault();

        if(temp != null)
        {
            _ctx.Likes.Remove(temp);
        }
        else
        {
            _ctx.Likes.Add(l);

            l.UserId = userId;
            l.PostId = postId;
        }

        _ctx.SaveChanges();

        int numOfLikes= _ctx.Likes.Where(x => x.PostId == postId).Count();

        await Clients.All.SendAsync("ReceiveMessage", numOfLikes, postId);
    }
}
</code>```

答:
You can identify the current user (who clicked the like button) via

var userId = $(this).attr("data-userid"); (as you did when someone clicks the like button).

But the problem is this, you are not checking for the userId when the SetLike is succeeded (inside the on ReceiveMessage javascript function).

so to solve this you need to send the userId of the user who clicked the like button from the backend to the frontend (to the on("ReceiveMessage"..) function)

e.g.: await Clients.All.SendAsync("ReceiveMessage", numOfLikes, postId, userId);

and on the ReciveMessage check if the userId you got from the backend match the current user who's browsing by var currentUserId = $(this).attr("data-userid");

if they are equal then color the like button, otherwise just update the like counter.

this way would solve your issue.

Another solution would be to send 2 requests one is specific for the user who clicked the like button and the other is to everyone to update the like counter.

Body:
Hy everyone,

sorry if my question is duplicate of some, but i didn't found solution for my problem.

However, i'm trying to implement custom like button for posts in my asp.net core mvc application and everything works fine, except when i click on like button, it changes color (like on facebook, blue color etc.) not just for current logged user, but for all logged users. But when other users refresh window, everything is back to normal...

What I want is, when I click on "like" button, to update "like counter" FOR EVERYONE and to change color JUST FOR ME (when I came back some other day, that I know that I liked that post.)

Does someone know how to acomplish this?
Here's my code

Index.cshtml

@using Fitness_Centar.Data
@using Fitness_Centar.Data.Models
@using Fitness_Centar.Web.Areas.ModulClan.ViewModels
@using Fitness_Centar.Web.Helper
@model List<TimelineVM>

@{
    ViewData["Title"] = "Index";
    MyContext _ctx = (MyContext)ViewData["_ctx"];

User u = Context.GetLoggedUser();
int userId = -1;
if (u.Coach != null)
{
    userId = u.Coach.CoachId;
}
if (u.Employee != null)
{
    userId = u.Employee.EmployeeId;
}
if (u.Member != null)
{
    userId = u.Member.MemberId;
}
}

Activities

            @foreach (var p in Model)
            {

                            @p.Post.User.Name @p.Post.User.LastName
                            Published: @p.Post.PostDate

@p.Post.Content

                        @{int n = p.Post.PostId + 1594;}
                        @{
                            var c = _ctx.Likes.Where(x => x.UserId == userId && x.PostId == p.Post.PostId).FirstOrDefault();

                            if (c != null && c.UserId == userId)
                            {

                                    Like

                            }
                            else
                            {

                                    Like

                            }
                        }

                            @p.Likes.Count()

                                @{
                                    string g = "";
                                    foreach (var l in p.Likes)
                                    {
                                        g += l.User.Ime + " " + l.Clan.Prezime;
                                    }
                                    @g;
                                }

                                Comments

                            <input type="text" class="form-control" placeholder="Komentiraj...">

                                <button type="button" class="btn btn-info btn-flat"></button>

            }

javascript.js

"use strict";
var $connection = new signalR.HubConnectionBuilder().withUrl("/ModulClan/Helper/LajkHub").build();

$(".likeButton").prop("disabled", true);

$connection.on("ReceiveMessage", function (numOfLikes, postId) {
    var x = postId + 1594;
    var s = "#post-" + x;
    if ($(s).hasClass("liked")) {
        $(s).removeClass("liked");
    } else {
        $(s).addClass("liked");
    }
    $(s + "-num-of-likes").text(numOfLikes);
});

$connection.start().then(function () {
    $(".likeButton").prop("disabled", false);
}).catch(function (err) {
    return console.error(err.toString());
});

$(".likeButton").bind("click", function (event) {
    var userId = $(this).attr("data-userid");
    var postId = $(this).attr("data-postid");

    $connection.invoke("SetLike", userId, postId).catch(function (err) {
        return console.error(err.toString());
    });
    event.preventDefault();
});

LikeHub.cs

public class LikeHub : Hub
{
    private readonly MyContext _ctx;
    public LikeHub (MyContext context)
    {
        _ctx = context;
    }

    public async Task SetLike(int userId, int postId)
    {
        Likes l = new Likes();
        Likes temp = _ctx.Likes.Where(x => x.PostId == postId && x.UserId == userId).FirstOrDefault();

        if(temp != null)
        {
            _ctx.Likes.Remove(temp);
        }
        else
        {
            _ctx.Likes.Add(l);

            l.UserId = userId;
            l.PostId = postId;
        }

        _ctx.SaveChanges();

        int numOfLikes= _ctx.Likes.Where(x => x.PostId == postId).Count();

        await Clients.All.SendAsync("ReceiveMessage", numOfLikes, postId);
    }
}