问:
getting error of undefined reference to vector2.h class | SFML
I am very sorry to pasted a very lengthy code here, but I found that's the best way to present this question. I think my compiler is ignoring the #include "Vector2.hpp". so please help me to solve this error. Your response would be very apricated!! thank you

getting error in this part of code (function name : liftpiece) :

```<code>if(e.key.code==Mouse::Left)
            {
                ismove=false;
                Vector2f p = s2[n].getPosition() + Vector2f(53.25,53.25);
                Vector2f newPos = Vector2f( 106.5*int(p.x/106.5), 106.5*int(p.y/106.5) );
                s2[n].setPosition(newPos);
            }
</code>```

Full code :

```<code>#include <SFML/Graphics.hpp>
#include <SFML/Window.hpp>

#include <time.h>
#include "texture.h"
#include "Mouse.h"
#include "Sprite.h"
#include "Vector2.hpp"
#include "Transformable.h"

using namespace sf;

int boardarr[8][8]= {-5,-4,-3,-2,-1,-3,-4,-5,
                     -6,-6,-6,-6,-6,-6,-6,-6,
                      0, 0, 0, 0, 0, 0, 0, 0,
                      0, 0, 0, 0, 0, 0, 0, 0,
                      0, 0, 0, 0, 0, 0, 0, 0,
                      0, 0, 0, 0, 0, 0, 0, 0,
                      6, 6, 6, 6, 6, 6, 6, 6,
                      5, 4, 3, 2, 1, 3, 4, 5};

class GAME

{

private:

    Texture board,piece;
    Sprite s1;
    Sprite s2[32];
    bool ismove=false;
    int dx=0,dy=0,n=0;

public :

    void droppiece(Vector2i POS)
    {
        if(this->ismove)
        {
            s2[n].setPosition(POS.x-dx,POS.y-dy);

        }
    }

    void liftpiece(Event e, Vector2i POS)
    {
        if(e.type==Event::MouseButtonPressed)
        {
            if(e.key.code==Mouse::Left)
            {
                for(int i=0; i<32; i++)
                {
                    if(s2[i].getGlobalBounds().contains(POS.x,POS.y))
                    {
                        ismove = true;
                        n=i;
                        dx = POS.x - s2[i].getPosition().x;
                        dy = POS.y - s2[i].getPosition().y;
                    }

                }
            }
        }

        if(e.type==Event::MouseButtonReleased)
        {
            if(e.key.code==Mouse::Left)
            {
                ismove=false;
                Vector2f p = s2[n].getPosition() + Vector2f(53.25,53.25);
                Vector2f newPos = Vector2f( 106.5*int(p.x/106.5), 106.5*int(p.y/106.5) );
                s2[n].setPosition(newPos);
            }
        }

    }

    void setimages()
    {

        board.loadFromFile("C:\\Users\\JIMMY RATHWA\\OneDrive\\Desktop\\images\\chessboard.png");
        piece.loadFromFile("C:\\Users\\JIMMY RATHWA\\OneDrive\\Desktop\\images\\chesspiece.png");

        s1.setTexture(board);
        piece.setSmooth(true);

        for(int i=0; i<32; i++)
        {
            s2[i].setTexture(piece);
        }

    }

    void setpieces()
    {
        int k=0;

        for(int i=0; i<8; i++)
        {
            for(int j=0; j<8; j++)
            {
                int n = boardarr[i][j];
                if(!n)
                {
                    continue;
                }
                int x = abs(n)-1;
                int y = n>0?0:1;
                s2[k].setTextureRect(IntRect(106.5*x,106.5*y,106.5,106.5));
                s2[k].setPosition(106.5*j,106.5*i);
                k++;
            }

        }

    }

    void windowdisplay()
    {

        RenderWindow Window(VideoMode(850,850),"JIMMY CHESS",Style::Titlebar|Style::Close);
        setimages();
        setpieces();

        while(Window.isOpen())
        {
            Event e;

            Vector2i POS = Mouse::getPosition(Window);

            while(Window.pollEvent(e))
            {

                if(e.type==Event::Closed)
                {
                    Window.close();
                }

                liftpiece(e,POS);

            }

            droppiece(POS);

            Window.clear();

            Window.draw(s1);

            for(int i=0; i<32; i++)
            {
                Window.draw(s2[i]);
            }
            //layer 1 : chess board
            Window.display();

        }

    }

};

int main()
{
    GAME game;

    game.windowdisplay();

    return 0;
}
</code>```

error : undefined reference to `sf::Vector2::Vector2(float, float)'

Vector2.hpp :

```<code>////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2018 Laurent Gomila (laurent@sfml-dev.org)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
//    you must not claim that you wrote the original software.
//    If you use this software in a product, an acknowledgment
//    in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
//    and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////

#ifndef SFML_VECTOR2_HPP
#define SFML_VECTOR2_HPP

namespace sf
{
////////////////////////////////////////////////////////////
/// \brief Utility template class for manipulating
///        2-dimensional vectors
///
////////////////////////////////////////////////////////////
template <typename T>
class Vector2
{
public:

    ////////////////////////////////////////////////////////////
    /// \brief Default constructor
    ///
    /// Creates a Vector2(0, 0).
    ///
    ////////////////////////////////////////////////////////////
    Vector2();

    ////////////////////////////////////////////////////////////
    /// \brief Construct the vector from its coordinates
    ///
    /// \param X X coordinate
    /// \param Y Y coordinate
    ///
    ////////////////////////////////////////////////////////////
    Vector2(T X, T Y);

    ////////////////////////////////////////////////////////////
    /// \brief Construct the vector from another type of vector
    ///
    /// This constructor doesn't replace the copy constructor,
    /// it's called only when U != T.
    /// A call to this constructor will fail to compile if U
    /// is not convertible to T.
    ///
    /// \param vector Vector to convert
    ///
    ////////////////////////////////////////////////////////////
    template <typename U>
    explicit Vector2(const Vector2<U>& vector);

    ////////////////////////////////////////////////////////////
    // Member data
    ////////////////////////////////////////////////////////////
    T x; ///< X coordinate of the vector
    T y; ///< Y coordinate of the vector
};

////////////////////////////////////////////////////////////
/// \relates Vector2
/// \brief Overload of unary operator -
///
/// \param right Vector to negate
///
/// \return Memberwise opposite of the vector
///
////////////////////////////////////////////////////////////
template <typename T>
Vector2<T> operator -(const Vector2<T>& right);

////////////////////////////////////////////////////////////
/// \relates Vector2
/// \brief Overload of binary operator +=
///
/// This operator performs a memberwise addition of both vectors,
/// and assigns the result to \a left.
///
/// \param left  Left operand (a vector)
/// \param right Right operand (a vector)
///
/// \return Reference to \a left
///
////////////////////////////////////////////////////////////
template <typename T>
Vector2<T>& operator +=(Vector2<T>& left, const Vector2<T>& right);

////////////////////////////////////////////////////////////
/// \relates Vector2
/// \brief Overload of binary operator -=
///
/// This operator performs a memberwise subtraction of both vectors,
/// and assigns the result to \a left.
///
/// \param left  Left operand (a vector)
/// \param right Right operand (a vector)
///
/// \return Reference to \a left
///
////////////////////////////////////////////////////////////
template <typename T>
Vector2<T>& operator -=(Vector2<T>& left, const Vector2<T>& right);

////////////////////////////////////////////////////////////
/// \relates Vector2
/// \brief Overload of binary operator +
///
/// \param left  Left operand (a vector)
/// \param right Right operand (a vector)
///
/// \return Memberwise addition of both vectors
///
////////////////////////////////////////////////////////////
template <typename T>
Vector2<T> operator +(const Vector2<T>& left, const Vector2<T>& right);

////////////////////////////////////////////////////////////
/// \relates Vector2
/// \brief Overload of binary operator -
///
/// \param left  Left operand (a vector)
/// \param right Right operand (a vector)
///
/// \return Memberwise subtraction of both vectors
///
////////////////////////////////////////////////////////////
template <typename T>
Vector2<T> operator -(const Vector2<T>& left, const Vector2<T>& right);

////////////////////////////////////////////////////////////
/// \relates Vector2
/// \brief Overload of binary operator *
///
/// \param left  Left operand (a vector)
/// \param right Right operand (a scalar value)
///
/// \return Memberwise multiplication by \a right
///
////////////////////////////////////////////////////////////
template <typename T>
Vector2<T> operator *(const Vector2<T>& left, T right);

////////////////////////////////////////////////////////////
/// \relates Vector2
/// \brief Overload of binary operator *
///
/// \param left  Left operand (a scalar value)
/// \param right Right operand (a vector)
///
/// \return Memberwise multiplication by \a left
///
////////////////////////////////////////////////////////////
template <typename T>
Vector2<T> operator *(T left, const Vector2<T>& right);

////////////////////////////////////////////////////////////
/// \relates Vector2
/// \brief Overload of binary operator *=
///
/// This operator performs a memberwise multiplication by \a right,
/// and assigns the result to \a left.
///
/// \param left  Left operand (a vector)
/// \param right Right operand (a scalar value)
///
/// \return Reference to \a left
///
////////////////////////////////////////////////////////////
template <typename T>
Vector2<T>& operator *=(Vector2<T>& left, T right);

////////////////////////////////////////////////////////////
/// \relates Vector2
/// \brief Overload of binary operator /
///
/// \param left  Left operand (a vector)
/// \param right Right operand (a scalar value)
///
/// \return Memberwise division by \a right
///
////////////////////////////////////////////////////////////
template <typename T>
Vector2<T> operator /(const Vector2<T>& left, T right);

////////////////////////////////////////////////////////////
/// \relates Vector2
/// \brief Overload of binary operator /=
///
/// This operator performs a memberwise division by \a right,
/// and assigns the result to \a left.
///
/// \param left  Left operand (a vector)
/// \param right Right operand (a scalar value)
///
/// \return Reference to \a left
///
////////////////////////////////////////////////////////////
template <typename T>
Vector2<T>& operator /=(Vector2<T>& left, T right);

////////////////////////////////////////////////////////////
/// \relates Vector2
/// \brief Overload of binary operator ==
///
/// This operator compares strict equality between two vectors.
///
/// \param left  Left operand (a vector)
/// \param right Right operand (a vector)
///
/// \return True if \a left is equal to \a right
///
////////////////////////////////////////////////////////////
template <typename T>
bool operator ==(const Vector2<T>& left, const Vector2<T>& right);

////////////////////////////////////////////////////////////
/// \relates Vector2
/// \brief Overload of binary operator !=
///
/// This operator compares strict difference between two vectors.
///
/// \param left  Left operand (a vector)
/// \param right Right operand (a vector)
///
/// \return True if \a left is not equal to \a right
///
////////////////////////////////////////////////////////////
template <typename T>
bool operator !=(const Vector2<T>& left, const Vector2<T>& right);

#include <SFML/System/Vector2.inl>

// Define the most common types
typedef Vector2<int>          Vector2i;
typedef Vector2<unsigned int> Vector2u;
typedef Vector2<float>        Vector2f;

} // namespace sf

#endif // SFML_VECTOR2_HPP

////////////////////////////////////////////////////////////
/// \class sf::Vector2
/// \ingroup system
///
/// sf::Vector2 is a simple class that defines a mathematical
/// vector with two coordinates (x and y). It can be used to
/// represent anything that has two dimensions: a size, a point,
/// a velocity, etc.
///
/// The template parameter T is the type of the coordinates. It
/// can be any type that supports arithmetic operations (+, -, /, *)
/// and comparisons (==, !=), for example int or float.
///
/// You generally don't have to care about the templated form (sf::Vector2<T>),
/// the most common specializations have special typedefs:
/// \li sf::Vector2<float> is sf::Vector2f
/// \li sf::Vector2<int> is sf::Vector2i
/// \li sf::Vector2<unsigned int> is sf::Vector2u
///
/// The sf::Vector2 class has a small and simple interface, its x and y members
/// can be accessed directly (there are no accessors like setX(), getX()) and it
/// contains no mathematical function like dot product, cross product, length, etc.
///
/// Usage example:
/// \code
/// sf::Vector2f v1(16.5f, 24.f);
/// v1.x = 18.2f;
/// float y = v1.y;
///
/// sf::Vector2f v2 = v1 * 5.f;
/// sf::Vector2f v3;
/// v3 = v1 + v2;
///
/// bool different = (v2 != v3);
/// \endcode
///
/// Note: for 3-dimensional vectors, see sf::Vector3.
///
////////////////////////////////////////////////////////////
</code>```

答: error : undefined reference to 'sf::Vector2::Vector2(float, float)' is a link error: It's saying it knows that you've declared that function, but when it went to find the implementation, it can't find it. You need to either have an implementation of template <typename T> sf::Vector2::Vector2(T,T) in the header, or provide it in a .cpp and link against it. For templated code like this it's typically in the .h.

Body:
I am very sorry to pasted a very lengthy code here, but I found that's the best way to present this question. I think my compiler is ignoring the #include "Vector2.hpp". so please help me to solve this error. Your response would be very apricated!! thank you

getting error in this part of code (function name : liftpiece) :

if(e.key.code==Mouse::Left)
            {
                ismove=false;
                Vector2f p = s2[n].getPosition() + Vector2f(53.25,53.25);
                Vector2f newPos = Vector2f( 106.5*int(p.x/106.5), 106.5*int(p.y/106.5) );
                s2[n].setPosition(newPos);
            }

Full code :

#include <SFML/Graphics.hpp>
#include <SFML/Window.hpp>

#include <time.h>
#include "texture.h"
#include "Mouse.h"
#include "Sprite.h"
#include "Vector2.hpp"
#include "Transformable.h"

using namespace sf;

int boardarr[8][8]= {-5,-4,-3,-2,-1,-3,-4,-5,
                     -6,-6,-6,-6,-6,-6,-6,-6,
                      0, 0, 0, 0, 0, 0, 0, 0,
                      0, 0, 0, 0, 0, 0, 0, 0,
                      0, 0, 0, 0, 0, 0, 0, 0,
                      0, 0, 0, 0, 0, 0, 0, 0,
                      6, 6, 6, 6, 6, 6, 6, 6,
                      5, 4, 3, 2, 1, 3, 4, 5};

class GAME

{

private:

    Texture board,piece;
    Sprite s1;
    Sprite s2[32];
    bool ismove=false;
    int dx=0,dy=0,n=0;

public :

    void droppiece(Vector2i POS)
    {
        if(this->ismove)
        {
            s2[n].setPosition(POS.x-dx,POS.y-dy);

        }
    }

    void liftpiece(Event e, Vector2i POS)
    {
        if(e.type==Event::MouseButtonPressed)
        {
            if(e.key.code==Mouse::Left)
            {
                for(int i=0; i<32; i++)
                {
                    if(s2[i].getGlobalBounds().contains(POS.x,POS.y))
                    {
                        ismove = true;
                        n=i;
                        dx = POS.x - s2[i].getPosition().x;
                        dy = POS.y - s2[i].getPosition().y;
                    }

                }
            }
        }

        if(e.type==Event::MouseButtonReleased)
        {
            if(e.key.code==Mouse::Left)
            {
                ismove=false;
                Vector2f p = s2[n].getPosition() + Vector2f(53.25,53.25);
                Vector2f newPos = Vector2f( 106.5*int(p.x/106.5), 106.5*int(p.y/106.5) );
                s2[n].setPosition(newPos);
            }
        }

    }

    void setimages()
    {

        board.loadFromFile("C:\\Users\\JIMMY RATHWA\\OneDrive\\Desktop\\images\\chessboard.png");
        piece.loadFromFile("C:\\Users\\JIMMY RATHWA\\OneDrive\\Desktop\\images\\chesspiece.png");

        s1.setTexture(board);
        piece.setSmooth(true);

        for(int i=0; i<32; i++)
        {
            s2[i].setTexture(piece);
        }

    }

    void setpieces()
    {
        int k=0;

        for(int i=0; i<8; i++)
        {
            for(int j=0; j<8; j++)
            {
                int n = boardarr[i][j];
                if(!n)
                {
                    continue;
                }
                int x = abs(n)-1;
                int y = n>0?0:1;
                s2[k].setTextureRect(IntRect(106.5*x,106.5*y,106.5,106.5));
                s2[k].setPosition(106.5*j,106.5*i);
                k++;
            }

        }

    }

    void windowdisplay()
    {

        RenderWindow Window(VideoMode(850,850),"JIMMY CHESS",Style::Titlebar|Style::Close);
        setimages();
        setpieces();

        while(Window.isOpen())
        {
            Event e;

            Vector2i POS = Mouse::getPosition(Window);

            while(Window.pollEvent(e))
            {

                if(e.type==Event::Closed)
                {
                    Window.close();
                }

                liftpiece(e,POS);

            }

            droppiece(POS);

            Window.clear();

            Window.draw(s1);

            for(int i=0; i<32; i++)
            {
                Window.draw(s2[i]);
            }
            //layer 1 : chess board
            Window.display();

        }

    }

};

int main()
{
    GAME game;

    game.windowdisplay();

    return 0;
}

error : undefined reference to `sf::Vector2::Vector2(float, float)'

Vector2.hpp :

////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2018 Laurent Gomila (laurent@sfml-dev.org)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
//    you must not claim that you wrote the original software.
//    If you use this software in a product, an acknowledgment
//    in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
//    and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////

#ifndef SFML_VECTOR2_HPP
#define SFML_VECTOR2_HPP

namespace sf
{
////////////////////////////////////////////////////////////
/// \brief Utility template class for manipulating
///        2-dimensional vectors
///
////////////////////////////////////////////////////////////
template <typename T>
class Vector2
{
public:

    ////////////////////////////////////////////////////////////
    /// \brief Default constructor
    ///
    /// Creates a Vector2(0, 0).
    ///
    ////////////////////////////////////////////////////////////
    Vector2();

    ////////////////////////////////////////////////////////////
    /// \brief Construct the vector from its coordinates
    ///
    /// \param X X coordinate
    /// \param Y Y coordinate
    ///
    ////////////////////////////////////////////////////////////
    Vector2(T X, T Y);

    ////////////////////////////////////////////////////////////
    /// \brief Construct the vector from another type of vector
    ///
    /// This constructor doesn't replace the copy constructor,
    /// it's called only when U != T.
    /// A call to this constructor will fail to compile if U
    /// is not convertible to T.
    ///
    /// \param vector Vector to convert
    ///
    ////////////////////////////////////////////////////////////
    template <typename U>
    explicit Vector2(const Vector2& vector);

    ////////////////////////////////////////////////////////////
    // Member data
    ////////////////////////////////////////////////////////////
    T x; ///< X coordinate of the vector
    T y; ///< Y coordinate of the vector
};

////////////////////////////////////////////////////////////
/// \relates Vector2
/// \brief Overload of unary operator -
///
/// \param right Vector to negate
///
/// \return Memberwise opposite of the vector
///
////////////////////////////////////////////////////////////
template <typename T>
Vector2<T> operator -(const Vector2<T>& right);

////////////////////////////////////////////////////////////
/// \relates Vector2
/// \brief Overload of binary operator +=
///
/// This operator performs a memberwise addition of both vectors,
/// and assigns the result to \a left.
///
/// \param left  Left operand (a vector)
/// \param right Right operand (a vector)
///
/// \return Reference to \a left
///
////////////////////////////////////////////////////////////
template <typename T>
Vector2<T>& operator +=(Vector2<T>& left, const Vector2<T>& right);

////////////////////////////////////////////////////////////
/// \relates Vector2
/// \brief Overload of binary operator -=
///
/// This operator performs a memberwise subtraction of both vectors,
/// and assigns the result to \a left.
///
/// \param left  Left operand (a vector)
/// \param right Right operand (a vector)
///
/// \return Reference to \a left
///
////////////////////////////////////////////////////////////
template <typename T>
Vector2<T>& operator -=(Vector2<T>& left, const Vector2<T>& right);

////////////////////////////////////////////////////////////
/// \relates Vector2
/// \brief Overload of binary operator +
///
/// \param left  Left operand (a vector)
/// \param right Right operand (a vector)
///
/// \return Memberwise addition of both vectors
///
////////////////////////////////////////////////////////////
template <typename T>
Vector2<T> operator +(const Vector2<T>& left, const Vector2<T>& right);

////////////////////////////////////////////////////////////
/// \relates Vector2
/// \brief Overload of binary operator -
///
/// \param left  Left operand (a vector)
/// \param right Right operand (a vector)
///
/// \return Memberwise subtraction of both vectors
///
////////////////////////////////////////////////////////////
template <typename T>
Vector2<T> operator -(const Vector2<T>& left, const Vector2<T>& right);

////////////////////////////////////////////////////////////
/// \relates Vector2
/// \brief Overload of binary operator *
///
/// \param left  Left operand (a vector)
/// \param right Right operand (a scalar value)
///
/// \return Memberwise multiplication by \a right
///
////////////////////////////////////////////////////////////
template <typename T>
Vector2<T> operator *(const Vector2<T>& left, T right);

////////////////////////////////////////////////////////////
/// \relates Vector2
/// \brief Overload of binary operator *
///
/// \param left  Left operand (a scalar value)
/// \param right Right operand (a vector)
///
/// \return Memberwise multiplication by \a left
///
////////////////////////////////////////////////////////////
template <typename T>
Vector2<T> operator *(T left, const Vector2<T>& right);

////////////////////////////////////////////////////////////
/// \relates Vector2
/// \brief Overload of binary operator *=
///
/// This operator performs a memberwise multiplication by \a right,
/// and assigns the result to \a left.
///
/// \param left  Left operand (a vector)
/// \param right Right operand (a scalar value)
///
/// \return Reference to \a left
///
////////////////////////////////////////////////////////////
template <typename T>
Vector2<T>& operator *=(Vector2<T>& left, T right);

////////////////////////////////////////////////////////////
/// \relates Vector2
/// \brief Overload of binary operator /
///
/// \param left  Left operand (a vector)
/// \param right Right operand (a scalar value)
///
/// \return Memberwise division by \a right
///
////////////////////////////////////////////////////////////
template <typename T>
Vector2<T> operator /(const Vector2<T>& left, T right);

////////////////////////////////////////////////////////////
/// \relates Vector2
/// \brief Overload of binary operator /=
///
/// This operator performs a memberwise division by \a right,
/// and assigns the result to \a left.
///
/// \param left  Left operand (a vector)
/// \param right Right operand (a scalar value)
///
/// \return Reference to \a left
///
////////////////////////////////////////////////////////////
template <typename T>
Vector2<T>& operator /=(Vector2<T>& left, T right);

////////////////////////////////////////////////////////////
/// \relates Vector2
/// \brief Overload of binary operator ==
///
/// This operator compares strict equality between two vectors.
///
/// \param left  Left operand (a vector)
/// \param right Right operand (a vector)
///
/// \return True if \a left is equal to \a right
///
////////////////////////////////////////////////////////////
template <typename T>
bool operator ==(const Vector2<T>& left, const Vector2<T>& right);

////////////////////////////////////////////////////////////
/// \relates Vector2
/// \brief Overload of binary operator !=
///
/// This operator compares strict difference between two vectors.
///
/// \param left  Left operand (a vector)
/// \param right Right operand (a vector)
///
/// \return True if \a left is not equal to \a right
///
////////////////////////////////////////////////////////////
template <typename T>
bool operator !=(const Vector2<T>& left, const Vector2<T>& right);

#include <SFML/System/Vector2.inl>

// Define the most common types
typedef Vector2<int>          Vector2i;
typedef Vector2<unsigned int> Vector2u;
typedef Vector2<float>        Vector2f;

} // namespace sf

#endif // SFML_VECTOR2_HPP

////////////////////////////////////////////////////////////
/// \class sf::Vector2
/// \ingroup system
///
/// sf::Vector2 is a simple class that defines a mathematical
/// vector with two coordinates (x and y). It can be used to
/// represent anything that has two dimensions: a size, a point,
/// a velocity, etc.
///
/// The template parameter T is the type of the coordinates. It
/// can be any type that supports arithmetic operations (+, -, /, *)
/// and comparisons (==, !=), for example int or float.
///
/// You generally don't have to care about the templated form (sf::Vector2<T>),
/// the most common specializations have special typedefs:
/// \li sf::Vector2<float> is sf::Vector2f
/// \li sf::Vector2<int> is sf::Vector2i
/// \li sf::Vector2<unsigned int> is sf::Vector2u
///
/// The sf::Vector2 class has a small and simple interface, its x and y members
/// can be accessed directly (there are no accessors like setX(), getX()) and it
/// contains no mathematical function like dot product, cross product, length, etc.
///
/// Usage example:
/// \code
/// sf::Vector2f v1(16.5f, 24.f);
/// v1.x = 18.2f;
/// float y = v1.y;
///
/// sf::Vector2f v2 = v1 * 5.f;
/// sf::Vector2f v3;
/// v3 = v1 + v2;
///
/// bool different = (v2 != v3);
/// \endcode
///
/// Note: for 3-dimensional vectors, see sf::Vector3.
///
////////////////////////////////////////////////////////////


来源: stackexchange

问:
Using `expect.any(Object)` or `expect.anything()` does not work to match `undefined` in Jest
I have the following module which I want to test.

```<code>import * as apiUtils from './apiUtils';

export function awardPoints(pointsAwarding) {
  return apiUtils.callApiService("POST", "points", pointsAwarding);
}
</code>```

And this is my test.

```<code>it("should call apiUtils with correct path", () => {
  //given
  jest.spyOn(apiUtils, 'callApiService');

  //when
  pointsAwardingApi.awardPoints();

  //then
  expect(apiUtils.callApiService).toBeCalledWith(expect.any(String), 'points', expect.any(Object));
});
</code>```

When I try to run this test I get the following error.

Any<Object> as argument 3, but it was called with undefined.

I was expecting that expect.any(Object) would also match undefined but it seems that's not the case.

I also tried with expect.anything() but I get a similar error.

I could simply specify undefined as the third parameter but my test is only intended to verify the second parameter.

Is there a way I can use a matcher that matches any object including undefined?

答:
You can use expect.toSatisfy(() => true) to get what you want (this also ships with jest-extended).

As for if the developer should be using this or not: when building software from scratch - probably not. But. This is a luxury most developers don't have.

Most people have to deal with untested legacy code-base and writing tests for some implementation as to provide some level of automatic validation on critical functionality when refactoring - such fuzzy argument expectations are pretty good tools to have.

ContentLicense: CC BY-SA 3.0

Body:
I have the following module which I want to test.

import * as apiUtils from './apiUtils';

export function awardPoints(pointsAwarding) {
  return apiUtils.callApiService("POST", "points", pointsAwarding);
}

And this is my test.

it("should call apiUtils with correct path", () => {
  //given
  jest.spyOn(apiUtils, 'callApiService');

  //when
  pointsAwardingApi.awardPoints();

  //then
  expect(apiUtils.callApiService).toBeCalledWith(expect.any(String), 'points', expect.any(Object));
});

When I try to run this test I get the following error.

Any<Object> as argument 3, but it was called with undefined.

I was expecting that expect.any(Object) would also match undefined but it seems that's not the case.

I also tried with expect.anything() but I get a similar error.

I could simply specify undefined as the third parameter but my test is only intended to verify the second parameter.

Is there a way I can use a matcher that matches any object including undefined?

ContentLicense: CC BY-SA 4.0


问:
Very basic JSON question
I have this JSON data:

```<code>var people = [
     { name : "John",  age : 25 },
     { name : "Jane",  age : 49 },
     { name : "Jim",   age : 31 },
     { name : "Julie", age : 39 },
     { name : "Joe",   age : 19 },
     { name : "Jack",  age : 48 }
];
</code>```

How can I loop through all the objects inside people and output their names along with their ages like so:

```<code>John 25
Jame 49
followed by the rest...
</code>```

答:
Not sure how you want to write it to the page, but here's a sample with document.write:

```<code>for (var i = 0, ilen = people.length; i < ilen; i++)
{
   document.write(people[i].name + ' ' + people[i].age + '<br/>');
}
</code>```

I highly recommend getting the length in the first expression of for-loop, not the second. In this case, people.length is not too expensive. But if it is costly and you put it in the second expression like so for (var i = 0; i < people.length; i++), then it'll get evaluated in every loop and you wonder where your CPU cycles went. :)

Title: Very basic JSON question

Body:
I have this JSON data:

var people = [
     { name : "John",  age : 25 },
     { name : "Jane",  age : 49 },
     { name : "Jim",   age : 31 },
     { name : "Julie", age : 39 },
     { name : "Joe",   age : 19 },
     { name : "Jack",  age : 48 }
];

How can I loop through all the objects inside people and output their names along with their ages like so:

John 25
Jame 49
followed by the rest...

Body:
Not sure how you want to write it to the page, but here's a sample with document.write:

for (var i = 0, ilen = people.length; i < ilen; i++)
{
   document.write(people[i].name + ' ' + people[i].age + '<br/>');
}

I highly recommend getting the length in the first expression of for-loop, not the second. In this case, people.length is not too expensive. But if it is costly and you put it in the second expression like so for (var i = 0; i < people.length; i++), then it'll get evaluated in every loop and you wonder where your CPU cycles went. :)


问:
Scrape Google with Python - What is the correct URL for requests.get?
Goal: I would like to verify, if a specific Google search has a suggested result on the right hand side and - in case of such a suggestion - scrape some information like company type / address / etc.

Approach: I wanted to use a Python scraper with Requests and BeautifulSoup4

```<code>import bs4
import requests

address='https://www.google.co.ve/?gws_rd=cr&ei=DgBqVpWJMoPA-gHy25fACg#q=caracas+arepa'
page = requests.get(address)
soup = bs4.BeautifulSoup(page.content,'html.parser')
print (soup.prettify())
</code>```

Issue:

The requested page does not include the search results (I am not sure if some variable on the Google page is set to invisible?), Rather only the header and footer of the Google page

Questions:

Alternative ways to obtain the described information? Any ideas?

Once I obtained results with the described method, but the respective address was constructed differently (I remember many numbers in the Google URL, but unfortunately cannot reproduce the search address). Therefore: Is there a requirement of the Google URL so that it can be scraped via requests.get?

答:
You need select_one() element (container) that contains all the needed data and check if it exists, and if so, scrape the data.

Make sure you're using user-agent to act as a "real" user visit, otherwise your request might be blocked or you receive a different HTML with different selectors. Check what's your user-agent.

Code and example in the online IDE:

from bs4 import BeautifulSoup
import requests, lxml

params = {
    "q": "caracas arepa bar google",
    "gl": "us"
}

headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.87 Safari/537.36"
}

html = requests.get("https://www.google.com/search", params=params, headers=headers, timeout=30)
soup = BeautifulSoup(html.text, "lxml")

# if right side knowledge graph is present -> parse the data.
if soup.select_one(".liYKde"):
    place_name = soup.select_one(".PZPZlf.q8U8x span").text
    place_type = soup.select_one(".YhemCb+ .YhemCb").text
    place_reviews = soup.select_one(".hqzQac span").text
    place_rating = soup.select_one(".Aq14fc").text

    print(place_name, place_type, place_reviews, place_rating, sep="\n")

# output:
'''
Caracas Arepa Bar
Venezuelan restaurant
1,123 Google reviews
4.5
'''
```
<hr />
<p>Alternatively, you can achieve the same thing using Google Knowledge Graph API from SerpApi. It's a paid API with a free plan.</p>
<p>The biggest difference is that you don't need to figure out how to parse the data, increase the number of requests, bypass blocks from Google, and other search engines.</p>
<pre class="lang-py prettyprint-override"><code>from serpapi import GoogleSearch

params = {
  "api_key": "YOUR_API_KEY",
  "engine": "google",
  "q": "caracas arepa bar place",
  "hl": "en"
}

search = GoogleSearch(params)
results = search.get_dict()

print(json.dumps([results["knowledge_graph"]], indent=2))

# part of the output:
'''
[
  {
    "title": "Caracas Arepa Bar",
    "type": "Venezuelan restaurant",
    "place_id": "ChIJVcQ2ll9ZwokRwmkvsArPXyo",
    "website": "http://caracasarepabar.com/",
    "description": "Arepa specialist offering creative, low-priced renditions of the Venezuelan corn-flour staple.",
    "local_map": {
      "image": "https://www.google.com/maps/vt/data=TF2Rd51PtEnU2M3pkZHYHKdSwhMDJ_ZwRfg0vfwlDRAmv1u919sgFl8hs_lo832ziTWxCZM9BKECs6Af-TA1hh0NLjuYAzOLFA1-RBEmj-8poygymcRX2KLNVTGGZZKDerZrKW6fnkONAM4Ui-BVN8XwFrwigoqqxObPg8bqFIgeM3LPCg",
      "link": "https://www.google.com/maps/place/Caracas+Arepa+Bar/@40.7131972,-73.9574167,15z/data=!4m2!3m1!1s0x0:0x2a5fcf0ab02f69c2?sa=X&hl=en",
      "gps_coordinates": {
        "latitude": 40.7131972,
        "longitude": -73.9574167,
        "altitude": 15
      }
    } ... much more results including place images, popular times, user reviews.
  }
]
'''
</code>```

Disclaimer: I work for SerpApi.

Body:
Goal: I would like to verify, if a specific Google search has a suggested result on the right hand side and - in case of such a suggestion - scrape some information like company type / address / etc.

Approach: I wanted to use a Python scraper with Requests and BeautifulSoup4

import bs4
import requests

address='https://www.google.co.ve/?gws_rd=cr&ei=DgBqVpWJMoPA-gHy25fACg#q=caracas+arepa'
page = requests.get(address)
soup = bs4.BeautifulSoup(page.content,'html.parser')
print (soup.prettify())

Issue:

The requested page does not include the search results (I am not sure if some variable on the Google page is set to invisible?), Rather only the header and footer of the Google page

Questions:

Alternative ways to obtain the described information? Any ideas?

Once I obtained results with the described method, but the respective address was constructed differently (I remember many numbers in the Google URL, but unfortunately cannot reproduce the search address). Therefore: Is there a requirement of the Google URL so that it can be scraped via requests.get?

Body:
You need select_one() element (container) that contains all the needed data and check if it exists, and if so, scrape the data.

Make sure you're using user-agent to act as a "real" user visit, otherwise your request might be blocked or you receive a different HTML with different selectors. Check what's your user-agent.

Code and example in the online IDE:

from bs4 import BeautifulSoup
import requests, lxml

params = {
    "q": "caracas arepa bar google",
    "gl": "us"
}

headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.87 Safari/537.36"
}

html = requests.get("https://www.google.com/search", params=params, headers=headers, timeout=30)
soup = BeautifulSoup(html.text, "lxml")

# if right side knowledge graph is present -> parse the data.
if soup.select_one(".liYKde"):
    place_name = soup.select_one(".PZPZlf.q8U8x span").text
    place_type = soup.select_one(".YhemCb+ .YhemCb").text
    place_reviews = soup.select_one(".hqzQac span").text
    place_rating = soup.select_one(".Aq14fc").text

    print(place_name, place_type, place_reviews, place_rating, sep="\n")

# output:
'''
Caracas Arepa Bar
Venezuelan restaurant
1,123 Google reviews
4.5
'''

Alternatively, you can achieve the same thing using Google Knowledge Graph API from SerpApi. It's a paid API with a free plan.

The biggest difference is that you don't need to figure out how to parse the data, increase the number of requests, bypass blocks from Google, and other search engines.

from serpapi import GoogleSearch

params = {
  "api_key": "YOUR_API_KEY",
  "engine": "google",
  "q": "caracas arepa bar place",
  "hl": "en"
}

search = GoogleSearch(params)
results = search.get_dict()

print(json.dumps([results["knowledge_graph"]], indent=2))

# part of the output:
'''
[
  {
    "title": "Caracas Arepa Bar",
    "type": "Venezuelan restaurant",
    "place_id": "ChIJVcQ2ll9ZwokRwmkvsArPXyo",
    "website": "http://caracasarepabar.com/",
    "description": "Arepa specialist offering creative, low-priced renditions of the Venezuelan corn-flour staple.",
    "local_map": {
      "image": "https://www.google.com/maps/vt/data=TF2Rd51PtEnU2M3pkZHYHKdSwhMDJ_ZwRfg0vfwlDRAmv1u919sgFl8hs_lo832ziTWxCZM9BKECs6Af-TA1hh0NLjuYAzOLFA1-RBEmj-8poygymcRX2KLNVTGGZZKDerZrKW6fnkONAM4Ui-BVN8XwFrwigoqqxObPg8bqFIgeM3LPCg",
      "link": "https://www.google.com/maps/place/Caracas+Arepa+Bar/@40.7131972,-73.9574167,15z/data=!4m2!3m1!1s0x0:0x2a5fcf0ab02f69c2?sa=X&hl=en",
      "gps_coordinates": {
        "latitude": 40.7131972,
        "longitude": -73.9574167,
        "altitude": 15
      }
    } ... much more results including place images, popular times, user reviews.
  }
]
'''

Disclaimer: I work for SerpApi.


问:
How to implement OCL (Object Constraint Language) in Python
I am working on Google Colaboratory, and I have to implement OCL (Object Constraint Language), I searched a lot, but I didn't find how to implement it. Can someone give me an idea please?</p>

答: AgileUML has a Python code generator from UML/OCL (itself written in OCL): this is the uml2py plugin for AgileUML (https://github.com/eclipse/agileuml). There are some videos on using the tool at: https://www.youtube.com/watch?v=NXq2L0fo7N4</p>


问:
java.lang.NullPointerException: Attempt to invoke virtual method on a null object reference to select sqlite
I am a newbie of android world. I have a problem of the coding. It was just a tiny error buy i dont know it doesnt work even i change others method but the error still the same error. Here the error occur at logcat:

```<code>java.lang.NullPointerException: Attempt to invoke virtual method 'android.database.Cursor com.example.zellon.surveyapps.DatabaseHelper.getAData()' on a null object reference
</code>```

I just want to select the data in the database to get an id but cant cuz of the error above.

I will give a code that i coded for select the data from database

surveyinstruction.java

```<code>package com.example.zellon.surveyapps;

import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class surveyinstruction extends AppCompatActivity {
DatabaseHelper myDb;

protected void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.surveyinstruction);

    TextView user = (TextView) findViewById(R.id.user);

    Intent in = getIntent();

    String nameUser = in.getStringExtra("nameUser");
    String tarikhUser = in.getStringExtra("tarikhUser");

    user.setText("Selamat Datang " + nameUser);

    Button btnSeterusnya = (Button) findViewById(R.id.btnTerus);

    btnSeterusnya.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intentTerus = new Intent(getApplicationContext(), surveymain.class);
            Cursor res = myDb.getAData();
            intentTerus.putExtra("id", res.getString(0));
            Log.e("ID ", res.getString(0));
            startActivity(intentTerus);
        }
    });
}
}
</code>```

And here is for database handler

DatabaseHelper.java

```<code>package com.example.zellon.surveyapps;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "survey.db";
public static final String TABLE_USER = "user";
public static final String COL_USER_1 = "ID";
public static final String COL_USER_2 = "NAMA";
public static final String COL_USER_3 = "TARIKH";
public static final String COL_USER_4 = "MARKAH";

public static final String TABLE_QUESTION = "question";

public static final String COL_QUES_1 = "ID";
public static final String COL_QUES_2 = "IDUSER";
public static final String COL_QUES_3 = "K1";
public static final String COL_QUES_4 = "K2";
public static final String COL_QUES_5 = "K3";
public static final String COL_QUES_6 = "K4";
public static final String COL_QUES_7 = "K5";
public static final String COL_QUES_8 = "A1";
public static final String COL_QUES_9 = "A2";
public static final String COL_QUES_10 = "A3";
public static final String COL_QUES_11 = "A4";
public static final String COL_QUES_12 = "A5";
public static final String COL_QUES_13 = "V1";
public static final String COL_QUES_14 = "V2";
public static final String COL_QUES_15 = "V3";
public static final String COL_QUES_16 = "V4";
public static final String COL_QUES_17 = "V5";
public static final String COL_QUES_18 = "D1";
public static final String COL_QUES_19 = "D2";
public static final String COL_QUES_20 = "D3";
public static final String COL_QUES_21 = "D4";
public static final String COL_QUES_22 = "D5";
public static final String COL_QUES_23 = "TOTK";
public static final String COL_QUES_24 = "TOTA";
public static final String COL_QUES_25 = "TOTV";
public static final String COL_QUES_26 = "TOTD";

public DatabaseHelper(Context context) {
    super(context, DATABASE_NAME, null, 1);
}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL("create table " + TABLE_USER + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAMA TEXT, TARIKH TEXT, MARKAH INTEGER)");
    db.execSQL("create table " + TABLE_QUESTION + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, IDUSER INTEGER, K1 TEXT, K2 TEXT, K3 TEXT, K4 TEXT, K5 TEXT, A1 TEXT, A2 TEXT, A3 TEXT, A4 TEXT, A5 TEXT, V1 TEXT, V2 TEXT, V3 TEXT, V4 TEXT, V5 TEXT, D1 TEXT, D2 TEXT, D3 TEXT, D4 TEXT, D5 TEXT, TOTK INTEGER, TOTA INTEGER, TOTV INTEGER, TOTD INTEGER)");
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_USER);
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_QUESTION);
    onCreate(db);
}

public boolean insertDataUser(String nama, String tarikh){
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(COL_USER_2, nama);
    contentValues.put(COL_USER_3, tarikh);
    long result = db.insert(TABLE_USER, null, contentValues);

    if(result == -1)
        return false;
    else
        return true;
}

public Cursor getCertainData(String namaUser, String tarikhUser){
    String selectQuery = "select * from " + TABLE_USER + " where NAMA like '" + namaUser + "' AND TARIKH like '" + tarikhUser + "'";
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor res = db.rawQuery(selectQuery, null);
    return res;
}

public Cursor getAData(){
    SQLiteDatabase db = this.getWritableDatabase();
    String selectAQuery = "SELECT ID FROM " + TABLE_USER;
    Cursor re = db.rawQuery(selectAQuery, null);
    return re;
}

public boolean insertDataQues(int id, String k1, String k2, String k3, String k4, String k5, String a1, String a2, String a3, String a4, String a5, String v1, String v2, String v3, String v4, String v5, String d1, String d2, String d3, String d4, String d5, int totalk, int totala, int totalv, int totald){
    SQLiteDatabase dbQues = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(COL_QUES_2, id);
    contentValues.put(COL_QUES_3, k1);
    contentValues.put(COL_QUES_4, k2);
    contentValues.put(COL_QUES_5, k3);
    contentValues.put(COL_QUES_6, k4);
    contentValues.put(COL_QUES_7, k5);

    contentValues.put(COL_QUES_8, a1);
    contentValues.put(COL_QUES_9, a2);
    contentValues.put(COL_QUES_10, a3);
    contentValues.put(COL_QUES_11, a4);
    contentValues.put(COL_QUES_12, a5);

    contentValues.put(COL_QUES_13, v1);
    contentValues.put(COL_QUES_14, v2);
    contentValues.put(COL_QUES_15, v3);
    contentValues.put(COL_QUES_16, v4);
    contentValues.put(COL_QUES_17, v5);

    contentValues.put(COL_QUES_18, d1);
    contentValues.put(COL_QUES_19, d2);
    contentValues.put(COL_QUES_20, d3);
    contentValues.put(COL_QUES_21, d4);
    contentValues.put(COL_QUES_22, d5);

    contentValues.put(COL_QUES_23, totalk);
    contentValues.put(COL_QUES_24, totala);
    contentValues.put(COL_QUES_25, totalv);
    contentValues.put(COL_QUES_26, totald);

    long result = dbQues.insert(TABLE_QUESTION, null, contentValues);

    if(result == -1)
        return false;
    else
        return true;
}
}
</code>```

So, in the code of surveyinstruction.java i only call getAData() function from DatabaseHelper.java the select an ID from database but the error shown that it null object reference. I dont know what the error is. I hope someone please help me for it to work fine. Thank you.

答:
What about this , I had declared the Helper class, " NoteDB db = new NoteDB(this)"
But the bug error indicate null pointer exception of this , " String title = db.getTitle" , no useful the declaration of the line  " NoteDB db = new NoteDB(this)".</p>
```<code> protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_note_detail);
    Toolbar toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    Intent i = getIntent();
    long id = i.getLongExtra("ID",1);
    NoteDatabase db = new NoteDatabase(getApplicationContext());
    Note note = db.getNote(id);
    getSupportActionBar().setTitle(note.getTitle());
    Toast.makeText(this,"ID -> "+id,Toast.LENGTH_LONG).show();
  //  Toast.makeText(this,"Title -> "+note.getTitle(),Toast.LENGTH_LONG).show();
    FloatingActionButton fab = findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });
}
</code>```

Body:
I am a newbie of android world. I have a problem of the coding. It was just a tiny error buy i dont know it doesnt work even i change others method but the error still the same error. Here the error occur at logcat:

java.lang.NullPointerException: Attempt to invoke virtual method 'android.database.Cursor com.example.zellon.surveyapps.DatabaseHelper.getAData()' on a null object reference

I just want to select the data in the database to get an id but cant cuz of the error above.

I will give a code that i coded for select the data from database

surveyinstruction.java

package com.example.zellon.surveyapps;

import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class surveyinstruction extends AppCompatActivity {
DatabaseHelper myDb;

protected void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.surveyinstruction);

    TextView user = (TextView) findViewById(R.id.user);

    Intent in = getIntent();

    String nameUser = in.getStringExtra("nameUser");
    String tarikhUser = in.getStringExtra("tarikhUser");

    user.setText("Selamat Datang " + nameUser);

    Button btnSeterusnya = (Button) findViewById(R.id.btnTerus);

    btnSeterusnya.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intentTerus = new Intent(getApplicationContext(), surveymain.class);
            Cursor res = myDb.getAData();
            intentTerus.putExtra("id", res.getString(0));
            Log.e("ID ", res.getString(0));
            startActivity(intentTerus);
        }
    });
}
}

And here is for database handler

DatabaseHelper.java

package com.example.zellon.surveyapps;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "survey.db";
public static final String TABLE_USER = "user";
public static final String COL_USER_1 = "ID";
public static final String COL_USER_2 = "NAMA";
public static final String COL_USER_3 = "TARIKH";
public static final String COL_USER_4 = "MARKAH";

public static final String TABLE_QUESTION = "question";

public static final String COL_QUES_1 = "ID";
public static final String COL_QUES_2 = "IDUSER";
public static final String COL_QUES_3 = "K1";
public static final String COL_QUES_4 = "K2";
public static final String COL_QUES_5 = "K3";
public static final String COL_QUES_6 = "K4";
public static final String COL_QUES_7 = "K5";
public static final String COL_QUES_8 = "A1";
public static final String COL_QUES_9 = "A2";
public static final String COL_QUES_10 = "A3";
public static final String COL_QUES_11 = "A4";
public static final String COL_QUES_12 = "A5";
public static final String COL_QUES_13 = "V1";
public static final String COL_QUES_14 = "V2";
public static final String COL_QUES_15 = "V3";
public static final String COL_QUES_16 = "V4";
public static final String COL_QUES_17 = "V5";
public static final String COL_QUES_18 = "D1";
public static final String COL_QUES_19 = "D2";
public static final String COL_QUES_20 = "D3";
public static final String COL_QUES_21 = "D4";
public static final String COL_QUES_22 = "D5";
public static final String COL_QUES_23 = "TOTK";
public static final String COL_QUES_24 = "TOTA";
public static final String COL_QUES_25 = "TOTV";
public static final String COL_QUES_26 = "TOTD";

public DatabaseHelper(Context context) {
    super(context, DATABASE_NAME, null, 1);
}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL("create table " + TABLE_USER + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAMA TEXT, TARIKH TEXT, MARKAH INTEGER)");
    db.execSQL("create table " + TABLE_QUESTION + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, IDUSER INTEGER, K1 TEXT, K2 TEXT, K3 TEXT, K4 TEXT, K5 TEXT, A1 TEXT, A2 TEXT, A3 TEXT, A4 TEXT, A5 TEXT, V1 TEXT, V2 TEXT, V3 TEXT, V4 TEXT, V5 TEXT, D1 TEXT, D2 TEXT, D3 TEXT, D4 TEXT, D5 TEXT, TOTK INTEGER, TOTA INTEGER, TOTV INTEGER, TOTD INTEGER)");
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_USER);
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_QUESTION);
    onCreate(db);
}

public boolean insertDataUser(String nama, String tarikh){
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(COL_USER_2, nama);
    contentValues.put(COL_USER_3, tarikh);
    long result = db.insert(TABLE_USER, null, contentValues);

    if(result == -1)
        return false;
    else
        return true;
}

public Cursor getCertainData(String namaUser, String tarikhUser){
    String selectQuery = "select * from " + TABLE_USER + " where NAMA like '" + namaUser + "' AND TARIKH like '" + tarikhUser + "'";
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor res = db.rawQuery(selectQuery, null);
    return res;
}

public Cursor getAData(){
    SQLiteDatabase db = this.getWritableDatabase();
    String selectAQuery = "SELECT ID FROM " + TABLE_USER;
    Cursor re = db.rawQuery(selectAQuery, null);
    return re;
}

public boolean insertDataQues(int id, String k1, String k2, String k3, String k4, String k5, String a1, String a2, String a3, String a4, String a5, String v1, String v2, String v3, String v4, String v5, String d1, String d2, String d3, String d4, String d5, int totalk, int totala, int totalv, int totald){
    SQLiteDatabase dbQues = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(COL_QUES_2, id);
    contentValues.put(COL_QUES_3, k1);
    contentValues.put(COL_QUES_4, k2);
    contentValues.put(COL_QUES_5, k3);
    contentValues.put(COL_QUES_6, k4);
    contentValues.put(COL_QUES_7, k5);

    contentValues.put(COL_QUES_8, a1);
    contentValues.put(COL_QUES_9, a2);
    contentValues.put(COL_QUES_10, a3);
    contentValues.put(COL_QUES_11, a4);
    contentValues.put(COL_QUES_12, a5);

    contentValues.put(COL_QUES_13, v1);
    contentValues.put(COL_QUES_14, v2);
    contentValues.put(COL_QUES_15, v3);
    contentValues.put(COL_QUES_16, v4);
    contentValues.put(COL_QUES_17, v5);

    contentValues.put(COL_QUES_18, d1);
    contentValues.put(COL_QUES_19, d2);
    contentValues.put(COL_QUES_20, d3);
    contentValues.put(COL_QUES_21, d4);
    contentValues.put(COL_QUES_22, d5);

    contentValues.put(COL_QUES_23, totalk);
    contentValues.put(COL_QUES_24, totala);
    contentValues.put(COL_QUES_25, totalv);
    contentValues.put(COL_QUES_26, totald);

    long result = dbQues.insert(TABLE_QUESTION, null, contentValues);

    if(result == -1)
        return false;
    else
        return true;
}
}

So, in the code of surveyinstruction.java i only call getAData() function from DatabaseHelper.java the select an ID from database but the error shown that it null object reference. I dont know what the error is. I hope someone please help me for it to work fine. Thank you.

Body:
What about this , I had declared the Helper class, " NoteDB db = new NoteDB(this)"
But the bug error indicate null pointer exception of this , " String title = db.getTitle" , no useful the declaration of the line  " NoteDB db = new NoteDB(this)".

 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_note_detail);
    Toolbar toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    Intent i = getIntent();
    long id = i.getLongExtra("ID",1);
    NoteDatabase db = new NoteDatabase(getApplicationContext());
    Note note = db.getNote(id);
    getSupportActionBar().setTitle(note.getTitle());
    Toast.makeText(this,"ID -> "+id,Toast.LENGTH_LONG).show();
  //  Toast.makeText(this,"Title -> "+note.getTitle(),Toast.LENGTH_LONG).show();
    FloatingActionButton fab = findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });
}


问:
What is the best way to execute a function after TWO or more async functions finish in React?
I have two functions that run asynchronously getting data from the API. Both of them are called from their own useEffect().

I have a third function that needs to run once those two functions have been fully completed.

How can this be accomplished?

Edit:
Both of the async functions look like this:

```<code>   useEffect(() => {
    fetchBudgetBucketsData();
  }, [fiscalYear]);

  useEffect(() => {
    fetchBudgetBucketsData();
  }, [fiscalYear]);

 const fetchBudgetsData = async () => {
    setIsFetchingBudgets(true);
    const res = await getBudgets(orgID, `${parseInt(fiscalYear)}`, '', budgetType);
    setIsFetchingBudgets(false);
    if (isErrorResponse(res)) {
      console.warn(res.details);
      message.error(res.displayText);
      return;
    }
    setBudgets(res.budgets);
  };

 const fetchBudgetBucketsData = async () => {
    setIsLoadingBudgetBuckets(true);
    if (orgID === undefined) {
      return;
    }

    const res = await getBudgetBuckets(orgID, fiscalYear);
    setIsLoadingBudgetBuckets(false);
    if (isErrorResponse(res)) {
      console.warn(res.details);
      message.error(res.displayText);
      return;
    }
    setBudgetBuckets(res.buckets);
  };
</code>```

Whenever the budget data or bucket data is updated, I want to call another function that checks for errors. However when the page loads, I need it to wait for both of those functions to be finished before it checks for errors.

Edit #2:

After some debugging, it looks like the issue might have to do with when React updates the state. Since I am trying to check for errors in data saved in the state.

答:
One way could be chaining Promises.

Promise.all([ApiCall1, ApiCall2])
// At this point two promises above will be resolved
.then(() => ApiCall3)
```

Read more

Body:
I have two functions that run asynchronously getting data from the API. Both of them are called from their own useEffect().

I have a third function that needs to run once those two functions have been fully completed.

How can this be accomplished?

Edit:
Both of the async functions look like this:

   useEffect(() => {
    fetchBudgetBucketsData();
  }, [fiscalYear]);

  useEffect(() => {
    fetchBudgetBucketsData();
  }, [fiscalYear]);

 const fetchBudgetsData = async () => {
    setIsFetchingBudgets(true);
    const res = await getBudgets(orgID, `${parseInt(fiscalYear)}`, '', budgetType);
    setIsFetchingBudgets(false);
    if (isErrorResponse(res)) {
      console.warn(res.details);
      message.error(res.displayText);
      return;
    }
    setBudgets(res.budgets);
  };

 const fetchBudgetBucketsData = async () => {
    setIsLoadingBudgetBuckets(true);
    if (orgID === undefined) {
      return;
    }

    const res = await getBudgetBuckets(orgID, fiscalYear);
    setIsLoadingBudgetBuckets(false);
    if (isErrorResponse(res)) {
      console.warn(res.details);
      message.error(res.displayText);
      return;
    }
    setBudgetBuckets(res.buckets);
  };

Whenever the budget data or bucket data is updated, I want to call another function that checks for errors. However when the page loads, I need it to wait for both of those functions to be finished before it checks for errors.

Edit #2:

After some debugging, it looks like the issue might have to do with when React updates the state. Since I am trying to check for errors in data saved in the state.

Body:
One way could be chaining Promises.

Promise.all([ApiCall1, ApiCall2])
// At this point two promises above will be resolved
.then(() => ApiCall3)

Read more


答:
With jquery you can do

```<code>$.each(people, function(){
  alert(this.name + " " + this.age);
});
</code>```

If you want to just append it to a div you can do

```<code>$.map(people, function(){
  return this.name + " " + this.age + "<br/>";
}).appendTo("#myDiv");
</code>```

Title: Very basic JSON question

Body:
With jquery you can do

$.each(people, function(){
  alert(this.name + " " + this.age);
});

If you want to just append it to a div you can do

$.map(people, function(){
  return this.name + " " + this.age + "<br/>";
}).appendTo("#myDiv");


问:
How to edit django-allauth default templates?
i'm using Django 1.10 and i want to add the allauth's app for login, signin, etc, to my website. I've installed allauth from pip, and tried to put the templates from allauth repository inside my templates folder and call them but i don't know how to make it work.</p>

答:
Like many have already told here, all we have to do is bring the account,openid and socialaccount folders from the templates folder of allauth into the templates folder of our project folder.

But one thing to keep in mind while adding the
 'DIRS': [os.path.join(BASE_DIR, 'project_name','templates')]
to the setting is that, the BASE_DIR in django points to the directory where manage.py is stored. And it is at this level we have our project folder and our templates folder within the project. So we need to add our 'project_name' and then 'templates' to the DIRS with os.path.join


问:
Using fewer if statements
I am trying to code the game One Night Ultimate Werewolf for Discord. I already figured out the first steps, of choosing cards, and sending roles through direct messages. The next step, is to create commands through DM, such as "!seer " for the seer to do her action. The problem is: I don't know how to make the bot check if the message author is actually a seer. I was thinking on doing the following: the variables dargon, ven, rocky, etc. are player names, where they have their player IDs stored. The variables dargon_c, ven_c, rocky_c, etc. have the players' Werewolf cards assigned to them.

```<code>  try:
    global dargon_c, ven_c, nastith_c, rocky_c, petra_c, center_c, left_center_c, right_center_c
    target = await bot.fetch_user(dargon)
    await target.send('Your card is: ' + cards[0])
    dargon_c = cards[0]

    target = await bot.fetch_user(ven)
    await target.send('Your card is: ' + cards[1])
    ven_c = cards[1]

    target = await bot.fetch_user(nastith)
    await target.send('Your card is: ' + cards[2])
    nastith_c = cards[2]

    target = await bot.fetch_user(rocky)
    await target.send('Your card is: ' + cards[3])
    rocky_c = cards[3]

    target = await bot.fetch_user(petra)
    await target.send('Your card is: ' + cards[4])
    petra_c = cards[4]

    center_c = cards[5]
    left_center_c = cards[6]
    right_center_c = cards[7]

  except:
    ctx.channel.send("Some users didn't recieve their cards")

dargon_c = 'Seer'

@bot.command()
async def seer(ctx):
  global see
  if ctx.author.id == dargon and dargon_c == 'Seer':
    ctx.channel.send('Card')
  if ctx.author.id == ven and ven_c == 'Seer':
    see = ctx.content[3:]
    ctx.channel.send('Card')
</code>```

Is there any way I could do this without needing to do 100 if blocks for every single command?

答:
Try using a list. The format looks like this:

Remember that list indexes start with 0, and go up.

So if the list is ["hello", "world] then [0] is hello and [1] is world.

```<code>myCards = [
    ["dargon", 0],
    ["ven",1]
]

for i in myCards:
    target = await bot.fetch_user(i[0])
    await target.send('Your card is: ' + cards[1])
</code>```

Alternatively and even better, put all this content in a json file and have the bot read from that.

```<code>{
    "dargon_c": { "name": "dargon", "index": 0},
    "ven_c": { "name": "ven", "index": 1},
}

json.load(open('path/to/file.json', 'r'))["dargon_c"]["name"] # "dargon"
</code>```

Title: Using fewer if statements

Body:
I am trying to code the game One Night Ultimate Werewolf for Discord. I already figured out the first steps, of choosing cards, and sending roles through direct messages. The next step, is to create commands through DM, such as "!seer " for the seer to do her action. The problem is: I don't know how to make the bot check if the message author is actually a seer. I was thinking on doing the following: the variables dargon, ven, rocky, etc. are player names, where they have their player IDs stored. The variables dargon_c, ven_c, rocky_c, etc. have the players' Werewolf cards assigned to them.

  try:
    global dargon_c, ven_c, nastith_c, rocky_c, petra_c, center_c, left_center_c, right_center_c
    target = await bot.fetch_user(dargon)
    await target.send('Your card is: ' + cards[0])
    dargon_c = cards[0]

    target = await bot.fetch_user(ven)
    await target.send('Your card is: ' + cards[1])
    ven_c = cards[1]

    target = await bot.fetch_user(nastith)
    await target.send('Your card is: ' + cards[2])
    nastith_c = cards[2]

    target = await bot.fetch_user(rocky)
    await target.send('Your card is: ' + cards[3])
    rocky_c = cards[3]

    target = await bot.fetch_user(petra)
    await target.send('Your card is: ' + cards[4])
    petra_c = cards[4]

    center_c = cards[5]
    left_center_c = cards[6]
    right_center_c = cards[7]

  except:
    ctx.channel.send("Some users didn't recieve their cards")

dargon_c = 'Seer'

@bot.command()
async def seer(ctx):
  global see
  if ctx.author.id == dargon and dargon_c == 'Seer':
    ctx.channel.send('Card')
  if ctx.author.id == ven and ven_c == 'Seer':
    see = ctx.content[3:]
    ctx.channel.send('Card')

Is there any way I could do this without needing to do 100 if blocks for every single command?

Body:
Try using a list. The format looks like this:

Remember that list indexes start with 0, and go up.

So if the list is ["hello", "world] then [0] is hello and [1] is world.

myCards = [
    ["dargon", 0],
    ["ven",1]
]

for i in myCards:
    target = await bot.fetch_user(i[0])
    await target.send('Your card is: ' + cards[1])

Alternatively and even better, put all this content in a json file and have the bot read from that.

{
    "dargon_c": { "name": "dargon", "index": 0},
    "ven_c": { "name": "ven", "index": 1},
}

json.load(open('path/to/file.json', 'r'))["dargon_c"]["name"] # "dargon"


问:
Kafka replication issue
I am using a 3 broker kafka.
If I stop the third node: no problem, I can consume LOGS from node 1 or 2.
If I stop the second node : no problem, I can consume LOGS from node 1 or 3.
If I stop the first node : I am not able to consume anything.

When I restart kafka-runner service . Logs are here and was wrote properly.

my topic configuration is:
Topic: log_topic    TopicId: xxx    PartitionCount: 32  ReplicationFactor: 3    Configs: segment.bytes=1073741824,retention.ms=7200000
Topic: log_topic    Partition: 0    Leader: 2   Replicas: 1,2,3 Isr: 2,3,1
Topic: log_topic    Partition: 1    Leader: 2   Replicas: 1,2,3 Isr: 2,3,1
Topic: log_topic    Partition: 2    Leader: 2   Replicas: 1,2,3 Isr: 2,3,1
Topic: log_topic    Partition: 3    Leader: 2   Replicas: 1,2,3 Isr: 2,3,1
Topic: log_topic    Partition: 4    Leader: 2   Replicas: 1,2,3 Isr: 2,3,1
Topic: log_topic    Partition: 5    Leader: 2   Replicas: 1,2,3 Isr: 2,3,1
Topic: log_topic    Partition: 6    Leader: 2   Replicas: 1,2,3 Isr: 2,3,1
Topic: log_topic    Partition: 7    Leader: 2   Replicas: 1,2,3 Isr: 2,3,1
Topic: log_topic    Partition: 8    Leader: 2   Replicas: 1,2,3 Isr: 2,3,1
Topic: log_topic    Partition: 9    Leader: 2   Replicas: 1,2,3 Isr: 2,3,1
Topic: log_topic    Partition: 10   Leader: 2   Replicas: 2,3,1 Isr: 2,3,1
Topic: log_topic    Partition: 11   Leader: 3   Replicas: 3,1,2 Isr: 2,3,1
Topic: log_topic    Partition: 12   Leader: 3   Replicas: 1,3,2 Isr: 2,3,1
Topic: log_topic    Partition: 13   Leader: 2   Replicas: 2,1,3 Isr: 2,3,1
Topic: log_topic    Partition: 14   Leader: 3   Replicas: 3,2,1 Isr: 2,3,1
Topic: log_topic    Partition: 15   Leader: 2   Replicas: 1,2,3 Isr: 2,3,1
Topic: log_topic    Partition: 16   Leader: 2   Replicas: 2,3,1 Isr: 2,3,1
Topic: log_topic    Partition: 17   Leader: 3   Replicas: 3,1,2 Isr: 2,3,1
Topic: log_topic    Partition: 18   Leader: 3   Replicas: 1,3,2 Isr: 2,3,1
Topic: log_topic    Partition: 19   Leader: 2   Replicas: 2,1,3 Isr: 2,3,1
Topic: log_topic    Partition: 20   Leader: 3   Replicas: 3,2,1 Isr: 2,3,1
Topic: log_topic    Partition: 21   Leader: 2   Replicas: 1,2,3 Isr: 2,3,1
Topic: log_topic    Partition: 22   Leader: 2   Replicas: 2,3,1 Isr: 2,3,1
Topic: log_topic    Partition: 23   Leader: 3   Replicas: 3,1,2 Isr: 2,3,1
Topic: log_topic    Partition: 24   Leader: 3   Replicas: 1,3,2 Isr: 2,3,1
Topic: log_topic    Partition: 25   Leader: 2   Replicas: 2,1,3 Isr: 2,3,1
Topic: log_topic    Partition: 26   Leader: 3   Replicas: 3,2,1 Isr: 2,3,1
Topic: log_topic    Partition: 27   Leader: 2   Replicas: 1,2,3 Isr: 2,3,1
Topic: log_topic    Partition: 28   Leader: 2   Replicas: 2,3,1 Isr: 2,3,1
Topic: log_topic    Partition: 29   Leader: 3   Replicas: 3,1,2 Isr: 2,3,1
Topic: log_topic    Partition: 30   Leader: 3   Replicas: 1,3,2 Isr: 2,3,1
Topic: log_topic    Partition: 31   Leader: 2   Replicas: 2,1,3 Isr: 2,3,1

When I stop leader node. leader changes properly.

Any Idea?

答: Make sure your __consumer_offsets topic has three replicas and is not only hosted on broker 1. By default it only has 1 replica, as established in server.properties

Title: Kafka replication issue


问:
I want to run Power Shell script with admin privileges
I want to run this powershell script with admin privileges so it won't give me the error:

Script Output with error

Here is the script:

```<code>$processes = "PDStyleAgent", "AdobeIPCBroker", "CCXProcess", "RichVideo64", "CCLibrary", "AdobeNotificationClient", "AdobeUpdateService", "PDHanumanSvr", "PDR"

Foreach ($process in $processes){
    try {
    $f = Get-Process $process -ErrorAction Stop
    $f | kill
    Write-Output "$process killed."
        }
    catch [Microsoft.PowerShell.Commands.ProcessCommandException]{
    Write-Output "No instances of $process running."
        }
}

Start-Sleep -Seconds 3
</code>```

I want to run this script so it kill the processes that are giving errors

答:
Some way to run PowerShell with admin privileges:

Search Powershell from the Windows search icon OR click the Windows button from the keyboard --> write Powershell --> You will see the Windows PowerShell --> Right-click on Powershell then click Run as administrator.

Run this command of a PowerShell console: Start-Process powershell -Verb runAs

Run your script from PowerShell like this: PowerShell -f C:\ScriptPath

For more details, you can check this StackOverflow question and answer.

Body:
I want to run this powershell script with admin privileges so it won't give me the error:

Script Output with error

Here is the script:

$processes = "PDStyleAgent", "AdobeIPCBroker", "CCXProcess", "RichVideo64", "CCLibrary", "AdobeNotificationClient", "AdobeUpdateService", "PDHanumanSvr", "PDR"

Foreach ($process in $processes){
    try {
    $f = Get-Process $process -ErrorAction Stop
    $f | kill
    Write-Output "$process killed."
        }
    catch [Microsoft.PowerShell.Commands.ProcessCommandException]{
    Write-Output "No instances of $process running."
        }
}

Start-Sleep -Seconds 3

I want to run this script so it kill the processes that are giving errors


问:
R group by show count of all factor levels even when zero dplyr
```<code>set.seed(1)
dat <- data.frame(ID = sample(letters,50,rep=TRUE))
dat %>%
  group_by(ID) %>%
  summarise(no_rows = length(ID))
</code>```

I have the above code which creates a random sample of letters. However can I make the summarised output show all count levels even when there is zero.

When I run the above code sometimes I get 20 rows and sometimes I get 25, etc.
I want this to return 26 rows every time.

答:
The tidyverse solution by akrun can be corrected as follows :

```<code>set.seed(1)
library(tidyverse)
#> Warning: package 'tibble' was built under R version 4.0.5
dat <- data.frame(ID = sample(letters,50,rep=TRUE))
dat %>%
  mutate(ID=factor(ID, levels = letters)) %>%
  group_by(ID) %>%
  summarise(no_rows = n()) %>%
  complete(ID, fill = list(no_rows = 0)) %>%
  print.data.frame()
#> `summarise()` ungrouping output (override with `.groups` argument)
#>    ID no_rows
#> 1   a       3
#> 2   b       2
#> 3   c       1
#> 4   d       1
#> 5   e       3
#> 6   f       3
#> 7   g       2
#> 8   h       1
#> 9   i       2
#> 10  j       5
#> 11  k       1
#> 12  l       3
#> 13  m       0
#> 14  n       3
#> 15  o       3
#> 16  p       0
#> 17  q       0
#> 18  r       1
#> 19  s       1
#> 20  t       3
#> 21  u       3
#> 22  v       1
#> 23  w       2
#> 24  x       0
#> 25  y       5
#> 26  z       1
</code>```

Body:
set.seed(1)
dat <- data.frame(ID = sample(letters,50,rep=TRUE))
dat %>%
  group_by(ID) %>%
  summarise(no_rows = length(ID))

I have the above code which creates a random sample of letters. However can I make the summarised output show all count levels even when there is zero.

When I run the above code sometimes I get 20 rows and sometimes I get 25, etc.
I want this to return 26 rows every time.

Body:
The tidyverse solution by akrun can be corrected as follows :

set.seed(1)
library(tidyverse)
#> Warning: package 'tibble' was built under R version 4.0.5
dat <- data.frame(ID = sample(letters,50,rep=TRUE))
dat %>%
  mutate(ID=factor(ID, levels = letters)) %>%
  group_by(ID) %>%
  summarise(no_rows = n()) %>%
  complete(ID, fill = list(no_rows = 0)) %>%
  print.data.frame()
#> `summarise()` ungrouping output (override with `.groups` argument)
#>    ID no_rows
#> 1   a       3
#> 2   b       2
#> 3   c       1
#> 4   d       1
#> 5   e       3
#> 6   f       3
#> 7   g       2
#> 8   h       1
#> 9   i       2
#> 10  j       5
#> 11  k       1
#> 12  l       3
#> 13  m       0
#> 14  n       3
#> 15  o       3
#> 16  p       0
#> 17  q       0
#> 18  r       1
#> 19  s       1
#> 20  t       3
#> 21  u       3
#> 22  v       1
#> 23  w       2
#> 24  x       0
#> 25  y       5
#> 26  z       1


问:
Rotate a set of object coordinates
I have a bunch of objects (ActiveRecord) that have x and y coordinates relative to a HTML5 canvas element. I need to rotate sets of them by different number of degrees (in 90 degrees increments) and then store them again for a one time data migration.

These objects are all relative to a canvas element so the coordinates start at (0,0) and I  would like them to stay in that quadrant (bottom right), if possible. I assume that I need to do a rotation around (0,0) and then a translation down and right.

Is there a way I can write a block that will do this?

答:
To rotate a point P an amount of R degrees around the origin:

P2.x = P.x * cos(R) - P.y * sin(R)

P2.y = P.x * sin(R) + P.y * cos(R)

[citation]

You probably want to rotate about an arbitrary point in the center of the quadrant you are keeping the objects in. If your quadrant is 200x100 units wide, you'd want to rotate around the point <100,50>.

To rotate a point P around a location C other than the origin, you want to first translate the location to the origin, then rotate around the origin, and then translate back to C. In other words,

P2 = P - C

P3 = rotate(P2)

P4 = P3 + C

You can see this in action at http://phrogz.net/SVG/rotations.xhtml - click to set the rotation center, or change the rotation amount, and a transform is set on the group of points that translates to the origin, rotates, and then translates back again.

Put it all together, and to rotate a point with x and y attributes around an arbitrary point in Ruby, you'd use code like this:

```<code>Point = Struct.new(:x,:y) do
  def self.to_proc
    lambda{ |x| self.new *x }
  end

  def rotate( degrees, origin=Point.new(0,0) )
    radians = degrees * Math::PI/180
    x2 = x-origin.x; y2 = y-origin.y
    cos = Math.cos(radians); sin = Math.sin(radians)
    self.class.new(
      x2*cos - y2*sin + origin.x,
      x2*sin + y2*cos + origin.y
    )
  end

  def inspect
    "<%.1f,%.1f>" % [x,y]
  end
end

points = [ [0,0], [1,2], [3,4], [5,6] ].map(&Point)
p points
#=> [<0.0,0.0>, <1.0,2.0>, <3.0,4.0>, <5.0,6.0>]

p points.map{ |p| p.rotate(90) }
#=> [<0.0,0.0>, <-2.0,1.0>, <-4.0,3.0>, <-6.0,5.0>]

p points.map{ |p| p.rotate(90,Point.new(3,4)) }
#=> [<7.0,1.0>, <5.0,2.0>, <3.0,4.0>, <1.0,6.0>]
</code>```

Title: Rotate a set of object coordinates

Body:
To rotate a point P an amount of R degrees around the origin:

P2.x = P.x * cos(R) - P.y * sin(R)

P2.y = P.x * sin(R) + P.y * cos(R)

[citation]

You probably want to rotate about an arbitrary point in the center of the quadrant you are keeping the objects in. If your quadrant is 200x100 units wide, you'd want to rotate around the point <100,50>.

To rotate a point P around a location C other than the origin, you want to first translate the location to the origin, then rotate around the origin, and then translate back to C. In other words,

P2 = P - C

P3 = rotate(P2)

P4 = P3 + C

You can see this in action at http://phrogz.net/SVG/rotations.xhtml - click to set the rotation center, or change the rotation amount, and a transform is set on the group of points that translates to the origin, rotates, and then translates back again.

Put it all together, and to rotate a point with x and y attributes around an arbitrary point in Ruby, you'd use code like this:

Point = Struct.new(:x,:y) do
  def self.to_proc
    lambda{ |x| self.new *x }
  end

  def rotate( degrees, origin=Point.new(0,0) )
    radians = degrees * Math::PI/180
    x2 = x-origin.x; y2 = y-origin.y
    cos = Math.cos(radians); sin = Math.sin(radians)
    self.class.new(
      x2*cos - y2*sin + origin.x,
      x2*sin + y2*cos + origin.y
    )
  end

  def inspect
    "<%.1f,%.1f>" % [x,y]
  end
end

points = [ [0,0], [1,2], [3,4], [5,6] ].map(&Point)
p points
#=> [<0.0,0.0>, <1.0,2.0>, <3.0,4.0>, <5.0,6.0>]

p points.map{ |p| p.rotate(90) }
#=> [<0.0,0.0>, <-2.0,1.0>, <-4.0,3.0>, <-6.0,5.0>]

p points.map{ |p| p.rotate(90,Point.new(3,4)) }
#=> [<7.0,1.0>, <5.0,2.0>, <3.0,4.0>, <1.0,6.0>]


问:
How to call manually Response.Listener in Android?
I have the following method that runs some web services commands in Android.

```<code>    Response.Listener Success = new Response.Listener<JSONObject >() {@Override
                public void onResponse(JSONObject  response) {
                    JSONObject  S = response;
                    // do something with the response
    }};

    Response.ErrorListener Fail = new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            if (error.networkResponse.statusCode == 400) {
                Success.notify();  // <<<<< According to some technical custom logic, this should be considered as a successful REST command. Hence run Success Response Listener
            }
            else {
                // operation failed, do something
            }
        }
    };

    JSONObject J = new JSONObject();
    J.put("param", some parameters);

    RequestQueue queue = Volley.newRequestQueue(Act);
    JsonObjectRequest JsonRequestObject = new JsonObjectRequest(Method, URL, J, Success, Fail);
    queue.add(JsonRequestObject);
</code>```

According to some custom technical logic, the requests that get 400 as a response should be considered as successful and hence run the success calback.

I tried this code but it crashes at the line :

```<code>                Success.notify();  // <<<<<
</code>```

Does anyone know how can I execute the Success call back manually please ?

Thanks
Cheers,

答:
Instead of notify() you should call onResponse() like Success.onResponse() with null argument or with some JSONObject mapped from error.networkResponse.

More generalized way - create custom Response Listener (to listen to the success/error events in one place):

```<code>public abstract class ResponseListener<T> implements Response.Listener<T>,
        Response.ErrorListener {

    @Override
    public final void onErrorResponse(VolleyError error) {
        if (error.networkResponse.statusCode == 400) {
            // redirect to onResponse()
            onResponse(null /* or some response T object mapped from [error.networkResponse] */);
        } else {
            onError(error);
        }
    }

    public abstract void onError(VolleyError error);
}
</code>```

...

```<code> final ResponseListener<JSONObject> responseListener =
            new ResponseListener<JSONObject>() {
                @Override
                public void onResponse(@Nullable JSONObject response) {
                    // do something with the response
                }

                @Override
                public void onError(VolleyError error) {
                    // operation failed, do something
                }
            };
    //
    final JsonObjectRequest JsonRequestObject =
            new JsonObjectRequest(Method, URL, J, responseListener, responseListener);
    //
</code>```

Body:
I have the following method that runs some web services commands in Android.

    Response.Listener Success = new Response.Listener<JSONObject >() {@Override
                public void onResponse(JSONObject  response) {
                    JSONObject  S = response;
                    // do something with the response
    }};

    Response.ErrorListener Fail = new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            if (error.networkResponse.statusCode == 400) {
                Success.notify();  // <<<<< According to some technical custom logic, this should be considered as a successful REST command. Hence run Success Response Listener
            }
            else {
                // operation failed, do something
            }
        }
    };

    JSONObject J = new JSONObject();
    J.put("param", some parameters);

    RequestQueue queue = Volley.newRequestQueue(Act);
    JsonObjectRequest JsonRequestObject = new JsonObjectRequest(Method, URL, J, Success, Fail);
    queue.add(JsonRequestObject);

According to some custom technical logic, the requests that get 400 as a response should be considered as successful and hence run the success calback.

I tried this code but it crashes at the line :

                Success.notify();  // <<<<<

Does anyone know how can I execute the Success call back manually please ?

Thanks
Cheers,

Body:
Instead of notify() you should call onResponse() like Success.onResponse() with null argument or with some JSONObject mapped from error.networkResponse.

More generalized way - create custom Response Listener (to listen to the success/error events in one place):

public abstract class ResponseListener<T> implements Response.Listener<T>,
        Response.ErrorListener {

    @Override
    public final void onErrorResponse(VolleyError error) {
        if (error.networkResponse.statusCode == 400) {
            // redirect to onResponse()
            onResponse(null /* or some response T object mapped from [error.networkResponse] */);
        } else {
            onError(error);
        }
    }

    public abstract void onError(VolleyError error);
}

...

 final ResponseListener<JSONObject> responseListener =
            new ResponseListener<JSONObject>() {
                @Override
                public void onResponse(@Nullable JSONObject response) {
                    // do something with the response
                }

                @Override
                public void onError(VolleyError error) {
                    // operation failed, do something
                }
            };
    //
    final JsonObjectRequest JsonRequestObject =
            new JsonObjectRequest(Method, URL, J, responseListener, responseListener);
    //


问:
If jupyter notebook is ready but Dask dashboard is still showing that its running some task, can I execute my next cell?
I am new to Dask. I was using it with an xarray dataset. I persisted the dataset in memory and the jupyter cell showed that it was ready (no more asterisk). But the dask dashboard was busy executing the task. I didn't understand. When this happens, should I wait till dask dashboard has stabilized or am I free to run the next cell?

答:
If the subsequent code doesn't depend on the task being calculated, it's possible to continue running some code.

For example, let's say you submitted calculation of ddf.map_partitions(some_func) and persist the dataframe:

ddf = ddf.map_partitions(some_func)
ddf = ddf.persist()
```
<p>Then, if you try to run some <code>ddf</code>-specific code, Jupyter will wait until <code>ddf</code> (or the relevant chunks/partitions) are computed by the scheduler, e.g. if you try to run <code>len(ddf)</code> it will block until the full <code>ddf</code> is computed.</p>
<p>If the subsequent code does not require submission to the scheduler, then it will run without waiting for <code>ddf</code>. For example, if downstream you want to create a list of some numbers this will run right away:</p>
<pre class="lang-py prettyprint-override"><code>list_evens = [i for i in range(1000) if i%2==0]
</code>```

Body:
If the subsequent code doesn't depend on the task being calculated, it's possible to continue running some code.

For example, let's say you submitted calculation of ddf.map_partitions(some_func) and persist the dataframe:

ddf = ddf.map_partitions(some_func)
ddf = ddf.persist()

Then, if you try to run some ddf-specific code, Jupyter will wait until ddf (or the relevant chunks/partitions) are computed by the scheduler, e.g. if you try to run len(ddf) it will block until the full ddf is computed.

If the subsequent code does not require submission to the scheduler, then it will run without waiting for ddf. For example, if downstream you want to create a list of some numbers this will run right away:

list_evens = [i for i in range(1000) if i%2==0]


问:
PowerShell: Restart Service By Executable Name
all

I implemented my first PowerShell script, that does some setup, sets registry keys and at then end needs to restart services. The problem is that I have only have name of the executable, but not service name. Restart-Service can work only with name of the service. Googling (well Binging also) around didn't give me much result.

I was wondering whether there is a way to restart service by executable name?

I know that I can get process by executable name, but just killing the process and starting it again is NOT good choice, since service Start/Stop functions are not called and it may not work properly.

Thanks.

答:
You can do this using WMI:

```<code>$process = Get-Process sqlservr| select -ExpandProperty Id

Get-WmiObject win32_Service|
    where {$process -contains $_.ProcessId}|
    foreach {Restart-Service $_.Name}
</code>```

Edit: Changed script to restart service, not just stop it.

Body:
You can do this using WMI:

$process = Get-Process sqlservr| select -ExpandProperty Id

Get-WmiObject win32_Service|
    where {$process -contains $_.ProcessId}|
    foreach {Restart-Service $_.Name}

Edit: Changed script to restart service, not just stop it.


问:
How to i chain two parts of an animation together in jetpack compose so the the offset increases then decreases?
Ive recently got into doing animations using jet pack compose and am wondering how you can make it so that when you increase a value in an offset, once the animation reaches that value it then changes the value to another value. So like update transition but instead of at the same time, one after the other.</p>

答:
Maybe you can use Animatable

```<code>val value = remember { Animatable(0f) }    //Initial Value
</code>```

Then in compose you can just use

```<code>value.animateTo(20f)
</code>```

then

```<code>value.animateTo(10f)
</code>```

For more information visit the official documentation

Body:
Maybe you can use Animatable

val value = remember { Animatable(0f) }    //Initial Value

Then in compose you can just use

value.animateTo(20f)

then

value.animateTo(10f)

For more information visit the official documentation


问:
Why isn't there an option to upsert data in Azure Data Factory inline sink
The problem I'm trying to tackle is inserting and/or updating dynamic tables in a sink within an Azure Data Factory data flow. I've managed to get the source data, transform it how I want it and then send it to a sink. The pipeline ran successfully and it said it copied 37 rows (as expected) but investigation showed that no data was actually deposited in the target table. This was because the Table Action on the sink was set to 'None'. So in trying to fix this last part, it seems I don't have the 'Create' option but do have the 'Recreate' option (see screenshot of the sink below) which is not what I want as the datasource will eventually only have changed data. I need the process to create the table if it doesn't exist and then Upsert data. (Recreate drops the table and then creates it).
If I change the sink type from Inline to Dataset, then I can select Insert and Upsert, etc options but this is then not dynamic as I need to select a specific dataset.
So has anyone come across the same issue and have you managed to have dynamic sinks in your data flow where the table is created if it doesn't exist, then upsert data.
I guess I can add a Pre SQL script which takes care of the 'create the table if it doesn't exist' but I still can't select the Upsert option with inline tables.

答:
For the CREATE TABLE IF NOT EXISTS issue, I would recommend a Stored Procedure that is executed in the pipeline prior to the Data Flow.

For Inline vs Dataset, you can make the Dataset very flexible:

So still based on your runtime table name and no schema, so no need to target a specific table.

For the UPSERT issue, make sure you have an AlterRow activity before the Sink:


问:
No .lib and .dll found, but .h is there
So I'm trying to use RtAudio to read microphone input in real time, but the problem is that when I download the .zip file, I found the header files but there is no .lib files or dll, and I need them Link with my project, where are they?

I'm a beginner in cpp:)

This is the RtAudio
https://github.com/thestk/rtaudio

答:
You seem to have downloaded a copy of source code repository. Compiled binaries such libraries are not stored in such repositories. That's why you won't find them there.

In order to get the compiled libraries from the source code, you must compile i.e. build the source code. Each project has their own way of building from source, although there  are common patterns. The frontpage that you link to contains instructions on how to build that project. The instructions to build it are under the heading "Building".

Title: No .lib and .dll found, but .h is there


问:
occurrence to score
I get a frequency of words I would like to convert number_of_occuerence to a number between 0-10.</p>
```<code>word     number_of_occurrence      score
and      200                       10
png      2                         1
where    50                        6
news     120                       7
</code>```

答:
Score is between 0-10. The maximum score is 10 for occurence 50, therefore anything higher than that should also has score 10. On the other hand, minimum score is 0, while the score is 1 for occurence 5, so assume anything lower than that has score 0.

Interpolation is based on your given condition only:

If a word appear 50 times it should be closer to 10 and if a word
appear 5 times it should be closer to 1.

```<code>df['score'] = df['number_of_occurrence'].apply(lambda x: x/5 if 5<=x<=50 else (0 if x< 5 else 10))
</code>```

Output:

Title: occurrence to score

Body:
I get a frequency of words I would like to convert number_of_occuerence to a number between 0-10.

word     number_of_occurrence      score
and      200                       10
png      2                         1
where    50                        6
news     120                       7

Body:
Score is between 0-10. The maximum score is 10 for occurence 50, therefore anything higher than that should also has score 10. On the other hand, minimum score is 0, while the score is 1 for occurence 5, so assume anything lower than that has score 0.

Interpolation is based on your given condition only:

If a word appear 50 times it should be closer to 10 and if a word
appear 5 times it should be closer to 1.

df['score'] = df['number_of_occurrence'].apply(lambda x: x/5 if 5<=x<=50 else (0 if x< 5 else 10))

Output:


问:
Disable buffering of repeated button clicks
When the user clicks a button, an action is started but if the user quickly clicks the button 10 times, it will execute 10 times.  I guess the disable doesn't take effect until control returns from the event.</p>

```<code>- (IBAction)btnQuickCheckClick:(id)sender {
  @try {
    self.btnQuickCheck.enabled = NO ;
    // Next line takes about 3 seconds to execute:
    [self pollRouter] ;
  }
  @finally {
    self.btnQuickCheck.enabled = YES ;
  }
}
</code>```

答:
another way to do this is with blocks :

Big Pro : you don't need to create an extra method :)

```<code>- (IBAction)btnQuickCheckClick:(id)sender {
    //UI changes must be done in the main thread
    self.btnQuickCheck.enabled = NO;

    //do your thing in a background thread
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT ,0);
    dispatch_async(queue, ^(){
        @try {
            //do your thing here
            [self pollRouter];

        } @catch (NSException * e) {
            //handle the exception, if needed

        } @finally {
            //change to the main thread again and re-enable the UI
            dispatch_queue_t mainQueue = dispatch_get_main_queue();
            dispatch_async(mainQueue, ^(){
                self.btnQuickCheck.enabled = YES;
            });
        }
    });
}
</code>```

This will run pollRouter in a background thread. So if you are not modifying the UI or other non thread safe things in there you want to use this approach :) Otherwise go for @Alex's approach

Body:
When the user clicks a button, an action is started but if the user quickly clicks the button 10 times, it will execute 10 times.  I guess the disable doesn't take effect until control returns from the event.

- (IBAction)btnQuickCheckClick:(id)sender {
  @try {
    self.btnQuickCheck.enabled = NO ;
    // Next line takes about 3 seconds to execute:
    [self pollRouter] ;
  }
  @finally {
    self.btnQuickCheck.enabled = YES ;
  }
}

Body:
another way to do this is with blocks :

Big Pro : you don't need to create an extra method :)

- (IBAction)btnQuickCheckClick:(id)sender {
    //UI changes must be done in the main thread
    self.btnQuickCheck.enabled = NO;

    //do your thing in a background thread
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT ,0);
    dispatch_async(queue, ^(){
        @try {
            //do your thing here
            [self pollRouter];

        } @catch (NSException * e) {
            //handle the exception, if needed

        } @finally {
            //change to the main thread again and re-enable the UI
            dispatch_queue_t mainQueue = dispatch_get_main_queue();
            dispatch_async(mainQueue, ^(){
                self.btnQuickCheck.enabled = YES;
            });
        }
    });
}

This will run pollRouter in a background thread. So if you are not modifying the UI or other non thread safe things in there you want to use this approach :) Otherwise go for @Alex's approach


问:
How to implement OCL(Object Constraint Language) in JAVA
I am working on a JavaEE project, and I have to implement OCL (Object Constraint Language), I search a lot, but I didn't find how to implement it.
Can someone give me an idea please?</p>

答: AgileUML has Java code generators from UML/OCL: for versions 4, 6, 7 and 8 of Java (https://github.com/eclipse/agileuml). There are some videos on using the tool at: https://www.youtube.com/watch?v=NKAK9eITDkw&t=41s</p>