问:
Problem with changing class variables' value
I have a problem. I'm working on a OpenGL project and I need to access a class variable by the class method. I got it done, but then changed some code and now it's not working and i cannot get it done. It's all about Yaw and Pitch variables. If i change them in their class method (e.g. ProccesMouseInput) they don't change their values, but I had already tried it in main function and then they do... Here's my code.

Camera.h

```<code>#pragma once
#include <glm/glm.hpp>
#include <glm/vec3.hpp>
#include <glm/gtc/matrix_transform.hpp>

enum class movement_direction{
    FORWARD,
    BACKWARD,
    LEFT,
    RIGHT,
    UP,
    DOWN
};

class Camera {
private:
    glm::vec3 m_Position;
    glm::vec3 m_Front;
    glm::vec3 m_Up;
    glm::vec3 m_Right;
    glm::vec3 m_WorldUp;
    float m_MouseSensitivity;
    float MovementSpeed = 2.5f;
    float MouseSensitivity = 0.1f;
    float FOV = 45.0f;
    float Yaw;
    float Pitch;

public:
    Camera(glm::vec3 pos, glm::vec3 up, float yaw, float pitch);
    Camera(float PosX, float PosY, float PosZ, float UpX, float UpY, float UpZ, float yaw, float pitch);
    void ProcessMouseInput(float offsetX, float offsetY, bool constrainPitch);
    void ProcessKeyboardInput(movement_direction direction, float deltaTime);
    void ProcessScrollInput(float offsetX, float offsetY);
    void UpdateCameraVectors();
    glm::mat4 GetViewMatrix();
};
</code>```

Camera.cpp

```<code>#include "Camera.h"
#include <iostream>

Camera::Camera(glm::vec3 pos = glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3 up = glm::vec3(0.0f, 1.0f, 0.0f), float yaw = -90.0f, float pitch = 0.0f)
    : m_Position(pos), m_Up(up), m_WorldUp(up), Yaw(yaw), Pitch(pitch), m_MouseSensitivity(MouseSensitivity)
{

    UpdateCameraVectors();
}

Camera::Camera(float PosX, float PosY, float PosZ, float UpX, float UpY, float UpZ, float yaw, float pitch)
    : m_Position(glm::vec3(PosX, PosY, PosZ)), m_Up(glm::vec3(UpX, UpY, UpZ)), m_WorldUp(glm::vec3(UpX, UpY, UpZ)), Yaw(yaw), Pitch(pitch), m_MouseSensitivity(MouseSensitivity)
{

    UpdateCameraVectors();
}

void Camera::ProcessMouseInput(float offsetX, float offsetY, bool constrainPitch = true)
{
    Yaw += offsetX * m_MouseSensitivity;
    Pitch += offsetY * m_MouseSensitivity;
    if (constrainPitch)
    {
        if (Pitch < -89.0f)
            Pitch = -89.0f;
        if (Pitch > 89.0f)
            Pitch = 89.0f;
    }

    UpdateCameraVectors();

}

void Camera::ProcessKeyboardInput(movement_direction direction, float deltaTime)
{
    float velocity = MovementSpeed * deltaTime;

    if (direction == movement_direction::FORWARD)
        m_Position +=  m_Front * velocity;
    if (direction == movement_direction::BACKWARD)
        m_Position -= m_Front * velocity;
    if (direction == movement_direction::LEFT)
        m_Position -= m_Right * velocity;
    if (direction == movement_direction::RIGHT)
        m_Position += m_Right * velocity;
    if (direction == movement_direction::UP)
        m_Position += m_WorldUp * velocity;
    if (direction == movement_direction::DOWN)
        m_Position -= m_WorldUp * velocity;
}

void Camera::ProcessScrollInput(float offsetX, float offsetY)
{
}

void Camera::UpdateCameraVectors()
{
    glm::vec3 direction;

    direction.x = cos(glm::radians(Yaw)) * cos(glm::radians(Pitch));
    direction.y = sin(glm::radians(Pitch));
    direction.z = sin(glm::radians(Yaw)) * cos(glm::radians(Pitch));

    m_Front = glm::normalize(direction);
    m_Right = glm::normalize(glm::cross(m_Front, m_WorldUp));
    m_Up = glm::normalize(glm::cross(m_Right, m_Front));
}

glm::mat4 Camera::GetViewMatrix()
{
    return glm::lookAt(m_Position, m_Position + m_Front, m_Up);
}

</code>```

Application.cpp

```<code>/* Including GLEW */
#include <GL/glew.h>

/* Including GLFW */
#include <GLFW/glfw3.h>

#define STB_IMAGE_IMPLEMENTATION
#include "vendor/stb_image/stb_image.h"

#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>

#include <iostream>
#include <string>
#include <conio.h>

#include "Shader.h"
#include "Camera.h"

void processInput(GLFWwindow* window);
void mouse_callback(GLFWwindow* window, double xpos, double ypos);
void scroll_callback(GLFWwindow* window, double offsetX, double offsetY);

const int SCR_WIDTH = 800;
const int SCR_HEIGHT = 600;

float deltaTime = 0.0f;
float currentFrame = 0.0f;
float lastFrame = 0.0f;

float lastX = SCR_WIDTH / 2;
float lastY = SCR_HEIGHT / 2;

bool firstMouse = true;

float fov = 45.0f;

Camera main_camera(glm::vec3(0.0f, 0.0f, -3.0f), glm::vec3(0.0f, 1.0f, 0.0f), -90.0f, 0.0f);

int main(void)
{

    GLFWwindow* window;

    /* Initializing the library */
    if (!glfwInit())
    {
        std::cout << "Failed to initialize GLFW.\n";
        return -1;
    }

    /* Creating a windowed mode window and its OpenGL context */

    window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "Hello World", NULL, NULL);

    if (!window)
    {
        std::cout << "Failed to open GLFW window.\n";
        glfwTerminate();
        return -1;
    }

    /* Making the window's context current */
    glfwMakeContextCurrent(window);
    if (glewInit() != GLEW_OK)
        std::cout << "Failed to initialize GLEW\n";

    glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
    glfwSetCursorPosCallback(window, mouse_callback);

    glfwSetScrollCallback(window, scroll_callback);

    /* Getting the version of GL */
    std::cout << "Using GL Version: " << glGetString(GL_VERSION) << std::endl;

    float vertices[] = {
        -0.5f, -0.5f, -0.5f,    0.0f, 0.0f, 0.0f,    0.0f, 0.0f,
         0.5f, -0.5f, -0.5f,    0.0f, 0.0f, 0.0f,    1.0f, 0.0f,
         0.5f,  0.5f, -0.5f,    0.0f, 0.0f, 0.0f,    1.0f, 1.0f,
         0.5f,  0.5f, -0.5f,    0.0f, 0.0f, 0.0f,    1.0f, 1.0f,
        -0.5f,  0.5f, -0.5f,    0.0f, 0.0f, 0.0f,    0.0f, 1.0f,
        -0.5f, -0.5f, -0.5f,    0.0f, 0.0f, 0.0f,    0.0f, 0.0f,

        -0.5f, -0.5f,  0.5f,    0.0f, 0.0f, 0.0f,    0.0f, 0.0f,
         0.5f, -0.5f,  0.5f,    0.0f, 0.0f, 0.0f,    1.0f, 0.0f,
         0.5f,  0.5f,  0.5f,    0.0f, 0.0f, 0.0f,    1.0f, 1.0f,
         0.5f,  0.5f,  0.5f,    0.0f, 0.0f, 0.0f,    1.0f, 1.0f,
        -0.5f,  0.5f,  0.5f,    0.0f, 0.0f, 0.0f,    0.0f, 1.0f,
        -0.5f, -0.5f,  0.5f,    0.0f, 0.0f, 0.0f,    0.0f, 0.0f,

        -0.5f,  0.5f,  0.5f,    0.0f, 0.0f, 0.0f,    1.0f, 0.0f,
        -0.5f,  0.5f, -0.5f,    0.0f, 0.0f, 0.0f,    1.0f, 1.0f,
        -0.5f, -0.5f, -0.5f,    0.0f, 0.0f, 0.0f,    0.0f, 1.0f,
        -0.5f, -0.5f, -0.5f,    0.0f, 0.0f, 0.0f,    0.0f, 1.0f,
        -0.5f, -0.5f,  0.5f,    0.0f, 0.0f, 0.0f,    0.0f, 0.0f,
        -0.5f,  0.5f,  0.5f,    0.0f, 0.0f, 0.0f,    1.0f, 0.0f,

         0.5f,  0.5f,  0.5f,    0.0f, 0.0f, 0.0f,    1.0f, 0.0f,
         0.5f,  0.5f, -0.5f,    0.0f, 0.0f, 0.0f,    1.0f, 1.0f,
         0.5f, -0.5f, -0.5f,    0.0f, 0.0f, 0.0f,    0.0f, 1.0f,
         0.5f, -0.5f, -0.5f,    0.0f, 0.0f, 0.0f,    0.0f, 1.0f,
         0.5f, -0.5f,  0.5f,    0.0f, 0.0f, 0.0f,    0.0f, 0.0f,
         0.5f,  0.5f,  0.5f,    0.0f, 0.0f, 0.0f,    1.0f, 0.0f,

        -0.5f, -0.5f, -0.5f,    0.0f, 0.0f, 0.0f,    0.0f, 1.0f,
         0.5f, -0.5f, -0.5f,    0.0f, 0.0f, 0.0f,    1.0f, 1.0f,
         0.5f, -0.5f,  0.5f,    0.0f, 0.0f, 0.0f,    1.0f, 0.0f,
         0.5f, -0.5f,  0.5f,    0.0f, 0.0f, 0.0f,    1.0f, 0.0f,
        -0.5f, -0.5f,  0.5f,    0.0f, 0.0f, 0.0f,    0.0f, 0.0f,
        -0.5f, -0.5f, -0.5f,    0.0f, 0.0f, 0.0f,    0.0f, 1.0f,

        -0.5f,  0.5f, -0.5f,    0.0f, 0.0f, 0.0f,    0.0f, 1.0f,
         0.5f,  0.5f, -0.5f,    0.0f, 0.0f, 0.0f,    1.0f, 1.0f,
         0.5f,  0.5f,  0.5f,    0.0f, 0.0f, 0.0f,    1.0f, 0.0f,
         0.5f,  0.5f,  0.5f,    0.0f, 0.0f, 0.0f,    1.0f, 0.0f,
        -0.5f,  0.5f,  0.5f,    0.0f, 0.0f, 0.0f,    0.0f, 0.0f,
        -0.5f,  0.5f, -0.5f,    0.0f, 0.0f, 0.0f,    0.0f, 1.0f
    };

    glm::vec3 cubes_positions[]{
        glm::vec3( 0.0f,  0.0f,  0.0f),
        glm::vec3( 2.0f,  5.0f, -15.0f),
        glm::vec3(-1.5f, -2.2f, -2.5f),
        glm::vec3(-3.8f, -2.0f, -12.3f),
        glm::vec3( 2.4f, -0.4f, -3.5f),
        glm::vec3(-1.7f,  3.0f, -7.5f),
        glm::vec3( 1.3f, -2.0f, -2.5f),
        glm::vec3( 1.5f,  2.0f, -2.5f),
        glm::vec3( 1.5f,  0.2f, -1.5f),
        glm::vec3(-1.3f,  1.0f, -1.5f)
    };

    /* VERTEX ARRAY */
    unsigned int VAO;
    glGenVertexArrays(1, &VAO);
    glBindVertexArray(VAO);

    /* VERTEX BUFFER */
    unsigned int VBO;
    glGenBuffers(1, &VBO);
    glBindBuffer(GL_ARRAY_BUFFER, VBO);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

    /* VERTEX LAYOUT */
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)0);
    glEnableVertexAttribArray(0);

    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(3 * sizeof(float)));
    glEnableVertexAttribArray(1);

    glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(6 * sizeof(float)));
    glEnableVertexAttribArray(2);

    /* LOADING TEXTURES */
    // --- first texture object ---
    unsigned int texture1;
    glGenTextures(1, &texture1);
    glBindTexture(GL_TEXTURE_2D, texture1);

    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);

    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);

    float borderColor1[]{
        0.1f, 0.1f, 0.0f, 1.0f
    };
    glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, borderColor1);

    int width, height, channelsNr;
    unsigned char* data = stbi_load("res/textures/container.jpg", &width, &height, &channelsNr, 0);
    if (data)
    {
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data);
        glGenerateMipmap(GL_TEXTURE_2D);
    }
    else
    {
        std::cout << "Failed to load texture\n";
    }
    stbi_image_free(data);

    // --- second texture object ---
    unsigned int texture2;
    glGenTextures(1, &texture2);
    glBindTexture(GL_TEXTURE_2D, texture2);

    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);

    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);

    float borderColor2[]{
        0.1f, 0.1f, 0.0f, 1.0f
    };
    glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, borderColor2);

    stbi_set_flip_vertically_on_load(true);
    data = stbi_load("res/textures/awesomeface.png", &width, &height, &channelsNr, 0);
    if (data)
    {
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);
    }
    else
    {
        std::cout << "Failed to load texture\n";
    }
    stbi_image_free(data);

    /* BINDING BEFORE THE DRAW CALL */
    // --- shader ---
    Shader basic("res/shaders/Basic.glsl");
    basic.Bind();
    basic.SetUniform1i("texture1", 0);
    basic.SetUniform1i("texture2", 1);
    glEnable(GL_DEPTH_TEST);
    // --- texture ---
    glBindTexture(GL_TEXTURE_2D, texture2);

    // --- vertex array object ---
    glBindVertexArray(VAO);

    float value = 0.5f;
    basic.SetUniform1f("mix_value", 0.2f);

    /* Loop until the user closes the window */
    while (!glfwWindowShouldClose(window))
    {
        currentFrame = (float)glfwGetTime();
        deltaTime = currentFrame - lastFrame;
        lastFrame = currentFrame;

        processInput(window);

        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        glClearColor(0.f, 0.2f, 0.2f, 1.f);
        /* Render here */

        glActiveTexture(GL_TEXTURE0);
        glBindTexture(GL_TEXTURE_2D, texture1);

        glActiveTexture(GL_TEXTURE1);
        glBindTexture(GL_TEXTURE_2D, texture2);

        glm::mat4 projection = glm::perspective(glm::radians(fov), (float)SCR_WIDTH / (float)SCR_HEIGHT, 0.1f, 100.0f);
        basic.SetUniformMatrix4fv("proj", 1, glm::value_ptr(projection));

        glm::mat4 view = main_camera.GetViewMatrix();
        basic.SetUniformMatrix4fv("view", 1, glm::value_ptr(view));

        for (int i = 0; i < (sizeof(cubes_positions) / sizeof(glm::vec3)); i++)
        {
            float angle = 20.0f * i;
            glm::mat4 model = glm::mat4(1.0f);
            model = glm::translate(model, cubes_positions[i]);
            model = glm::rotate(model, glm::radians(angle), glm::vec3(1.0f, 0.0f, 0.0f));
            basic.SetUniformMatrix4fv("model", 1, glm::value_ptr(model));

            glDrawArrays(GL_TRIANGLES, 0, 36);
        }

        /* Swap front and back buffers */
        glfwSwapBuffers(window);

        /* Poll for and process events */
        glfwPollEvents();

    }

    glfwTerminate();
    return 0;
}

void processInput(GLFWwindow *window)
{
    if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
        glfwSetWindowShouldClose(window, true);

    if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS)
        main_camera.ProcessKeyboardInput(movement_direction::FORWARD, deltaTime);
    if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS)
        main_camera.ProcessKeyboardInput(movement_direction::BACKWARD, deltaTime);
    if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS)
        main_camera.ProcessKeyboardInput(movement_direction::LEFT, deltaTime);
    if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS)
        main_camera.ProcessKeyboardInput(movement_direction::RIGHT, deltaTime);
    if (glfwGetKey(window, GLFW_KEY_SPACE) == GLFW_PRESS)
        main_camera.ProcessKeyboardInput(movement_direction::UP, deltaTime);
    if (glfwGetKey(window, GLFW_KEY_LEFT_CONTROL) == GLFW_PRESS)
        main_camera.ProcessKeyboardInput(movement_direction::DOWN, deltaTime);
}

void mouse_callback(GLFWwindow* window, double xpos, double ypos)
{
    if (firstMouse)
    {
        lastX = (float)xpos;
        lastY = (float)ypos;
        firstMouse = false;
    }

    float offsetX = (float)xpos - lastX;
    float offsetY = lastY - (float)ypos;
    lastX = (float)xpos;
    lastY = (float)ypos;
    main_camera.ProcessMouseInput(offsetX, offsetY, true);
}

void scroll_callback(GLFWwindow* window, double offsetX, double offsetY)
{
    fov -= (float)offsetY;
    if (fov < 1.0f)
        fov = 1.0f;
    if (fov > 90.0f)
        fov = 90.0f;
}
</code>```

答: I finally fixed it! It was something to do with multiplication of offsetX and offsetY by m_MouseSensitivity. For some reason it wasn't initializing right and thus was assigned to 0. By multiplying by zero you get zero so Yaw and Pitch didn't change. Thank you for  the help <3

Body:
I have a problem. I'm working on a OpenGL project and I need to access a class variable by the class method. I got it done, but then changed some code and now it's not working and i cannot get it done. It's all about Yaw and Pitch variables. If i change them in their class method (e.g. ProccesMouseInput) they don't change their values, but I had already tried it in main function and then they do... Here's my code.

Camera.h

#pragma once
#include <glm/glm.hpp>
#include <glm/vec3.hpp>
#include <glm/gtc/matrix_transform.hpp>

enum class movement_direction{
    FORWARD,
    BACKWARD,
    LEFT,
    RIGHT,
    UP,
    DOWN
};

class Camera {
private:
    glm::vec3 m_Position;
    glm::vec3 m_Front;
    glm::vec3 m_Up;
    glm::vec3 m_Right;
    glm::vec3 m_WorldUp;
    float m_MouseSensitivity;
    float MovementSpeed = 2.5f;
    float MouseSensitivity = 0.1f;
    float FOV = 45.0f;
    float Yaw;
    float Pitch;

public:
    Camera(glm::vec3 pos, glm::vec3 up, float yaw, float pitch);
    Camera(float PosX, float PosY, float PosZ, float UpX, float UpY, float UpZ, float yaw, float pitch);
    void ProcessMouseInput(float offsetX, float offsetY, bool constrainPitch);
    void ProcessKeyboardInput(movement_direction direction, float deltaTime);
    void ProcessScrollInput(float offsetX, float offsetY);
    void UpdateCameraVectors();
    glm::mat4 GetViewMatrix();
};

Camera.cpp

#include "Camera.h"
#include <iostream>

Camera::Camera(glm::vec3 pos = glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3 up = glm::vec3(0.0f, 1.0f, 0.0f), float yaw = -90.0f, float pitch = 0.0f)
    : m_Position(pos), m_Up(up), m_WorldUp(up), Yaw(yaw), Pitch(pitch), m_MouseSensitivity(MouseSensitivity)
{

    UpdateCameraVectors();
}

Camera::Camera(float PosX, float PosY, float PosZ, float UpX, float UpY, float UpZ, float yaw, float pitch)
    : m_Position(glm::vec3(PosX, PosY, PosZ)), m_Up(glm::vec3(UpX, UpY, UpZ)), m_WorldUp(glm::vec3(UpX, UpY, UpZ)), Yaw(yaw), Pitch(pitch), m_MouseSensitivity(MouseSensitivity)
{

    UpdateCameraVectors();
}

void Camera::ProcessMouseInput(float offsetX, float offsetY, bool constrainPitch = true)
{
    Yaw += offsetX * m_MouseSensitivity;
    Pitch += offsetY * m_MouseSensitivity;
    if (constrainPitch)
    {
        if (Pitch < -89.0f)
            Pitch = -89.0f;
        if (Pitch > 89.0f)
            Pitch = 89.0f;
    }

    UpdateCameraVectors();

}

void Camera::ProcessKeyboardInput(movement_direction direction, float deltaTime)
{
    float velocity = MovementSpeed * deltaTime;

    if (direction == movement_direction::FORWARD)
        m_Position +=  m_Front * velocity;
    if (direction == movement_direction::BACKWARD)
        m_Position -= m_Front * velocity;
    if (direction == movement_direction::LEFT)
        m_Position -= m_Right * velocity;
    if (direction == movement_direction::RIGHT)
        m_Position += m_Right * velocity;
    if (direction == movement_direction::UP)
        m_Position += m_WorldUp * velocity;
    if (direction == movement_direction::DOWN)
        m_Position -= m_WorldUp * velocity;
}

void Camera::ProcessScrollInput(float offsetX, float offsetY)
{
}

void Camera::UpdateCameraVectors()
{
    glm::vec3 direction;

    direction.x = cos(glm::radians(Yaw)) * cos(glm::radians(Pitch));
    direction.y = sin(glm::radians(Pitch));
    direction.z = sin(glm::radians(Yaw)) * cos(glm::radians(Pitch));

    m_Front = glm::normalize(direction);
    m_Right = glm::normalize(glm::cross(m_Front, m_WorldUp));
    m_Up = glm::normalize(glm::cross(m_Right, m_Front));
}

glm::mat4 Camera::GetViewMatrix()
{
    return glm::lookAt(m_Position, m_Position + m_Front, m_Up);
}

Application.cpp

/* Including GLEW */
#include <GL/glew.h>

/* Including GLFW */
#include <GLFW/glfw3.h>

#define STB_IMAGE_IMPLEMENTATION
#include "vendor/stb_image/stb_image.h"

#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>

#include <iostream>
#include <string>
#include <conio.h>

#include "Shader.h"
#include "Camera.h"

void processInput(GLFWwindow* window);
void mouse_callback(GLFWwindow* window, double xpos, double ypos);
void scroll_callback(GLFWwindow* window, double offsetX, double offsetY);

const int SCR_WIDTH = 800;
const int SCR_HEIGHT = 600;

float deltaTime = 0.0f;
float currentFrame = 0.0f;
float lastFrame = 0.0f;

float lastX = SCR_WIDTH / 2;
float lastY = SCR_HEIGHT / 2;

bool firstMouse = true;

float fov = 45.0f;

Camera main_camera(glm::vec3(0.0f, 0.0f, -3.0f), glm::vec3(0.0f, 1.0f, 0.0f), -90.0f, 0.0f);

int main(void)
{

    GLFWwindow* window;

    /* Initializing the library */
    if (!glfwInit())
    {
        std::cout << "Failed to initialize GLFW.\n";
        return -1;
    }

    /* Creating a windowed mode window and its OpenGL context */

    window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "Hello World", NULL, NULL);

    if (!window)
    {
        std::cout << "Failed to open GLFW window.\n";
        glfwTerminate();
        return -1;
    }

    /* Making the window's context current */
    glfwMakeContextCurrent(window);
    if (glewInit() != GLEW_OK)
        std::cout << "Failed to initialize GLEW\n";

    glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
    glfwSetCursorPosCallback(window, mouse_callback);

    glfwSetScrollCallback(window, scroll_callback);

    /* Getting the version of GL */
    std::cout << "Using GL Version: " << glGetString(GL_VERSION) << std::endl;

    float vertices[] = {
        -0.5f, -0.5f, -0.5f,    0.0f, 0.0f, 0.0f,    0.0f, 0.0f,
         0.5f, -0.5f, -0.5f,    0.0f, 0.0f, 0.0f,    1.0f, 0.0f,
         0.5f,  0.5f, -0.5f,    0.0f, 0.0f, 0.0f,    1.0f, 1.0f,
         0.5f,  0.5f, -0.5f,    0.0f, 0.0f, 0.0f,    1.0f, 1.0f,
        -0.5f,  0.5f, -0.5f,    0.0f, 0.0f, 0.0f,    0.0f, 1.0f,
        -0.5f, -0.5f, -0.5f,    0.0f, 0.0f, 0.0f,    0.0f, 0.0f,

        -0.5f, -0.5f,  0.5f,    0.0f, 0.0f, 0.0f,    0.0f, 0.0f,
         0.5f, -0.5f,  0.5f,    0.0f, 0.0f, 0.0f,    1.0f, 0.0f,
         0.5f,  0.5f,  0.5f,    0.0f, 0.0f, 0.0f,    1.0f, 1.0f,
         0.5f,  0.5f,  0.5f,    0.0f, 0.0f, 0.0f,    1.0f, 1.0f,
        -0.5f,  0.5f,  0.5f,    0.0f, 0.0f, 0.0f,    0.0f, 1.0f,
        -0.5f, -0.5f,  0.5f,    0.0f, 0.0f, 0.0f,    0.0f, 0.0f,

        -0.5f,  0.5f,  0.5f,    0.0f, 0.0f, 0.0f,    1.0f, 0.0f,
        -0.5f,  0.5f, -0.5f,    0.0f, 0.0f, 0.0f,    1.0f, 1.0f,
        -0.5f, -0.5f, -0.5f,    0.0f, 0.0f, 0.0f,    0.0f, 1.0f,
        -0.5f, -0.5f, -0.5f,    0.0f, 0.0f, 0.0f,    0.0f, 1.0f,
        -0.5f, -0.5f,  0.5f,    0.0f, 0.0f, 0.0f,    0.0f, 0.0f,
        -0.5f,  0.5f,  0.5f,    0.0f, 0.0f, 0.0f,    1.0f, 0.0f,

         0.5f,  0.5f,  0.5f,    0.0f, 0.0f, 0.0f,    1.0f, 0.0f,
         0.5f,  0.5f, -0.5f,    0.0f, 0.0f, 0.0f,    1.0f, 1.0f,
         0.5f, -0.5f, -0.5f,    0.0f, 0.0f, 0.0f,    0.0f, 1.0f,
         0.5f, -0.5f, -0.5f,    0.0f, 0.0f, 0.0f,    0.0f, 1.0f,
         0.5f, -0.5f,  0.5f,    0.0f, 0.0f, 0.0f,    0.0f, 0.0f,
         0.5f,  0.5f,  0.5f,    0.0f, 0.0f, 0.0f,    1.0f, 0.0f,

        -0.5f, -0.5f, -0.5f,    0.0f, 0.0f, 0.0f,    0.0f, 1.0f,
         0.5f, -0.5f, -0.5f,    0.0f, 0.0f, 0.0f,    1.0f, 1.0f,
         0.5f, -0.5f,  0.5f,    0.0f, 0.0f, 0.0f,    1.0f, 0.0f,
         0.5f, -0.5f,  0.5f,    0.0f, 0.0f, 0.0f,    1.0f, 0.0f,
        -0.5f, -0.5f,  0.5f,    0.0f, 0.0f, 0.0f,    0.0f, 0.0f,
        -0.5f, -0.5f, -0.5f,    0.0f, 0.0f, 0.0f,    0.0f, 1.0f,

        -0.5f,  0.5f, -0.5f,    0.0f, 0.0f, 0.0f,    0.0f, 1.0f,
         0.5f,  0.5f, -0.5f,    0.0f, 0.0f, 0.0f,    1.0f, 1.0f,
         0.5f,  0.5f,  0.5f,    0.0f, 0.0f, 0.0f,    1.0f, 0.0f,
         0.5f,  0.5f,  0.5f,    0.0f, 0.0f, 0.0f,    1.0f, 0.0f,
        -0.5f,  0.5f,  0.5f,    0.0f, 0.0f, 0.0f,    0.0f, 0.0f,
        -0.5f,  0.5f, -0.5f,    0.0f, 0.0f, 0.0f,    0.0f, 1.0f
    };

    glm::vec3 cubes_positions[]{
        glm::vec3( 0.0f,  0.0f,  0.0f),
        glm::vec3( 2.0f,  5.0f, -15.0f),
        glm::vec3(-1.5f, -2.2f, -2.5f),
        glm::vec3(-3.8f, -2.0f, -12.3f),
        glm::vec3( 2.4f, -0.4f, -3.5f),
        glm::vec3(-1.7f,  3.0f, -7.5f),
        glm::vec3( 1.3f, -2.0f, -2.5f),
        glm::vec3( 1.5f,  2.0f, -2.5f),
        glm::vec3( 1.5f,  0.2f, -1.5f),
        glm::vec3(-1.3f,  1.0f, -1.5f)
    };

    /* VERTEX ARRAY */
    unsigned int VAO;
    glGenVertexArrays(1, &VAO);
    glBindVertexArray(VAO);

    /* VERTEX BUFFER */
    unsigned int VBO;
    glGenBuffers(1, &VBO);
    glBindBuffer(GL_ARRAY_BUFFER, VBO);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

    /* VERTEX LAYOUT */
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)0);
    glEnableVertexAttribArray(0);

    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(3 * sizeof(float)));
    glEnableVertexAttribArray(1);

    glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(6 * sizeof(float)));
    glEnableVertexAttribArray(2);

    /* LOADING TEXTURES */
    // --- first texture object ---
    unsigned int texture1;
    glGenTextures(1, &texture1);
    glBindTexture(GL_TEXTURE_2D, texture1);

    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);

    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);

    float borderColor1[]{
        0.1f, 0.1f, 0.0f, 1.0f
    };
    glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, borderColor1);

    int width, height, channelsNr;
    unsigned char* data = stbi_load("res/textures/container.jpg", &width, &height, &channelsNr, 0);
    if (data)
    {
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data);
        glGenerateMipmap(GL_TEXTURE_2D);
    }
    else
    {
        std::cout << "Failed to load texture\n";
    }
    stbi_image_free(data);

    // --- second texture object ---
    unsigned int texture2;
    glGenTextures(1, &texture2);
    glBindTexture(GL_TEXTURE_2D, texture2);

    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);

    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);

    float borderColor2[]{
        0.1f, 0.1f, 0.0f, 1.0f
    };
    glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, borderColor2);

    stbi_set_flip_vertically_on_load(true);
    data = stbi_load("res/textures/awesomeface.png", &width, &height, &channelsNr, 0);
    if (data)
    {
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);
    }
    else
    {
        std::cout << "Failed to load texture\n";
    }
    stbi_image_free(data);

    /* BINDING BEFORE THE DRAW CALL */
    // --- shader ---
    Shader basic("res/shaders/Basic.glsl");
    basic.Bind();
    basic.SetUniform1i("texture1", 0);
    basic.SetUniform1i("texture2", 1);
    glEnable(GL_DEPTH_TEST);
    // --- texture ---
    glBindTexture(GL_TEXTURE_2D, texture2);

    // --- vertex array object ---
    glBindVertexArray(VAO);

    float value = 0.5f;
    basic.SetUniform1f("mix_value", 0.2f);

    /* Loop until the user closes the window */
    while (!glfwWindowShouldClose(window))
    {
        currentFrame = (float)glfwGetTime();
        deltaTime = currentFrame - lastFrame;
        lastFrame = currentFrame;

        processInput(window);

        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        glClearColor(0.f, 0.2f, 0.2f, 1.f);
        /* Render here */

        glActiveTexture(GL_TEXTURE0);
        glBindTexture(GL_TEXTURE_2D, texture1);

        glActiveTexture(GL_TEXTURE1);
        glBindTexture(GL_TEXTURE_2D, texture2);

        glm::mat4 projection = glm::perspective(glm::radians(fov), (float)SCR_WIDTH / (float)SCR_HEIGHT, 0.1f, 100.0f);
        basic.SetUniformMatrix4fv("proj", 1, glm::value_ptr(projection));

        glm::mat4 view = main_camera.GetViewMatrix();
        basic.SetUniformMatrix4fv("view", 1, glm::value_ptr(view));

        for (int i = 0; i < (sizeof(cubes_positions) / sizeof(glm::vec3)); i++)
        {
            float angle = 20.0f * i;
            glm::mat4 model = glm::mat4(1.0f);
            model = glm::translate(model, cubes_positions[i]);
            model = glm::rotate(model, glm::radians(angle), glm::vec3(1.0f, 0.0f, 0.0f));
            basic.SetUniformMatrix4fv("model", 1, glm::value_ptr(model));

            glDrawArrays(GL_TRIANGLES, 0, 36);
        }

        /* Swap front and back buffers */
        glfwSwapBuffers(window);

        /* Poll for and process events */
        glfwPollEvents();

    }

    glfwTerminate();
    return 0;
}

void processInput(GLFWwindow *window)
{
    if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
        glfwSetWindowShouldClose(window, true);

    if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS)
        main_camera.ProcessKeyboardInput(movement_direction::FORWARD, deltaTime);
    if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS)
        main_camera.ProcessKeyboardInput(movement_direction::BACKWARD, deltaTime);
    if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS)
        main_camera.ProcessKeyboardInput(movement_direction::LEFT, deltaTime);
    if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS)
        main_camera.ProcessKeyboardInput(movement_direction::RIGHT, deltaTime);
    if (glfwGetKey(window, GLFW_KEY_SPACE) == GLFW_PRESS)
        main_camera.ProcessKeyboardInput(movement_direction::UP, deltaTime);
    if (glfwGetKey(window, GLFW_KEY_LEFT_CONTROL) == GLFW_PRESS)
        main_camera.ProcessKeyboardInput(movement_direction::DOWN, deltaTime);
}

void mouse_callback(GLFWwindow* window, double xpos, double ypos)
{
    if (firstMouse)
    {
        lastX = (float)xpos;
        lastY = (float)ypos;
        firstMouse = false;
    }

    float offsetX = (float)xpos - lastX;
    float offsetY = lastY - (float)ypos;
    lastX = (float)xpos;
    lastY = (float)ypos;
    main_camera.ProcessMouseInput(offsetX, offsetY, true);
}

void scroll_callback(GLFWwindow* window, double offsetX, double offsetY)
{
    fov -= (float)offsetY;
    if (fov < 1.0f)
        fov = 1.0f;
    if (fov > 90.0f)
        fov = 90.0f;
}


来源: stackexchange

问:
Best way to plot a 2D square lattice of atoms in Python?
Summary of the problem:
I'm working on a Physics problem and I want to plot a 2D lattice of atoms, where the nodes have been connected using arrows as shown here 2D lattice figure.

What I've tried:
I've tried using grid_2d_graph from NetworkX, taking help from this answer but wasn't able to get it to work as I wanted it to.  The code I used was as follows:

```<code>G = nx.grid_2d_graph(4,4)
pos = dict( (n, n) for n in G.nodes() )
nx.draw_networkx(G, pos=pos)
plt.axis('off')
plt.show()
</code>```

This produced the following image, which wasn't exactly what I had in mind.

答:
I was trying to use quiver plots when I came up on Jan's answer. I've modified his code to work with quiver plots

```<code>def plot_vector(p1,p2):
    p1 = np.array(p1)
    p2 = np.array(p2)
    dp = p2-p1
    plt.quiver(p1[0], p1[1], dp[0], dp[1],angles='xy', scale_units='xy', scale=1, headwidth = 5, headlength = 7)

grid = {  # point(x, y), outgoing connections [points]
    (0, 0): [(0, 1), (1, 0)],
    (0, 1): [],
    (1, 0): [],
    (1, 1): [(1, 0), (0, 1)]
}

fig, ax = plt.subplots()
for point, connections in grid.items():
    for outgoing in connections:
        plot_vector(point,outgoing)
    plt.plot(*point,
            marker="o", markersize=10, markeredgecolor="k",
            markerfacecolor="red",
            zorder=1)
plt.show()
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Summary of the problem:
I'm working on a Physics problem and I want to plot a 2D lattice of atoms, where the nodes have been connected using arrows as shown here 2D lattice figure.

What I've tried:
I've tried using grid_2d_graph from NetworkX, taking help from this answer but wasn't able to get it to work as I wanted it to.  The code I used was as follows:

G = nx.grid_2d_graph(4,4)
pos = dict( (n, n) for n in G.nodes() )
nx.draw_networkx(G, pos=pos)
plt.axis('off')
plt.show()

This produced the following image, which wasn't exactly what I had in mind.

Body:
I was trying to use quiver plots when I came up on Jan's answer. I've modified his code to work with quiver plots

def plot_vector(p1,p2):
    p1 = np.array(p1)
    p2 = np.array(p2)
    dp = p2-p1
    plt.quiver(p1[0], p1[1], dp[0], dp[1],angles='xy', scale_units='xy', scale=1, headwidth = 5, headlength = 7)

grid = {  # point(x, y), outgoing connections [points]
    (0, 0): [(0, 1), (1, 0)],
    (0, 1): [],
    (1, 0): [],
    (1, 1): [(1, 0), (0, 1)]
}

fig, ax = plt.subplots()
for point, connections in grid.items():
    for outgoing in connections:
        plot_vector(point,outgoing)
    plt.plot(*point,
            marker="o", markersize=10, markeredgecolor="k",
            markerfacecolor="red",
            zorder=1)
plt.show()


问:
Spring Boot Rest API Returns Empty JSON Used with Lombok
I have Spring Boot Application with Web, JPA, H2, Web, Lombok dependency.
I have entities as follows

```<code>@NoArgsConstructor
@AllArgsConstructor
@Data
@Entity
@Getter
public class Book {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false)
    private String name;

    @Column(nullable = false)
    private Integer pageCount;

    @ManyToOne
    @JoinColumn(name = "author_id")
    private Author author;

}
</code>```

```<code>@NoArgsConstructor
@AllArgsConstructor
@Data
@Entity
@Getter
public class Author {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false)
    private String firstName;

    @Column
    private String lastName;

}
</code>```

I am getting following JSON in repose for the /books REST endpoint

```<code>[
    {},
    {}
]
</code>```

If I add getters and setters to entity it works fine. How can I get the actual values in response without adding getters setters as I am using @Data annotation

答:
First of all , In spring it is not a good approach to return the entity object directly from  a controller to be converted to json. Use the DTO approach so that you will always have a DTO object returned from the controller endpoint. This way you will have more control over the type and structure of data you want to retun from the endpoint.

Read here about the advantages of using a DTO .

Secondly, verify that your tables follow the basic spring jpa naming conventions or is same as the entity class names if not please add the @Table(name="") annotation to specify the table name. Check that data is being populated to your entity classes.

Remove the @Data annotation.

@Data should not be used on JPA Entities as Entity toString, equals, and hashCode methods need to be authored in a very specific manner. See here for details.

Body:
I have Spring Boot Application with Web, JPA, H2, Web, Lombok dependency.
I have entities as follows

@NoArgsConstructor
@AllArgsConstructor
@Data
@Entity
@Getter
public class Book {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false)
    private String name;

    @Column(nullable = false)
    private Integer pageCount;

    @ManyToOne
    @JoinColumn(name = "author_id")
    private Author author;

}

@NoArgsConstructor
@AllArgsConstructor
@Data
@Entity
@Getter
public class Author {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false)
    private String firstName;

    @Column
    private String lastName;

}

I am getting following JSON in repose for the /books REST endpoint

[
    {},
    {}
]

If I add getters and setters to entity it works fine. How can I get the actual values in response without adding getters setters as I am using @Data annotation


问:
AWS Elastic Beanstalk Django Migration
I have an EC2 instance set up through Beanstalk, but I cannot get the config to run migration

my .ebextension/django.config

```<code>option_settings:
  aws:elasticbeanstalk:application:environment:
    DJANGO_SETTINGS_MODULE: my_app.settings
  aws:elasticbeanstalk:container:python:
    WSGIPath: my_app.wsgi:application
    NumProcesses: 3
    NumThreads: 20
container_commands:
  00_test_output:
    command: "echo 'testing.....'"
  01_migrate:
    command: "python manage.py migrate"
    leader_only: true
</code>```

After checking the logs, it says

```<code>Invalid HTTP_HOST header: '52.37.179.147'. You may need to add '52.37.179.147' to ALLOWED_HOSTS.
Invalid HTTP_HOST header: '172.31.0.249'. You may need to add '172.31.0.249' to ALLOWED_HOSTS.
</code>```

Now even if I add these ip's to ALLOWED_HOSTS in my settings.py, the problem remains. I searched around here and found no answer to this specific issue

Without the migration commands, my server is built successfully and is running.

Anyone know why?

EDIT:

to add more info:

When I run eb deploy after committing to my github, i got error as following

```<code>2020-06-03 03:45:10    ERROR   [Instance: i-05f872f7e96ccd26d] Command failed on instance. An unexpected error has occurred [ErrorCode: 0000000001].
2020-06-03 03:45:11    INFO    Command execution completed on all instances. Summary: [Successful: 0, Failed: 1].
2020-06-03 03:45:11    ERROR   Unsuccessful command execution on instance id(s) 'i-05f872f7e96ccd26d'. Aborting the operation.
2020-06-03 03:45:11    ERROR   Failed to deploy application.
</code>```

Then I go into web.stdout.log to find those allowed_host errors. Then again, from another post, it doesn't seem like adding these ip's help since they are AWS ip's

I can't locate other error logs from cloudwatch. This seems like the only suspect

The eb-engine.log only says

```<code>Error occurred during build: Command 01_migrate failed
</code>```

so I knoe the echo worked.....

答:
If you are using MySQL, you have to do the below steps:

Add mysqlclient to your requirements.txt.

Add some packages to be installed in your EC2 instance with a config file:

```<code>packages:
  yum:
    python3-devel: []
    mariadb-devel: []
</code>```

Check my recent question and answer for more details:
mysqlclient installation error in AWS Elastic Beanstalk

Title: AWS Elastic Beanstalk Django Migration

Body:
I have an EC2 instance set up through Beanstalk, but I cannot get the config to run migration

my .ebextension/django.config

option_settings:
  aws:elasticbeanstalk:application:environment:
    DJANGO_SETTINGS_MODULE: my_app.settings
  aws:elasticbeanstalk:container:python:
    WSGIPath: my_app.wsgi:application
    NumProcesses: 3
    NumThreads: 20
container_commands:
  00_test_output:
    command: "echo 'testing.....'"
  01_migrate:
    command: "python manage.py migrate"
    leader_only: true

After checking the logs, it says

Invalid HTTP_HOST header: '52.37.179.147'. You may need to add '52.37.179.147' to ALLOWED_HOSTS.
Invalid HTTP_HOST header: '172.31.0.249'. You may need to add '172.31.0.249' to ALLOWED_HOSTS.

Now even if I add these ip's to ALLOWED_HOSTS in my settings.py, the problem remains. I searched around here and found no answer to this specific issue

Without the migration commands, my server is built successfully and is running.

Anyone know why?

EDIT:

to add more info:

When I run eb deploy after committing to my github, i got error as following

2020-06-03 03:45:10    ERROR   [Instance: i-05f872f7e96ccd26d] Command failed on instance. An unexpected error has occurred [ErrorCode: 0000000001].
2020-06-03 03:45:11    INFO    Command execution completed on all instances. Summary: [Successful: 0, Failed: 1].
2020-06-03 03:45:11    ERROR   Unsuccessful command execution on instance id(s) 'i-05f872f7e96ccd26d'. Aborting the operation.
2020-06-03 03:45:11    ERROR   Failed to deploy application.

Then I go into web.stdout.log to find those allowed_host errors. Then again, from another post, it doesn't seem like adding these ip's help since they are AWS ip's

I can't locate other error logs from cloudwatch. This seems like the only suspect

The eb-engine.log only says

Error occurred during build: Command 01_migrate failed

so I knoe the echo worked.....

Body:
If you are using MySQL, you have to do the below steps:

Add mysqlclient to your requirements.txt.

Add some packages to be installed in your EC2 instance with a config file:

packages:
  yum:
    python3-devel: []
    mariadb-devel: []

Check my recent question and answer for more details:
mysqlclient installation error in AWS Elastic Beanstalk


问:
How can I run a dotnet application in the background using sudo on Linux?
I am experiencing some weird problems that I'm not sure how to solve. I am using CodeDeploy to deploy my applications to an AWS EC2 instance, and in there I need to specify a script to execute the processes on my instances, one of which is a .NET Core application.

I am publishing my application using dotnet publish on Windows, and copying the required dlls to the EC2 Linux instance.

I can run the application fine using and this behaves as expected

```<code>sudo dotnet application.dll
</code>```

However this is simply until I terminate the application and is not in the background.

The problem is happening when I am trying to run my application in the background, so that I can continue running other applications or perform other tasks.

I usually use screen or nohup to run applications in the background however it doesn't seem to work for this application. Screen doesn't work in the script, and nohup runs the application, but throws an error

To run using nohup I am using sudo nohup dotnet application.dll & and I receive the error in the log

```<code>Unhandled Exception: System.UnauthorizedAccessException: Access to the path is denied. ---> System.IO.IOException: Bad file descriptor
   --- End of inner exception stack trace ---
   at Interop.ThrowExceptionForIoErrno(ErrorInfo errorInfo, String path, Boolean isDirectory, Func`2 errorRewriter)
   at Interop.CheckIo(Int64 result, String path, Boolean isDirectory, Func`2 errorRewriter)
   at System.ConsolePal.Read(SafeFileHandle fd, Byte[] buffer, Int32 offset, Int32 count)
   at System.ConsolePal.UnixConsoleStream.Read(Byte[] buffer, Int32 offset, Int32 count)
   at System.IO.StreamReader.ReadBuffer()
   at System.IO.StreamReader.ReadLine()
   at System.IO.SyncTextReader.ReadLine()
   at System.Console.ReadLine()
   at Application.Program.Main(String[] args) in F:\Applications\Server\Program.cs:line 38
</code>```

Now I can see why this is thrown, as the path in the error is the path to my project on Windows, but why is this happening only using nohup? This works fine if I run it in the foreground and does not throw the error.

How can I run this application in the background without using screen?

EDIT

My initial thought was that is was some compatibility issue as it was built on Windows, however this is not the case. I have moved the project over to the Linux instance and re-published it there, and I am still receiving the same error when running sudo nohup dotnet application.dll &

```<code> Unhandled Exception: System.UnauthorizedAccessException: Access to the path is denied. ---> System.IO.IOException: Bad file descriptor
   --- End of inner exception stack trace ---
   at Interop.ThrowExceptionForIoErrno(ErrorInfo errorInfo, String path, Boolean isDirectory, Func`2 errorRewriter)
   at Interop.CheckIo(Int64 result, String path, Boolean isDirectory, Func`2 errorRewriter)
   at System.ConsolePal.Read(SafeFileHandle fd, Byte[] buffer, Int32 offset, Int32 count)
   at System.ConsolePal.UnixConsoleStream.Read(Byte[] buffer, Int32 offset, Int32 count)
   at System.IO.StreamReader.ReadBuffer()
   at System.IO.StreamReader.ReadLine()
   at System.IO.SyncTextReader.ReadLine()
   at System.Console.ReadLine()
   at Application.Program.Main(String[] args) in /opt/servers/Server/Program.cs:line 38
</code>```

I have just tried

sudo dotnet application.dll > out.log 2>&1 &

which seems to run the program without error, however whenever another command is performed, the background application is sent into a STOPPED state and does not continue to run.

[1]+  Stopped                 sudo dotnet application.dll > out.log 2>&1

```<code>ubuntu@:/opt/servers/Server$ sudo dotnet application.dll > out.log  2>&1 &
[1] 2448
ubuntu@:/opt/servers/Server$ netstat -tulpn
(Not all processes could be identified, non-owned process info
 will not be shown, you would have to be root to see it all.)
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      -
tcp6       0      0 :::22                   :::*                    LISTEN      -
udp   214656      0 0.0.0.0:1000            0.0.0.0:*                           -
udp        0      0 0.0.0.0:68              0.0.0.0:*                           -
udp        0      0 0.0.0.0:68              0.0.0.0:*                           -

[1]+  Stopped                 sudo dotnet application.dll > out.log 2>&1
</code>```

Next step would be to look into using screen in detached mode.

screen -d -m bash -c 'cd /opt/server && sudo dotnet application.dll &'

This command currently doesn't spawn a screen window...

EDIT

I had to remove the & at the end and now it works as expected.

screen -d -m -S SERVER bash -c 'cd /opt/server && sudo dotnet application.dll'

答:
The previous solution did not work for me where message listener would not pick up message, so I replaced Console.ReadLine() with Thread.Sleep(Timeout.Infinite) in the last line of my main program. That solved the nohup issue, logging issue, and running in background..
I don't recall I have to do these things in Java to hold up Tibco or Rabbit message listener.

ContentLicense: CC BY-SA 3.0

Body:
I am experiencing some weird problems that I'm not sure how to solve. I am using CodeDeploy to deploy my applications to an AWS EC2 instance, and in there I need to specify a script to execute the processes on my instances, one of which is a .NET Core application.

I am publishing my application using dotnet publish on Windows, and copying the required dlls to the EC2 Linux instance.

I can run the application fine using and this behaves as expected

sudo dotnet application.dll

However this is simply until I terminate the application and is not in the background.

The problem is happening when I am trying to run my application in the background, so that I can continue running other applications or perform other tasks.

I usually use screen or nohup to run applications in the background however it doesn't seem to work for this application. Screen doesn't work in the script, and nohup runs the application, but throws an error

To run using nohup I am using sudo nohup dotnet application.dll & and I receive the error in the log

Unhandled Exception: System.UnauthorizedAccessException: Access to the path is denied. ---> System.IO.IOException: Bad file descriptor
   --- End of inner exception stack trace ---
   at Interop.ThrowExceptionForIoErrno(ErrorInfo errorInfo, String path, Boolean isDirectory, Func`2 errorRewriter)
   at Interop.CheckIo(Int64 result, String path, Boolean isDirectory, Func`2 errorRewriter)
   at System.ConsolePal.Read(SafeFileHandle fd, Byte[] buffer, Int32 offset, Int32 count)
   at System.ConsolePal.UnixConsoleStream.Read(Byte[] buffer, Int32 offset, Int32 count)
   at System.IO.StreamReader.ReadBuffer()
   at System.IO.StreamReader.ReadLine()
   at System.IO.SyncTextReader.ReadLine()
   at System.Console.ReadLine()
   at Application.Program.Main(String[] args) in F:\Applications\Server\Program.cs:line 38

Now I can see why this is thrown, as the path in the error is the path to my project on Windows, but why is this happening only using nohup? This works fine if I run it in the foreground and does not throw the error.

How can I run this application in the background without using screen?

EDIT

My initial thought was that is was some compatibility issue as it was built on Windows, however this is not the case. I have moved the project over to the Linux instance and re-published it there, and I am still receiving the same error when running sudo nohup dotnet application.dll &

 Unhandled Exception: System.UnauthorizedAccessException: Access to the path is denied. ---> System.IO.IOException: Bad file descriptor
   --- End of inner exception stack trace ---
   at Interop.ThrowExceptionForIoErrno(ErrorInfo errorInfo, String path, Boolean isDirectory, Func`2 errorRewriter)
   at Interop.CheckIo(Int64 result, String path, Boolean isDirectory, Func`2 errorRewriter)
   at System.ConsolePal.Read(SafeFileHandle fd, Byte[] buffer, Int32 offset, Int32 count)
   at System.ConsolePal.UnixConsoleStream.Read(Byte[] buffer, Int32 offset, Int32 count)
   at System.IO.StreamReader.ReadBuffer()
   at System.IO.StreamReader.ReadLine()
   at System.IO.SyncTextReader.ReadLine()
   at System.Console.ReadLine()
   at Application.Program.Main(String[] args) in /opt/servers/Server/Program.cs:line 38

I have just tried

sudo dotnet application.dll > out.log 2>&1 &

which seems to run the program without error, however whenever another command is performed, the background application is sent into a STOPPED state and does not continue to run.

[1]+  Stopped                 sudo dotnet application.dll > out.log 2>&1

ubuntu@:/opt/servers/Server$ sudo dotnet application.dll > out.log  2>&1 &
[1] 2448
ubuntu@:/opt/servers/Server$ netstat -tulpn
(Not all processes could be identified, non-owned process info
 will not be shown, you would have to be root to see it all.)
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      -
tcp6       0      0 :::22                   :::*                    LISTEN      -
udp   214656      0 0.0.0.0:1000            0.0.0.0:*                           -
udp        0      0 0.0.0.0:68              0.0.0.0:*                           -
udp        0      0 0.0.0.0:68              0.0.0.0:*                           -

[1]+  Stopped                 sudo dotnet application.dll > out.log 2>&1

Next step would be to look into using screen in detached mode.

screen -d -m bash -c 'cd /opt/server && sudo dotnet application.dll &'

This command currently doesn't spawn a screen window...

EDIT

I had to remove the & at the end and now it works as expected.

screen -d -m -S SERVER bash -c 'cd /opt/server && sudo dotnet application.dll'


问:
Image Submit buttons in Codeigniter - what am i missing?
I've got the following Codeigniter code to display a form, with two image submit buttons. I need to know which button has been clicked by the user.  Normally I just reference the name or value that is passed through, but nothing is passed from these buttons.  All other fields/textboxes etc.. on the form pass through ok, but nothing from these buttons....

.... what am i missing? I've been pondering this for a couple of hours and no help from the net either!

Ta

```<code><?
            $attributes = array('id' => 'formname','name' => 'formname');
            echo form_open('processform',$attributes);
            $btn_input = array(
                'subtype'   => ''
            );
            echo form_hidden($btn_input);

            $btn_search = array(
                'type'  => 'image',
                'src'       => '/graphics/button1.gif',
                'id'        => 'button1',
                'name'  => 'button1',
                'value' => 'button1'
            );
            ?>
            <div id='1stbutton' style='text-align: center'>
                <? echo form_input($btn_search);?>
            </div>

            <?
            $btn_search = array(
                'type'  => 'image',
                'src'       => '/graphics/button2.gif',
                'id'        => 'button2',
                'name'  => 'button2',
                'value' => 'button2'
            );
            ?>
            <div id='2ndbutton' style='text-align: center'>
                <? echo form_input($btn_search);?>
            </div>

            <? echo form_close(); ?>
</code>```

答:
I had a similar issue (with Zend though)!
The thing is, the browser does not pass the “value” when input type=image.
to check wich button was clicked you could still reference the button by adding "_x" or "_y" to your button name (Ex 'Button2_x')and check the $_Post array against this.

```<code>if(isset($_POST['button2_x']))
{
  //button2 was clicked!
}
else if(isset($_POST['button1_x']))
{
  //button1 was clicked go on!
}
</code>```

If you need a look here.Same Issue Explained in Codeigniter forum

Body:
I've got the following Codeigniter code to display a form, with two image submit buttons. I need to know which button has been clicked by the user.  Normally I just reference the name or value that is passed through, but nothing is passed from these buttons.  All other fields/textboxes etc.. on the form pass through ok, but nothing from these buttons....

.... what am i missing? I've been pondering this for a couple of hours and no help from the net either!

Ta

<?
            $attributes = array('id' => 'formname','name' => 'formname');
            echo form_open('processform',$attributes);
            $btn_input = array(
                'subtype'   => ''
            );
            echo form_hidden($btn_input);

            $btn_search = array(
                'type'  => 'image',
                'src'       => '/graphics/button1.gif',
                'id'        => 'button1',
                'name'  => 'button1',
                'value' => 'button1'
            );
            ?>

                <? echo form_input($btn_search);?>

            <?
            $btn_search = array(
                'type'  => 'image',
                'src'       => '/graphics/button2.gif',
                'id'        => 'button2',
                'name'  => 'button2',
                'value' => 'button2'
            );
            ?>

                <? echo form_input($btn_search);?>

            <? echo form_close(); ?>

Body:
I had a similar issue (with Zend though)!
The thing is, the browser does not pass the “value” when input type=image.
to check wich button was clicked you could still reference the button by adding "_x" or "_y" to your button name (Ex 'Button2_x')and check the $_Post array against this.

if(isset($_POST['button2_x']))
{
  //button2 was clicked!
}
else if(isset($_POST['button1_x']))
{
  //button1 was clicked go on!
}

If you need a look here.Same Issue Explained in Codeigniter forum


问:
Last row of column using the column number
This should be really easy, but I can't see it.

I've several columns, one for each team (over the range shL.Range(S2:AA2)). Below each team is a series of values which should be available in a Userform Listbox, depending on the team which has been selected.

I've got a code which reports the Column number of the team, and I'm trying to find the last row number based on that column. This is causing a Run-Time error 1004 (Method 'Range' of object '_Worksheet' failed), which I expect is caused by shL.Range(Cells( but I'm not seeing how to fix it.

Is there a better way to find the last row of the column?

```<code>Dim y As Long, c As Long
Dim shE As Worksheet, shL As Worksheet, FoundTeam As Range
Set shE = Sheets("EnteredData")
Set shL = Sheets("Lookups")

Set FoundTeam = shL.Range("S2:AA2").Find(what:=shE.Range("D3"))
    c = FoundTeam.Column
    y = shL.Range(Cells(3, c) & Rows.Count).End(xlUp).Row
</code>```

I appreciate any help with this issue. Thanks

答:
Not sure what you are trying to do with the concatenation, but try:</p>

```<code>y = shL.Cells(shL.Rows.Count, c).End(xlUp).Row
</code>```

Body:
This should be really easy, but I can't see it.

I've several columns, one for each team (over the range shL.Range(S2:AA2)). Below each team is a series of values which should be available in a Userform Listbox, depending on the team which has been selected.

I've got a code which reports the Column number of the team, and I'm trying to find the last row number based on that column. This is causing a Run-Time error 1004 (Method 'Range' of object '_Worksheet' failed), which I expect is caused by shL.Range(Cells( but I'm not seeing how to fix it.

Is there a better way to find the last row of the column?

Dim y As Long, c As Long
Dim shE As Worksheet, shL As Worksheet, FoundTeam As Range
Set shE = Sheets("EnteredData")
Set shL = Sheets("Lookups")

Set FoundTeam = shL.Range("S2:AA2").Find(what:=shE.Range("D3"))
    c = FoundTeam.Column
    y = shL.Range(Cells(3, c) & Rows.Count).End(xlUp).Row

I appreciate any help with this issue. Thanks

Body:
Not sure what you are trying to do with the concatenation, but try:

y = shL.Cells(shL.Rows.Count, c).End(xlUp).Row


问:
Why I can not test python datetime moudle
I will test python3.7 datetime.date.today method,and got a variable value,but even I comment the today method,It still work.

python 3.7 python is :

I find the datetime path first

```<code>>>> import datetime
>>> datetime.__file__
'/usr/local/python3.7/lib/python3.7/datetime.py'
</code>```

I do this:

```<code>>>> datetime.date.today()
datetime.date(2020, 6, 3)
</code>```

date is not inherit from any class,

```<code> 773 class date:
 774     """Concrete date type.
</code>```

I comment the today method code in date class

```<code> 833  #   @classmethod
 834  #   def today(cls):
 835  #       "Construct a date from time.time()."
 836  #       t = _time.time()
 837  #       return cls.fromtimestamp(t)
</code>```

I reload the datetime and execute the script,It still have a result

```<code>>>> import datetime
>>> datetime.date.today()
datetime.date(2020, 6, 3)
</code>```

who can tell me why ?

6.When I reconnect the SecureCRT,The comment code is effect.

thanks

答:
You already imported datetime module, try to re-import with importlib.reload:

from importlib import reload

reload(datetime)
```

Body:
I will test python3.7 datetime.date.today method,and got a variable value,but even I comment the today method,It still work.

python 3.7 python is :

I find the datetime path first

>>> import datetime
>>> datetime.__file__
'/usr/local/python3.7/lib/python3.7/datetime.py'

I do this:

>>> datetime.date.today()
datetime.date(2020, 6, 3)

date is not inherit from any class,

 773 class date:
 774     """Concrete date type.

I comment the today method code in date class

 833  #   @classmethod
 834  #   def today(cls):
 835  #       "Construct a date from time.time()."
 836  #       t = _time.time()
 837  #       return cls.fromtimestamp(t)

I reload the datetime and execute the script,It still have a result

>>> import datetime
>>> datetime.date.today()
datetime.date(2020, 6, 3)

who can tell me why ?

6.When I reconnect the SecureCRT,The comment code is effect.

thanks


问:
How to group the objects in an array so that they are not the same objects according to certain conditions in Node.js?
I have an object array. I will create groups according to certain conditions and then set in node-cache.

My conditions are:

First group will be: <=300, Second group will be: <= 600,Last group will be : <= 900.

when grouping, even if a data satisfies all conditions, it will only be in the first group.

For Example:

```<code>array :[{no:1,price:500},{No:2,price:400},{No:3,price:300},{No:4,price:200},{No:5,price:600},{No:6,price:700},{No:7,price:800},{No:8,price:900}]
</code>```

Result:

```<code>firsGroup :[{No:3,price:300},{No:4,price:200}];
secondGroup :[{no:1,price:500},{No:2,price:400},{No:5,price:600]
lastGroup :[{No:6,price:700},{No:7,price:800},{No:8,price:900}]
</code>```

Note : We will not remove item in array when we groupping.

答:
You can use a formula to get the right array from a given price:

let array = [{no:1,price:500},{no:2,price:400},{no:3,price:300},{no:4,price:200},{no:5,price:600},{no:6,price:700},{no:7,price:800},{no:8,price:900}];

let result = [[], [], []];
for (let obj of array) {
    let cat = Math.floor((obj.price - 1) / 300);
    result[cat].push(obj);
}

console.log(result);```
</div>
</div>
</p>

<p>If the formula <code>(price - 1) / 300</code> would not be appropriate, you can just use a ternary expression to evaluate to the right index value:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let array = [{no:1,price:500},{no:2,price:400},{no:3,price:300},{no:4,price:200},{no:5,price:600},{no:6,price:700},{no:7,price:800},{no:8,price:900}];

let result = [[], [], []];
for (let obj of array) {
    let cat = obj.price <= 300 ? 0
            : obj.price <= 600 ? 1
            : 2
    result[cat].push(obj);
}

console.log(result);</code>```

Body:
I have an object array. I will create groups according to certain conditions and then set in node-cache.

My conditions are:

First group will be: <=300, Second group will be: <= 600,Last group will be : <= 900.

when grouping, even if a data satisfies all conditions, it will only be in the first group.

For Example:

array :[{no:1,price:500},{No:2,price:400},{No:3,price:300},{No:4,price:200},{No:5,price:600},{No:6,price:700},{No:7,price:800},{No:8,price:900}]

Result:

firsGroup :[{No:3,price:300},{No:4,price:200}];
secondGroup :[{no:1,price:500},{No:2,price:400},{No:5,price:600]
lastGroup :[{No:6,price:700},{No:7,price:800},{No:8,price:900}]

Note : We will not remove item in array when we groupping.

Body:
You can use a formula to get the right array from a given price:

let array = [{no:1,price:500},{no:2,price:400},{no:3,price:300},{no:4,price:200},{no:5,price:600},{no:6,price:700},{no:7,price:800},{no:8,price:900}];

let result = [[], [], []];
for (let obj of array) {
    let cat = Math.floor((obj.price - 1) / 300);
    result[cat].push(obj);
}

console.log(result);

If the formula (price - 1) / 300 would not be appropriate, you can just use a ternary expression to evaluate to the right index value:

let array = [{no:1,price:500},{no:2,price:400},{no:3,price:300},{no:4,price:200},{no:5,price:600},{no:6,price:700},{no:7,price:800},{no:8,price:900}];

let result = [[], [], []];
for (let obj of array) {
    let cat = obj.price <= 300 ? 0
            : obj.price <= 600 ? 1
            : 2
    result[cat].push(obj);
}

console.log(result);


问:
Keras internal weights memory - why multiple fits() with one epoch still sees improvement
I am writing a keras lstm model in python. If I have the below fit() code

```<code>for i in range(0, epochs):
    model.fit(X_train, y_train, epochs=1, batch_size=32, validation_data=[X_test, y_test], shuffle=True)
</code>```

I would expect that each epoch is independent of the previous, i.e. there is no visible improvement with each consecutive epoch. However, this is not the case. The above code works exactly the same as writing:

```<code>model.fit(X_train, y_train, epochs=epochs, batch_size=32, validation_data=[X_test, y_test], shuffle=True)
</code>```

I know that keras has a model.reset_states() function but I don't believe that resetting the states, resets the weights, and starts a new epoch independently in the first code block. So how is keras saving weights and other data between independent fit() functions and how can I reset it?

答:
as @Yoskutik points out, fit only updates the weights.

To reset the weights after each epoch you could do something like this:

```<code>import numpy as np
import tensorflow as tf # (TensorFlow version 2.2)

# build dummy model
inputs = tf.keras.layers.Input((1,))
output = tf.keras.layers.Dense(1, kernel_initializer='zeros')(inputs)
model = tf.keras.models.Model(inputs=inputs, outputs=output)
model.compile(loss='mse', optimizer='sgd')

# dummy data
X = np.arange(10)
y = np.arange(10, 20)

initial_weights = model.get_weights() # get the initial weights (in this case zeros)
for _ in range(5):
    model.fit(X, y, epochs=1, verbose=0)
    print('weights after one epoch of training =')
    print('kernel:0 = {}'.format(np.squeeze(model.trainable_variables[0].numpy())))
    print('bias:0 = {}\n'.format(np.squeeze(model.trainable_variables[1].numpy())))
    model.set_weights(initial_weights) # set initial_weights after epoch is done

>> output:
weights after one epoch of training =
kernel:0 = 1.46999990940094
bias:0 = 0.28999999165534973

weights after one epoch of training =
kernel:0 = 1.46999990940094
bias:0 = 0.28999999165534973

weights after one epoch of training =
kernel:0 = 1.46999990940094
bias:0 = 0.28999999165534973

weights after one epoch of training =
kernel:0 = 1.46999990940094
bias:0 = 0.28999999165534973

weights after one epoch of training =
kernel:0 = 1.46999990940094
bias:0 = 0.2900000214576721
</code>```

Hope it helps!

Body:
I am writing a keras lstm model in python. If I have the below fit() code

for i in range(0, epochs):
    model.fit(X_train, y_train, epochs=1, batch_size=32, validation_data=[X_test, y_test], shuffle=True)

I would expect that each epoch is independent of the previous, i.e. there is no visible improvement with each consecutive epoch. However, this is not the case. The above code works exactly the same as writing:

model.fit(X_train, y_train, epochs=epochs, batch_size=32, validation_data=[X_test, y_test], shuffle=True)

I know that keras has a model.reset_states() function but I don't believe that resetting the states, resets the weights, and starts a new epoch independently in the first code block. So how is keras saving weights and other data between independent fit() functions and how can I reset it?

Body:
as @Yoskutik points out, fit only updates the weights.

To reset the weights after each epoch you could do something like this:

import numpy as np
import tensorflow as tf # (TensorFlow version 2.2)

# build dummy model
inputs = tf.keras.layers.Input((1,))
output = tf.keras.layers.Dense(1, kernel_initializer='zeros')(inputs)
model = tf.keras.models.Model(inputs=inputs, outputs=output)
model.compile(loss='mse', optimizer='sgd')

# dummy data
X = np.arange(10)
y = np.arange(10, 20)

initial_weights = model.get_weights() # get the initial weights (in this case zeros)
for _ in range(5):
    model.fit(X, y, epochs=1, verbose=0)
    print('weights after one epoch of training =')
    print('kernel:0 = {}'.format(np.squeeze(model.trainable_variables[0].numpy())))
    print('bias:0 = {}\n'.format(np.squeeze(model.trainable_variables[1].numpy())))
    model.set_weights(initial_weights) # set initial_weights after epoch is done

>> output:
weights after one epoch of training =
kernel:0 = 1.46999990940094
bias:0 = 0.28999999165534973

weights after one epoch of training =
kernel:0 = 1.46999990940094
bias:0 = 0.28999999165534973

weights after one epoch of training =
kernel:0 = 1.46999990940094
bias:0 = 0.28999999165534973

weights after one epoch of training =
kernel:0 = 1.46999990940094
bias:0 = 0.28999999165534973

weights after one epoch of training =
kernel:0 = 1.46999990940094
bias:0 = 0.2900000214576721

Hope it helps!


问:
Execute code after 2 seconds in pure Kotlin
I need to execute some code after two seconds of waiting (without blocking the UI thread). The problem is that this is usually resolved with Timer or Handler but my app is using Kotlin Multiplatform, so I need it to be just pure Kotlin, not any Java library.

I would also need to be able to cancel the timer if I want to.

I have seen this answer asking more or less the same but they solve it using:

```<code>runBlocking {
    println("Wait for 5sec")
    delay(5000)
    println("Done waiting for 5sec")
}
</code>```

But I don't really know how to cancel it and also if this is blocking the rest of the app.

答:
You could get a Job reference when launching coroutine. You could do something like this:

```<code>    val job = coroutineScope.launch {
        delay(1000)
        doYourStuff()
    }
</code>```

After thay you can use job.cancel(), or what ever you need. Also, you can define coroutine scope like this.

```<code>CoroutineScope(Dispatchers.Main)
</code>```

Or any other dispatcher that suits your needs.
Good luck.

Body:
I need to execute some code after two seconds of waiting (without blocking the UI thread). The problem is that this is usually resolved with Timer or Handler but my app is using Kotlin Multiplatform, so I need it to be just pure Kotlin, not any Java library.

I would also need to be able to cancel the timer if I want to.

I have seen this answer asking more or less the same but they solve it using:

runBlocking {
    println("Wait for 5sec")
    delay(5000)
    println("Done waiting for 5sec")
}

But I don't really know how to cancel it and also if this is blocking the rest of the app.

Body:
You could get a Job reference when launching coroutine. You could do something like this:

    val job = coroutineScope.launch {
        delay(1000)
        doYourStuff()
    }

After thay you can use job.cancel(), or what ever you need. Also, you can define coroutine scope like this.

CoroutineScope(Dispatchers.Main)

Or any other dispatcher that suits your needs.
Good luck.


问:
Bind onlick events on several links
I am currently working on a solution for an application that is written in PHP, but needs a JS solution for a preview link and I am stuck with binding onclick-events on the links. The HTML is given and may not be changed. (so no adding of classes and stuff, even though that would be easier)

My initial thought was to just get each of the li and perform a callable that sets the event and defines the rules for what happens, when the link is clicked.

I am unsure what is the best possible solution to get the values of the two Inputs, belonging to the preview link, as while I was running the code mentioned above on what ever link I clicked, the last item was logged.

So basically this is 2 questions in one:
1. how to properly bind the click events.
2. how to best acces the inputs belonging to the link

var items = $('div.foobar').find('li');
items.each(function() {
  this = $(this);

  url = lo_this.find('a').attr('href');
  this.find('a').click(function(event) {
    event.preventDefault();
    console.log(this)

    /** here is the point, where I got stuck **/
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="foobar">
  <li>
    Link
    <div class="justaname">
      <input type="text" name="somenamewith[ID][foo]" value="">
      <input type="text" name="somenamewith[ID][bar]" maxlength="50" value="">
    </div>
  </li>
  <li>
    Link
    <div class="justaname">
      <input type="text" name="somenamewith[OTHERID][foo]" value="">
      <input type="text" name="somenamewith[OTHERID][bar]" maxlength="50" value="">
    </div>
  </li>
</div></code>```

答:
You can do this to bind click events to your links and then do whatever with the input elements contained by the div after the clicked link:</p>

```<code>$('.foobar li a').on('click',function(event){
  event.preventDefault();
  $(this).next().find('input').each(function(){
    //Whatever you want to do for each input
  });
});
</code>```

Title: Bind onlick events on several links

Body:
I am currently working on a solution for an application that is written in PHP, but needs a JS solution for a preview link and I am stuck with binding onclick-events on the links. The HTML is given and may not be changed. (so no adding of classes and stuff, even though that would be easier)

My initial thought was to just get each of the li and perform a callable that sets the event and defines the rules for what happens, when the link is clicked.

I am unsure what is the best possible solution to get the values of the two Inputs, belonging to the preview link, as while I was running the code mentioned above on what ever link I clicked, the last item was logged.

So basically this is 2 questions in one:
1. how to properly bind the click events.
2. how to best acces the inputs belonging to the link

var items = $('div.foobar').find('li');
items.each(function() {
  this = $(this);

  url = lo_this.find('a').attr('href');
  this.find('a').click(function(event) {
    event.preventDefault();
    console.log(this)

    /** here is the point, where I got stuck **/
  });
});

    Link

      <input type="text" name="somenamewith[ID][foo]" value="">
      <input type="text" name="somenamewith[ID][bar]" maxlength="50" value="">

    Link

      <input type="text" name="somenamewith[OTHERID][foo]" value="">
      <input type="text" name="somenamewith[OTHERID][bar]" maxlength="50" value="">

Body:
You can do this to bind click events to your links and then do whatever with the input elements contained by the div after the clicked link:

$('.foobar li a').on('click',function(event){
  event.preventDefault();
  $(this).next().find('input').each(function(){
    //Whatever you want to do for each input
  });
});


问:
Box plot with only one Whisker line?
I wanted to compare a variable among two different places. For this I used the following code in R:

```<code>boxplot(variable~place)
</code>```

As my place had two levels. However, I get a weird looking box plot. Do you know what seems to be the problem?

答:
As has been noted in comments, there's nothing wrong with the boxplots. The fact that there is just one whisker each is a reflection of your data.

Boxplots are an extremely instructive type of graphic: they not only show the location and spread of data but also indicate skewness. The interpretation of the boxplot depends on its ‘syntax’, i.e., its main graphical elements. There are five such elements:

```<code>1. bold horizontal line: depicts the median (the middle value of a sorted distribution)
2. box: represents the interquartile range (IQR)
3. whiskers: separate values lying outside the IQR (but still somewhat typical of the data) from outliers
3. empty circles: depict outliers (values surprisingly large or small given all values considered)
4. notches (optional): give a rough impression of the significance of the difference between the medians
</code>```

The fact that there's just one whisker in each boxplot is, then, due to the extreme skewness of your data: in the case of box 1 the upper limit of the values is the upper limit of the IQR, and in the case of box 2 there exists no value smaller than the median!

Hope this helps.

Title: Box plot with only one Whisker line?

Body:
I wanted to compare a variable among two different places. For this I used the following code in R:

boxplot(variable~place)

As my place had two levels. However, I get a weird looking box plot. Do you know what seems to be the problem?

Body:
As has been noted in comments, there's nothing wrong with the boxplots. The fact that there is just one whisker each is a reflection of your data.

Boxplots are an extremely instructive type of graphic: they not only show the location and spread of data but also indicate skewness. The interpretation of the boxplot depends on its ‘syntax’, i.e., its main graphical elements. There are five such elements:

1. bold horizontal line: depicts the median (the middle value of a sorted distribution)
2. box: represents the interquartile range (IQR)
3. whiskers: separate values lying outside the IQR (but still somewhat typical of the data) from outliers
3. empty circles: depict outliers (values surprisingly large or small given all values considered)
4. notches (optional): give a rough impression of the significance of the difference between the medians

The fact that there's just one whisker in each boxplot is, then, due to the extreme skewness of your data: in the case of box 1 the upper limit of the values is the upper limit of the IQR, and in the case of box 2 there exists no value smaller than the median!

Hope this helps.


问:
issue using Ionic QRScanner on Android browser: zoom in too much
I use https://ionicframework.com/docs/native/qr-scanner in an Ionic 4/Angular application for browsers.

The application works fine on laptop browsers and it's possible to have the camera preview and read QR codes.

However, when trying on Android browsers the camera zooms in too much and it's impossible to scan codes.

On the internet there's not much (just people asking to add the zoom in/out feature to the plugin) and I tried to control the camera zoom via another plugin (https://ionicframework.com/docs/native/camera-preview) but it didn't work.

Does anyone have any idea on how to fix this?

For reference, I append my code at the end of this message.

Thanks,

```<code>  scanCode() {
    console.log('entering scan function');
    this.qrScanner.prepare()
    .then((status: QRScannerStatus) => {
      console.log('checking status');
       if (status.authorized) {
         this.statusScanning=true;
         // camera permission was granted
         console.log('camera permission granted');
         // start scanning
         this.scanSub = this.qrScanner.scan().subscribe( (scanRes: string) => {
          let object:any=scanRes;
          if(isDefined(object.result))
          {
            let text: string=""+object.result;
            this.myfunction(text);
            this.qrScanner.hide(); // hide camera preview
            this.scanSub.unsubscribe(); // stop scanning
          }
         });
       } else if (status.denied) {
         // camera permission was permanently denied
         // you must use QRScanner.openSettings() method to guide the user to the settings page
         // then they can grant the permission from there
         console.log('status denied');
       } else {
        console.log('permissions denied for now');
         // permission was denied, but not permanently. You can ask for permission again at a later time.
       }
    })
    .catch((e: any) => console.log('Error:', e));
  }
</code>```

答:
in case anyone gets the same issue I had, the best option I found was to just give up the QRScanner component and use jsQR.
I followed the principles in the tutorial in this page (https://devdactic.com/pwa-qr-scanner-ionic/) and everything ended-up working fine.
Cheers,</p>

Body:
I use https://ionicframework.com/docs/native/qr-scanner in an Ionic 4/Angular application for browsers.

The application works fine on laptop browsers and it's possible to have the camera preview and read QR codes.

However, when trying on Android browsers the camera zooms in too much and it's impossible to scan codes.

On the internet there's not much (just people asking to add the zoom in/out feature to the plugin) and I tried to control the camera zoom via another plugin (https://ionicframework.com/docs/native/camera-preview) but it didn't work.

Does anyone have any idea on how to fix this?

For reference, I append my code at the end of this message.

Thanks,

  scanCode() {
    console.log('entering scan function');
    this.qrScanner.prepare()
    .then((status: QRScannerStatus) => {
      console.log('checking status');
       if (status.authorized) {
         this.statusScanning=true;
         // camera permission was granted
         console.log('camera permission granted');
         // start scanning
         this.scanSub = this.qrScanner.scan().subscribe( (scanRes: string) => {
          let object:any=scanRes;
          if(isDefined(object.result))
          {
            let text: string=""+object.result;
            this.myfunction(text);
            this.qrScanner.hide(); // hide camera preview
            this.scanSub.unsubscribe(); // stop scanning
          }
         });
       } else if (status.denied) {
         // camera permission was permanently denied
         // you must use QRScanner.openSettings() method to guide the user to the settings page
         // then they can grant the permission from there
         console.log('status denied');
       } else {
        console.log('permissions denied for now');
         // permission was denied, but not permanently. You can ask for permission again at a later time.
       }
    })
    .catch((e: any) => console.log('Error:', e));
  }


答:
You mean this?

Assuming your inputs are in the same LI as the anchor

Ignoring the ID of the anchor and just getting the inputs in the same LI

Other code is needed if you want to use the ID of the link to access the named links

$('div.foobar li a').on("click",function(e) {
  e.preventDefault();
  $(this).closest("li").find("input").each(function() {
     console.log(this.name,this.value)
  })
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="foobar">
  <li>
    Link
    <div class="justaname">
      <input type="text" name="somenamewith[ID][foo]" value="">
      <input type="text" name="somenamewith[ID][bar]" maxlength="50" value="">
    </div>
  </li>
  <li>
    Link
    <div class="justaname">
      <input type="text" name="somenamewith[OTHERID][foo]" value="">
      <input type="text" name="somenamewith[OTHERID][bar]" maxlength="50" value="">
    </div>
  </li>
</div></code>```

Title: Bind onlick events on several links

Body:
You mean this?

Assuming your inputs are in the same LI as the anchor

Ignoring the ID of the anchor and just getting the inputs in the same LI

Other code is needed if you want to use the ID of the link to access the named links

$('div.foobar li a').on("click",function(e) {
  e.preventDefault();
  $(this).closest("li").find("input").each(function() {
     console.log(this.name,this.value)
  })
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="foobar">
  <li>
    <a href="somelinkwithID">Link</a>
    <div class="justaname">
      <input type="text" name="somenamewith[ID][foo]" value="">
      <input type="text" name="somenamewith[ID][bar]" maxlength="50" value="">
    </div>
  </li>
  <li>
    <a href="somelinkwithOTHERID">Link</a>
    <div class="justaname">
      <input type="text" name="somenamewith[OTHERID][foo]" value="">
      <input type="text" name="somenamewith[OTHERID][bar]" maxlength="50" value="">
    </div>
  </li>
</div>


问:
Implementing Real Time frequency spectrum for a beginner
I want to develop an application that would take audio(.wav) as input and display its real time simultaneous frequency spectrum . From what i have looked upon the subject , this requires fourier transform of the waves . Can someone suggest where i should start with ? Possible references and books . I want to learn the details of the implementations of realtime frequency spetrum rather than the development of GUI which i am quite familiar with(in C# and in C++).</p>

答:
There are already many libraries to do FFTs for you. No reason to reinvent the wheel. DirectX has an implementation but it might only be in the most recent version. Here's an open source C library for it.

If you want to understand the math behind it, here's a simple explanation and here's a complicated explanation.


问:
how can make Burger Menu with Angular?
How can make Burger Menu with Angular ?
I do not understand how to do in Typescript I am quite a beginner.

when i switch my screen to smartphone mode should i hide the nav menu ?

homepage.component.html

```<code><div class="wrapper">
        <div class="sidebar-wrapper">
            <div class="title-content">
                <h1 class="title-wrapper">Furniture</h1>
                <button (click)="burgerMenuClick">☰</button>
            </div>
            <nav class="sidebar-wrapper-nav">
                <ul>
                    <li class="list-wrapper">
                        Home
                    </li>
                    <li class="list-wrapper">
                        Shop
                    </li>
                    <li class="list-wrapper">
                        Product
                    </li>
                    <li class="list-wrapper">
                        Cart
                    </li>
                </ul>
            </nav>
        </div>
        <div class="main-content-wrapper">
            <img src="https://colorlib.com/preview/theme/amado/img/product-img/pro-big-1.jpg">
            <img src="https://colorlib.com/preview/theme/amado/img/product-img/pro-big-1.jpg">
            <img src="https://colorlib.com/preview/theme/amado/img/product-img/pro-big-1.jpg">
        </div>
    </div>
</code>```

homepage.component.ts

```<code>import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-homepage',
  templateUrl: './homepage.component.html',
  styleUrls: ['./homepage.component.css']
})
export class HomepageComponent implements OnInit {

  constructor() { }

  ngOnInit() {
    this.burgerMenuClick();
  }

  burgerMenuClick() {

  }

}
</code>```

答:
What do you mean by this?

when i switch my screen to smartphone mode should i hide the nav menu ?

Usually you want to show the nav bar as a normal menu bar when you are on a laptop screen and collaps it to an hamburger menu when you are on a smartphone.

If you use bootstrap you will get this behaviour out of the box with the navbar.
Please check out this resource:
https://mdbootstrap.com/docs/angular/navigation/navbar/

Title: how can make Burger Menu with Angular?

Body:
How can make Burger Menu with Angular ?
I do not understand how to do in Typescript I am quite a beginner.

when i switch my screen to smartphone mode should i hide the nav menu ?

homepage.component.html

Furniture

                <button (click)="burgerMenuClick">☰</button>

                        Home

                        Shop

                        Product

                        Cart

homepage.component.ts

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-homepage',
  templateUrl: './homepage.component.html',
  styleUrls: ['./homepage.component.css']
})
export class HomepageComponent implements OnInit {

  constructor() { }

  ngOnInit() {
    this.burgerMenuClick();
  }

  burgerMenuClick() {

  }

}


问:
Firebase blaze plan limit budget script?
Firebase is now making cloud function only for blaze plan. The problem is there is no budget limit.. only budget notifications ! i've heard it can be done with a script like pub/sub when notification of budget is received , the app engine is disabled ? is it really possible doing this ?</p>

答:
Yes, you can set up budget notifications and use them as triggers to Cloud Functions in order to disable certain API or resources when your defined budget threeshold is reached.

To that effect you could follow the setps outlined in "set budget" documentation that explains how to set the notifications and then follow this doc about how to make these notifications to create a Pub/Sub event. Afterwards you'll need to create a Cloud Function to handle such events in the way you feel more appropiate, some examples could be found here.

On top of that, some API offer the possibility to cap it's usage as explained here. This might allow to set API limits so to stay below the free usage quotas or restrict how much usage could the API get before it starts rejecting requests.

Keep in mind that if you shutdown resources such as VM instances they won't be recoverable so read carefully the documentation of whatever API or resource you're trying to control to avoid unexpected outcomes.


问:
AppWidget crashes launcher after configuration activity finish (Xiaomi and Huawei only)
I'm trying to display an AppWidget on device home. I can't figure why, only on Xiaomi and Huawei devices it doesn't work.

When I drag the widget on the home screen, it nicely open my config activity.
I close that activity using :

```<code>private void saveConfig() {
    AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(this);

    ComponentName thisAppWidget = new ComponentName(getPackageName(),
        ConfigActivity.class.getName());

    Intent updateIntent = new Intent(this, ConfigActivity.class);

    int[] appWidgetIds = appWidgetManager.getAppWidgetIds(thisAppWidget);

    updateIntent.setAction(ACTION_APPWIDGET_UPDATE);
    updateIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds);

    setResult(RESULT_OK, updateIntent);

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

After that, the launcher seems buggy : screen become black, recent app drawer is open, I'm not on the same page I was...

There is nothing special in the LogCat.

Everything is fine one other devices like Samsung's or OnePlus.

Does someone had similar problem ?

Manifest.xml

```<code><uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
<uses-permission android:name="android.permission.ACTIVITY_RECOGNITION" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@drawable/ic_launcher_round"
        android:usesCleartextTraffic="true"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        tools:ignore="GoogleAppIndexingWarning"
        tools:targetApi="m">

        <activity
            android:name="com.######.presentation.activity.ConfigActivity"
            android:screenOrientation="portrait"
            android:configChanges="orientation|keyboardHidden">
            <intent-filter>
                <action android:name="android.appwidget.action.APPWIDGET_CONFIGURE" />
            </intent-filter>
        </activity>

       <activity
            android:name=".presentation.activity.HomeActivity"
            android:screenOrientation="portrait"
            android:configChanges="orientation|keyboardHidden"/>

       <activity
            android:name=".presentation.activity.LegalNoticeActivity"
            android:screenOrientation="portrait"
            android:configChanges="orientation|keyboardHidden"/>

       <receiver
            android:name="com.######.provider.EnergyMixWidgetProvider"
            android:icon="@drawable/ic_launcher_round"
            android:label="@string/app_name">
        <intent-filter>
        <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
    </intent-filter>

    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
    </intent-filter>

    <meta-data
        android:name="android.appwidget.provider"
        android:resource="@xml/appwidget_info" />
    </receiver>

    <receiver android:name=".presentation.receiver.NotificationActionReceiver"/>

    <service android:name=".data.service.ListenerService" />
</application>
</code>```

appwidget_provider

```<code><appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
     android:initialKeyguardLayout="@layout/app_widget_4"
     android:initialLayout="@layout/app_widget_4"
     android:minHeight="110dp"
     android:minWidth="250dp"
     android:updatePeriodMillis="0"
     android:resizeMode="horizontal"
     android:widgetCategory="home_screen"
     android:previewImage="@mipmap/ic_launcher"
  android:configure="com.########.presentation.activity.ConfigActivity"/>
</code>```

Any help would be gladly appreciate

EDIT
If I remove the config activity from the android:configure attribute of the apwidget-provider, appwidget does appear on the home screen.
It let me think that the problem is in the intent sent in the result of my config activity

答:
Method 1, Entering  phone settings, finding Huawei desktop program, choosing  clear cache, and switching to the desktop.

Method 2, Have you installed a third-party mobile Butler app? Try uninstalling it. The main reason for icon restoration may be the theme. Try changing the theme, You can switch back to the default theme if you use a non self provided theme.

Method 3, Locking the screen without rotation or horizontal screen.

Method 4, Resetting Huawei desktop application.

Click settings

Click applications

Click application management

Click Huawei desktop

Click storage

Click delete data

Click delete

Body:
I'm trying to display an AppWidget on device home. I can't figure why, only on Xiaomi and Huawei devices it doesn't work.

When I drag the widget on the home screen, it nicely open my config activity.
I close that activity using :

private void saveConfig() {
    AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(this);

    ComponentName thisAppWidget = new ComponentName(getPackageName(),
        ConfigActivity.class.getName());

    Intent updateIntent = new Intent(this, ConfigActivity.class);

    int[] appWidgetIds = appWidgetManager.getAppWidgetIds(thisAppWidget);

    updateIntent.setAction(ACTION_APPWIDGET_UPDATE);
    updateIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds);

    setResult(RESULT_OK, updateIntent);

    finish();
}

After that, the launcher seems buggy : screen become black, recent app drawer is open, I'm not on the same page I was...

There is nothing special in the LogCat.

Everything is fine one other devices like Samsung's or OnePlus.

Does someone had similar problem ?

Manifest.xml

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
<uses-permission android:name="android.permission.ACTIVITY_RECOGNITION" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@drawable/ic_launcher_round"
        android:usesCleartextTraffic="true"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        tools:ignore="GoogleAppIndexingWarning"
        tools:targetApi="m">

        <activity
            android:name="com.######.presentation.activity.ConfigActivity"
            android:screenOrientation="portrait"
            android:configChanges="orientation|keyboardHidden">
            <intent-filter>
                <action android:name="android.appwidget.action.APPWIDGET_CONFIGURE" />
            </intent-filter>
        </activity>

       <activity
            android:name=".presentation.activity.HomeActivity"
            android:screenOrientation="portrait"
            android:configChanges="orientation|keyboardHidden"/>

       <activity
            android:name=".presentation.activity.LegalNoticeActivity"
            android:screenOrientation="portrait"
            android:configChanges="orientation|keyboardHidden"/>

       <receiver
            android:name="com.######.provider.EnergyMixWidgetProvider"
            android:icon="@drawable/ic_launcher_round"
            android:label="@string/app_name">
        <intent-filter>
        <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
    </intent-filter>

    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
    </intent-filter>

    <meta-data
        android:name="android.appwidget.provider"
        android:resource="@xml/appwidget_info" />
    </receiver>

    <receiver android:name=".presentation.receiver.NotificationActionReceiver"/>

    <service android:name=".data.service.ListenerService" />
</application>

appwidget_provider

<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
     android:initialKeyguardLayout="@layout/app_widget_4"
     android:initialLayout="@layout/app_widget_4"
     android:minHeight="110dp"
     android:minWidth="250dp"
     android:updatePeriodMillis="0"
     android:resizeMode="horizontal"
     android:widgetCategory="home_screen"
     android:previewImage="@mipmap/ic_launcher"
  android:configure="com.########.presentation.activity.ConfigActivity"/>

Any help would be gladly appreciate

EDIT
If I remove the config activity from the android:configure attribute of the apwidget-provider, appwidget does appear on the home screen.
It let me think that the problem is in the intent sent in the result of my config activity


问:
What is a good amount of code to have in a single file?
I was wondering today about how much code people normally have in a single source file before they decide to split it into multiple smaller files.

Personally I tend to keep my files fairly small (exspecally header files when working with C/C++). That is I will generally only have one class or a bunch of functions in a given file so the file is generaly <500 lines. However all the stuff related normally shares the same namespace.

On the other hand some of the stuff I work with seem to quite happily try to stick as much as possible into a single file which is then 1000's of lines long.

I like the small files better since any changes only requires recompiling that one piece of code, and I find it easier to navigate the source when it is broken into smaller files each with a specific purpose, rather than one massive file about the entire thing. Is there any real advantage to a few massive files?

For example my particle system is broken into system.h, emitter.h, load.h, particle.h, etc and corosponding .cpp files for each one. However some particle systems ive looked at seem to have put the entire source into a single .h and .cpp 1000's of lines long.

答: Smaller files are without any doubt easier to read and understand. However, I don't think you can make this decision based on the number of lines in a class or source file. Consider splitting up your code if you feel that common functionality should be placed in a different file instead. It will also allow for better reuse of code.</p>

OwnerDisplayName: Fire Lancer

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: X-Istence

OwnerDisplayName: Christophe Herreman


问:
How to Prevent Keyboard appearing for EditText that is not enabled
My activity has an EditText which is supposedly not editable until user clicks on edit button for the screen.

I did edit.setEnabled(false) but still a keyboard appears for the user and values can be added to the EditText in the screen via the keyboard even though the screen might look a bit greyed out.  What else do I have to do to prevent editing of the EditText until user has specifically pushed an edit button.

Thanks,
Steve

答:
in your layout file add the attribute to your EditText

android:editable="false"