问:
Returning a 2D Array from a method using the class name as the input
I'm receiving the error message "type mismatch cannot convert from String[][] to GameBoard[][]" on the line return gameBoard;.  How can I change this my public class GameBoard so that I am able to return string values in the 2D array?  (I do not want to change the methods return type to String[][])

```<code>
public class GameBoard {

    String[][] gameBoard;

    /**
     * Constructor
     */

    public GameBoard() {
        gameBoard = new String[4][5];
    }

    /**
     * Filling the playable board with Strings
     * @return
     */

     public GameBoard[][] fillGameBoard() {

        gameBoard[0][0] = new String("1");
        gameBoard[0][1] = new String("2");
        gameBoard[0][2] = new String("3");
        gameBoard[0][3] = new String("4");
        gameBoard[0][4] = new String("5");
        gameBoard[1][0] = new String("6");
        gameBoard[1][1] = new String("7");
        gameBoard[1][2] = new String("8");
        gameBoard[1][3] = new String("9");
        gameBoard[1][4] = new String("10");
        gameBoard[2][1] = new String("11");
        gameBoard[2][2] = new String("12");
        gameBoard[2][3] = new String("13");
        gameBoard[3][1] = new String("14");
        gameBoard[3][2] = new String("15");
        gameBoard[3][3] = new String("16");

        return gameBoard;

    }```

```

答:
That happens because you tell the compiler you are going to return a GameBoard[][] type but are actually returning a String[][] type, you probably confused yourself by naming your member variable the same way you named your class. You probably want to come up with a less confusing name for it.

Generally your approach of defining a class for your GameBoard is fine, since you probably want to perform different actions on it later on like, move() a content from 1 cell to another or something else. But remember, that your 'client-class' doesn't know about how the interior of your class looks and thus you cannot just store a GameObject as String[][] and vice versa

Here is an example of your class with some comments on how to declare variables that use your GameBoard along with suggestions:
(This will not work as is, you have to remove the methods you do not want to use, since they are not matching in return types)

```<code>public class GameBoard {

    String[][] gameBoard;

    /**
     * Constructor
     */
    public GameBoard() {
        gameBoard = new String[4][5];
    }

    // Approach 1
     public void fillGameBoard() {

        gameBoard[0][0] = "1";
        gameBoard[0][1] = "2";
        gameBoard[0][2] = "3";
        gameBoard[0][3] = "4";
        gameBoard[0][4] = "5";
        gameBoard[1][0] = "6";
        gameBoard[1][1] = "7";
        gameBoard[1][2] = "8";
        gameBoard[1][3] = "9";
        gameBoard[1][4] = "10";
        gameBoard[2][1] = "11";
        gameBoard[2][2] = "12";
        gameBoard[2][3] = "13";
        gameBoard[3][1] = "14";
        gameBoard[3][2] = "15";
        gameBoard[3][3] = "16";
    }

    // Approach 2
    // If you really want to go with the way you had your declaration set up
    // GameBoard board = new GameBoard().fillGameBoard();
    // you would have to do this
    public GameBoard fillGameBoard() {
        fillGameBoard();

        return this;
    }

    // Approach 3
    // If you want to do this, you don't need your class at all and your fillGameBoard
    // has to return a String[][] type. I would recommend against it though,
    // since you are using a highly object oriented language as Java
    public String[][] fillGameBoard() {
        fillGameBoard();

        return gameBoard;
    }

    public static void main(String[] args) {
        // Approach 1
        // I recommend this approach!
        GameBoard board2 = new GameBoard();
        board2.fillGameBoard();

        // Approach 2
        GameBoard board = new GameBoard().fillGameBoard();

        // Approach 3
        String[][] board3 = new GameBoard().fillGameBoard();
    }
}
</code>```

Body:
I'm receiving the error message "type mismatch cannot convert from String[][] to GameBoard[][]" on the line return gameBoard;.  How can I change this my public class GameBoard so that I am able to return string values in the 2D array?  (I do not want to change the methods return type to String[][])

public class GameBoard {

    String[][] gameBoard;

    /**
     * Constructor
     */

    public GameBoard() {
        gameBoard = new String[4][5];
    }

    /**
     * Filling the playable board with Strings
     * @return
     */

     public GameBoard[][] fillGameBoard() {

        gameBoard[0][0] = new String("1");
        gameBoard[0][1] = new String("2");
        gameBoard[0][2] = new String("3");
        gameBoard[0][3] = new String("4");
        gameBoard[0][4] = new String("5");
        gameBoard[1][0] = new String("6");
        gameBoard[1][1] = new String("7");
        gameBoard[1][2] = new String("8");
        gameBoard[1][3] = new String("9");
        gameBoard[1][4] = new String("10");
        gameBoard[2][1] = new String("11");
        gameBoard[2][2] = new String("12");
        gameBoard[2][3] = new String("13");
        gameBoard[3][1] = new String("14");
        gameBoard[3][2] = new String("15");
        gameBoard[3][3] = new String("16");

        return gameBoard;

    }```

Body:
That happens because you tell the compiler you are going to return a GameBoard[][] type but are actually returning a String[][] type, you probably confused yourself by naming your member variable the same way you named your class. You probably want to come up with a less confusing name for it.

Generally your approach of defining a class for your GameBoard is fine, since you probably want to perform different actions on it later on like, move() a content from 1 cell to another or something else. But remember, that your 'client-class' doesn't know about how the interior of your class looks and thus you cannot just store a GameObject as String[][] and vice versa

Here is an example of your class with some comments on how to declare variables that use your GameBoard along with suggestions:
(This will not work as is, you have to remove the methods you do not want to use, since they are not matching in return types)

public class GameBoard {

    String[][] gameBoard;

    /**
     * Constructor
     */
    public GameBoard() {
        gameBoard = new String[4][5];
    }

    // Approach 1
     public void fillGameBoard() {

        gameBoard[0][0] = "1";
        gameBoard[0][1] = "2";
        gameBoard[0][2] = "3";
        gameBoard[0][3] = "4";
        gameBoard[0][4] = "5";
        gameBoard[1][0] = "6";
        gameBoard[1][1] = "7";
        gameBoard[1][2] = "8";
        gameBoard[1][3] = "9";
        gameBoard[1][4] = "10";
        gameBoard[2][1] = "11";
        gameBoard[2][2] = "12";
        gameBoard[2][3] = "13";
        gameBoard[3][1] = "14";
        gameBoard[3][2] = "15";
        gameBoard[3][3] = "16";
    }

    // Approach 2
    // If you really want to go with the way you had your declaration set up
    // GameBoard board = new GameBoard().fillGameBoard();
    // you would have to do this
    public GameBoard fillGameBoard() {
        fillGameBoard();

        return this;
    }

    // Approach 3
    // If you want to do this, you don't need your class at all and your fillGameBoard
    // has to return a String[][] type. I would recommend against it though,
    // since you are using a highly object oriented language as Java
    public String[][] fillGameBoard() {
        fillGameBoard();

        return gameBoard;
    }

    public static void main(String[] args) {
        // Approach 1
        // I recommend this approach!
        GameBoard board2 = new GameBoard();
        board2.fillGameBoard();

        // Approach 2
        GameBoard board = new GameBoard().fillGameBoard();

        // Approach 3
        String[][] board3 = new GameBoard().fillGameBoard();
    }
}


来源: stackexchange

问:
Select for login and update at the same time
Is it possible to use SQL command for login and update at the same time? I mean when the Login is done, I want to change logat in 1. Do I have to create a new if with OpenConnection()?

```<code>public bool IsLogin(string user, string pass) {
            string query = $"SELECT * from utiliz WHERE username='{user}' AND password='{GetSha1(pass)}'";
            string query_update = $"UPDATE utiliz SET logat='{1}' WHERE username='{user}'";
            try
            {
                if (OpenConnection())
                {
                    MySqlCommand cmd = new MySqlCommand(query, conn);
                    MySqlDataReader reader = cmd.ExecuteReader();
                    if (reader.Read())
                    {
                        reader.Close();
                        conn.Close();
                        return true;
                    }
                    else
                    {
                        reader.Close();
                        conn.Close();
                        return false;
                    }
                }
                else {
                    conn.Close();
                    return false;
                }
            }
            catch (Exception ex) {
                conn.Close();
                return false;
            }
            }
</code>```

EDITED

Guys, I have edited my code, following parameters procedure. Is it good what I did?

```<code>if (String.IsNullOrEmpty(textBox_pass_login.Text) && String.IsNullOrEmpty(textBox_usr_login.Text) || String.IsNullOrEmpty(textBox_usr_login.Text) || String.IsNullOrEmpty(textBox_pass_login.Text))
            {
                System.Windows.Forms.MessageBox.Show("Both fields (username,password) are required");
            }
            else
            {
                string user = textBox_usr_login.Text;
                string password = textBox_pass_login.Text;
                string encryptedpass = GetSha1(password);
                try
                {
                    using (var connection = conn)
                    {
                        string query = "SELECT * from utiliz WHERE username=@user AND password=@password";
                        using (var command = new MySqlCommand(query, conn))
                        {
                            command.Parameters.AddWithValue("@user", user);
                            command.Parameters.AddWithValue("@password", encryptedpass);
                            MySqlDataAdapter sda = new MySqlDataAdapter(command);
                            DataTable dt = new DataTable();
                            sda.Fill(dt);
                            conn.Open();
                            int i = command.ExecuteNonQuery();
                            conn.Close();
                            if (dt.Rows.Count > 0)
                            {
                                this.Hide();
                                var form2 = new Form1();
                                form2.Closed += (s, args) => this.Close();
                                form2.Show();
                            }
                            else
                            {
                                System.Windows.Forms.MessageBox.Show("Wrong credentials");
                                textBox_usr_login.Clear();
                                textBox_pass_login.Clear();
                            }
                        }
                    }
                }
                catch
                {
                    System.Windows.Forms.MessageBox.Show("Wrong credentials");
                    textBox_usr_login.Clear();
                    textBox_pass_login.Clear();
                }
            }
</code>```

答:
There are some important points here. You must use Parameterized queries to improve the performence of your query on the database layer and avoid some problems such as sql injection. You also could use transactions to keep data integrity.

Check the sample bellow with comments (I didn't test this code, may not work properly on your environment):

```<code>public bool IsLogin(string user, string pass)
{
    // prepare the queries with parameters with '@' and parameter name
    const string query = "SELECT count(username) from utiliz WHERE username = @username AND password = @password";
    const string query_update = "UPDATE utiliz SET logat = @logat WHERE username = @username";

    // prepare the encrypted password
    string encryptedPass = GetSha1(pass);

    // use a result variable to use as the function result

    bool result = false;
    try
    {
        if (OpenConnection())
        {
            // start a transaction from the connection object
            using (MySqlTransaction tran = conn.BeginTransaction())
            {
                try
                {
                    int userFound = 0;
                    // prepare the MySqlCommand to use the query, connection and transaction.
                    using (MySqlCommand userCommand = new MySqlCommand(query, conn, tran))
                    {
                        userCommand.Parameters.AddWithValue("@username", user);
                        userCommand.Parameters.AddWithValue("@password", encryptedPass);

                        userFound = (int) userCommand.ExecuteScalar();
                    }

                    if (userFound > 0)
                    {
                        // prepare the MySqlCommand to use the query, connection and transaction to update data
                        using (MySqlCommand logatCommand = new MySqlCommand(query_update, conn, tran))
                        {
                            logatCommand.Parameters.AddWithValue("@logat", DateTime.Now);
                            logatCommand.Parameters.AddWithValue("@username", user);

                            logatCommand.ExecuteNonQuery();
                        }
                    }

                    // commit the transaction
                    tran.Commit();

                    result = true;
                }
                catch (Exception ex)
                {
                    // perform some log with ex object.

                    tran.Rollback();
                }
                finally
                {
                    conn.Close();
                }
            }
        }
    }
    catch (Exception e)
    {
        // perform some log...

        return false;
    }

    return result;
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Is it possible to use SQL command for login and update at the same time? I mean when the Login is done, I want to change logat in 1. Do I have to create a new if with OpenConnection()?

public bool IsLogin(string user, string pass) {
            string query = $"SELECT * from utiliz WHERE username='{user}' AND password='{GetSha1(pass)}'";
            string query_update = $"UPDATE utiliz SET logat='{1}' WHERE username='{user}'";
            try
            {
                if (OpenConnection())
                {
                    MySqlCommand cmd = new MySqlCommand(query, conn);
                    MySqlDataReader reader = cmd.ExecuteReader();
                    if (reader.Read())
                    {
                        reader.Close();
                        conn.Close();
                        return true;
                    }
                    else
                    {
                        reader.Close();
                        conn.Close();
                        return false;
                    }
                }
                else {
                    conn.Close();
                    return false;
                }
            }
            catch (Exception ex) {
                conn.Close();
                return false;
            }
            }

EDITED

Guys, I have edited my code, following parameters procedure. Is it good what I did?

if (String.IsNullOrEmpty(textBox_pass_login.Text) && String.IsNullOrEmpty(textBox_usr_login.Text) || String.IsNullOrEmpty(textBox_usr_login.Text) || String.IsNullOrEmpty(textBox_pass_login.Text))
            {
                System.Windows.Forms.MessageBox.Show("Both fields (username,password) are required");
            }
            else
            {
                string user = textBox_usr_login.Text;
                string password = textBox_pass_login.Text;
                string encryptedpass = GetSha1(password);
                try
                {
                    using (var connection = conn)
                    {
                        string query = "SELECT * from utiliz WHERE username=@user AND password=@password";
                        using (var command = new MySqlCommand(query, conn))
                        {
                            command.Parameters.AddWithValue("@user", user);
                            command.Parameters.AddWithValue("@password", encryptedpass);
                            MySqlDataAdapter sda = new MySqlDataAdapter(command);
                            DataTable dt = new DataTable();
                            sda.Fill(dt);
                            conn.Open();
                            int i = command.ExecuteNonQuery();
                            conn.Close();
                            if (dt.Rows.Count > 0)
                            {
                                this.Hide();
                                var form2 = new Form1();
                                form2.Closed += (s, args) => this.Close();
                                form2.Show();
                            }
                            else
                            {
                                System.Windows.Forms.MessageBox.Show("Wrong credentials");
                                textBox_usr_login.Clear();
                                textBox_pass_login.Clear();
                            }
                        }
                    }
                }
                catch
                {
                    System.Windows.Forms.MessageBox.Show("Wrong credentials");
                    textBox_usr_login.Clear();
                    textBox_pass_login.Clear();
                }
            }

Body:
There are some important points here. You must use Parameterized queries to improve the performence of your query on the database layer and avoid some problems such as sql injection. You also could use transactions to keep data integrity.

Check the sample bellow with comments (I didn't test this code, may not work properly on your environment):

public bool IsLogin(string user, string pass)
{
    // prepare the queries with parameters with '@' and parameter name
    const string query = "SELECT count(username) from utiliz WHERE username = @username AND password = @password";
    const string query_update = "UPDATE utiliz SET logat = @logat WHERE username = @username";

    // prepare the encrypted password
    string encryptedPass = GetSha1(pass);

    // use a result variable to use as the function result

    bool result = false;
    try
    {
        if (OpenConnection())
        {
            // start a transaction from the connection object
            using (MySqlTransaction tran = conn.BeginTransaction())
            {
                try
                {
                    int userFound = 0;
                    // prepare the MySqlCommand to use the query, connection and transaction.
                    using (MySqlCommand userCommand = new MySqlCommand(query, conn, tran))
                    {
                        userCommand.Parameters.AddWithValue("@username", user);
                        userCommand.Parameters.AddWithValue("@password", encryptedPass);

                        userFound = (int) userCommand.ExecuteScalar();
                    }

                    if (userFound > 0)
                    {
                        // prepare the MySqlCommand to use the query, connection and transaction to update data
                        using (MySqlCommand logatCommand = new MySqlCommand(query_update, conn, tran))
                        {
                            logatCommand.Parameters.AddWithValue("@logat", DateTime.Now);
                            logatCommand.Parameters.AddWithValue("@username", user);

                            logatCommand.ExecuteNonQuery();
                        }
                    }

                    // commit the transaction
                    tran.Commit();

                    result = true;
                }
                catch (Exception ex)
                {
                    // perform some log with ex object.

                    tran.Rollback();
                }
                finally
                {
                    conn.Close();
                }
            }
        }
    }
    catch (Exception e)
    {
        // perform some log...

        return false;
    }

    return result;
}


问:
I am not able to see Click Wrap option all the time from my DocuSign sandbox account
DocuSign have recently released Click Wraps at their Momentum. I would like to take advantage of this new feature and was exploring this a little.
 Once, I was able to add a few click wrap templates using my DocuSign sandbox account but at times, I do not see them when I click on "Manage" button once I login to my DocuSign demo account.

Please advise,

Thanks,

Minal

答:
We had a similar issue here and as a workaround after we logged into our demo account we were able to enter the url for the clickwraps directly to navigate to the clickwraps page.</p>

```<code>https://appdemo.docusign.com/documents?view=active&type=clickwraps
</code>```

Body:
We had a similar issue here and as a workaround after we logged into our demo account we were able to enter the url for the clickwraps directly to navigate to the clickwraps page.

https://appdemo.docusign.com/documents?view=active&type=clickwraps


问:
Bash redirect all output to file (beyond stderr and stdout)
You can redirect stderr and stdout of a bash command to file using foo > out.txt 2>&1

But, consider: ssh user@host > out.txt 2>&1. In my experience, if a password is needed to connect, the password prompt will be displayed to the screen and not be sent to file.

For a more extreme example, tmux > out.txt 2>&1 fails to redirect anything to file, except for a final [exited] message.

What's going on here, and is it possible to redirect all output?

答:
Have you tried using "| tee out.txt 2>&1" ?
Sorry, didn't understood your question... You need a terminal print and a file output?</p>


问:
Can we build a Xamarin based android system application in visual studio or Android studio IDE?
I want build and debug a xamarin based "SYSTEM" android application in visual studio. Is it doable?</p>

答:
Here is some basic information from MSDN that you can start with for distributing your Xamarin.Android app as a System app.

It's difficult to provide specifics on this topic because the way you go about doing this can shift dramatically depending on your setup. Even MSDN states that. The article provided though is a great starting point to begin to understand how to go about installing your app as a system app.


问:
How can I stop my camera clipping through terrain?
Having a bit of a problem in Unity3D. I have a fly camera with both a box collider and rigidbody, and it still moves through my terrain, which has a terrain collider and a rigidbody. The thing is, it interacts with my capsules just fine, bounces them away and everything. Obvious this is the exact opposite of what I want ha ha...

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class FlyCamera : MonoBehaviour
{.
    /*
Writen by Windexglow 11-13-10.  Use it, edit it, steal it I don't care.
Converted to C# 27-02-13 - no credit wanted.
Simple flycam I made, since I couldn't find any others made public.
Made simple to use (drag and drop, done) for regular keyboard layout
wasd : basic movement
shift : Makes camera accelerate
space : Moves camera on X and Z axis only.  So camera doesn't gain any height*/

float mainSpeed = 25.0f; //regular speed
float shiftAdd = 250.0f; //multiplied by how long shift is held.  Basically running
float maxShift = 1000.0f; //Maximum speed when holdin gshift
float camSens = 0.25f; //How sensitive it with mouse
private Vector3 lastMouse = new Vector3(255, 255, 255); //kind of in the middle of the screen, rather than at the top (play)
private float totalRun = 1.0f;

void Update()
{
    if (Input.GetKey(KeyCode.R))
    {
        transform.position = new Vector3(26f, 4f, 14f);
    }

    lastMouse = Input.mousePosition - lastMouse;
    lastMouse = new Vector3(-lastMouse.y * camSens, lastMouse.x * camSens, 0);
    lastMouse = new Vector3(transform.eulerAngles.x + lastMouse.x, transform.eulerAngles.y + lastMouse.y, 0);
    transform.eulerAngles = lastMouse;
    lastMouse = Input.mousePosition;
    //Mouse  camera angle done.

    //Keyboard commands
    float f = 0.0f;
    Vector3 p = GetBaseInput();
    if (Input.GetKey(KeyCode.LeftShift))
    {
        totalRun += Time.deltaTime;
        p = p * totalRun * shiftAdd;
        p.x = Mathf.Clamp(p.x, -maxShift, maxShift);
        p.y = Mathf.Clamp(p.y, -maxShift, maxShift);
        p.z = Mathf.Clamp(p.z, -maxShift, maxShift);
    }
    else
    {
        totalRun = Mathf.Clamp(totalRun * 0.5f, 1f, 1000f);
        p = p * mainSpeed;
    }

    p = p * Time.deltaTime;
    Vector3 newPosition = transform.position;
    if (Input.GetKey(KeyCode.Space))
    { //If player wants to move on X and Z axis only
        transform.Translate(p);
        newPosition.x = transform.position.x;
        newPosition.z = transform.position.z;
        transform.position = newPosition;
    }
    else
    {
        transform.Translate(p);
    }

}

private Vector3 GetBaseInput()
{ //returns the basic values, if it's 0 than it's not active.
    Vector3 p_Velocity = new Vector3();
    if (Input.GetKey(KeyCode.W))
    {
        if (transform.position.x > 2 && transform.position.x < 53)
        {
            if (transform.position.y > 0 && transform.position.y < 40)
            {
                if (transform.position.z > 5 && transform.position.z < 52)
                {
                    p_Velocity += new Vector3(0, 0, 1);
                }

            }

        }

    }
    if (Input.GetKey(KeyCode.S))
    {
        if (transform.position.x > 2 && transform.position.x < 53)
        {
            if (transform.position.y > 0 && transform.position.y < 40)
            {
                if (transform.position.z > 5 && transform.position.z < 52)
                {
                    p_Velocity += new Vector3(0, 0, -1);
                }

            }

        }

    }
    if (Input.GetKey(KeyCode.A))
    {
        if (transform.position.x > 2 && transform.position.x < 53)
        {
            if (transform.position.y > 0 && transform.position.y < 40)
            {
                if (transform.position.z > 5 && transform.position.z < 52)
                {
                    p_Velocity += new Vector3(-1, 0, 0);
                }

            }

        }

    }
    if (Input.GetKey(KeyCode.D))
    {
        if (transform.position.x > 2 && transform.position.x < 53)
        {
            if (transform.position.y > 0 && transform.position.y < 40)
            {
                if (transform.position.z > 5 && transform.position.z < 52)
                {
                    p_Velocity += new Vector3(1, 0, 0);
                }

            }

        }

    }
    return p_Velocity;

}
</code>```

}

This flycam isn't mine so if it's not optimal for the use I'm looking for, please notify me about that too.

答:
Never mind, I fixed the problem.
I ended up having Kinematic ticked on the box collider of the camera, so that must have messed it up.</p>

Body:
Having a bit of a problem in Unity3D. I have a fly camera with both a box collider and rigidbody, and it still moves through my terrain, which has a terrain collider and a rigidbody. The thing is, it interacts with my capsules just fine, bounces them away and everything. Obvious this is the exact opposite of what I want ha ha...

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class FlyCamera : MonoBehaviour
{.
    /*
Writen by Windexglow 11-13-10.  Use it, edit it, steal it I don't care.
Converted to C# 27-02-13 - no credit wanted.
Simple flycam I made, since I couldn't find any others made public.
Made simple to use (drag and drop, done) for regular keyboard layout
wasd : basic movement
shift : Makes camera accelerate
space : Moves camera on X and Z axis only.  So camera doesn't gain any height*/

float mainSpeed = 25.0f; //regular speed
float shiftAdd = 250.0f; //multiplied by how long shift is held.  Basically running
float maxShift = 1000.0f; //Maximum speed when holdin gshift
float camSens = 0.25f; //How sensitive it with mouse
private Vector3 lastMouse = new Vector3(255, 255, 255); //kind of in the middle of the screen, rather than at the top (play)
private float totalRun = 1.0f;

void Update()
{
    if (Input.GetKey(KeyCode.R))
    {
        transform.position = new Vector3(26f, 4f, 14f);
    }

    lastMouse = Input.mousePosition - lastMouse;
    lastMouse = new Vector3(-lastMouse.y * camSens, lastMouse.x * camSens, 0);
    lastMouse = new Vector3(transform.eulerAngles.x + lastMouse.x, transform.eulerAngles.y + lastMouse.y, 0);
    transform.eulerAngles = lastMouse;
    lastMouse = Input.mousePosition;
    //Mouse  camera angle done.

    //Keyboard commands
    float f = 0.0f;
    Vector3 p = GetBaseInput();
    if (Input.GetKey(KeyCode.LeftShift))
    {
        totalRun += Time.deltaTime;
        p = p * totalRun * shiftAdd;
        p.x = Mathf.Clamp(p.x, -maxShift, maxShift);
        p.y = Mathf.Clamp(p.y, -maxShift, maxShift);
        p.z = Mathf.Clamp(p.z, -maxShift, maxShift);
    }
    else
    {
        totalRun = Mathf.Clamp(totalRun * 0.5f, 1f, 1000f);
        p = p * mainSpeed;
    }

    p = p * Time.deltaTime;
    Vector3 newPosition = transform.position;
    if (Input.GetKey(KeyCode.Space))
    { //If player wants to move on X and Z axis only
        transform.Translate(p);
        newPosition.x = transform.position.x;
        newPosition.z = transform.position.z;
        transform.position = newPosition;
    }
    else
    {
        transform.Translate(p);
    }

}

private Vector3 GetBaseInput()
{ //returns the basic values, if it's 0 than it's not active.
    Vector3 p_Velocity = new Vector3();
    if (Input.GetKey(KeyCode.W))
    {
        if (transform.position.x > 2 && transform.position.x < 53)
        {
            if (transform.position.y > 0 && transform.position.y < 40)
            {
                if (transform.position.z > 5 && transform.position.z < 52)
                {
                    p_Velocity += new Vector3(0, 0, 1);
                }

            }

        }

    }
    if (Input.GetKey(KeyCode.S))
    {
        if (transform.position.x > 2 && transform.position.x < 53)
        {
            if (transform.position.y > 0 && transform.position.y < 40)
            {
                if (transform.position.z > 5 && transform.position.z < 52)
                {
                    p_Velocity += new Vector3(0, 0, -1);
                }

            }

        }

    }
    if (Input.GetKey(KeyCode.A))
    {
        if (transform.position.x > 2 && transform.position.x < 53)
        {
            if (transform.position.y > 0 && transform.position.y < 40)
            {
                if (transform.position.z > 5 && transform.position.z < 52)
                {
                    p_Velocity += new Vector3(-1, 0, 0);
                }

            }

        }

    }
    if (Input.GetKey(KeyCode.D))
    {
        if (transform.position.x > 2 && transform.position.x < 53)
        {
            if (transform.position.y > 0 && transform.position.y < 40)
            {
                if (transform.position.z > 5 && transform.position.z < 52)
                {
                    p_Velocity += new Vector3(1, 0, 0);
                }

            }

        }

    }
    return p_Velocity;

}

}

This flycam isn't mine so if it's not optimal for the use I'm looking for, please notify me about that too.


问:
Clarification on Tensorflow 2.0 Masking
From the Tensorflow documentation when using Keras subclassing API, they give this example on how to pass a mask along to other layers that implement masking. I am wondering if this is explicitly required or if it is handled correctly after the Embedding layer has mask_zero=True.

```<code>class MyLayer(layers.Layer):

  def __init__(self, **kwargs):
    super(MyLayer, self).__init__(**kwargs)
    self.embedding = layers.Embedding(input_dim=5000, output_dim=16, mask_zero=True)
    self.lstm = layers.LSTM(32)

  def call(self, inputs):
    x = self.embedding(inputs)
    # Note that you could also prepare a `mask` tensor manually.
    # It only needs to be a boolean tensor
    # with the right shape, i.e. (batch_size, timesteps).
    mask = self.embedding.compute_mask(inputs)
    output = self.lstm(x, mask=mask)  # The layer will ignore the masked values
    return output

layer = MyLayer()
x = np.random.random((32, 10)) * 100
x = x.astype('int32')
layer(x)
</code>```

My confusion comes from another area of the documentation which states:

Masking

This layer supports masking for input data with a variable number of
  timesteps. To introduce masks to your data, use an Embedding layer
  with the mask_zero parameter set to True.

Which seems to mean that if mask_zero=True no further commands need to be done on subsequent layers.

答:
If you read about the Masking layer, it will also support that once you used the mask at the beginning, all the rest of the layers get the mask automatically.

Quote:

For each timestep in the input tensor (dimension #1 in the tensor), if all values in the input tensor at that timestep are equal to mask_value, then the timestep will be masked (skipped) in all downstream layers (as long as they support masking).

If any downstream layer does not support masking yet receives such an input mask, an exception will be raised.

This other link also states the same. The mask will be propagated to all layers.

Quote:

When using the Functional API or the Sequential API, a mask generated by an Embedding or Masking layer will be propagated through the network for any layer that is capable of using them (for example, RNN layers). Keras will automatically fetch the mask corresponding to an input and pass it to any layer that knows how to use it.

The second link is really full of details on masking.

Notice that the code you showed is for a custom embedding. If teaches you how to "create and pass" a mask, if you want to create a layer that will create a mask. It's basically showing what the normal Embedding layer does.

So, we can conclude that if you're using a normal Embedding layer, all you need is mask_zero=True and everything will go down the stream.

Title: Clarification on Tensorflow 2.0 Masking

Body:
From the Tensorflow documentation when using Keras subclassing API, they give this example on how to pass a mask along to other layers that implement masking. I am wondering if this is explicitly required or if it is handled correctly after the Embedding layer has mask_zero=True.

class MyLayer(layers.Layer):

  def __init__(self, **kwargs):
    super(MyLayer, self).__init__(**kwargs)
    self.embedding = layers.Embedding(input_dim=5000, output_dim=16, mask_zero=True)
    self.lstm = layers.LSTM(32)

  def call(self, inputs):
    x = self.embedding(inputs)
    # Note that you could also prepare a `mask` tensor manually.
    # It only needs to be a boolean tensor
    # with the right shape, i.e. (batch_size, timesteps).
    mask = self.embedding.compute_mask(inputs)
    output = self.lstm(x, mask=mask)  # The layer will ignore the masked values
    return output

layer = MyLayer()
x = np.random.random((32, 10)) * 100
x = x.astype('int32')
layer(x)

My confusion comes from another area of the documentation which states:

Masking

This layer supports masking for input data with a variable number of
  timesteps. To introduce masks to your data, use an Embedding layer
  with the mask_zero parameter set to True.

Which seems to mean that if mask_zero=True no further commands need to be done on subsequent layers.


问:
How to plot this data in ggplot?
This is my data:

```<code>structure(list(Time = c(0L, 2L, 4L, 6L, 8L, 10L, 12L, 14L, 16L,
18L), Volume.1 = c(14L, 14L, 14L, 14L, 14L, 14L, 14L, 14L, 14L,
14L), CO21 = c(0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L), Volume2 = c(13.5,
13.5, 13.5, 13.5, 13.5, 13.5, 13.5, 13.5, 13.5, 13.5), CO22 = c(0L,
0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L), Volume3 = c(13.5, 13.5,
13.5, 13.5, 13, 12.5, 12.5, 12, 12, 11.5), CO23 = c(0, 0, 0,
0, 0.5, 1, 1, 1.5, 1.5, 2), Volume4 = c(13.5, 13.5, 13, 12.5,
12, 11, 9, 7.5, 5.5, 4.5), CO24 = c(0, 0, 0.05, 1, 1.5, 2.5,
4.5, 6, 8, 9)), row.names = c(NA, 10L), class = "data.frame")
</code>```

This is data for yeast fermentation for a bio lab. We were told to use graphing software to plot the data. I need to make a graph that shows the difference in levels over time of CO2 production per tube. Tube 1 = Volume1+CO2, Tube 2 = Volume2+CO22, etc. I'm very new to R and am not sure how to proceed.

Title: How to plot this data in ggplot?

Body:
This is my data:

structure(list(Time = c(0L, 2L, 4L, 6L, 8L, 10L, 12L, 14L, 16L,
18L), Volume.1 = c(14L, 14L, 14L, 14L, 14L, 14L, 14L, 14L, 14L,
14L), CO21 = c(0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L), Volume2 = c(13.5,
13.5, 13.5, 13.5, 13.5, 13.5, 13.5, 13.5, 13.5, 13.5), CO22 = c(0L,
0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L), Volume3 = c(13.5, 13.5,
13.5, 13.5, 13, 12.5, 12.5, 12, 12, 11.5), CO23 = c(0, 0, 0,
0, 0.5, 1, 1, 1.5, 1.5, 2), Volume4 = c(13.5, 13.5, 13, 12.5,
12, 11, 9, 7.5, 5.5, 4.5), CO24 = c(0, 0, 0.05, 1, 1.5, 2.5,
4.5, 6, 8, 9)), row.names = c(NA, 10L), class = "data.frame")

This is data for yeast fermentation for a bio lab. We were told to use graphing software to plot the data. I need to make a graph that shows the difference in levels over time of CO2 production per tube. Tube 1 = Volume1+CO2, Tube 2 = Volume2+CO22, etc. I'm very new to R and am not sure how to proceed.

Body:
Maybe this is what you are looking for? Although, the co2 levels don't really change much across time with each tube so maybe I'm not understanding what you are attempting to graph.

library(tidyverse)

df <- data.frame(Time = c(0L, 2L, 4L, 6L, 8L, 10L, 12L, 14L, 16L, 18L), Volume1 = c(14L, 14L, 14L, 14L, 14L, 14L, 14L, 14L, 14L, 14L), CO21 = c(0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L), Volume2 = c(13.5, 13.5, 13.5, 13.5, 13.5, 13.5, 13.5, 13.5, 13.5, 13.5), CO22 = c(0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L), Volume3 = c(13.5, 13.5, 13.5, 13.5, 13, 12.5, 12.5, 12, 12, 11.5), CO23 = c(0, 0, 0, 0, 0.5, 1, 1, 1.5, 1.5, 2), Volume4 = c(13.5, 13.5, 13, 12.5, 12, 11, 9, 7.5, 5.5, 4.5), CO24 = c(0, 0, 0.05, 1, 1.5, 2.5, 4.5, 6, 8, 9))

df1 <-
  df %>%
  pivot_longer(cols = -Time) %>%
  mutate(name = str_replace(name, "(\\d)$", ",\\1")) %>%
  separate(name, c("name", "tube")) %>%
  group_by(Time, tube) %>%
  summarize(co2 = sum(value))

ggplot(df1, aes(x = Time, y = co2, color = tube)) +
  geom_line() +
  geom_point()


问:
Check if user is an admin vue router and vuex
I am building an app that has an admin area. Users are flagged as admin or not in the database via:

```<code>admin = 1
</code>```

I am pulling my data in using axios, then setting the user in my state using vuex. However, I am struggling how to return the users admin status from within vue router. Here is a sample of what I am trying to do.

```<code>import store from '@/js/store/store.js';
// etc
router.beforeEach((to, from, next) => {
    if(to.matched.some(record => record.meta.isAdmin)) {
        if (store.getters.getUser.admin == 1) {

            next();
            return;
        }

        next('/dashboard');

    } else {
        next();
    }
});
</code>```

So if the user is flagged as admin, they can view the admin area but if not they are redirected to the dashboard.

However, store.getters.getUser.admin == 1 returns undefined.

In my store, I have the below:

```<code>import Vue from 'vue';
import Vuex from 'vuex';
import axios from 'axios';

Vue.use(Vuex);

// set up our api end point
var get_url = window.location;
var base_url = get_url .protocol + '//' + get_url.host;
const api_base = base_url + '/api/v1';

export default new Vuex.Store({
    state: {
        status: false,
        token: localStorage.getItem('token') || '',
        user: {}
    },
    mutations: {
      auth_request(state){
        state.status = 'loading';
      },
      auth_success(state, {token, user}) {
        state.status = 'success';
        state.token = token;
        state.user = user;
      },
      auth_error(state){
        state.status = 'error';
      },
      logout(state){
        state.status = '';
        state.token = '';
      },
      set_user(state, user) {
        state.user = user;
      }
    },
    actions: {
      login({commit}, user){
        return new Promise((resolve, reject) => {
          commit('auth_request');
          axios({url: api_base + '/login', data: user, method: 'post' })
          .then(resp => {
            const token = resp.data.data;
            localStorage.setItem('token', token);
            axios.defaults.headers.common['Authorization'] = token;
            commit('auth_success', {token, token});
            resolve(resp);
          })
          .catch(err => {
            commit('auth_error');
            localStorage.removeItem('token');
            reject(err);
          });
        });
      },
      logout({commit}) {
        return new Promise((resolve, reject) => {
          commit('logout');
          localStorage.removeItem('token');
          delete axios.defaults.headers.common['Authorization'];
          resolve();
        });
      },
      register({commit}, user) {
        return new Promise((resolve, reject) => {
          commit('auth_request');
          axios({url: api_base + '/register', data: user, method: 'post'})
          .then(resp => {
            const token = resp.data.token;
            localStorage.setItem('token', token);
            axios.defaults.headers.common['Authorization'] = token;
            commit('auth_success', {token, token});
            resolve(resp);
          })
          .catch(err => {
            commit('auth_error', err);
            localStorage.removeItem('token');
            reject(err);
          });
        });
      },
      fetchUser({state, commit}) {

        var instance = axios.create({
          baseURL: api_base,
          headers: {
            Accept: 'application/json',
            Authorization: 'Bearer ' + state.token,
            'Content-Type': 'application/json'
          }
        });

        instance.get('/user')
        .then(resp => {
          let user = resp.data;
          commit('set_user', user);
        })
        .catch(err => {
          console.log(err);
          commit('set_user', null);
        });

      }
    },
    getters : {
      isLoggedIn: state => !!state.token,
      authStatus: state => state.status,
      getUser: state => state.user
    }

  });
</code>```

console.log'in state.getters returns the expected data but console logging state.getters.getUser returns undefined.

Is there an easier way to check if the user is an admin?

Thanks

答:
...console logging state.getters.getUser returns undefined.

Are you trying to access getters in state instead of in store?
Does console logging store.getters.getUser make a difference?

Is there an easier way to check if the user is an admin?

I don't know if you'd consider this easier but typically I set up a specific getter for a check like that.

```<code>getters : {
  isLoggedIn: state => !!state.token,
  authStatus: state => state.status,
  getUser: state => state.user,
  isAdmin: state => state.user.admin == 1
}
</code>```

And if non-admin is admin = 0 and admin is admin = 1, then you can simplify it as,

```<code>  isAdmin: state => state.user.admin
</code>```

since 1 resolves to true and 0 to false, you can just use

```<code>if (isAdmin) {
   // allow access
}
</code>```

But then be sure you're storing user.admin as 1 or 0 and not "1" or "0".

Body:
I am building an app that has an admin area. Users are flagged as admin or not in the database via:

admin = 1

I am pulling my data in using axios, then setting the user in my state using vuex. However, I am struggling how to return the users admin status from within vue router. Here is a sample of what I am trying to do.

import store from '@/js/store/store.js';
// etc
router.beforeEach((to, from, next) => {
    if(to.matched.some(record => record.meta.isAdmin)) {
        if (store.getters.getUser.admin == 1) {

            next();
            return;
        }

        next('/dashboard');

    } else {
        next();
    }
});

So if the user is flagged as admin, they can view the admin area but if not they are redirected to the dashboard.

However, store.getters.getUser.admin == 1 returns undefined.

In my store, I have the below:

import Vue from 'vue';
import Vuex from 'vuex';
import axios from 'axios';

Vue.use(Vuex);

// set up our api end point
var get_url = window.location;
var base_url = get_url .protocol + '//' + get_url.host;
const api_base = base_url + '/api/v1';

export default new Vuex.Store({
    state: {
        status: false,
        token: localStorage.getItem('token') || '',
        user: {}
    },
    mutations: {
      auth_request(state){
        state.status = 'loading';
      },
      auth_success(state, {token, user}) {
        state.status = 'success';
        state.token = token;
        state.user = user;
      },
      auth_error(state){
        state.status = 'error';
      },
      logout(state){
        state.status = '';
        state.token = '';
      },
      set_user(state, user) {
        state.user = user;
      }
    },
    actions: {
      login({commit}, user){
        return new Promise((resolve, reject) => {
          commit('auth_request');
          axios({url: api_base + '/login', data: user, method: 'post' })
          .then(resp => {
            const token = resp.data.data;
            localStorage.setItem('token', token);
            axios.defaults.headers.common['Authorization'] = token;
            commit('auth_success', {token, token});
            resolve(resp);
          })
          .catch(err => {
            commit('auth_error');
            localStorage.removeItem('token');
            reject(err);
          });
        });
      },
      logout({commit}) {
        return new Promise((resolve, reject) => {
          commit('logout');
          localStorage.removeItem('token');
          delete axios.defaults.headers.common['Authorization'];
          resolve();
        });
      },
      register({commit}, user) {
        return new Promise((resolve, reject) => {
          commit('auth_request');
          axios({url: api_base + '/register', data: user, method: 'post'})
          .then(resp => {
            const token = resp.data.token;
            localStorage.setItem('token', token);
            axios.defaults.headers.common['Authorization'] = token;
            commit('auth_success', {token, token});
            resolve(resp);
          })
          .catch(err => {
            commit('auth_error', err);
            localStorage.removeItem('token');
            reject(err);
          });
        });
      },
      fetchUser({state, commit}) {

        var instance = axios.create({
          baseURL: api_base,
          headers: {
            Accept: 'application/json',
            Authorization: 'Bearer ' + state.token,
            'Content-Type': 'application/json'
          }
        });

        instance.get('/user')
        .then(resp => {
          let user = resp.data;
          commit('set_user', user);
        })
        .catch(err => {
          console.log(err);
          commit('set_user', null);
        });

      }
    },
    getters : {
      isLoggedIn: state => !!state.token,
      authStatus: state => state.status,
      getUser: state => state.user
    }

  });

console.log'in state.getters returns the expected data but console logging state.getters.getUser returns undefined.

Is there an easier way to check if the user is an admin?

Thanks

Body:
...console logging state.getters.getUser returns undefined.

Are you trying to access getters in state instead of in store?
Does console logging store.getters.getUser make a difference?

Is there an easier way to check if the user is an admin?

I don't know if you'd consider this easier but typically I set up a specific getter for a check like that.

getters : {
  isLoggedIn: state => !!state.token,
  authStatus: state => state.status,
  getUser: state => state.user,
  isAdmin: state => state.user.admin == 1
}

And if non-admin is admin = 0 and admin is admin = 1, then you can simplify it as,

  isAdmin: state => state.user.admin

since 1 resolves to true and 0 to false, you can just use

if (isAdmin) {
   // allow access
}

But then be sure you're storing user.admin as 1 or 0 and not "1" or "0".


问:
jenkins pipeline script close() getting called without executing Closure
The following Jenkins pipeline script does not execute the code in the Closure.

```<code>class MyClass implements Closeable, Serializable {
    private final script

    MyClass(final script) {
        this.script = script
        this.script.echo "In MyClass()"
    }

    @Override
    public void close() throws Exception {
        this.script.echo "In MyClass.close()"
    }
}

def sdk = new MyClass(this).withCloseable {
    println "In Closure ..."
}

println "Done"
</code>```

```<code>This is the output:
[Pipeline] Start of Pipeline
[Pipeline] echo
In MyClass()
[Pipeline] echo
In MyClass.close()
[Pipeline] echo
Done
[Pipeline] End of Pipeline
Finished: SUCCESS
</code>```

Note that there is no "InClosure ..." string.
I had to approve the signature: method groovy.lang.GroovyObject invokeMethod java.lang.String java.lang.Object in order to run the above script.

答:
Short version:

I believe that the groovy version included with your Jenkins install does not support .withCloseable. Specifically, note that many Jenkins installs only have groovy version 1.8.9. Groovy didn't add the automatic withCloseable stuff until version 2, I think.

Longer:

You should not have approved the signature groovy.lang.GroovyObject invokeMethod java.lang.String java.lang.Object. Go and unapprove it, because it's not doing you any good, will potentially hide other errors/make them harder to track down, and is a security hole if you have non-admin developers submitting jobs to your Jenkins instance.

The interaction of groovy and Jenkins has an annoying little UI failure: if you try to invoke a method on an object that does not have that method, and the object's class is written in Groovy, you'll get a "Scripts not permitted to use method" error referring to groovy.lang.GroovyObject invokeMethod java.lang.String java.lang.Object. Not a NoSuchMethodException, not a helpful message about a bad method name, but a security error.

If you get that error message specifically referring to groovy.lang.GroovyObject invokeMethod, it usually means "you have invoked a method that doesn't exist". In this case, I believe it was because the groovy installed on your Jenkins instance is too old and doesn't automatically add withCloseable to classes that implement Closeable.

Body:
The following Jenkins pipeline script does not execute the code in the Closure.

class MyClass implements Closeable, Serializable {
    private final script

    MyClass(final script) {
        this.script = script
        this.script.echo "In MyClass()"
    }

    @Override
    public void close() throws Exception {
        this.script.echo "In MyClass.close()"
    }
}

def sdk = new MyClass(this).withCloseable {
    println "In Closure ..."
}

println "Done"

This is the output:
[Pipeline] Start of Pipeline
[Pipeline] echo
In MyClass()
[Pipeline] echo
In MyClass.close()
[Pipeline] echo
Done
[Pipeline] End of Pipeline
Finished: SUCCESS

Note that there is no "InClosure ..." string.
I had to approve the signature: method groovy.lang.GroovyObject invokeMethod java.lang.String java.lang.Object in order to run the above script.


问:
How to hit URL with parameters within an API
How to pass parameters to an url for get request in python?

Suppose this is my url:

```<code>url = "http://105.119.2.20/data/personal/get/Id/<Id>/empId/<empId>/org_id/<orgId>"
</code>```

I have to pass three parameters to this url:

Id

empId

orgId

I want to know how would be the syntax of passing paramaters to hit this url. Whether to pass through dictionary or by variable?

```<code>r = request.get(url)
</code>```

答:
Just pass it as a dict to params arg

```<code>import requests

response = requests.get("http://example.com/some/api/blah", params={"id": 1, "empId": 2, "orgId": 3})
</code>```

Body:
How to pass parameters to an url for get request in python?

Suppose this is my url:

url = "http://105.119.2.20/data/personal/get/Id/<Id>/empId/<empId>/org_id/<orgId>"

I have to pass three parameters to this url:

Id

empId

orgId

I want to know how would be the syntax of passing paramaters to hit this url. Whether to pass through dictionary or by variable?

r = request.get(url)

Body:
Just pass it as a dict to params arg

import requests

response = requests.get("http://example.com/some/api/blah", params={"id": 1, "empId": 2, "orgId": 3})


问:
My access VBA code for creating excel files with data connections works on the first file then always fails at random points
I have written some code in Access to copy an excel template file, perform some refresh and simple transsformations on the copy, save, and then move to the next file.  Initially i could create multiple files by looping through a list but kept getting odd errors on random lines during subsequent iterations.  I've avoided Active anything as that seems to be problematic, but still the code fails on the second iteration.  Mostly its on the Connection.Refresh but sometimes it is other lines such as "Method Rows of object Global failed".  I'm fairly experienced on this.  I also tried setting all my vba excel objects to nothing at the end of each loop but that didnt help.  Code below.  Any ideas gratefully recieved:</p>

```<code>Sub CreateFilesIndividual()

     Dim mw As Variant
     Dim ccount As Integer
     Dim rs As Recordset
     Dim i As Integer

     Set rs = CurrentDb.OpenRecordset("SELECT CM1920 as CM from Comm1920 order by rscount desc", dbOpenSnapshot)
     If rs.RecordCount = 0 Then
         MsgBox "No Commissioners Codes available - exiting"
         Exit Sub
     End If

     For i = 1 To rs.RecordCount
         CreateFile rs("CM")
     Next

End Sub

Sub CreateFile(commCode)

     Dim templateloc As String
     Dim fileloc As String
     Dim Xl As Excel.Application
     Dim wb As Excel.Workbook
     Dim ws As Excel.Worksheet
     Dim ws2 As Excel.Worksheet
     Dim ws3 As Excel.Worksheet
     Dim ws4 As Excel.Worksheet

     templateloc = "\\gstt.local\Users\01\MWaring\Documents\Bespoke Report Requests\Contracts automation\Proposal template CCGs 2021 v2.6.xlsm"
     fileloc = "\\gstt.local\Users\01\MWaring\Documents\Bespoke Report Requests\Contracts automation\test\Proposal CCGs 1920 v2.6 " & commCode & ".xlsm"

     FileCopy templateloc, fileloc
    '
     Set Xl = CreateObject("Excel.Application")
     Set wb = Xl.Workbooks.Open(fileloc)
     Set ws = wb.Sheets("Commissioner Summary")
     ws.Unprotect
     ws.Cells(2, 4) = commCode.Value
     Debug.Print ws.Cells(2, 4).Value & " - " & commCode.Value
     wb.Connections("Update1").Refresh
     Set ws2 = wb.Sheets("Contract Category Detail")
     ws2.Range("A:AM").Copy

     Set ws3 = wb.Sheets("CC detail")
     ws3.Range("A1").PasteSpecial Paste:=xlPasteColumnWidths
     ws3.Range("A1").PasteSpecial Paste:=xlPasteFormats
     ws3.Range("A1").PasteSpecial Paste:=xlPasteValuesAndNumberFormats, Operation:= _
    xlNone, SkipBlanks:=False, Transpose:=False

    ws3.Range("AG3").FormulaR1C1 = "=ROUND(RC[-2]+RC[-1],0)"
    Dim myrange As Integer
    myrange = ws3.Range("A" & Rows.Count).End(xlUp).Row
    ws3.Range("AG3:AG" & myrange).FillDown

    ws3.Range("AL3").FormulaR1C1 = "=RC[-5]*RC34"
    ws3.Range("AL3:AL" & myrange).FillDown
    ws3.Range("A:AM").Copy

    Set ws4 = wb.Sheets("Contract_Category_detail")
    ws4.Range("A1").PasteSpecial Paste:=xlPasteColumnWidths
    ws4.Range("A1").PasteSpecial Paste:=xlPasteFormats
    ws4.Range("A1").PasteSpecial Paste:=xlPasteValuesAndNumberFormats, Operation:= _
    xlNone, SkipBlanks:=False, Transpose:=False

    ws2.Delete
    ws3.Delete

    wb.Save
    wb.Close

    'Clean up
    Xl.Quit
    Set ws = Nothing
    Set ws2 = Nothing
    Set ws3 = Nothing
    Set ws4 = Nothing
    Set wb = Nothing
    Set Xl = Nothing

End Sub
</code>```

答:
I think I had a strange error (probably the same) when I performed lots of copy-paste operations with Excel from Access. Than I created a function ClearClipboard() which I call after all such operation. Here it is:

Private Declare Function OpenClipboard Lib "user32" (ByVal hWnd As Long) As Long
Private Declare Function CloseClipboard Lib "user32" () As Long
Private Declare Function EmptyClipboard Lib "user32" () As Long

Public Function ClearClipboard()
    OpenClipboard (0&)
    EmptyClipboard
    CloseClipboard
End Function
```

Try it. I hope it helps.

Body:
I have written some code in Access to copy an excel template file, perform some refresh and simple transsformations on the copy, save, and then move to the next file.  Initially i could create multiple files by looping through a list but kept getting odd errors on random lines during subsequent iterations.  I've avoided Active anything as that seems to be problematic, but still the code fails on the second iteration.  Mostly its on the Connection.Refresh but sometimes it is other lines such as "Method Rows of object Global failed".  I'm fairly experienced on this.  I also tried setting all my vba excel objects to nothing at the end of each loop but that didnt help.  Code below.  Any ideas gratefully recieved:

Sub CreateFilesIndividual()

     Dim mw As Variant
     Dim ccount As Integer
     Dim rs As Recordset
     Dim i As Integer

     Set rs = CurrentDb.OpenRecordset("SELECT CM1920 as CM from Comm1920 order by rscount desc", dbOpenSnapshot)
     If rs.RecordCount = 0 Then
         MsgBox "No Commissioners Codes available - exiting"
         Exit Sub
     End If

     For i = 1 To rs.RecordCount
         CreateFile rs("CM")
     Next

End Sub

Sub CreateFile(commCode)

     Dim templateloc As String
     Dim fileloc As String
     Dim Xl As Excel.Application
     Dim wb As Excel.Workbook
     Dim ws As Excel.Worksheet
     Dim ws2 As Excel.Worksheet
     Dim ws3 As Excel.Worksheet
     Dim ws4 As Excel.Worksheet

     templateloc = "\\gstt.local\Users\01\MWaring\Documents\Bespoke Report Requests\Contracts automation\Proposal template CCGs 2021 v2.6.xlsm"
     fileloc = "\\gstt.local\Users\01\MWaring\Documents\Bespoke Report Requests\Contracts automation\test\Proposal CCGs 1920 v2.6 " & commCode & ".xlsm"

     FileCopy templateloc, fileloc
    '
     Set Xl = CreateObject("Excel.Application")
     Set wb = Xl.Workbooks.Open(fileloc)
     Set ws = wb.Sheets("Commissioner Summary")
     ws.Unprotect
     ws.Cells(2, 4) = commCode.Value
     Debug.Print ws.Cells(2, 4).Value & " - " & commCode.Value
     wb.Connections("Update1").Refresh
     Set ws2 = wb.Sheets("Contract Category Detail")
     ws2.Range("A:AM").Copy

     Set ws3 = wb.Sheets("CC detail")
     ws3.Range("A1").PasteSpecial Paste:=xlPasteColumnWidths
     ws3.Range("A1").PasteSpecial Paste:=xlPasteFormats
     ws3.Range("A1").PasteSpecial Paste:=xlPasteValuesAndNumberFormats, Operation:= _
    xlNone, SkipBlanks:=False, Transpose:=False

    ws3.Range("AG3").FormulaR1C1 = "=ROUND(RC[-2]+RC[-1],0)"
    Dim myrange As Integer
    myrange = ws3.Range("A" & Rows.Count).End(xlUp).Row
    ws3.Range("AG3:AG" & myrange).FillDown

    ws3.Range("AL3").FormulaR1C1 = "=RC[-5]*RC34"
    ws3.Range("AL3:AL" & myrange).FillDown
    ws3.Range("A:AM").Copy

    Set ws4 = wb.Sheets("Contract_Category_detail")
    ws4.Range("A1").PasteSpecial Paste:=xlPasteColumnWidths
    ws4.Range("A1").PasteSpecial Paste:=xlPasteFormats
    ws4.Range("A1").PasteSpecial Paste:=xlPasteValuesAndNumberFormats, Operation:= _
    xlNone, SkipBlanks:=False, Transpose:=False

    ws2.Delete
    ws3.Delete

    wb.Save
    wb.Close

    'Clean up
    Xl.Quit
    Set ws = Nothing
    Set ws2 = Nothing
    Set ws3 = Nothing
    Set ws4 = Nothing
    Set wb = Nothing
    Set Xl = Nothing

End Sub

Body:
I think I had a strange error (probably the same) when I performed lots of copy-paste operations with Excel from Access. Than I created a function ClearClipboard() which I call after all such operation. Here it is:

Private Declare Function OpenClipboard Lib "user32" (ByVal hWnd As Long) As Long
Private Declare Function CloseClipboard Lib "user32" () As Long
Private Declare Function EmptyClipboard Lib "user32" () As Long

Public Function ClearClipboard()
    OpenClipboard (0&)
    EmptyClipboard
    CloseClipboard
End Function

Try it. I hope it helps.


问:
is this correct re returning a date re memory management?
is this correct re returning a date re memory management?

The assumption here I have is I want to return a date back to the caller, but I don't want the caller to be able to be change the date and impact the method's date, hence I thought I would return a copy.

So the code in the method I have is:

```<code>- (NSDate*)dateForMyTest {
     return [[self.endDate copy] autorelease];
}
</code>```

I was assuming I have to autorelease it so the caller doesn't have to, as they would not have called an init/copy/etc themselves.

答: You are correct, as far as it goes. But note that NSDate is immutable, so there is really no reason not to just return self.endDate.

ContentLicense: CC BY-SA 3.0

Body:
is this correct re returning a date re memory management?

The assumption here I have is I want to return a date back to the caller, but I don't want the caller to be able to be change the date and impact the method's date, hence I thought I would return a copy.

So the code in the method I have is:

- (NSDate*)dateForMyTest {
     return [[self.endDate copy] autorelease];
}

I was assuming I have to autorelease it so the caller doesn't have to, as they would not have called an init/copy/etc themselves.


问:
Using || and && in a for loop
So when I was trying to set up my loop conditions to be for(char input = ' '; input != 'X' || input != 'E';) it wouldn't exit out the loop with either 'X' or 'E'. I was just wondering why something like for(char input = ' '; input != 'X' && input != 'E';) does work ?

答:
That's because true || false is true (but true && false is false).

So,

when you try to exit by passing X, the condition is effectively true because it is not E;

when you try to exit by passing E, the condition is effectively true because it is not X.

Hence, the loop continues and doesn't exit.

Title: Using || and && in a for loop


问:
How can you add paragraphs using a Direct SQL call in Postgres
Using direct SQL (as that's all I have access to) I've tried to use this query but the output doesn't add a new line...

```<code>SELECT ('LINE 1' || CHR(13) || 'LINE 4') AS column_name;

Output:
column_name
LINE 1 LINE 4
</code>```

Does anyone know how to add a new line using Direct SQL?

答:
You will generally need char(10) not char(13).  Or if you are displaying your information directly in HTML, you will need '
'.

Body:
Using direct SQL (as that's all I have access to) I've tried to use this query but the output doesn't add a new line...

SELECT ('LINE 1' || CHR(13) || 'LINE 4') AS column_name;

Output:
column_name
LINE 1 LINE 4

Does anyone know how to add a new line using Direct SQL?

Body: You will generally need char(10) not char(13).  Or if you are displaying your information directly in HTML, you will need '<br>'.


问:
Powershell looping through files to pass to a program as a parameter
I have the following two cmd.exe commands, but I need to convert them to Powershell, and I've failed miserably trying to figure it out. Line 1 is finding a dll, but only when in a bin folder and line two then takes all the entries it finds and runs a command with it, e.g. bin\Debug\file, bin\Release\file

Can anyone help? The only limitation is this is inside a yaml runner file so I don't think I can split lines for each part, e.g. I don't think a Foreach-Object will work.

```<code>dir /s /b RunnerUnitTest.dll | findstr /r bin\\ > tests_list.txt
for /f %f in (tests_list.txt) do vstest.console.exe "%f"
</code>```

I got as far as this

```<code>(gci -r RunnerUnitTest.dll).FullName | select-string bin
</code>```

thanks.

答:
A single command (pipeline), spread across 3 lines for readability, using built-in command aliases for brevity (but the parameter names are spelled out, for long-term robustness):

```<code>gci -Recurse -Filter RunnerUnitTest.dll |
  ? FullName -match bin\\ |
    % { vstest.console.exe $_.FullName }
</code>```

gci -Recurse -Filter RunnerUnitTest.dll finds all RunnerUnitTest.dll in the current directory's subtree; -Filter makes for faster matching than using the (positionally implied) -Path parameter.

? FullName -match bin\\ uses ? (Where-Object) to test the .FullName (full path) property values of the input file-info objects for matching regex bin\\, i.e. for a literal bin\ substring, and only passes matching file-info objects on.

% { vstest.console.exe $_.FullName } uses % (ForEach-Object) to invoke vstest.console.exe with each matching file's full path.

Note that no intermediate file with a list of DLLs to process is created, because it isn't necessary.

If you need to pass the above to an explicit invocation of the PowerShell CLI, you'd do:

```<code>powershell -noprofile -command "gci -Recurse -Filter RunnerUnitTest.dll | ? FullName -match bin\\ | % { vstest.console.exe $_.FullName }"
</code>```

If you're using PowerShell [Core] 6+, substitute pwsh for powershell.

Body:
I have the following two cmd.exe commands, but I need to convert them to Powershell, and I've failed miserably trying to figure it out. Line 1 is finding a dll, but only when in a bin folder and line two then takes all the entries it finds and runs a command with it, e.g. bin\Debug\file, bin\Release\file

Can anyone help? The only limitation is this is inside a yaml runner file so I don't think I can split lines for each part, e.g. I don't think a Foreach-Object will work.

dir /s /b RunnerUnitTest.dll | findstr /r bin\\ > tests_list.txt
for /f %f in (tests_list.txt) do vstest.console.exe "%f"

I got as far as this

(gci -r RunnerUnitTest.dll).FullName | select-string bin

thanks.

Body:
A single command (pipeline), spread across 3 lines for readability, using built-in command aliases for brevity (but the parameter names are spelled out, for long-term robustness):

gci -Recurse -Filter RunnerUnitTest.dll |
  ? FullName -match bin\\ |
    % { vstest.console.exe $_.FullName }

gci -Recurse -Filter RunnerUnitTest.dll finds all RunnerUnitTest.dll in the current directory's subtree; -Filter makes for faster matching than using the (positionally implied) -Path parameter.

? FullName -match bin\\ uses ? (Where-Object) to test the .FullName (full path) property values of the input file-info objects for matching regex bin\\, i.e. for a literal bin\ substring, and only passes matching file-info objects on.

% { vstest.console.exe $_.FullName } uses % (ForEach-Object) to invoke vstest.console.exe with each matching file's full path.

Note that no intermediate file with a list of DLLs to process is created, because it isn't necessary.

If you need to pass the above to an explicit invocation of the PowerShell CLI, you'd do:

powershell -noprofile -command "gci -Recurse -Filter RunnerUnitTest.dll | ? FullName -match bin\\ | % { vstest.console.exe $_.FullName }"

If you're using PowerShell [Core] 6+, substitute pwsh for powershell.


Title: Extract mean from categorical data type column

Body:
For example have this table:

list_1=[['1','y',474.0],
        ['2','n',482.0],
       ['3','n',564.0,],
       ['4','y',549.0,],
       ['5','y',551.0,],
       ['6','y',555.0,],
       ['7','n',600.0,],
       ['8','y',357.0,],
       ['9','y',542.0,],
       ['10','n',462.0,],
       ['11','n',513.0,],
       ['12','y',526.0,]]
labels=['id','order_?','hours_spend']
df=pd.DataFrame(list_1,columns=labels)
df

Result:

    id  order_? hours_spend
0   1   y        474.0
1   2   n        482.0
2   3   n        564.0
3   4   y        549.0
4   5   y        551.0
5   6   y        555.0
6   7   n        600.0
7   8   y        357.0
8   9   y        542.0
9   10  n        462.0
10  11  n        513.0
11  12  y        526.0

I'm going to divide the hours_spend column to 3 groups with NTILE method without lables:

df['ntile']=pd.qcut(df['hours_spend'],3)
df

Result:

id  order_? hours_spend      ntile
0   1   y   474.0        (356.999, 502.667]
1   2   n   482.0        (356.999, 502.667]
2   3   n   564.0        (549.667, 600.0]
3   4   y   549.0        (502.667, 549.667]
4   5   y   551.0        (549.667, 600.0]
5   6   y   555.0        (549.667, 600.0]
6   7   n   600.0        (549.667, 600.0]
7   8   y   357.0        (356.999, 502.667]
8   9   y   542.0        (502.667, 549.667]
9   10  n   462.0        (356.999, 502.667]
10  11  n   513.0        (502.667, 549.667]
11  12  y   526.0        (502.667, 549.667]

Now i have column 'ntile' with data type 'category':

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 12 entries, 0 to 11
Data columns (total 4 columns):
id             12 non-null object
order_?        12 non-null object
hours_spend    12 non-null float64
ntile          12 non-null category
dtypes: category(1), float64(1), object(2)
memory usage: 556.0+ bytes

How I can add new column with mean of range in 'ntile' column ??

Body:
You can simply define it as:

df['mean_ntile'] = (df['ntile'].apply(lambda x: x.left).astype(int) + df['ntile'].apply(lambda x: x.right).astype(int))/2
print(df)

Output:

    id order_?  hours_spend               ntile  mean_ntile
0    1       y        474.0  (356.999, 502.667]       429.0
1    2       n        482.0  (356.999, 502.667]       429.0
2    3       n        564.0    (549.667, 600.0]       574.5
3    4       y        549.0  (502.667, 549.667]       525.5
4    5       y        551.0    (549.667, 600.0]       574.5
5    6       y        555.0    (549.667, 600.0]       574.5
6    7       n        600.0    (549.667, 600.0]       574.5
7    8       y        357.0  (356.999, 502.667]       429.0
8    9       y        542.0  (502.667, 549.667]       525.5
9   10       n        462.0  (356.999, 502.667]       429.0
10  11       n        513.0  (502.667, 549.667]       525.5
11  12       y        526.0  (502.667, 549.667]       525.5

As @ALlolz suggested an easier way is:

df['mean_ntile'] = df['ntile'].apply(lambda x: x.mid)


问:
How to update "select-editable" value through other html elements
I have a web application which has a zoom-in, zoom-out and zoom-by feature, which I have implemented as below :

HTML

```<code><ul class="canvas-zoom">
    <li id="id_zoom_in"><span class="icon-Icon-ZoomIn"></span><span class="lblText">Zoom In</span></li>
    <li id="id_zoom_out"><span class="icon-Icon-ZoomOut"></span><span class="lblText">Zoom Out</span>
    </li>
    <li>
        <div class="select-editable">
            <select id="id_zoom_select" class="zoom-combo-box" >
                <option value="25">25%</option>
                <option value="50">50%</option>
                <option value="66">66%</option>
                <option value="75">75%</option>
                <option value="100">100%</option>
                <option value="Fit" selected>Fit</option>
            </select>
            <input type="text" id="id_zoom_text" value="" maxlength="4" />
        </div>

        <span class="lblText">Zoom By</span>
    </li>
</ul>
</code>```

JS

```<code>  zoom: function (event) {
        var textElem = $('.canvas-zoom #id_zoom_text'),
            selectElem = $('.canvas-zoom #id_zoom_select');

        if (this.id == "id_zoom_in") {

            var zoom_in = parseInt(textElem.val()) + 10;
            console.log("value of zoom is : " + zoom_in );
            textElem.val(zoom_in + "%");
            selectElem.val(zoom_in);
            console.log("value of zoom by should be : " + textElem.val());
            textElem.trigger('change');
        }
        else if (this.id == "id_zoom_out") {
            var zoom_out = parseInt(textElem.val()) - 10;
            console.log("value of zoom is : " + zoom_out );
            textElem.val(zoom_out + "%");
            selectElem.val(zoom_out);
            textElem.trigger('change');
        }
        else if (this.id == "id_zoom_select") {
            var zoomValue = $(this).val();
            textElem.val(zoomValue + "%");
            textElem.trigger('change');
        }
        else if (this.id == "id_zoom_text") {
            var percent = textElem.val();
            //validate the input text
            if (/^[0-9%]+$/.test(percent) && percent.indexOf("%") !== 0) {
                var symbolCount = percent.match(/%/g) || [].length;
                //append % if only numeric is entered
                if (symbolCount == 0)
                    textElem.val(percent + "%");
                percent = parseInt(percent);
                if (percent < ZOOM_MIN)
                    percent = ZOOM_MIN;
                //else if (percent > ZOOM_MAX)
                //    percent = ZOOM_MAX
            }
            else
                percent = ZOOM_MAX;

            textElem.val(percent + "%");
            selectElem.val(percent);
            ContentEditor.setCanvasArea(percent);

        }
    }
</code>```

I am able to select the zoom percentage from zoom-by like so :

However, when I hit zoom-in or zoom-out, the zoom-by text doesn't update, unless the zoom-in/out percentage coincides with one of the preset options in the html code [25,50,66,75,100, "Fit"]

I was able to add some console.log to verify that if the zoom-in/out percentage is not one of the presets the text in zoom-by doesn't change. Ideally I would like that if the zoom-in increases the zoom percentage to 72% then the zoom-by text should show that value instead of a blank, as shown in the screenshot.

Is there a way I can implement the functionality I want to? Thanks in advance!

答:
You can zoom process with CSS & jQuery

/* scale : 1 is no zoom */
function zoomElement(element, scale){
  var originZoom = parseInt($(element).css("transform").match(/scale\ +\((\d)\)/m) || 1);
  var originWidth = $(element).width / originZoom;
  var originHeight = $(element).height / originZoom;
  $(element).css({
    transform:"scale("+scale+")",
    "transform-origin":"left top",
    width: (100/scale)+"%",
    height:(originHeight/scale)+"px"
  });
}

function zoom(z){
 zoomElement($("div"),z);
}```
<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>
<button onclick="zoom(.5)">0.5</button>
<button onclick="zoom(1)">1</button>
<button onclick="zoom(2)">2</button>
<button onclick="zoom(5)">5</button>
<div style="">
Hello World. This is zoom text example
</div></code>```

Body:
I have a web application which has a zoom-in, zoom-out and zoom-by feature, which I have implemented as below :

HTML

Zoom In

Zoom Out

            <select id="id_zoom_select" class="zoom-combo-box" >
                <option value="25">25%</option>
                <option value="50">50%</option>
                <option value="66">66%</option>
                <option value="75">75%</option>
                <option value="100">100%</option>
                <option value="Fit" selected>Fit</option>
            </select>
            <input type="text" id="id_zoom_text" value="" maxlength="4" />

        Zoom By

JS

  zoom: function (event) {
        var textElem = $('.canvas-zoom #id_zoom_text'),
            selectElem = $('.canvas-zoom #id_zoom_select');

        if (this.id == "id_zoom_in") {

            var zoom_in = parseInt(textElem.val()) + 10;
            console.log("value of zoom is : " + zoom_in );
            textElem.val(zoom_in + "%");
            selectElem.val(zoom_in);
            console.log("value of zoom by should be : " + textElem.val());
            textElem.trigger('change');
        }
        else if (this.id == "id_zoom_out") {
            var zoom_out = parseInt(textElem.val()) - 10;
            console.log("value of zoom is : " + zoom_out );
            textElem.val(zoom_out + "%");
            selectElem.val(zoom_out);
            textElem.trigger('change');
        }
        else if (this.id == "id_zoom_select") {
            var zoomValue = $(this).val();
            textElem.val(zoomValue + "%");
            textElem.trigger('change');
        }
        else if (this.id == "id_zoom_text") {
            var percent = textElem.val();
            //validate the input text
            if (/^[0-9%]+$/.test(percent) && percent.indexOf("%") !== 0) {
                var symbolCount = percent.match(/%/g) || [].length;
                //append % if only numeric is entered
                if (symbolCount == 0)
                    textElem.val(percent + "%");
                percent = parseInt(percent);
                if (percent < ZOOM_MIN)
                    percent = ZOOM_MIN;
                //else if (percent > ZOOM_MAX)
                //    percent = ZOOM_MAX
            }
            else
                percent = ZOOM_MAX;

            textElem.val(percent + "%");
            selectElem.val(percent);
            ContentEditor.setCanvasArea(percent);

        }
    }

I am able to select the zoom percentage from zoom-by like so :

However, when I hit zoom-in or zoom-out, the zoom-by text doesn't update, unless the zoom-in/out percentage coincides with one of the preset options in the html code [25,50,66,75,100, "Fit"]

I was able to add some console.log to verify that if the zoom-in/out percentage is not one of the presets the text in zoom-by doesn't change. Ideally I would like that if the zoom-in increases the zoom percentage to 72% then the zoom-by text should show that value instead of a blank, as shown in the screenshot.

Is there a way I can implement the functionality I want to? Thanks in advance!

Body:
You can zoom process with CSS & jQuery

/* scale : 1 is no zoom */
function zoomElement(element, scale){
  var originZoom = parseInt($(element).css("transform").match(/scale\ +\((\d)\)/m) || 1);
  var originWidth = $(element).width / originZoom;
  var originHeight = $(element).height / originZoom;
  $(element).css({
    transform:"scale("+scale+")",
    "transform-origin":"left top",
    width: (100/scale)+"%",
    height:(originHeight/scale)+"px"
  });
}

function zoom(z){
 zoomElement($("div"),z);
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button onclick="zoom(.5)">0.5</button>
<button onclick="zoom(1)">1</button>
<button onclick="zoom(2)">2</button>
<button onclick="zoom(5)">5</button>
<div style="">
Hello World. This is zoom text example
</div>


问:
How can I point this string to the structure?
```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

    typedef struct{
    char firstName[20];
    char lastName[20];
    int id;
    char gender[10];
    int monthOfBirth;
    int dayOfBirth;
    int yearOfBirth;
    } HealthProfile;

void setName(HealthProfile *HP) {
    char firstName;
    char lastName;
    printf("Enter your first and last name: ");
    scanf("%s" "%s", &firstName, &lastName);
    HP->firstName = firstName;
    HP->lastName = lastName;
}

void setID(HealthProfile *HP) {
    int id;
    printf("Enter ID: ");
    scanf("%d", &id);
    HP->id = id;
}

void setGender(HealthProfile *HP) {
    char gender;
    // HealthProfile hp;
   // strcpy(hp.gender, &gender);
    printf("Enter your gender: ");
    scanf("%s", &gender);

    HP->gender = gender;

}
void setBD(HealthProfile *HP) {
    int monthOfBirth;
    int dayOfBirth;
    int yearOfBirth;
    printf("Enter your month of birth, day of birth and year of birth: ");
    scanf("%d" "%d" "%d", &monthOfBirth, &dayOfBirth, &yearOfBirth);
    HP->monthOfBirth = monthOfBirth;
    HP->dayOfBirth = dayOfBirth;
    HP->yearOfBirth = yearOfBirth;
}

int main(){
    // pointer declared to HealthProfile structure
    HealthProfile *HP;
    // pointer initialized using malloc
    HP = (HealthProfile*) malloc(sizeof(HealthProfile));

// Calls various functions

    setID(HP);
    setGender(HP);
    setName(HP);
    setBD(HP);

    // Creates your profile
    printf("Creating your Health Profile! \n");
    printf("Profile created for: %s\n", HP->firstName);
    printf("Lastname: %s\n", HP->lastName);
    // prints ID
    printf("ID: %d\n", HP->id);
    printf("Gender: %s\n", HP->gender);
    printf("Month of birth: %d\n", HP->monthOfBirth);
    printf("day of birth: %d\n", HP->dayOfBirth);
    printf("year of birth: %d\n", HP->yearOfBirth);
}
</code>```

What I am trying to do is assign HP to  a string but I get this error.

```<code>array type 'char [10]' is not assignable
    HP->gender = gender;
</code>```

(same error with first and last name of course) So I searched online and found out that char can't be assigned and strcpy should be used instead. As you can see by my failed attempt in the gender function.

Can someone help me fix my errors? Thanks

答: actually I think that you should not using Assignment for string and array .Instead you  should use strcpy and include string.h library.</p>

Body:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

    typedef struct{
    char firstName[20];
    char lastName[20];
    int id;
    char gender[10];
    int monthOfBirth;
    int dayOfBirth;
    int yearOfBirth;
    } HealthProfile;

void setName(HealthProfile *HP) {
    char firstName;
    char lastName;
    printf("Enter your first and last name: ");
    scanf("%s" "%s", &firstName, &lastName);
    HP->firstName = firstName;
    HP->lastName = lastName;
}

void setID(HealthProfile *HP) {
    int id;
    printf("Enter ID: ");
    scanf("%d", &id);
    HP->id = id;
}

void setGender(HealthProfile *HP) {
    char gender;
    // HealthProfile hp;
   // strcpy(hp.gender, &gender);
    printf("Enter your gender: ");
    scanf("%s", &gender);

    HP->gender = gender;

}
void setBD(HealthProfile *HP) {
    int monthOfBirth;
    int dayOfBirth;
    int yearOfBirth;
    printf("Enter your month of birth, day of birth and year of birth: ");
    scanf("%d" "%d" "%d", &monthOfBirth, &dayOfBirth, &yearOfBirth);
    HP->monthOfBirth = monthOfBirth;
    HP->dayOfBirth = dayOfBirth;
    HP->yearOfBirth = yearOfBirth;
}

int main(){
    // pointer declared to HealthProfile structure
    HealthProfile *HP;
    // pointer initialized using malloc
    HP = (HealthProfile*) malloc(sizeof(HealthProfile));

// Calls various functions

    setID(HP);
    setGender(HP);
    setName(HP);
    setBD(HP);

    // Creates your profile
    printf("Creating your Health Profile! \n");
    printf("Profile created for: %s\n", HP->firstName);
    printf("Lastname: %s\n", HP->lastName);
    // prints ID
    printf("ID: %d\n", HP->id);
    printf("Gender: %s\n", HP->gender);
    printf("Month of birth: %d\n", HP->monthOfBirth);
    printf("day of birth: %d\n", HP->dayOfBirth);
    printf("year of birth: %d\n", HP->yearOfBirth);
}

What I am trying to do is assign HP to  a string but I get this error.

array type 'char [10]' is not assignable
    HP->gender = gender;

(same error with first and last name of course) So I searched online and found out that char can't be assigned and strcpy should be used instead. As you can see by my failed attempt in the gender function.

Can someone help me fix my errors? Thanks


问:
Unable to build IdentityServer4 on Windows 10 machine
I am getting the error message "exited with code -532462766" when I attempt to build IdentityServer4.  The error appears to be happening inside the "MinVer" Nuget package.

I downloaded the IdentityServer4 zip file onto a Windows 10 machine from the github site at https://github.com/IdentityServer/IdentityServer4 and unzipped it into a local directory, then followed the directions, which are:

Download the latest .Net Core SDK.  I already had the latest sdk installed, but after getting the errors in the "MinVer" nuget package (see below) I decided to download a couple of older version as well.   My C:\Program Files\dotnet folder contains the following sub-folders in the "sdk" folder:

2.1.202

2.1.803

2.2.108

3.0.101

3.1.100

3.1.101

Run build.ps1 in the root directory.  Build.ps1 does a nuget restore and then executes 5 other build files, this is the contents:

```<code>$ErrorActionPreference = "Stop";

New-Item -ItemType Directory -Force -Path ./nuget

dotnet tool restore

pushd ./src/Storage
./build.ps1 $args
popd

pushd ./src/IdentityServer4
./build.ps1 $args
popd

pushd ./src/EntityFramework.Storage
./build.ps1 $args
popd

pushd ./src/EntityFramework
./build.ps1 $args
popd

pushd ./src/AspNetIdentity
./build.ps1 $args
popd
</code>```

When I run build.ps1 I see that "dotnet tool restore" succeeds in updating all nuget packages.

I then get the same "exited with code -532462766" error message for all 5 build.ps1 commands, here is one of the error messages:

C:\Users\tregan.nuget\packages\minver\2.0.0\build\MinVer.targets(39,5): error MSB3073: The command "dotnet "C:\Users\tregan.nuget\packages\minver\2.0.0\build../minver/MinVer.dll" --auto-increment "" --build-metadata "" --default-pre-release-phase "" --minimum-major-minor "" --repo "C:\Repo\Core\IdentityServer4-master\src\Storage\build" --tag-prefix "" --verbosity "" --version-override """ exited with code -532462766. [C:\Repo\Core\IdentityServer4-master\src\Storage\build\build.csproj]

I have verified that the paths it is looking for all exist (C:\Users\tregan.nuget\packages\minver\2.0.0\build, C:\Repo\Core\IdentityServer4-master\src\Storage\build\build.csproj).

Extracting from the error message, it appears this command is failing:

dotnet
  "C:\Users\tregan.nuget\packages\minver\2.0.0\build../minver/MinVer.dll"

The error message complains about the file MinVer.Targets, line 39.  That points to the following section of the file, which is obviously responsible for creating the command that is failing to execute:

```<code>    <Exec Command="dotnet "$(MSBuildThisFileDirectory)../minver/MinVer.dll" @(MinVerInputs->'%(Identity)', ' ')" ConsoleToMSBuild="true" StandardOutputImportance="Low" >
  <Output TaskParameter="ConsoleOutput" ItemName="MinVerConsoleOutput" />
</Exec>
</code>```

答:
This failed because Git was not installed on my machine.

I discovered this by running the command that build.ps1 was trying to execute in a command prompt:

```<code>dotnet "C:\Users\tregan.nuget\packages\minver\2.0.0\build../minver/MinVer.dll"
</code>```

This gave me the error message that the command failed because Git is not installed.  Since I have Choclately installed, I just had to run this from a command prompt running as administrator:

```<code>choco install git
</code>```

You may need to refresh your enviornment variables (and close/reopen Visual Studio if that's what you're using):

```<code>refreshenv
</code>```

Body:
I am getting the error message "exited with code -532462766" when I attempt to build IdentityServer4.  The error appears to be happening inside the "MinVer" Nuget package.

I downloaded the IdentityServer4 zip file onto a Windows 10 machine from the github site at https://github.com/IdentityServer/IdentityServer4 and unzipped it into a local directory, then followed the directions, which are:

Download the latest .Net Core SDK.  I already had the latest sdk installed, but after getting the errors in the "MinVer" nuget package (see below) I decided to download a couple of older version as well.   My C:\Program Files\dotnet folder contains the following sub-folders in the "sdk" folder:

2.1.202

2.1.803

2.2.108

3.0.101

3.1.100

3.1.101

Run build.ps1 in the root directory.  Build.ps1 does a nuget restore and then executes 5 other build files, this is the contents:

$ErrorActionPreference = "Stop";

New-Item -ItemType Directory -Force -Path ./nuget

dotnet tool restore

pushd ./src/Storage
./build.ps1 $args
popd

pushd ./src/IdentityServer4
./build.ps1 $args
popd

pushd ./src/EntityFramework.Storage
./build.ps1 $args
popd

pushd ./src/EntityFramework
./build.ps1 $args
popd

pushd ./src/AspNetIdentity
./build.ps1 $args
popd

When I run build.ps1 I see that "dotnet tool restore" succeeds in updating all nuget packages.

I then get the same "exited with code -532462766" error message for all 5 build.ps1 commands, here is one of the error messages:

C:\Users\tregan.nuget\packages\minver\2.0.0\build\MinVer.targets(39,5): error MSB3073: The command "dotnet "C:\Users\tregan.nuget\packages\minver\2.0.0\build../minver/MinVer.dll" --auto-increment "" --build-metadata "" --default-pre-release-phase "" --minimum-major-minor "" --repo "C:\Repo\Core\IdentityServer4-master\src\Storage\build" --tag-prefix "" --verbosity "" --version-override """ exited with code -532462766. [C:\Repo\Core\IdentityServer4-master\src\Storage\build\build.csproj]

I have verified that the paths it is looking for all exist (C:\Users\tregan.nuget\packages\minver\2.0.0\build, C:\Repo\Core\IdentityServer4-master\src\Storage\build\build.csproj).

Extracting from the error message, it appears this command is failing:

dotnet
  "C:\Users\tregan.nuget\packages\minver\2.0.0\build../minver/MinVer.dll"

The error message complains about the file MinVer.Targets, line 39.  That points to the following section of the file, which is obviously responsible for creating the command that is failing to execute:

    <Exec Command="dotnet "$(MSBuildThisFileDirectory)../minver/MinVer.dll" @(MinVerInputs->'%(Identity)', ' ')" ConsoleToMSBuild="true" StandardOutputImportance="Low" >
  <Output TaskParameter="ConsoleOutput" ItemName="MinVerConsoleOutput" />
</Exec>

Body:
This failed because Git was not installed on my machine.

I discovered this by running the command that build.ps1 was trying to execute in a command prompt:

dotnet "C:\Users\tregan.nuget\packages\minver\2.0.0\build../minver/MinVer.dll"

This gave me the error message that the command failed because Git is not installed.  Since I have Choclately installed, I just had to run this from a command prompt running as administrator:

choco install git

You may need to refresh your enviornment variables (and close/reopen Visual Studio if that's what you're using):

refreshenv


问:
PHP Warning: mysqli_connect(): (HY000/2002): Connection refused
I am using PHP 5.5 and MAMP (downloaded from here):

I have a basic script like this:

```<code><?php
$servername = "127.0.0.1";
$username = "root";
$password = "root";

// Create connection
$conn = mysqli_connect($servername, $username, $password);

// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
</code>```

and when I run this script I get this error:

```<code>PHP Warning:  mysqli_connect(): (HY000/2002): Connection refused in /Applications/MAMP/htdocs/test/test.php on line 7
</code>```

Is there some configuration issue that I need to set up within MAMP or PHP?

答: In WAMP, right click on WAMP tray icon then change the port from 3308 to 3306 like this:

Body:
I am using PHP 5.5 and MAMP (downloaded from here):

I have a basic script like this:

<?php
$servername = "127.0.0.1";
$username = "root";
$password = "root";

// Create connection
$conn = mysqli_connect($servername, $username, $password);

// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>

and when I run this script I get this error:

PHP Warning:  mysqli_connect(): (HY000/2002): Connection refused in /Applications/MAMP/htdocs/test/test.php on line 7

Is there some configuration issue that I need to set up within MAMP or PHP?


问:
Oracle.ManagedDataAccess Procedures with Date as a Parameter causing exception

create or replace PROCEDURE     PROCEDURE_ONE(
 T1_CURSOR OUT SYS_REFCURSOR,
 Date_Start_P in Date Default sysdate
)
as
begin
OPEN T1_CURSOR FOR ...
```

<p>This works when testing with Oracle SQL Developer</p>

<p>My VB.Net code doesn't like the parameter</p>

<pre class="lang-vb prettyprint-override"><code>Private Function Load_Aging_Stock() As DataTable
    Try
        Dim dba As New Data_Access_Class
        Dim strSQL As String = "JOHN.PROCEDURE_ONE"
        Dim dt As DataTable

        Dim cmd As OracleCommand = dba.CreateStoredProcCommand(strSQL)
        Dim oracleParameter(1) As OracleParameter
        oracleParameter(0) = New OracleParameter()
        oracleParameter(1) = New OracleParameter()

        cmd.BindByName = True
        With cmd
            oracleParameter(0) = cmd.Parameters.Add("T1_Cursor", dbType:=Oracle.ManagedDataAccess.Client.OracleDbType.RefCursor, ParameterDirection.Output)
            '.Parameters.Add("T1_CURSOR", OracleClient.OracleType.Cursor).Direction = ParameterDirection.Output

            If Me.chk_No_Date_Start.Checked = False Then
                Dim tmpDate As String = CDate(Me.dt_Start_Date.Text.Trim).ToString("yyyy-MM-dd")
                oracleParameter(1) = cmd.Parameters.Add("Date_Start_P", dbType:=Oracle.ManagedDataAccess.Client.OracleDbType.Varchar2, val:=tmpDate, ParameterDirection.Input)
                '.Parameters.Add("Date_Start_P", OracleClient.OracleType.DateTime).Value = Me.dt_Start_Date.Text
            End If
        End With

        dt = dba.ExecuteSelectCmdDataTbl(cmd)

        Return dt

    Catch ex As Exception
        Dim Err As New SS_Errors("frm__Report", "Load_Report", ex)
        Return Nothing
    End Try

End Function
</code>```

I've also tried the same code but replaced Varchar2 with Date and both times, I get the same exception

One of the identified items was in an invalid format.

答:
Don't pass the string as parameter value, just use the Date value, i.e.

```<code>oracleParameter(1) = cmd.Parameters.Add("Date_Start_P", dbType:=OracleDbType.Date, val:=CDate(Me.dt_Start_Date.Text.Trim), ParameterDirection.Input)
</code>```

Body:
create or replace PROCEDURE     PROCEDURE_ONE(
 T1_CURSOR OUT SYS_REFCURSOR,
 Date_Start_P in Date Default sysdate
)
as
begin
OPEN T1_CURSOR FOR ...

This works when testing with Oracle SQL Developer

My VB.Net code doesn't like the parameter

Private Function Load_Aging_Stock() As DataTable
    Try
        Dim dba As New Data_Access_Class
        Dim strSQL As String = "JOHN.PROCEDURE_ONE"
        Dim dt As DataTable

        Dim cmd As OracleCommand = dba.CreateStoredProcCommand(strSQL)
        Dim oracleParameter(1) As OracleParameter
        oracleParameter(0) = New OracleParameter()
        oracleParameter(1) = New OracleParameter()

        cmd.BindByName = True
        With cmd
            oracleParameter(0) = cmd.Parameters.Add("T1_Cursor", dbType:=Oracle.ManagedDataAccess.Client.OracleDbType.RefCursor, ParameterDirection.Output)
            '.Parameters.Add("T1_CURSOR", OracleClient.OracleType.Cursor).Direction = ParameterDirection.Output

            If Me.chk_No_Date_Start.Checked = False Then
                Dim tmpDate As String = CDate(Me.dt_Start_Date.Text.Trim).ToString("yyyy-MM-dd")
                oracleParameter(1) = cmd.Parameters.Add("Date_Start_P", dbType:=Oracle.ManagedDataAccess.Client.OracleDbType.Varchar2, val:=tmpDate, ParameterDirection.Input)
                '.Parameters.Add("Date_Start_P", OracleClient.OracleType.DateTime).Value = Me.dt_Start_Date.Text
            End If
        End With

        dt = dba.ExecuteSelectCmdDataTbl(cmd)

        Return dt

    Catch ex As Exception
        Dim Err As New SS_Errors("frm__Report", "Load_Report", ex)
        Return Nothing
    End Try

End Function

I've also tried the same code but replaced Varchar2 with Date and both times, I get the same exception

One of the identified items was in an invalid format.

Body:
Don't pass the string as parameter value, just use the Date value, i.e.

oracleParameter(1) = cmd.Parameters.Add("Date_Start_P", dbType:=OracleDbType.Date, val:=CDate(Me.dt_Start_Date.Text.Trim), ParameterDirection.Input)


答:
It may work, but creating a copy is not necessary. NSDate is immutable and cannot be edited later.

This should suffice...

```<code>- (NSDate*)dateForMyTest {
     return self.endDate;
}
</code>```

Title: is this correct re returning a date re memory management?

Body:
It may work, but creating a copy is not necessary. NSDate is immutable and cannot be edited later.

This should suffice...

- (NSDate*)dateForMyTest {
     return self.endDate;
}